text
stringlengths
1
1.05M
#pragma once #include <GL/glew.h> #include "../renderer.h" namespace valk { namespace graphics { class IndexBuffer { private: GLuint m_BufferID; GLuint m_Count; public: IndexBuffer(GLushort* data, GLsizei count); ~IndexBuffer(); void bind() const; void unbind() const; inline GLuint getCount() const { return m_Count; } }; } }
/* * Copyright 2009-2011 junithelper.org. * * 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.junithelper.core.generator; import org.junithelper.core.config.Configuration; import org.junithelper.core.config.TestingTarget; import org.junithelper.core.config.extension.ExtInstantiation; import org.junithelper.core.constant.StringValue; import org.junithelper.core.meta.AccessModifier; import org.junithelper.core.meta.ClassMeta; import org.junithelper.core.meta.MethodMeta; import org.junithelper.core.meta.TestMethodMeta; import org.junithelper.core.util.Assertion; class GeneratorImplFunction { private GeneratorImplFunction() { } static boolean isPublicMethodAndTestingRequired(MethodMeta methodMeta, TestingTarget target) { return methodMeta.accessModifier == AccessModifier.Public && target.isPublicMethodRequired; } static boolean isProtectedMethodAndTestingRequired(MethodMeta methodMeta, TestingTarget target) { return methodMeta.accessModifier == AccessModifier.Protected && target.isProtectedMethodRequired; } static boolean isPackageLocalMethodAndTestingRequired(MethodMeta methodMeta, TestingTarget target) { return methodMeta.accessModifier == AccessModifier.PackageLocal && target.isPackageLocalMethodRequired; } static boolean isCanonicalClassNameUsed(String expectedCanonicalClassName, String usedClassName, ClassMeta targetClassMeta) { Assertion.on("expectedCanonicalClassName").mustNotBeNull(expectedCanonicalClassName); Assertion.on("usedClassName").mustNotBeNull(usedClassName); Assertion.on("targetClassMeta").mustNotBeNull(targetClassMeta); if (usedClassName.equals(expectedCanonicalClassName) || usedClassName.equals(expectedCanonicalClassName.replace("java.lang.", ""))) { // canonical class name // e.g. // "com.example.ArgBean" return true; } else { // imported type // e.g. // (same package) // import com.example.*; // import com.example.ArgBean; // "ArgBean" String[] extSplitted = expectedCanonicalClassName.split("\\."); String extClassName = extSplitted[extSplitted.length - 1]; if (usedClassName.equals(extClassName)) { String extInSamplePackage = targetClassMeta.packageName + "." + extClassName; if (extInSamplePackage.equals(expectedCanonicalClassName)) { return true; } else { for (String imported : targetClassMeta.importedList) { String target = expectedCanonicalClassName.replaceFirst(extClassName, ""); if (imported.matches(expectedCanonicalClassName) || imported.matches(target + ".+")) { return true; } } } } } return false; } static String getInstantiationSourceCode(Configuration config, SourceCodeAppender appender, TestMethodMeta testMethodMeta) { Assertion.on("config").mustNotBeNull(config); Assertion.on("testMethodMeta").mustNotBeNull(testMethodMeta); // ----------- // Extension if (config.isExtensionEnabled && config.extConfiguration.extInstantiations != null) { for (ExtInstantiation ins : config.extConfiguration.extInstantiations) { if (isCanonicalClassNameUsed(ins.canonicalClassName, testMethodMeta.classMeta.name, testMethodMeta.classMeta)) { // add import list for (String newImport : ins.importList) { testMethodMeta.classMeta.importedList.add(newImport); } // instantiation code // e.g. Sample target = new Sample(); StringBuilder buf = new StringBuilder(); if (ins.preAssignCode != null && ins.preAssignCode.trim().length() > 0) { appender.appendExtensionSourceCode(buf, ins.preAssignCode); } appender.appendTabs(buf, 2); buf.append(testMethodMeta.classMeta.name); buf.append(" target = "); buf.append(ins.assignCode.trim()); if (!ins.assignCode.trim().endsWith(StringValue.Semicolon)) { buf.append(StringValue.Semicolon); } appender.appendLineBreak(buf); if (ins.postAssignCode != null && ins.postAssignCode.trim().length() > 0) { appender.appendExtensionPostAssignSourceCode(buf, ins.postAssignCode, new String[] { "\\{instance\\}" }, "target"); } return buf.toString(); } } } // TODO better implementation ConstructorGenerator constructorGenerator = ConstructorGeneratorFactory.create(config, appender .getLineBreakProvider()); return constructorGenerator.getFirstInstantiationSourceCode(config, testMethodMeta.classMeta); } }
class Student: def __init__(self, name, age, marks): self.name = name self.age = age self.marks = marks def get_name(self): return self.name def get_age(self): return self.age def get_total_marks(self): return sum(self.marks)
<reponame>ChrisLMerrill/museide<gh_stars>0 package org.museautomation.ui.ide.navigation; import javafx.scene.*; import net.christophermerrill.testfx.*; import org.junit.jupiter.api.*; import org.museautomation.ui.ide.navigation.resources.*; import org.museautomation.ui.ide.navigation.resources.actions.*; import org.museautomation.core.*; import org.museautomation.core.project.*; import org.museautomation.core.steptask.*; import org.museautomation.core.variables.*; import org.museautomation.ui.extend.actions.*; import org.museautomation.ui.extend.components.*; import java.io.*; /** * @author <NAME> (see LICENSE.txt for license details) */ public class CreateResourcePanelTests extends ComponentTest { @Test void createResource() { final String resource_id = setup(); Assertions.assertTrue(exists(new VariableList.VariableListResourceType().getName())); Node node = lookup(resource_id).query(); Assertions.assertNotNull(node); Assertions.assertFalse(InputValidation.isShowingError(node)); CreateResourceAction action = _panel.getAction(); Assertions.assertNotNull(action, "no action created"); Assertions.assertTrue(action.getType() instanceof VariableList.VariableListResourceType); Assertions.assertEquals(resource_id, action.getId()); } @Test void duplicateId() { final String resource_id = setup(); Node node = lookup(resource_id).query(); fillFieldAndTabAway(node, TESTID); Assertions.assertTrue(InputValidation.isShowingError(node)); Assertions.assertNull(_panel.getAction(), "should not create action when provided ID already exists in repository"); } @Test void blankId() { final String resource_id = setup(); Node node = lookup(resource_id).query(); clearFieldAndTabAway(resource_id); Assertions.assertTrue(InputValidation.isShowingError(node)); Assertions.assertNull(_panel.getAction(), "should not create action when no ID is provided"); } @Test void changeDefaults() { final String resource_id = setup(); clickOn(new VariableList.VariableListResourceType().getName()); clickOn(new MuseTask.TaskResourceType().getName()); final String changed_id = "changed"; fillFieldAndTabAway(resource_id, changed_id); CreateResourceAction action = _panel.getAction(); Assertions.assertTrue(action.getType() instanceof MuseTask.TaskResourceType); Assertions.assertEquals(changed_id, action.getId()); } private String setup() { _panel.setType(new VariableList.VariableListResourceType()); final String new_id = "newlist"; _panel.setId(new_id); waitForUiEvents(); return new_id; } @Override public Node createComponentNode() throws IOException { MuseProject project = new SimpleProject(); SteppedTest test1 = new SteppedTest(); test1.setId(TESTID); project.getResourceStorage().addResource(test1); _panel = new CreateResourcePanel(project, new UndoStack()); return _panel.getNode(); } private CreateResourcePanel _panel; private final static String TESTID = "test1"; }
fn process_response(response: Vec<(u32, String, String)>) -> bool { let expected_result = vec![(3, "test_insert".to_string(), "test_update".to_string())]; response == expected_result }
#! /usr/bin/env bash # 编译并docker中运行 realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}" } PROJECT_PATH=$(dirname $(dirname $(dirname $(realpath $0)))) source ${PROJECT_PATH}/misc/scripts/dist.sh docker build -t x-stock ${PROJECT_PATH} docker run -p 4869:4869 -p 4870:4870 x-stock
#include <QObject> #include <QThread> #include <QVector> #include <complex> #include <fftw3.h> class FFTWorker : public QObject { Q_OBJECT public: FFTWorker(int fftLength) : m_fftLength(fftLength) { m_inputSignal.resize(fftLength); // Initialize and configure FFTW plans, threads, etc. m_fftPlan = fftw_plan_dft_1d(fftLength, reinterpret_cast<fftw_complex*>(m_inputSignal.data()), reinterpret_cast<fftw_complex*>(m_outputResult.data()), FFTW_FORWARD, FFTW_ESTIMATE); } ~FFTWorker() { fftw_destroy_plan(m_fftPlan); } public slots: void processInputSignal(const QVector<double>& inputSignal) { // Copy input signal to member variable for processing std::copy(inputSignal.begin(), inputSignal.end(), m_inputSignal.begin()); // Perform FFT computation in a separate thread m_fftThread = new QThread(); moveToThread(m_fftThread); connect(m_fftThread, &QThread::started, this, &FFTWorker::computeFFT); connect(this, &FFTWorker::fftResultReady, m_fftThread, &QThread::quit); connect(this, &FFTWorker::fftResultReady, this, &FFTWorker::deleteLater); connect(m_fftThread, &QThread::finished, m_fftThread, &QThread::deleteLater); m_fftThread->start(); } signals: void fftResultReady(const QVector<std::complex<double>>& result); private: int m_fftLength; QVector<double> m_inputSignal; QVector<std::complex<double>> m_outputResult; fftw_plan m_fftPlan; QThread* m_fftThread; void computeFFT() { // Execute the FFT computation fftw_execute(m_fftPlan); // Convert the output to QVector<std::complex<double>> for emitting the result QVector<std::complex<double>> result(m_fftLength); for (int i = 0; i < m_fftLength; ++i) { result[i] = std::complex<double>(m_outputResult[i].real(), m_outputResult[i].imag()); } // Emit the computed FFT result emit fftResultReady(result); } };
export * from './response' ; export * from './enum' ;
add_lunch_combo lineage_harpia-userdebug add_lunch_combo lineage_harpia-eng
#!/bin/bash echo "" > versions
<filename>AVVideoCompositingSample/AVVideoCompositingSample/Video/Metal/SSMetalRenderer.h // // SSMetalRenderer.h // AVVideoCompositingSample // // Created by king on 2020/10/25. // Copyright © 2020 taihe. All rights reserved. // #import <Foundation/Foundation.h> #import "SSRenderer.h" NS_ASSUME_NONNULL_BEGIN @interface SSMetalRenderer : NSObject<SSRenderer> @property (nonatomic, readonly, nullable) NSDictionary<NSString *, id> *sourcePixelBufferAttributes; @property (nonatomic, readonly) NSDictionary<NSString *, id> *requiredPixelBufferAttributesForRenderContext; - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; - (instancetype)initWithError:(__autoreleasing NSError **)error NS_DESIGNATED_INITIALIZER; - (CVPixelBufferRef)renderedPixelBufferForRequest:(AVAsynchronousVideoCompositionRequest *)request; @end NS_ASSUME_NONNULL_END
class StorageTracker: def __init__(self): self._storage_allocated = None self._storage_used = None self._storage_used_by_table_space = None def allocate_storage(self, amount): self._storage_allocated = amount def update_storage_used(self, amount): if self._storage_used is None: self._storage_used = amount else: self._storage_used += amount def get_storage_used_by_table_space(self): if self._storage_allocated is not None and self._storage_used is not None: self._storage_used_by_table_space = self._storage_allocated - self._storage_used return self._storage_used_by_table_space else: return "Storage allocation or usage information is missing." # Example usage tracker = StorageTracker() tracker.allocate_storage(1000) tracker.update_storage_used(300) print(tracker.get_storage_used_by_table_space()) # Output: 700 tracker.update_storage_used(200) print(tracker.get_storage_used_by_table_space()) # Output: 500
<filename>chapter1/hello_di_with_security.py from typing import Protocol class MessageWriter(Protocol): def write(self, message: str) -> None: ... class Identity(Protocol): is_authenticated: bool class CurrentUser(Identity): @property def is_authenticated(self) -> bool: return True class ConsoleMessageWriter(MessageWriter): def write(self, message: str) -> None: print(message) class SecurityMessageWriter(MessageWriter): _writer: MessageWriter _identity: Identity def __init__(self, writer: MessageWriter, identity: Identity): if writer is None: raise ValueError("writer can't be None") if identity is None: raise ValueError("identity can't be None") self._writer = writer self._identity = identity def write(self, message: str) -> None: if self._identity.is_authenticated: self._writer.write(message) class Salutation: _writer: MessageWriter def __init__(self, writer: MessageWriter): if writer is None: raise ValueError('Writer can\'t be None') self._writer = writer def exclaim(self): self._writer.write('Hello DI!') def main(): writer = SecurityMessageWriter( writer=ConsoleMessageWriter(), identity=CurrentUser(), ) salutation = Salutation(writer) salutation.exclaim() if __name__ == '__main__': main()
<reponame>cbartram/HealthKit-Consumer<gh_stars>0 import React, { Component } from 'react'; import Container from './Container/Container'; /** * Attaches a <Container /> Component around the * base component which shows the Navbar and footer on the page. * @param BaseComponent * @param props * @returns {{new(props: Readonly<P>): EnhancedComponent, new(props: P, context?: any): EnhancedComponent, prototype: EnhancedComponent}} */ const withContainer = (BaseComponent, props = {}) => { return class EnhancedComponent extends Component { constructor(props) { super(props); this.state = { alerts: [] } } render() { return ( <Container {...props}> <BaseComponent /> </Container> ); } } }; export default withContainer;
export {}; //# sourceMappingURL=run.d.ts.map
import numpy as np def process_matrix(valid, mask, rule_names, mt): product = 1 while np.any(mask): cur = valid & mask axissum = cur.sum(axis=1) field = np.where(axissum == 1)[0][0] rule = np.where(cur[field, :])[0][0] if rule_names[rule].startswith("departure"): product *= int(mt[field]) mask[:, rule] = False return product
<reponame>epicosy/svd<filename>svd/core/exc.py class SVDError(Exception): """Generic errors.""" pass
select c.value || '/' || d.instance_name || '_ora_' || a.spid || '.trc' trace from v$process a, v$session b, v$parameter c, v$instance d where a.addr = b.paddr and b.audsid = userenv('sessionid') and c.name = 'user_dump_dest' /
#!/usr/bin/ruby require 'simplecov' if ENV['COVERAGE'] require 'rspec' require 'fileutils' require 'tmpdir' require_relative '../lib/ezmlm' module SpecHelpers include FileUtils TEST_LIST_NAME = 'waffle-lovers' TEST_LIST_HOST = 'lists.syrup.info' TEST_OWNER = '<EMAIL>' TEST_SUBSCRIBERS = %w[ <EMAIL> <EMAIL> <EMAIL> ] TEST_MODERATORS = %w[ <EMAIL> ] ############### module_function ############### ### Create a copy of a fresh listdir into /tmp. ### def make_listdir dirname = "%s/%s.%d.%0.4f" % [ Dir.tmpdir, 'ezmlm_list', Process.pid, (Time.now.to_f % 3600), ] list = Pathname.new( __FILE__ ).dirname + 'data' + 'testlist' cp_r( list.to_s, dirname ) return dirname end end RSpec.configure do |config| include SpecHelpers config.run_all_when_everything_filtered = true config.filter_run :focus config.order = 'random' config.mock_with( :rspec ) do |mock| mock.syntax = :expect end config.include( SpecHelpers ) end
<reponame>RemiBou/Blazor import { System_Object, System_String, System_Array, MethodHandle, Pointer } from '../Platform/Platform'; import { platform } from '../Environment'; import { renderBatch as renderBatchStruct, arrayRange, arraySegment, renderTreeDiffStructLength, renderTreeDiff, RenderBatchPointer, RenderTreeDiffPointer } from './RenderBatch'; import { BrowserRenderer } from './BrowserRenderer'; type BrowserRendererRegistry = { [browserRendererId: number]: BrowserRenderer }; const browserRenderers: BrowserRendererRegistry = {}; export function attachRootComponentToElement(browserRendererId: number, elementSelector: System_String, componentId: number) { const elementSelectorJs = platform.toJavaScriptString(elementSelector); const element = document.querySelector(elementSelectorJs); if (!element) { throw new Error(`Could not find any element matching selector '${elementSelectorJs}'.`); } let browserRenderer = browserRenderers[browserRendererId]; if (!browserRenderer) { browserRenderer = browserRenderers[browserRendererId] = new BrowserRenderer(browserRendererId); } clearElement(element); browserRenderer.attachRootComponentToElement(componentId, element); } export function renderBatch(browserRendererId: number, batch: RenderBatchPointer) { const browserRenderer = browserRenderers[browserRendererId]; if (!browserRenderer) { throw new Error(`There is no browser renderer with ID ${browserRendererId}.`); } const updatedComponents = renderBatchStruct.updatedComponents(batch); const updatedComponentsLength = arrayRange.count(updatedComponents); const updatedComponentsArray = arrayRange.array(updatedComponents); const referenceFramesStruct = renderBatchStruct.referenceFrames(batch); const referenceFrames = arrayRange.array(referenceFramesStruct); for (let i = 0; i < updatedComponentsLength; i++) { const diff = platform.getArrayEntryPtr(updatedComponentsArray, i, renderTreeDiffStructLength); const componentId = renderTreeDiff.componentId(diff); const editsArraySegment = renderTreeDiff.edits(diff); const edits = arraySegment.array(editsArraySegment); const editsOffset = arraySegment.offset(editsArraySegment); const editsLength = arraySegment.count(editsArraySegment); browserRenderer.updateComponent(componentId, edits, editsOffset, editsLength, referenceFrames); } const disposedComponentIds = renderBatchStruct.disposedComponentIds(batch); const disposedComponentIdsLength = arrayRange.count(disposedComponentIds); const disposedComponentIdsArray = arrayRange.array(disposedComponentIds); for (let i = 0; i < disposedComponentIdsLength; i++) { const componentIdPtr = platform.getArrayEntryPtr(disposedComponentIdsArray, i, 4); const componentId = platform.readInt32Field(componentIdPtr); browserRenderer.disposeComponent(componentId); } const disposedEventHandlerIds = renderBatchStruct.disposedEventHandlerIds(batch); const disposedEventHandlerIdsLength = arrayRange.count(disposedEventHandlerIds); const disposedEventHandlerIdsArray = arrayRange.array(disposedEventHandlerIds); for (let i = 0; i < disposedEventHandlerIdsLength; i++) { const eventHandlerIdPtr = platform.getArrayEntryPtr(disposedEventHandlerIdsArray, i, 4); const eventHandlerId = platform.readInt32Field(eventHandlerIdPtr); browserRenderer.disposeEventHandler(eventHandlerId); } } function clearElement(element: Element) { let childNode: Node | null; while (childNode = element.firstChild) { element.removeChild(childNode); } }
<filename>record.js const title = process.argv[2]; const url = process.argv[3]; const m3u8stream = require('m3u8stream'); const fs = require('fs'); function convertToValidFilename(string) { return (string.replace(/[\/|\\:*?"<>]/g, " ")); } m3u8stream(url).pipe( fs.createWriteStream( "./videos/" + convertToValidFilename(title) + ".mp4" ) );
#!/bin/bash # script to increment or decrement bar counter and also increment or decrement completed task counter # Connor Rhodes (connorrhodes.com) remaining=$HOME/.cache/count.txt done=$HOME/.cache/donecount.txt case $1 in inc) echo $(expr $(cat $remaining) + 1) > $remaining echo $(expr $(cat $done) - 1) > $done ;; dec) echo $(expr $(cat $remaining) - 1) > $remaining echo $(expr $(cat $done) + 1) > $done ;; esac /home/connor/.local/dotfiles/shared/system_scripts/path/refbar
#!/bin/sh java \ -XX:MinHeapFreeRatio=5 \ -XX:MaxHeapFreeRatio=10 \ -XX:GCTimeRatio=4 \ -XX:AdaptiveSizePolicyWeight=90 \ -XX:MaxRAMPercentage=70 \ --module-path /libs \ --add-modules ALL-MODULE-PATH \ --add-opens java.base/java.nio=ALL-UNNAMED \ --add-opens java.base/sun.nio.ch=ALL-UNNAMED \ --add-opens java.base/sun.net.dns=ALL-UNNAMED \ -Dvertx.logger-delegate-factory-class-name=io.vertx.core.logging.SLF4JLogDelegateFactory \ $DEBUG_OPTS com.nextbreakpoint.blueprint.accounts.Verticle $@
<gh_stars>0 package me.chris.SimpleChat; /** * @author <NAME> * @date Feb 29, 2012 * @file SimpleChatHelperMethods.java * @package me.chris.SimpleChat * * @purpose */ public class SimpleChatChatState { public static String chatState; public SimpleChatChatState() { chatState = "on"; } public static String getChatState() { if(chatState.equalsIgnoreCase("on")) return "on"; else if(chatState.equalsIgnoreCase("off")) return "off"; else return "on"; } public static void setChatState(String state) { if(state.equalsIgnoreCase("on")) chatState = "on"; else if(state.equalsIgnoreCase("off")) chatState = "off"; else chatState = "on"; } }
<gh_stars>0 import tKinter as tk root = tk.Tk() class window_native: def __init__( self, size ): self.size = size self.window = tk.Toplevel( root ) def write( location, color ): self class line: def __init__( self, start, end ): self.start = start self.end = end def write( self, window ): x0 = start.x; y0 = start.y; x1 = end.x; y1 = end.y; // http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm // http://homepages.enterprise.net/murphy/thickline/index.html Dx = x1 - x0 Dy = y1 - y0 steep = (abs(Dy) >= abs(Dx)) if steep: ( x0, y0, x1, y1 ) = ( y0, x0, y1, x1 ) // recompute Dx, Dy after swap Dx = x1 - x0 Dy = y1 - y0 xstep = 1 if Dx < 0: xstep = -1 Dx = -Dx ystep = 1 if Dy < 0: ystep = -1 Dy = -Dy TwoDy = 2 * Dy TwoDyTwoDx = TwoDy - 2 * Dx # 2*Dy - 2*Dx E = TwoDy - Dx # 2*Dy - Dx y = y0 x = x0 while x != x1: if steep: xDraw = y yDraw = x else: xDraw = x yDraw = y window.write( xy( xDraw, yDraw ), color ); if E > 0: E += TwoDyTwoDx # E += 2*Dy - 2*Dx; y = y + ystep else: E += TwoDy # E += 2*Dy; x += xstep root.mainloop()
<filename>Devices/Base.js<gh_stars>1-10 // Base Base = function() { this.platform = null; } Base.prototype.init = function(platform, config) { this.platform = platform; this.config = config; } Base.prototype.obj2array = function(obj) { var array = []; for(var item in obj) { array.push(obj[item]); } return array; }
<reponame>modernizer-bot/stakerwatch import {L2_OPTIMISM, getNodeURL} from 'staker-freenodes' import {jsonRpcFetch} from '../helpers/jsonRpc'; export const optimismFetch = (fetch, body) => jsonRpcFetch(fetch, getNodeURL(L2_OPTIMISM), body);
#!/bin/bash # # Investigation of https://github.com/oilshell/oil/issues/268 # # Usage: # ./plugins-and-shell-state.sh <function name> # Corrupts shell state in OSH. # # bash has save_parser_state and restore_parser_state, and bizarrely the exit # code and pipe status are part of that! # # OK variables are protected because they're in a subshell. PS1='$(echo ${MUTATED=hi }; echo $MUTATED; exit 42) $(echo $?)\$ ' foo() { argv foo "$@"; } complete_foo() { local first=$1 local cur=$2 local prev=$3 for candidate in one two three bin; do if [[ $candidate == $cur* ]]; then COMPREPLY+=("$candidate") fi done COMP_MUTATED='mutated by completion plugin' # visible afterward return 23 # doesn't appear anywhere? } complete -F complete_foo foo
package com.common.system.mapper; import com.common.system.entity.RcBaseArea; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author yangxiufeng * @since 2017-09-12 */ public interface RcBaseAreaMapper extends BaseMapper<RcBaseArea> { }
public static int getMax(int[] arr) { int max = arr[0]; for (int i=1; i<arr.length; i++) if (arr[i] > max) max = arr[i]; return max; } int arr[] = {3, 5, 9, 11, 17, 23, 27, 32}; System.out.println("Maximum element of the array: "+getMax(arr)); # Output should be -> Maximum element of the array: 32
<reponame>bowen0701/python-algorithms-data-structures """Leetcode 678. Valid Parenthesis String Medium URL: https://leetcode.com/problems/valid-parenthesis-string/ Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: - Any left parenthesis '(' must have a corresponding right parenthesis ')'. - Any right parenthesis ')' must have a corresponding left parenthesis '('. - Left parenthesis '(' must go before the corresponding right parenthesis ')'. - '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. - An empty string is also valid. Example 1: Input: "()" Output: True Example 2: Input: "(*)" Output: True Example 3: Input: "(*))" Output: True Note: The string size will be in the range [1, 100]. """ class SolutionBruteForce(object): def _enumerate(self, s): """Enumerate s by replacing '*' by '(', '', & ')'.""" s_set = set() queue = [s] while queue: for i in range(len(queue)): si = list(queue.pop()) if si.count('*'): for j, c in enumerate(si): if c == '*': for r in ['(', 'a', ')']: si[j] = r if not si.count('*'): s_set.add(''.join(si)) else: queue.append(''.join(si)) else: s_set.add(''.join(si)) return list(s_set) def _is_valid(self, s): """Check s is valid with parentheses.""" stack = [] for c in s: if c == '(': stack.append('(') elif c == ')': if not stack: return False stack.pop() return not stack def checkValidString(self, s): """ :type s: str :rtype: bool Note: Time Limit Exceeded. Time complexity: O(3^k), where k is the number of '*'s. Space complexity: O(3^k). """ # Edge case. if len(s) == 1: return s == '*' # Enumerate all strings with '*' replaced by, '(', '', ')'. s_list = self._enumerate(s) # Iterate through list to check if there is one valid. for si in s_list: if self._is_valid(si): return True return False class SolutionMinMaxCloseCount(object): def checkValidString(self, s): """ :type s: str :rtype: bool Time complexity: O(n). Space complexity: O(1). """ if len(s) == 1: return s == '*' # Iterate through s to collect expected min/max number of '('. # - max_ncloses treats each '*' as '(', should never be negative. # - min_ncloses treats each '*' as ')'; treat it as '' if < 0. min_ncloses = max_ncloses = 0 for c in s: if c == '(': max_ncloses += 1 min_ncloses += 1 elif c == ')': max_ncloses -= 1 min_ncloses = max(min_ncloses - 1, 0) else: max_ncloses += 1 min_ncloses = max(min_ncloses - 1, 0) if max_ncloses < 0: return False # If min_ncloses > 0, there are not enough ')'. return min_ncloses == 0 def main(): # Output: True s = "()" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: True s = "(*)" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: True s = "(*))" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: False s = "*((" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: False s = "**((" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: False s = "()(()(*(())()*)(*)))()))*)((()(*(((()())()))()()*)((*)))()))(*)(()()(((()*()()((()))((*((*)()" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) if __name__ == '__main__': main()
/* * @Author: <NAME> * @Date: 2021-12-02 18:32:55 * @Last Modified by: <NAME> * @Last Modified time: 2021-12-06 18:25:34 */ import getGitPreset, { GitStatus } from '@@contribute/utils/get-git-preset'; /** * Initialize context with git info. * * @returns {Promise<GitStatus>} */ const gitPreset = async (): Promise<GitStatus> => { const state = await getGitPreset(); return state; }; export default gitPreset;
<gh_stars>1-10 /* eslint-disable no-console */ // Register babel to have ES6 support on the server require('babel-polyfill'); require('babel-register'); require('./src/server');
<reponame>jreijn/hippo-groovy-addon<gh_stars>1-10 /** * Copyright (C) 2011 Hippo * * 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.onehippo.forge.cms.groovy.plugin.codemirror; import org.apache.wicket.behavior.AbstractBehavior; import org.apache.wicket.markup.html.CSSPackageResource; import org.apache.wicket.markup.html.IHeaderResponse; import org.apache.wicket.markup.html.JavascriptPackageResource; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.model.IModel; /** * Component that displays a CodeMirror panel which gives a nice syntax highlighting for Groovy. * @author <NAME> */ public class CodeMirrorEditor extends TextArea { private String markupId; public CodeMirrorEditor(final String id, final IModel iModel) { super(id, iModel); setOutputMarkupId(true); markupId = getMarkupId(); add(JavascriptPackageResource.getHeaderContribution(CodeMirrorEditor.class, "v3_20/lib/codemirror.js")); add(CSSPackageResource.getHeaderContribution(CodeMirrorEditor.class, "v3_20/lib/codemirror.css")); add(CSSPackageResource.getHeaderContribution(CodeMirrorEditor.class, "v3_20/theme/eclipse.css")); add(JavascriptPackageResource.getHeaderContribution(CodeMirrorEditor.class, "v3_20/mode/groovy/groovy.js")); add(new AbstractBehavior() { @Override public void renderHead(IHeaderResponse response) { response.renderOnLoadJavascript(getJavaScriptForEditor()); } }); } private String getJavaScriptForEditor() { StringBuffer jsInit = new StringBuffer(); jsInit.append("var cm = CodeMirror.fromTextArea(document.getElementById('"+markupId+"'), {lineNumbers: true, matchBrackets: true, mode: \"text/x-groovy\", onChange: function(cm) { cm.save(); }});"); return jsInit.toString(); } }
#!/bin/bash set -e set -o pipefail JENKINSUID=${JENKINSUID:-1000} JENKINSGUID=${JENKINSGUID:-1000} cleanup() { chown -R "$JENKINSUID:$JENKINSGUID" tmp log } trap "cleanup" SIGINT SIGTERM SIGHUP SIGQUIT EXIT PACKAGE=${PACKAGE:-} OPT_REPO=${OPT_REPO:-} BUILD_ARCH=${BUILD_ARCH:-} sed -i '/stty sane/d' /usr/sbin/slackrepo sed -i '/^PKGBACKUP/d' "/etc/slackrepo/slackrepo_$OPT_REPO.conf" sed -i "/^LINT/s/'n'/'y'/" "/etc/slackrepo/slackrepo_$OPT_REPO.conf" if [[ "$BUILD_ARCH" != "" ]] ; then sed -i "s/^ARCH.*$/ARCH=$BUILD_ARCH/" "/etc/slackrepo/slackrepo_$OPT_REPO.conf" fi # use the sources from the build CWD="$(pwd)" ( cd "/var/lib/slackrepo/$OPT_REPO" if [ -L slackbuilds ] ; then unlink slackbuilds fi ln -sf "$CWD" slackbuilds ) mkdir -p tmp echo "Determining list of packages to build" su -l -c "slackrepo --preview build $PACKAGE" > tmp/preview_build sed -i -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" tmp/preview_build <tmp/preview_build sed '0,/^SUMMARY/d' | sed '0,/^Pending/d' | sed -n '/Estimated/q;p' | sed 's/^[[:space:]]*//' | cut -d' ' -f1 > tmp/project_list
// Node.cpp #include "AllocationInfo.h" #include "DebugSupport.h" #include "EntryIterator.h" #include "LastModifiedIndex.h" #include "Node.h" #include "Volume.h" // is_user_in_group inline static bool is_user_in_group(gid_t gid) { // Either I miss something, or we don't have getgroups() in the kernel. :-( /* gid_t groups[NGROUPS_MAX]; int groupCount = getgroups(NGROUPS_MAX, groups); for (int i = 0; i < groupCount; i++) { if (gid == groups[i]) return true; } */ return (gid == getegid()); } // constructor Node::Node(Volume *volume, uint8 type) : fVolume(volume), fID(fVolume->NextNodeID()), fRefCount(0), fMode(0), fUID(0), fGID(0), fATime(0), fMTime(0), fCTime(0), fCrTime(0), fModified(0), fIsKnownToVFS(false), // attribute management fAttributes(), // referrers fReferrers() { // set file type switch (type) { case NODE_TYPE_DIRECTORY: fMode = S_IFDIR; break; case NODE_TYPE_FILE: fMode = S_IFREG; break; case NODE_TYPE_SYMLINK: fMode = S_IFLNK; break; } // set defaults for time fATime = fMTime = fCTime = fCrTime = time(NULL); } // destructor Node::~Node() { // delete all attributes while (Attribute *attribute = fAttributes.First()) { status_t error = DeleteAttribute(attribute); if (error != B_OK) { FATAL(("Node::~Node(): Failed to delete attribute!\n")); break; } } } // InitCheck status_t Node::InitCheck() const { return (fVolume && fID >= 0 ? B_OK : B_NO_INIT); } // AddReference status_t Node::AddReference() { if (++fRefCount == 1) { status_t error = GetVolume()->PublishVNode(this); if (error != B_OK) { fRefCount--; return error; } fIsKnownToVFS = true; } return B_OK; } // RemoveReference void Node::RemoveReference() { if (--fRefCount == 0) { GetVolume()->RemoveVNode(this); fRefCount++; } } // Link status_t Node::Link(Entry *entry) { PRINT(("Node[%Ld]::Link(): %ld ->...\n", fID, fRefCount)); fReferrers.Insert(entry); status_t error = AddReference(); if (error != B_OK) fReferrers.Remove(entry); return error; } // Unlink status_t Node::Unlink(Entry *entry) { PRINT(("Node[%Ld]::Unlink(): %ld ->...\n", fID, fRefCount)); RemoveReference(); fReferrers.Remove(entry); return B_OK; } // SetMTime void Node::SetMTime(time_t mTime) { time_t oldMTime = fMTime; fATime = fMTime = mTime; if (oldMTime != fMTime) { if (LastModifiedIndex *index = fVolume->GetLastModifiedIndex()) index->Changed(this, oldMTime); } } // CheckPermissions status_t Node::CheckPermissions(int mode) const { int userPermissions = (fMode & S_IRWXU) >> 6; int groupPermissions = (fMode & S_IRWXG) >> 3; int otherPermissions = fMode & S_IRWXO; // get the permissions for this uid/gid int permissions = 0; uid_t uid = geteuid(); // user is root if (uid == 0) { // root has always read/write permission, but at least one of the // X bits must be set for execute permission permissions = userPermissions | groupPermissions | otherPermissions | ACCESS_R | ACCESS_W; // user is node owner } else if (uid == fUID) permissions = userPermissions; // user is in owning group else if (is_user_in_group(fGID)) permissions = groupPermissions; // user is one of the others else permissions = otherPermissions; // do the check return ((mode & ~permissions) ? B_NOT_ALLOWED : B_OK); } // CreateAttribute status_t Node::CreateAttribute(const char *name, Attribute **_attribute) { status_t error = (name && _attribute ? B_OK : B_BAD_VALUE); if (error == B_OK) { // create attribute Attribute *attribute = new(nothrow) Attribute(fVolume, NULL, name); if (attribute) { error = attribute->InitCheck(); if (error == B_OK) { // add attribute to node error = AddAttribute(attribute); if (error == B_OK) *_attribute = attribute; } if (error != B_OK) delete attribute; } else SET_ERROR(error, B_NO_MEMORY); } return error; } // DeleteAttribute status_t Node::DeleteAttribute(Attribute *attribute) { status_t error = RemoveAttribute(attribute); if (error == B_OK) delete attribute; return error; } // AddAttribute status_t Node::AddAttribute(Attribute *attribute) { status_t error = (attribute && !attribute->GetNode() ? B_OK : B_BAD_VALUE); if (error == B_OK) { error = GetVolume()->NodeAttributeAdded(GetID(), attribute); if (error == B_OK) { fAttributes.Insert(attribute); attribute->SetNode(this); MarkModified(B_STAT_MODIFICATION_TIME); } } return error; } // RemoveAttribute status_t Node::RemoveAttribute(Attribute *attribute) { status_t error = (attribute && attribute->GetNode() == this ? B_OK : B_BAD_VALUE); if (error == B_OK) { // move all iterators pointing to the attribute to the next attribute if (GetVolume()->IteratorLock()) { // set the iterators' current entry Attribute *nextAttr = fAttributes.GetNext(attribute); DoublyLinkedList<AttributeIterator> *iterators = attribute->GetAttributeIteratorList(); for (AttributeIterator *iterator = iterators->First(); iterator; iterator = iterators->GetNext(iterator)) { iterator->SetCurrent(nextAttr, true); } // Move the iterators from one list to the other, or just remove // them, if there is no next attribute. if (nextAttr) { DoublyLinkedList<AttributeIterator> *nextIterators = nextAttr->GetAttributeIteratorList(); nextIterators->MoveFrom(iterators); } else iterators->RemoveAll(); GetVolume()->IteratorUnlock(); } else error = B_ERROR; // remove the attribute if (error == B_OK) { error = GetVolume()->NodeAttributeRemoved(GetID(), attribute); if (error == B_OK) { fAttributes.Remove(attribute); attribute->SetNode(NULL); MarkModified(B_STAT_MODIFICATION_TIME); } } } return error; } // FindAttribute status_t Node::FindAttribute(const char *name, Attribute **_attribute) const { status_t error = (name && _attribute ? B_OK : B_BAD_VALUE); if (error == B_OK) { /* Attribute *attribute = NULL; while (GetNextAttribute(&attribute) == B_OK) { if (!strcmp(attribute->GetName(), name)) { *_attribute = attribute; return B_OK; } } error = B_ENTRY_NOT_FOUND; */ error = GetVolume()->FindNodeAttribute(GetID(), name, _attribute); } return error; } // GetPreviousAttribute status_t Node::GetPreviousAttribute(Attribute **attribute) const { status_t error = (attribute ? B_OK : B_BAD_VALUE); if (error == B_OK) { if (!*attribute) *attribute = fAttributes.Last(); else if ((*attribute)->GetNode() == this) *attribute = fAttributes.GetPrevious(*attribute); else error = B_BAD_VALUE; if (error == B_OK && !*attribute) error = B_ENTRY_NOT_FOUND; } return error; } // GetNextAttribute status_t Node::GetNextAttribute(Attribute **attribute) const { status_t error = (attribute ? B_OK : B_BAD_VALUE); if (error == B_OK) { if (!*attribute) *attribute = fAttributes.First(); else if ((*attribute)->GetNode() == this) *attribute = fAttributes.GetNext(*attribute); else error = B_BAD_VALUE; if (error == B_OK && !*attribute) error = B_ENTRY_NOT_FOUND; } return error; } // GetFirstReferrer Entry * Node::GetFirstReferrer() const { return fReferrers.First(); } // GetLastReferrer Entry * Node::GetLastReferrer() const { return fReferrers.Last(); } // GetPreviousReferrer Entry * Node::GetPreviousReferrer(Entry *entry) const { return (entry ? fReferrers.GetPrevious(entry) : NULL ); } // GetNextReferrer Entry * Node::GetNextReferrer(Entry *entry) const { return (entry ? fReferrers.GetNext(entry) : NULL ); } // GetAllocationInfo void Node::GetAllocationInfo(AllocationInfo &info) { Attribute *attribute = NULL; while (GetNextAttribute(&attribute) == B_OK) attribute->GetAllocationInfo(info); }
/* eslint-disable indent */ 'use strict'; //------------------------------// Third Party Resources \\----------------------------\\ const Discord = require('discord.js'); const { MessageButton, MessageActionRow } = require('discord-buttons'); require('dotenv').config(); //---------------------------------// Import Resources \\-------------------------------\\ const createChannel = require('../create-channel'); const getNickname = require('../get-nickname'); const clickHandler = require('./click-handler'); const ticketMethods = require('./methods'); const { io } = require('../dashboard/index'); const methods = require('../dashboard/methods'); //--------------------------------// Esoteric Resources \\-------------------------------\\ const GUILD = process.env.GUILD; // const CLOSED = process.env.CLOSED; // const SAVED = process.env.SAVED; const STUDENT_ROLE = process.env.STUDENT_ROLE; const QUEUE = process.env.QUEUE; const TA_ROLE = process.env.TA_ROLE; const DEV_ROLE = process.env.DEV_ROLE; const WAITING_ROOM = process.env.WAITING_ROOM; const TICKETS_LOG = process.env.TICKETS_LOG; const ticketsIDs = ['102', '201', '301', '401js', '401py', '401java', 'role']; let close = new MessageButton() .setLabel('Close') .setEmoji('🔒') .setStyle('red') .setID('close'); let claim = new MessageButton() .setLabel('Claim') .setEmoji('📌') .setStyle('green') .setID('claim'); let unclaim = new MessageButton() .setLabel('Unclaim') .setEmoji('📌') .setStyle('gray') .setID('unclaim'); // let deleteBtn = new MessageButton() // .setLabel('Delete') // .setEmoji('🗑️') // .setStyle('red') // .setID('delete'); // let save = new MessageButton() // .setLabel('Save') // .setEmoji('💾') // .setStyle('blurple') // .setID('save'); let row1 = new MessageActionRow() .addComponent(close) .addComponent(claim); let row2 = new MessageActionRow() .addComponent(close) .addComponent(unclaim); // let row3 = new MessageActionRow() // .addComponent(deleteBtn) // .addComponent(save); //---------------------------------// Bot Loading \\-------------------------------\\ module.exports = async (client) => { client.on('clickButton', async (button) => { await button.defer(); if (ticketsIDs.includes(button.id)) { await button.clicker.fetch(); const clickerRoles = button.clicker.member._roles; const nickname = await getNickname(client, button.clicker.user); const isDev = clickerRoles.includes(DEV_ROLE); if (clickerRoles.includes(TA_ROLE) && !isDev) { const embed = new Discord.MessageEmbed().setDescription(`TAs can't create tickets.`).setTitle('ASAC Tickets System').setColor('#ffc107'); console.log(nickname, 'tried to create ticket'); button.clicker.user.send(embed); return; } let check = await ticketMethods.checkTicket(button.clicker.user.id); if (check) { console.log(nickname, 'spam ticket'); const embed = new Discord.MessageEmbed().setDescription(`You already have an open ticket.`).setTitle('ASAC Tickets System').setColor('#ffc107'); button.clicker.user.send(embed); return; } let guild = await client.guilds.fetch(GUILD); const channel = await createChannel(guild, `${button.id}-${nickname}`, QUEUE, 'text', button.clicker.user.id); await ticketMethods.addTicket(button.clicker.user.id, channel.id, `${button.id}-${nickname}`); check = await ticketMethods.checkTicket2(button.clicker.user.id); if (check) { console.log(nickname, 'spam ticket'); const embed = new Discord.MessageEmbed().setDescription(`You already have an open ticket.`).setTitle('ASAC Tickets System').setColor('#ffc107'); button.clicker.user.send(embed); // ticketMethods.closeTicket(channel.id); ticketMethods.deleteTicket(channel.id); channel.delete(); return; } // if (!result) { // console.log('?'); // return; // } const embed = new Discord.MessageEmbed().setDescription(`Support will be with you shortly.`).setTitle('ASAC Tickets System').setFooter('by <NAME>').setColor('#b006c6'); const embedDesc = new Discord.MessageEmbed().setDescription(`<@${button.<EMAIL>}> Kindly add a description of your issue here`).setColor('#ffc107'); const embedMeeting = new Discord.MessageEmbed().setDescription(`<@${button.clicker.user.id}> Please note all TA are currently in a meeting, so expect to get help later than usual. We will get back to you as soon as possible.`).setColor('#ffc107'); const embedTime = new Discord.MessageEmbed().setDescription(`<@${button.<EMAIL>}> You raised a ticket out of our working hours. You may not get the support fast. `).setColor('#ffc107'); channel.send(`<@${button.<EMAIL>.id}> Welcome, How can we help you? Please write a description of your problem then do the following: - Go to "TEMPORARY CHANNELS" section. - Join ":hourglass:Waiting for Help:hourglass:". - Wait until one of the TAs move you to the breakout room. One of our Teacher Assistants will join you as soon as possible.`, { embed, component: row1 }); const time = new Date().getHours(); setTimeout(async () => { channel.send(embedDesc); if (time > 16 || time < 9) { channel.send(embedTime); } }, 1000); // setTimeout(() => { // channel.send(embedMeeting); // }, 5000); setTimeout(async () => { try { await guild.member(button.clicker.user.id).voice.setChannel(WAITING_ROOM); } catch (err) { const embed = new Discord.MessageEmbed().setDescription(`<@${button.clicker.user.id}> please join "⌛Waiting for Help⌛" channel`).setColor('#ffc107'); await channel.send(embed); } }, 3000); const embedLog = new Discord.MessageEmbed() .addFields( { inline: false, name: 'Description', value: `🔨 <@${button.clicker.user.id}> created a ticket 🔨` }, { inline: false, name: 'Ticket', value: `${button.id}-${nickname}` }, ) .setAuthor(button.clicker.user.username, button.clicker.user.avatarURL()) .setColor('#008CBA') .setFooter('ASAC Bot - tickets'); client.channels.fetch(TICKETS_LOG).then((channel) => { channel.send(embedLog); }); // emit to dashboard io.emit('createTicket' , {total : await methods.getTotals(client) , chart : await methods.getHours() ,dailyTicketsLevels : await methods.dailyTicketsLevels() ,dailyTicketsInfo : await methods.dailyTicketsInfo() , average : await methods.average() }); setTimeout(async () => { let noStudentMessages = true; try { const messages = await channel.messages.fetch({ limit: 100 }); messages.forEach(message => { if (message.member.roles.cache.has(STUDENT_ROLE)) { noStudentMessages = false; } }); } catch (err) { noStudentMessages = false; } // const isClaimed = await ticketMethods.isClaimed(button.channel.id); if (noStudentMessages) { await ticketMethods.closeTicket(channel.id); const embed = new Discord.MessageEmbed().setDescription(`<@${button.clicker.user.id}> ticket will close in 15 seconds because there is no description`).setColor('#f44336'); await channel.send(embed); setTimeout(async () => { try { channel.delete(); } catch (err) { console.log('already deleted', channel.name); } }, 15000); } }, (5000 * 60 * 1)); } // Create ticket end ------------------------------------------------------------------------------------------------ if (button.id === 'claim') { clickHandler(button, row2, button.id, client); } if (button.id === 'unclaim') { clickHandler(button, row1, button.id, client); } // if (button.id === 'delete') { // clickHandler(button, null, button.id, client); // } if (button.id === 'close') { await button.clicker.fetch(); const clickerRoles = button.clicker.member._roles; const isDev = clickerRoles.includes(DEV_ROLE); if (clickerRoles.includes(TA_ROLE) && !isDev) { let check = await ticketMethods.checkClaimer(button.clicker.user.id, button.channel.id); if (!check) { const embed = new Discord.MessageEmbed().setDescription(`You can't close the ticket, you are not the claimer of it. `).setTitle('ASAC Tickets System').setColor('#ffc107'); console.log(button.clicker.user.username, 'tried to close ticket'); button.clicker.user.send(embed); return; } } const oldEmbed = new Discord.MessageEmbed().setDescription(`Support will be with you shortly.`).setTitle('ASAC Tickets System').setFooter('by <NAME>').setColor('#b006c6'); const embed = new Discord.MessageEmbed().setDescription(`Ticket closed by <@${button.clicker.user.id}>`).setColor('#f44336'); button.message.edit(button.message.content, { oldEmbed, component: null }); button.channel.send(embed); setTimeout(async () => { await ticketMethods.closeTicket(button.channel.id); button.channel.delete(); const embedLog = new Discord.MessageEmbed() .addFields( { inline: false, name: 'Description', value: `🔒 <@${button.clicker.user.id}> closed a ticket 🔒` }, { inline: false, name: 'Ticket', value: button.channel.name }, ) .setAuthor(button.clicker.user.username, button.clicker.user.avatarURL()) .setColor('#008CBA') .setFooter('ASAC Bot - tickets'); client.channels.fetch('856858334439145492').then((channel) => { channel.send(embedLog); }); io.emit('claimUnclaimCloseTicket',{ dailyTicketsInfo : await methods.dailyTicketsInfo() ,users : await methods.getUsers(client) ,average : await methods.average()}); }, 3000); } }); }; //-----------------------------------------------------------------------------------------\\
<gh_stars>10-100 package io.jenkins.plugins.gcr.models; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import java.util.stream.Stream; @XmlRootElement(name = "report") public class JacocoCoverage extends XmlCoverage { public static final String TYPE_INSTRUCTION = "INSTRUCTION"; public static final String TYPE_BRANCH = "BRANCH"; public static final String TYPE_LINE = "LINE"; public static final String TYPE_COMPLEXITY = "COMPLEXITY"; // Fields @XmlElement(name = "counter") public List<JacocoCounter> counters; // Constructor public JacocoCoverage() { } // Coverage Interface public double getLineRate() { JacocoCounter counter = filterStreamFor(TYPE_LINE).findAny().get(); return rateForCounter(counter); } public double getBranchRate() { JacocoCounter counter = filterStreamFor(TYPE_BRANCH).findAny().get(); return rateForCounter(counter); } // Jacoco Utilities private Stream<JacocoCounter> filterStreamFor(String type) { return counters.stream().filter(obj -> obj.type.equals(type)); } private double rateForCounter(JacocoCounter counter) { return ((double)counter.covered / (double)counter.getTotal()); } // Other @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[ "); builder.append(String.format("lineRate=%f, branchRate=%f", getLineRate(), getBranchRate())); builder.append(" ]"); return builder.toString(); } }
<filename>jdbc/deployment/src/test/java/io/quarkiverse/config/jdbc/extensions/test/JdbcConfigCustomParamsTest.java package io.quarkiverse.config.jdbc.extensions.test; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.inject.Inject; import javax.sql.DataSource; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.test.QuarkusUnitTest; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.h2.H2DatabaseTestResource; @QuarkusTestResource(H2DatabaseTestResource.class) public class JdbcConfigCustomParamsTest { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap .create(JavaArchive.class).addAsResource("custom_application.properties", "application.properties")); @Inject DataSource dataSource; @Test @DisplayName("Reads a property from config DB") public void readGreetingFromDB() throws SQLException { Config c = ConfigProvider.getConfig(); String message = c.getValue("greeting.message", String.class); Assertions.assertEquals("hello from custom table", message); int result = updateConfigValue("greeting.message", "updated hello from custom table"); Assertions.assertTrue(result > 0); // assert we are getting the updated message because cache is disabled message = c.getValue("greeting.message", String.class); Assertions.assertEquals("updated hello from custom table", message); } private int updateConfigValue(String key, String value) throws SQLException { PreparedStatement updateStatement = dataSource.getConnection() .prepareStatement("UPDATE custom_config c SET c.b = ? WHERE c.a = ?"); updateStatement.setString(1, value); updateStatement.setString(2, key); return updateStatement.executeUpdate(); } }
<filename>apps/faultmanagement/fmgui/src/main/java/org/onosproject/faultmanagement/alarms/gui/AlarmTopovMessageHandler.java<gh_stars>1-10 /* * Copyright 2015-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.faultmanagement.alarms.gui; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableSet; import org.onlab.osgi.ServiceDirectory; import org.onosproject.incubator.net.faultmanagement.alarm.Alarm; import org.onosproject.incubator.net.faultmanagement.alarm.AlarmService; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceService; import org.onosproject.ui.RequestHandler; import org.onosproject.ui.UiConnection; import org.onosproject.ui.UiMessageHandler; import org.onosproject.ui.topo.DeviceHighlight; import org.onosproject.ui.topo.Highlights; import org.onosproject.ui.topo.NodeBadge; import org.onosproject.ui.topo.NodeBadge.Status; import org.onosproject.ui.topo.TopoJson; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Set; /** * FaultManagement UI Topology-Overlay message handler. */ public class AlarmTopovMessageHandler extends UiMessageHandler { private static final String ALARM_TOPOV_DISPLAY_START = "alarmTopovDisplayStart"; private static final String ALARM_TOPOV_DISPLAY_STOP = "alarmTopovDisplayStop"; private static final int DELAY_MS = 500; private final Logger log = LoggerFactory.getLogger(getClass()); protected AlarmService alarmService; private DeviceService deviceService; private AlarmMonitor alarmMonitor; // ======================================================================= @Override public void init(UiConnection connection, ServiceDirectory directory) { super.init(connection, directory); deviceService = directory.get(DeviceService.class); alarmService = directory.get(AlarmService.class); alarmMonitor = new AlarmMonitor(this); } @Override protected Collection<RequestHandler> createRequestHandlers() { return ImmutableSet.of( new DisplayStartHandler(), new DisplayStopHandler() ); } // === ------------------------- // === Handler classes private final class DisplayStartHandler extends RequestHandler { public DisplayStartHandler() { super(ALARM_TOPOV_DISPLAY_START); } @Override public void process(ObjectNode payload) { log.debug("Start Display"); sendDelayedAlarmHighlights(); alarmMonitor.startMonitorig(); } } private final class DisplayStopHandler extends RequestHandler { public DisplayStopHandler() { super(ALARM_TOPOV_DISPLAY_STOP); } @Override public void process(ObjectNode payload) { log.debug("Stop Display"); alarmMonitor.stopMonitoring(); clearHighlights(); } } /** * Sends the highlights with a delay to the client side on the browser. */ protected void sendDelayedAlarmHighlights() { createAndSendHighlights(true); } /** * Sends the highlights to the client side on the browser. */ protected void sendAlarmHighlights() { createAndSendHighlights(false); } private void createAndSendHighlights(boolean toDelay) { Highlights highlights = new Highlights(); createBadges(highlights); if (toDelay) { highlights.delay(DELAY_MS); } sendHighlights(highlights); } private void sendHighlights(Highlights highlights) { sendMessage(TopoJson.highlightsMessage(highlights)); } private void createBadges(Highlights highlights) { deviceService.getAvailableDevices().forEach(d -> { Set<Alarm> alarmsOnDevice = alarmService.getAlarms(d.id()); int alarmSize = alarmsOnDevice.size(); log.debug("{} Alarms on device {}", alarmSize, d.id()); if (alarmSize > 0) { addDeviceBadge(highlights, d.id(), alarmSize); } }); } private void clearHighlights() { sendHighlights(new Highlights()); } private void addDeviceBadge(Highlights h, DeviceId devId, int n) { DeviceHighlight dh = new DeviceHighlight(devId.toString()); dh.setBadge(createBadge(n)); h.add(dh); } private NodeBadge createBadge(int n) { Status status = n > 0 ? Status.ERROR : Status.INFO; String noun = n > 0 ? "(Alarmed)" : "(Normal)"; String msg = "Alarms: " + n + " " + noun; return NodeBadge.number(status, n, msg); } }
<gh_stars>0 let asignatura; let tipoinstitucion; let localidad; let nombreinstitucion; $(document).ready(function() { $('body').scrollTop(0); $('input:text[name="nombreins"]').alphanum({ allowNumeric: false, allow: '()' }); $('select[name="genero"]').on('change', function() { $('.genero_error').addClass('hidden'); }); $('input:radio[name="asignatura"]').on('change', function() { asignatura = $(this).val(); $('.asignatura_error').addClass('hidden'); }); $('select[name="tipoins"]').on('change', function() { tipoinstitucion = $(this).val(); $('.tipoins_error').addClass('hidden'); }); $('select[name="localidad"]').on('change', function() { localidad = $(this).val(); $('.localidad_error').addClass('hidden'); }); $('input:text[name="nombreins"]').keyup(function() { nombreinstitucion = $(this).val(); if (nombreinstitucion === '') { $('.nombreins_error').html('*Por favor indique el nombre de la institución.'); $('.nombreins_error').removeClass('hidden'); $('.enviar_btn').show(); } else if (nombreinstitucion.length < 3) { $('.nombreins_error').html('*Nombre de la institución demasiado corto.'); $('.nombreins_error').removeClass('hidden'); $('.enviar_btn').show(); } else { $('.nombreins_error').addClass('hidden'); } }); $('.siguiente_btn').on('click', function() { $('.siguiente_btn').addClass('hidden'); localStorage.removeItem('Género'); localStorage.removeItem('Asignatura'); localStorage.removeItem('Tipo_institucion'); localStorage.removeItem('Localidad'); localStorage.removeItem('Nombre_institucion'); genero = $('select[name="genero"]').val(); asignatura_ratio = $('input:radio[name="asignatura"]'); tipoinstitucion = $('select[name="tipoins"]').val(); localidad = $('select[name="localidad"]').val(); nombreinstitucion = $('input:text[name="nombreins"]').val(); nombreinstitucion = nombreinstitucion.toUpperCase(); if(genero == 0) { $('.genero_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } if( !(asignatura_ratio[0].checked || asignatura_ratio[1].checked) ) { $('.asignatura_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } if(tipoinstitucion == 0) { $('.tipoins_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } if(localidad == 0) { $('.localidad_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } if(nombreinstitucion == '' || nombreinstitucion == null) { $('.nombreins_error').html('*Por favor indique el nombre de la institución.'); $('.nombreins_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } if(nombreinstitucion.length <= 8) { $('.nombreins_error').html('*Nombre de la institución demasiado corto.'); $('.nombreins_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } if(genero == 0) { $('.genero_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } else if( !(asignatura_ratio[0].checked || asignatura_ratio[1].checked) ) { $('.asignatura_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } else if(tipoinstitucion == 0) { $('.tipoins_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } else if(localidad == 0) { $('.localidad_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } else if(nombreinstitucion == '' || nombreinstitucion == null) { $('.nombreins_error').html('*Por favor indique el nombre de la institución.'); $('.nombreins_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } else if(nombreinstitucion.length <= 3) { $('.nombreins_error').html('*Nombre de la institución demasiado corto.'); $('.nombreins_error').removeClass('hidden'); $('.siguiente_btn').removeClass('hidden'); } else { localStorage.setItem('Género', genero); localStorage.setItem('Asignatura', asignatura); localStorage.setItem('Tipo_institucion', tipoinstitucion); localStorage.setItem('Localidad', localidad); localStorage.setItem('Nombre_institucion', nombreinstitucion); window.location = '/years'; } }); });
#!/usr/bin/env bash #github-action genshdoc echo -ne " ------------------------------------------------------------------------- █████╗ ██████╗ ██████╗██╗ ██╗████████╗██╗████████╗██╗ ██╗███████╗ ██╔══██╗██╔══██╗██╔════╝██║ ██║╚══██╔══╝██║╚══██╔══╝██║ ██║██╔════╝ ███████║██████╔╝██║ ███████║ ██║ ██║ ██║ ██║ ██║███████╗ ██╔══██║██╔══██╗██║ ██╔══██║ ██║ ██║ ██║ ██║ ██║╚════██║ ██║ ██║██║ ██║╚██████╗██║ ██║ ██║ ██║ ██║ ╚██████╔╝███████║ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ------------------------------------------------------------------------- Automated Arch Linux Installer SCRIPTHOME: ArchTitus ------------------------------------------------------------------------- " source $HOME/ArchTitus/configs/setup.conf echo -ne " ------------------------------------------------------------------------- Network Setup ------------------------------------------------------------------------- " pacman -S --noconfirm --needed networkmanager dhclient systemctl enable --now NetworkManager echo -ne " ------------------------------------------------------------------------- Setting up mirrors for optimal download ------------------------------------------------------------------------- " pacman -S --noconfirm --needed pacman-contrib curl pacman -S --noconfirm --needed reflector rsync grub arch-install-scripts git cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak nc=$(grep -c ^processor /proc/cpuinfo) echo -ne " ------------------------------------------------------------------------- You have " $nc" cores. And changing the makeflags for "$nc" cores. Aswell as changing the compression settings. ------------------------------------------------------------------------- " TOTAL_MEM=$(cat /proc/meminfo | grep -i 'memtotal' | grep -o '[[:digit:]]*') if [[ $TOTAL_MEM -gt 8000000 ]]; then sed -i "s/#MAKEFLAGS=\"-j2\"/MAKEFLAGS=\"-j$nc\"/g" /etc/makepkg.conf sed -i "s/COMPRESSXZ=(xz -c -z -)/COMPRESSXZ=(xz -c -T $nc -z -)/g" /etc/makepkg.conf fi echo -ne " ------------------------------------------------------------------------- Setup Language to US and set locale ------------------------------------------------------------------------- " sed -i 's/^#en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen locale-gen timedatectl --no-ask-password set-timezone ${TIMEZONE} timedatectl --no-ask-password set-ntp 1 localectl --no-ask-password set-locale LANG="en_US.UTF-8" LC_TIME="en_US.UTF-8" ln -s /usr/share/zoneinfo/${TIMEZONE} /etc/localtime # Set keymaps localectl --no-ask-password set-keymap ${KEYMAP} # Add sudo no password rights sed -i 's/^# %wheel ALL=(ALL) NOPASSWD: ALL/%wheel ALL=(ALL) NOPASSWD: ALL/' /etc/sudoers sed -i 's/^# %wheel ALL=(ALL:ALL) NOPASSWD: ALL/%wheel ALL=(ALL:ALL) NOPASSWD: ALL/' /etc/sudoers #Add parallel downloading sed -i 's/^#ParallelDownloads/ParallelDownloads/' /etc/pacman.conf #Enable multilib sed -i "/\[multilib\]/,/Include/"'s/^#//' /etc/pacman.conf pacman -Sy --noconfirm --needed # determine processor type and install microcode proc_type=$(lscpu) if grep -E "GenuineIntel" <<< ${proc_type}; then echo "Installing Intel microcode" pacman -S --noconfirm --needed intel-ucode proc_ucode=intel-ucode.img elif grep -E "AuthenticAMD" <<< ${proc_type}; then echo "Installing AMD microcode" pacman -S --noconfirm --needed amd-ucode proc_ucode=amd-ucode.img fi echo -ne " ------------------------------------------------------------------------- Installing Graphics Drivers ------------------------------------------------------------------------- " # Graphics Drivers find and install gpu_type=$(lspci) if grep -E "NVIDIA|GeForce" <<< ${gpu_type}; then pacman -S --noconfirm --needed nvidia nvidia-utils nvidia-xconfig elif lspci | grep 'VGA' | grep -E "Radeon|AMD"; then pacman -S --noconfirm --needed xf86-video-amdgpu elif grep -E "Integrated Graphics Controller" <<< ${gpu_type}; then pacman -S --noconfirm --needed libva-intel-driver libvdpau-va-gl lib32-vulkan-intel vulkan-intel libva-intel-driver libva-utils lib32-mesa elif grep -E "Intel Corporation UHD" <<< ${gpu_type}; then pacman -S --needed --noconfirm libva-intel-driver libvdpau-va-gl lib32-vulkan-intel vulkan-intel libva-intel-driver libva-utils lib32-mesa fi #SETUP IS WRONG THIS IS RUN if ! source $HOME/ArchTitus/configs/setup.conf; then # Loop through user input until the user gives a valid username while true do read -p "Please enter username:" username # username regex per response here https://unix.stackexchange.com/questions/157426/what-is-the-regex-to-validate-linux-users # lowercase the username to test regex if [[ "${username,,}" =~ ^[a-z_]([a-z0-9_-]{0,31}|[a-z0-9_-]{0,30}\$)$ ]] then break fi echo "Incorrect username." done # convert name to lowercase before saving to setup.conf echo "username=${username,,}" >> ${HOME}/ArchTitus/configs/setup.conf #Set Password read -p "Please enter password:" password echo "password=${password,,}" >> ${HOME}/ArchTitus/configs/setup.conf # Loop through user input until the user gives a valid hostname, but allow the user to force save while true do read -p "Please name your machine:" name_of_machine # hostname regex (!!couldn't find spec for computer name!!) if [[ "${name_of_machine,,}" =~ ^[a-z][a-z0-9_.-]{0,62}[a-z0-9]$ ]] then break fi # if validation fails allow the user to force saving of the hostname read -p "Hostname doesn't seem correct. Do you still want to save it? (y/n)" force if [[ "${force,,}" = "y" ]] then break fi done echo "NAME_OF_MACHINE=${name_of_machine,,}" >> ${HOME}/ArchTitus/configs/setup.conf fi echo -ne " ------------------------------------------------------------------------- Adding User ------------------------------------------------------------------------- " echo -ne " ------------------------------------------------------------------------- Installing Base System ------------------------------------------------------------------------- " # sed $INSTALL_TYPE is using install type to check for MINIMAL installation, if it's true, stop # stop the script and move on, not installing any more packages below that line if [[ ! $DESKTOP_ENV == server ]]; then sed -n '/'$INSTALL_TYPE'/q;p' $HOME/ArchTitus/pkg-files/pacman-pkgs.txt | while read line do if [[ ${line} == '--END OF MINIMAL INSTALL--' ]]; then # If selected installation type is FULL, skip the --END OF THE MINIMAL INSTALLATION-- line continue fi echo "INSTALLING: ${line}" sudo pacman -S --noconfirm --needed ${line} done fi echo -ne " ------------------------------------------------------------------------- Installing Microcode ------------------------------------------------------------------------- " if [ $(whoami) = "root" ]; then groupadd libvirt useradd -m -G wheel,libvirt -s /bin/bash $USERNAME echo "$USERNAME created, home directory created, added to wheel and libvirt group, default shell set to /bin/bash" # use chpasswd to enter $USERNAME:$password echo "$USERNAME:$PASSWORD" | chpasswd echo "$USERNAME password set" cp -R $HOME/ArchTitus /home/$USERNAME/ chown -R $USERNAME: /home/$USERNAME/ArchTitus echo "ArchTitus copied to home directory" # enter $NAME_OF_MACHINE to /etc/hostname echo $NAME_OF_MACHINE > /etc/hostname else echo "You are already a user proceed with aur installs" fi if [[ ${FS} == "luks" ]]; then # Making sure to edit mkinitcpio conf if luks is selected # add encrypt in mkinitcpio.conf before filesystems in hooks sed -i 's/filesystems/encrypt filesystems/g' /etc/mkinitcpio.conf # making mkinitcpio with linux kernel mkinitcpio -p linux fi echo -ne " ------------------------------------------------------------------------- SYSTEM READY FOR 2-user.sh ------------------------------------------------------------------------- "
<gh_stars>10-100 package io.opensphere.wps.ui.detail.provider; import java.util.function.Supplier; import javax.inject.Named; import org.apache.commons.lang3.StringUtils; import com.google.inject.Singleton; import io.opensphere.core.Toolbox; import io.opensphere.core.util.javafx.input.ValidatedIdentifiedControl; import javafx.scene.control.CheckBox; import jidefx.scene.control.validation.ValidationGroup; import net.opengis.wps._100.InputDescriptionType; /** * A boolean input provider in which a checkbox is generated. */ @Singleton @Named("boolean") public class WpsBooleanInputProvider implements WpsInputControlProvider { /** * {@inheritDoc} * * @see io.opensphere.wps.ui.detail.provider.WpsInputControlProvider#create(io.opensphere.core.Toolbox, * java.lang.String, net.opengis.wps._100.InputDescriptionType, * java.lang.String, ValidationGroup) */ @Override public ValidatedIdentifiedControl<?> create(Toolbox pToolbox, String pTitle, InputDescriptionType pInputDescription, String pDefaultValue, ValidationGroup pValidationGroup) { ValidatedIdentifiedControl<?> returnValue; CheckBox checkBox = new CheckBox(); if (StringUtils.isNotBlank(pDefaultValue)) { checkBox.setSelected(Boolean.parseBoolean(pDefaultValue)); } Supplier<String> resultAccessorFunction = () -> Boolean.toString(checkBox.isSelected()); returnValue = new ValidatedIdentifiedControl<>(pInputDescription.getIdentifier().getValue(), pTitle, resultAccessorFunction, checkBox); returnValue.setValidationGroup(pValidationGroup); return returnValue; } }
<reponame>thatpub/pub var App = function ( _ ) { 'use strict'; var regMini = / ?mini ?/g, months = { '01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May', '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec' }; function filterOutliers ( someArray ) { /* Thanks to jpau for the outlier function * http://stackoverflow.com/a/20811670/2780033 */ var values = someArray.concat(); values.sort( function ( a, b ) { return a - b; }); var q1 = values[Math.floor((values.length / 4))]; var q3 = values[Math.ceil((values.length * (3 / 4)))]; var iqr = q3 - q1; var maxValue = q3 + iqr*1.5; var filteredValues = values.filter( function ( x ) { return (x > maxValue); }); return filteredValues; } return { placeContent: document.cookie.placeContent || '', placeMeta: document.cookie.placeMeta || '', traveling: false, regMini: regMini, term: '' }; }
package sdg.equations; import sdg.Equation; /** * Represents the SDE: * [2X(t)/(1+t) + (1+t)^2] dt + (1+t)^2 dW(t) */ public class Linear3 extends Equation { public Linear3(double x0, double t0, double tN) { super(x0, t0, tN); } @Override public double drift(double X, double t) { return 2 * X / (1 + t) + Math.pow(1 + t, 2); } @Override public double driftPrime(double X, double t) { return 2 / (1 + t); } @Override public double diffusion(double X, double t) { return Math.pow(1 + t, 2); } @Override public double diffusionPrime(double X, double t) { return 0; } @Override public double diffusionDoublePrime(double X, double t) { return 0; } @Override public double exactSolution(double t, double totalNoise) { return Math.pow(1 + t, 3) + Math.pow(1 + t, 2) * totalNoise; } }
# Flask class for initializing the app. # render_template for loading templates from # templates/ folder. from flask import Flask, render_template # Importing blueprints from .frontended import frontended from .servered import servered # Initializing the app app = Flask(__name__) # Configuring the app from config.py app.config.from_object("config") # Blueprints have to be registered, we do it # for both of them app.register_blueprint(frontended) app.register_blueprint(servered) # To handle 404 Not Found Error @app.errorhandler(404) def not_found(error): return render_template("errors/404.html"), 404 # To handle 405 Method Not Allowed Error @app.errorhandler(405) def method_not_allowed(error): return render_template("errors/405.html"), 405
#!/bin/bash -e # # Deploys Infrastructure for samples # # Prompt User for Input echo "Enter resource group name:" read rg_name echo "Enter key vault name:" read kv_name echo "Enter location (westus, westus2, eastus, ...):" read location # Get Tenant ID tenant_id=$(az account show --query tenantId -o tsv) # Create Resource Group echo "Creating Resource Group: $rg_name" az group create --name $rg_name --location $location # Create KeyVault and save keyvault_url echo "Creating Key Vault: $kv_name" keyvault_url=$(az keyvault create --name $kv_name --resource-group $rg_name | grep "vaultUri" | cut -d '"' -f 4) # Create Service Principal sp_name=sample-service-principal echo "Creating Service Principal: $sp_name" client_secret=$(az ad sp create-for-rbac --name $sp_name --skip-assignment --query password -o tsv) client_id=$(az ad sp show --id http://$sp_name --query appId --output tsv) object_id=$(az ad sp show --id http://$sp_name --query objectId --output tsv) # Assign Key Vault Policy # The service principal has the follow permissions to keys: # get, list, update, create, delete, decrypt, encrypt, unwrapKey, wrapKey az keyvault set-policy --name $kv_name -g $rg_name --object-id $object_id --key-permissions get list update create delete decrypt encrypt unwrapKey wrapKey # Create Asymetric Key key_name=sample-key az keyvault key create -n $key_name -p software --vault-name $kv_name --size 2048 key_version=$(az keyvault key list-versions --name sample-key --vault-name $kv_name | grep "kid" | cut -d '/' -f 6 | cut -d '"' -f 1) echo "export AZURE_TENANT_ID=$tenant_id" echo "export AZURE_CLIENT_ID=$client_id" echo "export AZURE_CLIENT_SECRET=$client_secret" echo "export VAULT_URI=$keyvault_url" echo "export KEY_NAME=$key_name" echo "export KEY_VERSION=$key_version"
package ch.uzh.ifi.seal.soprafs20.service; import ch.uzh.ifi.seal.soprafs20.constant.GameStatus; import ch.uzh.ifi.seal.soprafs20.constant.PlayerStatus; import ch.uzh.ifi.seal.soprafs20.entity.*; import ch.uzh.ifi.seal.soprafs20.exceptions.ConflictException; import ch.uzh.ifi.seal.soprafs20.exceptions.NotFoundException; import ch.uzh.ifi.seal.soprafs20.exceptions.UnauthorizedException; import ch.uzh.ifi.seal.soprafs20.repository.GameRepository; import ch.uzh.ifi.seal.soprafs20.repository.TileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; @Service @Transactional public class GameService { private final GameRepository gameRepository; private final TileRepository tileRepository; @Autowired public GameService(@Qualifier("gameRepository")GameRepository gameRepository, @Qualifier("tileRepository")TileRepository tileRepository) { this.gameRepository = gameRepository; this.tileRepository = tileRepository; } public Game getGame(long gameId) { // fetch game from db Game game; Optional<Game> foundGame = gameRepository.findByIdIs(gameId); // check if game exists if (foundGame.isEmpty()) { throw new NotFoundException("The game with the id " + gameId + " is not existing."); } else { game = foundGame.get(); } return game; } public List<Game> getGames() { return gameRepository.findAll(); } public List<Player> getPlayers(long gameId) { // fetch game from db Game game = getGame(gameId); return game.getPlayers(); } public List<Word> getWords(long gameId) { Game game; Optional<Game> foundGame = gameRepository.findByIdIs(gameId); // check if game is present if (foundGame.isPresent()) { game = foundGame.get(); } else { throw new NotFoundException("The game with the id " + gameId + " could not be found"); } return game.getWords(); } public void saveGame(Game game) { gameRepository.save(game); gameRepository.flush(); } public void addChat(Chat chat) { // add player to the user Game game = chat.getGame(); game.setChat(chat); // save change saveGame(game); } public Game createGame(Game game, Player owner) { // check if owner is already hosting another game if (owner.getUser().getGame() != null) { throw new ConflictException("The user with the id " + owner.getUser().getId() + " is hosting another game."); } game.setOwner(owner.getUser()); game.setStatus(GameStatus.WAITING); // initialise list game.initGame(); createGrid(game); // add stones to the game addAllStones(game); // add player game.addPlayer(owner); game.setCurrentPlayerId(owner.getId()); // save changes game = gameRepository.save(game); gameRepository.flush(); return game; } public Game joinGame(long gameId, Player player, String password) { // fetch game from db Game game = getGame(gameId); // check if game is waiting if (game.getStatus() != GameStatus.WAITING) { throw new ConflictException("The game is already running. You cannot join a running game."); } // check that only 4 players can play the game if (game.getPlayers().size() == 4) { throw new ConflictException("The game has already 4 players. You cannot join a full game."); } // check if password is correct if (!(game.getPassword() == null || password == null)){ if (!(game.getPassword().equals(password))){ throw new ConflictException("Wrong password. Therefore the player could not join the game"); } } else { throw new ConflictException("There was a problem with the password: password <PASSWORD>'t be null"); } // add player to the game game.addPlayer(player); // save the game game = gameRepository.save(game); gameRepository.flush(); return game; } public void startGame(Game game, String token) { // check if user is authorized to start the game if (!game.getOwner().getToken().equals(token)) { throw new UnauthorizedException("The user is not authorized to start the game"); } // fetch players from the game List<Player> players = game.getPlayers(); User owner = game.getOwner(); Player ownerplayer = owner.getPlayer(); // check if all players are ready for (Player player : players) { if (player.getStatus() == PlayerStatus.NOT_READY && player != ownerplayer) { throw new ConflictException("Not all players are ready to start."); } } // check if the game can be started if (game.getStatus() == GameStatus.RUNNING) { throw new ConflictException("The game is already running."); } else if (game.getStatus() == GameStatus.ENDED) { throw new ConflictException("The game has already ended."); } // set flag to running game.setStatus(GameStatus.RUNNING); // save change saveGame(game); } public Game leaveGame(Game game, Player player, String token) { // check if player is the lobbyLeader if (game.getStatus() != GameStatus.ENDED && player.getUser().getId().equals(game.getOwner().getId()) && game.getPlayers().size() > 1) { throw new UnauthorizedException("The game owner cannot leave the game. Choose to end the game."); } // check if the user is authorized to leave the game if (!player.getUser().getToken().equals(token) && !game.getOwner().getToken().equals(token)) { throw new ConflictException("The user is not authorized to leave this game"); } // remove the player game.removePlayer(player); // save changes game = gameRepository.save(game); gameRepository.flush(); return game; } public void endGame(long gameId) { // fetch game from db Game game = getGame(gameId); // delete grid so that global tiles wont be deleted game.setGrid(null); // delete the game gameRepository.delete(game); gameRepository.flush(); } public void createGrid(Game game){ List<Tile> grid = new ArrayList<>(); String error = "Grid cannot be initialized since the tiles couldn't be found"; Integer[] doubles = {3, 11,16,28,32,36,38,42,45,48,52,56,59,64,70,84,92,96,98,102,108}; Integer[] triples= {0,7,14,20,24,76,80,84,88,105}; Integer[] doubleWord = {16,28,32,42,48,56,64,70}; Integer[] tripleWord = {0,7,14,105}; //create half of board, then flip and append testTest for(int i =0; i < 112; i++){ //check if double field if(Arrays.asList(doubles).contains(i)){ //check if word or letter Optional<Tile> foundTile; if(Arrays.asList(doubleWord).contains(i)){ foundTile = tileRepository.findByMultiplierAndStoneSymbolAndMultivariant(2, null, "w"); } else { foundTile = tileRepository.findByMultiplierAndStoneSymbolAndMultivariant(2, null, "l"); } // check if tile exists and add to grid if yes if (foundTile.isEmpty()) { throw new NotFoundException(error); } else { grid.add(foundTile.get()); } } //check if triple tile else if(Arrays.asList(triples).contains(i)){ Optional<Tile> foundTile; //check if word or letter if(Arrays.asList(tripleWord).contains(i)){ foundTile = tileRepository.findByMultiplierAndStoneSymbolAndMultivariant(3, null, "w"); } else { foundTile = tileRepository.findByMultiplierAndStoneSymbolAndMultivariant(3, null, "l"); } // check if tile exists and add to grid if yes if (foundTile.isEmpty()) { throw new NotFoundException(error); } else { grid.add(foundTile.get()); } } //else its single tile else { Optional<Tile> foundTile = tileRepository.findByMultiplierAndStoneSymbolAndMultivariant(1,null,"l"); // check if tile exists if (foundTile.isEmpty()) { throw new NotFoundException(error); } else { grid.add(foundTile.get()); } } } //make a clone and reverse it List<Tile> clone = new ArrayList<>(grid); Collections.reverse(clone); //add the middle star Optional<Tile> foundTile = tileRepository.findByMultiplierAndStoneSymbolAndMultivariant(2,null,"w"); // check if tile exists if (foundTile.isEmpty()) { throw new NotFoundException(error); } else { grid.add(foundTile.get()); } // fill second half of the grid grid.addAll(clone); // add grid to game game.setGrid(grid); } private void addAllStones(Game game) { game.addStone(new Stone("q", 10)); game.addStone(new Stone("j", 8)); game.addStone(new Stone("k", 5)); game.addStone(new Stone("x", 8)); game.addStone(new Stone("z", 10)); for (int i = 0; i < 3; i++) { game.addStone(new Stone("b", 3)); game.addStone(new Stone("c", 3)); game.addStone(new Stone("f", 4)); game.addStone(new Stone("h", 4)); game.addStone(new Stone("p", 3)); game.addStone(new Stone("v", 4)); game.addStone(new Stone("w", 4)); game.addStone(new Stone("y", 4)); game.addStone(new Stone("m", 3)); } for (int i = 0; i < 4; i++) { game.addStone(new Stone("g", 2)); } for (int i = 0; i < 5; i++) { game.addStone(new Stone("d", 2)); game.addStone(new Stone("l", 1)); game.addStone(new Stone("s", 1)); game.addStone(new Stone("u", 1)); } for (int i = 0; i < 7; i++) { game.addStone(new Stone("n", 1)); game.addStone(new Stone("r", 1)); game.addStone(new Stone("t", 1)); } for (int i = 0; i < 9; i++) { game.addStone(new Stone("o", 1)); } for (int i = 0; i < 10; i++) { game.addStone(new Stone("a", 1)); game.addStone(new Stone("i", 1)); } for (int i = 0; i < 13; i++) { game.addStone(new Stone("e", 1)); } } public void checkIfGameEnded(Game game) { // check if bag of game is empty if (!game.getBag().isEmpty()) { return; } // fetch the players from the game List<Player> players = game.getPlayers(); // check if a bag of a player is empty -> if a bag of one player is empty, the game ends for (Player player : players) { if (player.getBag().isEmpty()) { game.setStatus(GameStatus.ENDED); updateScore(game); break; } } } private void updateScore(Game game) { List<Player> players = game.getPlayers(); //determine winner(s) List<Player> winners = new ArrayList<>(); winners.add(players.get(0)); for(Player player1: players){ for(Player player2 : players){ if(player1.getScore() > winners.get(0).getScore()){ winners.clear(); winners.add(player1); } if(player2.getScore() == player1.getScore() && player1 != player2){ winners.add(player2); } } } //if highest score is 0, doesnt count as game if(winners.get(0).getScore() == 0){ return; } for(Player winner : winners){ winner.getUser().setWonGames(winner.getUser().getWonGames() + 1); } // update score for every player/user for (Player player : players) { User user = player.getUser(); user.setPlayedGames(user.getPlayedGames() + 1); user.setOverallScore(user.getOverallScore() + player.getScore()); //manage userHistory manageHistory(player,user); //manage userHistoryTime manageHistoryTime(user); } } protected void manageHistory(Player player, User user){ int length; String history = user.getHistory(); if (history.isEmpty()){ length = 0; } else { String[] words = history.split("\\s+"); length = words.length; } if (length < 10){ user.setHistory(user.getHistory() + player.getScore() + " "); } else { int index = history.indexOf(' ') + 1; user.setHistory(user.getHistory().substring(index) + player.getScore() + " "); } } protected void manageHistoryTime(User user){ int length; String historyTime = user.getHistoryTime(); if (historyTime.isEmpty()){ length = 0; } else { String[] words = historyTime.split("\\s+"); length = words.length; } if (length < 10){ user.setHistoryTime(user.getHistoryTime() + System.currentTimeMillis() + " "); } else { int index = historyTime.indexOf(' ') + 1; user.setHistoryTime(user.getHistoryTime().substring(index) + System.currentTimeMillis() + " "); } } }
#!/bin/bash sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config sed -i 's/SELINUX=permissive/SELINUX=disabled/' /etc/selinux/config reboot
<filename>lightconvpoint/knn/random_sampling.py import torch import math from lightconvpoint.knn import knn import importlib knn_c_func_spec = importlib.util.find_spec('lightconvpoint.knn_c_func') if knn_c_func_spec is not None: knn_c_func = importlib.util.module_from_spec(knn_c_func_spec) knn_c_func_spec.loader.exec_module(knn_c_func) def random_pick_knn(points: torch.Tensor, nqueries: int, K: int): if knn_c_func_spec is not None: return knn_c_func.random_pick_knn(points, nqueries, K) bs, dim, nx = points.shape indices_queries = [] points_queries = [] for b_id in range(bs): indices_queries_ = torch.randperm(nx)[:nqueries] indices_queries.append(indices_queries_) x = points[b_id].transpose(0,1) points_queries.append(x[indices_queries_]) indices_queries = torch.stack(indices_queries, dim=0) points_queries = torch.stack(points_queries, dim=0) points_queries = points_queries.transpose(1,2) indices_knn = knn(points, points_queries, K) return indices_queries, indices_knn, points_queries
import PageContainer from './PageContainer' export default PageContainer
import { Module } from '@nestjs/common'; import { GlobalPipes } from './pipes'; import { GlobalInterceptors } from './interceptors'; import { GlobalProvider } from './providers'; @Module({ imports: [], providers: [...GlobalPipes, ...GlobalInterceptors, ...GlobalProvider], exports: [...GlobalProvider], }) export class CommonModule {}
parallel --jobs 64 < ./results/exp_threads/run-2/sea_cp_5n_64t_6d_1000f_617m_5i/jobs/jobs_n2.txt
package com.java.study.zuo.vedio.basic.chapter3; import java.util.HashMap; import java.util.Map; /** * <Description> * * @author hushiye * @since 2020-08-22 15:09 */ public class RandomPool { public static class RandomPoolObject<T> { private Map<Integer, T> indexAndEntityMap = new HashMap<>(); private Map<T, Integer> entityAndIndexMap = new HashMap<>(); private int size = 0; public void add(T value) { if (!entityAndIndexMap.containsKey(value)) { entityAndIndexMap.put(value, size); indexAndEntityMap.put(size, value); size++; } } public void delete(T value) { if (entityAndIndexMap.containsKey(value)) { Integer oldIndex = entityAndIndexMap.get(value); T lastEntity = indexAndEntityMap.get(--size); entityAndIndexMap.put(lastEntity, oldIndex); indexAndEntityMap.put(oldIndex, lastEntity); entityAndIndexMap.remove(value); indexAndEntityMap.remove(size); } } public T getRandom() { int randomIndex = (int) (Math.random() * this.size); return indexAndEntityMap.get(randomIndex); } } public static void main(String[] args) { RandomPoolObject<String> pool = new RandomPoolObject<String>(); pool.add("zuo"); pool.add("cheng"); pool.add("yun"); pool.delete("zuo"); System.out.println(pool.getRandom()); System.out.println(pool.getRandom()); System.out.println(pool.getRandom()); System.out.println(pool.getRandom()); System.out.println(pool.getRandom()); System.out.println(pool.getRandom()); } }
import {Namespace, Project, ProjectDetail} from "../models/gitlab/gitlab"; const SAMPLE_PROJECT = { id: 0, description: "Sample Project", name: "sample", name_with_namespace: "test/sample", path: "sample", path_with_namespace: "test/sample", created_at: "", default_branch: "main", forks_count: 0, star_count: 0, last_activity_at: "", namespace: { id: 0, name: "test", path: "test", kind: "test", full_path: "test", parent_id: 0, }, }; export const MOCK_GIT_NAMESPACES = [] as Namespace[]; export const MOCK_GIT_RECENT_PROJECTS = [SAMPLE_PROJECT] as Project[]; export const MOCK_GIT_PERSONAL_PROJECTS = [SAMPLE_PROJECT] as Project[]; export const MOCK_PROJECT_DETAIL = { ...SAMPLE_PROJECT, empty_repo: true, archived: false, visibility: "private", owner: { id: 0, name: "test", username: "test", state: "active", }, issues_enabled: false, merge_requests_enabled: false, wiki_enabled: false, jobs_enabled: false, snippets_enabled: false, can_create_merge_request_in: false, open_issues_count: 0, } as ProjectDetail; export const MOCK_PROJECT_BRANCH = { name: "main", merged: true, protected: true, developers_can_push: true, developers_can_merge: true, can_push: true, default: true, commit: { id: "test", short_id: "test", created_at: "", title: "Initial commit", message: "", author_name: "test", author_email: "<EMAIL>", authored_date: "", committer_name: "test", committer_email: "<EMAIL>", committed_date: "", }, };
import qrcode from io import BytesIO def generate_qr_code(content, size, color): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=int(size), border=4, ) qr.add_data(content) qr.make(fit=True) img = qr.make_image(fill_color=color, back_color='white') buffer = BytesIO() img.save(buffer) buffer.seek(0) return buffer.getvalue()
<reponame>Novout/generi<filename>src/commands/log.ts import { createChangelog } from '../changelog'; import { GitNewTag, LogOptions } from '../types'; import { nextTag, lastTag, setVersion, setTag, newCommits, isValidTag, pushCommits, } from '../git'; import { success, error, getHeader } from '../console'; import { isChangesForCommit, existsConfig, getFile, getLernaRoot } from '../utils'; import { getGeneriConfig } from '../generi'; import { isGit } from '../git'; import { publish } from '../npm'; const validateLog = (tag: GitNewTag) => { const commits = newCommits(); if (!existsConfig()) { error('Generi not exists! Use <generi init> command instead.'); return false; } if (commits.length < 1) { error('There are no valid commits to create a new release.'); return false; } if (!isValidTag(tag)) { error('Invalid Tag. Use patch|minor|major'); return false; } return true; }; export const setup = (tag: GitNewTag, options: LogOptions) => { const config = getGeneriConfig(); if (options.header) getHeader(`generi log ${tag}`); isChangesForCommit(isGit()); if (!validateLog(tag)) return; const lerna = getFile(getLernaRoot()); const last = lerna ? 'v' + JSON.parse(lerna).version : lastTag(); const next = nextTag({ last, tag, }); if (!next) { error('Unable to create a required tag!'); return; } if (config.version) { success(`${last} to ${next} (${tag.toUpperCase()})`); setVersion(next, tag); } createChangelog(!config.version ? lastTag() : next); if (config.tag && (!options.init || !lerna)) setTag(next); pushCommits(); publish(next); };
package org.ednovo.gooru.core.api.model; import java.io.Serializable; import java.util.Date; public class UserCollectionItemAssoc implements Serializable{ /** * */ private static final long serialVersionUID = -306690946964358328L; private User user; private CollectionItem collectionItem; private CustomTableValue status; private Date lastModifiedOn; private String minimumScore; private String assignmentCompleted; private String timeStudying; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public CollectionItem getCollectionItem() { return collectionItem; } public void setCollectionItem(CollectionItem collectionItem) { this.collectionItem = collectionItem; } public CustomTableValue getStatus() { return status; } public void setStatus(CustomTableValue status) { this.status = status; } public Date getLastModifiedOn() { return lastModifiedOn; } public void setLastModifiedOn(Date lastModifiedOn) { this.lastModifiedOn = lastModifiedOn; } public void setMinimumScore(String minimumScore) { this.minimumScore = minimumScore; } public String getMinimumScore() { return minimumScore; } public void setAssignmentCompleted(String assignmentCompleted) { this.assignmentCompleted = assignmentCompleted; } public String getAssignmentCompleted() { return assignmentCompleted; } public void setTimeStudying(String timeStudying) { this.timeStudying = timeStudying; } public String getTimeStudying() { return timeStudying; } }
/************************************************************************** * * * Algorithmic C (tm) Datatypes * * * * Software Version: 3.7 * * * * Release Date : Tue May 30 14:25:58 PDT 2017 * * Release Type : Production Release * * Release Build : 3.7.2 * * * * Copyright 2013-2016, Mentor Graphics Corporation, * * * * All Rights Reserved. * * ************************************************************************** * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * * implied. * * See the License for the specific language governing permissions and * * limitations under the License. * ************************************************************************** * * * The most recent version of this package is available at github. * * * *************************************************************************/ // Source: ac_float.h // Description: class for floating point operation handling in C++ // Author: <NAME>, Ph.D. #ifndef __AC_FLOAT_H #define __AC_FLOAT_H #include <ac_fixed.h> #ifndef __SYNTHESIS__ #include <cmath> #endif #if (defined(__GNUC__) && __GNUC__ < 3 && !defined(__EDG__)) #error GCC version 3 or greater is required to include this header file #endif #if (defined(_MSC_VER) && _MSC_VER < 1400 && !defined(__EDG__)) #error Microsoft Visual Studio 8 or newer is required to include this header file #endif #if (defined(_MSC_VER) && !defined(__EDG__)) #pragma warning( push ) #pragma warning( disable: 4003 4127 4308 4365 4514 4800 ) #endif #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wparentheses" #pragma clang diagnostic ignored "-Wlogical-op-parentheses" #pragma clang diagnostic ignored "-Wbitwise-op-parentheses" #endif // for safety #if (defined(E) || defined(WF) || defined(IF) || defined(SF)) #error One or more of the following is defined: E, WF, IF, SF. Definition conflicts with their usage as template parameters. #error DO NOT use defines before including third party header files. #endif #define AC_FL(v) ac_float<W##v,I##v,E##v,Q##v> #define AC_FL0(v) ac_float<W##v,I##v,E##v> #define AC_FL_T(v) int W##v, int I##v, int E##v, ac_q_mode Q##v #define AC_FL_TV(v) W##v, I##v, E##v, Q##v #define AC_FL_T0(v) int W##v, int I##v, int E##v #define AC_FL_TV0(v) W##v, I##v, E##v #ifdef __AC_NAMESPACE namespace __AC_NAMESPACE { #endif template<int W, int I, int E, ac_q_mode Q=AC_TRN> class ac_float; namespace ac_private { typedef ac_float<54,2,11> ac_float_cdouble_t; typedef ac_float<25,2,8> ac_float_cfloat_t; template<typename T> struct rt_ac_float_T { template< AC_FL_T0() > struct op1 { typedef AC_FL0() fl_t; typedef typename T::template rt_T<fl_t>::mult mult; typedef typename T::template rt_T<fl_t>::plus plus; typedef typename T::template rt_T<fl_t>::minus2 minus; typedef typename T::template rt_T<fl_t>::minus minus2; typedef typename T::template rt_T<fl_t>::logic logic; typedef typename T::template rt_T<fl_t>::div2 div; typedef typename T::template rt_T<fl_t>::div div2; }; }; // specializations after definition of ac_float inline ac_float_cdouble_t double_to_ac_float(double d); inline ac_float_cfloat_t float_to_ac_float(float f); } ////////////////////////////////////////////////////////////////////////////// // ac_float ////////////////////////////////////////////////////////////////////////////// template< AC_FL_T() > class ac_float:public ac_base_type { enum { NO_UN = true, S = true, S2 = true, SR = true }; public: typedef ac_fixed<W,I,S> mant_t; typedef ac_int<E,true> exp_t; mant_t m; exp_t e; void set_mantissa(const ac_fixed<W,I,S> &man) { m = man; } void set_exp(const ac_int<E,true> &exp) { if(E) e = exp; } private: inline bool is_neg() const { return m < 0; } // is_neg would be more efficient enum {NZ_E = !!E, MIN_EXP = (unsigned int)(-NZ_E) << (E-NZ_E), MAX_EXP = (1 << (E-NZ_E))-1}; public: static const int width = W; static const int i_width = I; static const int e_width = E; static const bool sign = S; static const ac_q_mode q_mode = Q; static const ac_o_mode o_mode = AC_SAT; struct is_ac_basic_type : std::false_type {}; template< AC_FL_T0(2) > struct rt { enum { // need to validate F=W-I, F2=W2-I2, mult_w = W+W2, mult_i = I+I2, mult_e = AC_MAX(E,E2)+1, mult_s = S||S2, plus_w = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1+AC_MAX(F,F2), plus_i = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1, plus_e = AC_MAX(E,E2), plus_s = S||S2, minus_w = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1+AC_MAX(F,F2), minus_i = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+1, minus_e = AC_MAX(E,E2), minus_s = true, div_w = W+AC_MAX(W2-I2,0)+S2, div_i = I+(W2-I2)+S2, div_e = AC_MAX(E,E2)+1, div_s = S||S2, logic_w = AC_MAX(I+(S2&&!S),I2+(S&&!S2))+AC_MAX(F,F2), logic_i = AC_MAX(I+(S2&&!S),I2+(S&&!S2)), logic_s = S||S2, logic_e = AC_MAX(E,E2) }; typedef ac_float<mult_w, mult_i, mult_e> mult; typedef ac_float<plus_w, plus_i, plus_e> plus; typedef ac_float<minus_w, minus_i, minus_e> minus; typedef ac_float<logic_w, logic_i, logic_e> logic; typedef ac_float<div_w, div_i, div_e> div; typedef ac_float arg1; }; template<int WI, bool SI> struct rt_i { enum { lshift_w = W, lshift_i = I, lshift_s = S, lshift_e_0 = exp_t::template rt<WI,SI>::plus::width, lshift_e = AC_MIN(lshift_e_0, 24), rshift_w = W, rshift_i = I, rshift_s = S, rshift_e_0 = exp_t::template rt<WI,SI>::minus::width, rshift_e = AC_MIN(rshift_e_0, 24) }; typedef ac_float<lshift_w, lshift_i, lshift_e> lshift; typedef ac_float<rshift_w, rshift_i, rshift_e> rshift; }; template<typename T> struct rt_T { typedef typename ac_private::map<T>::t map_T; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::mult mult; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::plus plus; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus minus; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus2 minus2; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::logic logic; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div div; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div2 div2; typedef ac_float arg1; }; template<typename T> struct rt_T2 { typedef typename ac_private::map<T>::t map_T; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::mult mult; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::plus plus; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus2 minus; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::minus minus2; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::logic logic; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div2 div; typedef typename ac_private::rt_ac_float_T<map_T>::template op1< AC_FL_TV0() >::div div2; typedef ac_float arg1; }; struct rt_unary { enum { neg_w = W+1, neg_i = I+1, neg_e = E, neg_s = true, mag_sqr_w = 2*W-S + NO_UN, mag_sqr_i = 2*I-S + NO_UN, mag_sqr_e = E, mag_sqr_s = false | NO_UN, mag_w = W+S + NO_UN, mag_i = I+S + NO_UN, mag_e = E, mag_s = false | NO_UN, to_fx_i = I + MAX_EXP, to_fx_w = W + MAX_EXP - MIN_EXP, to_fx_s = S, to_i_w = AC_MAX(to_fx_i,1), to_i_s = S }; typedef ac_float<neg_w, neg_i, neg_e> neg; typedef ac_float<mag_sqr_w, mag_sqr_i, mag_sqr_e> mag_sqr; typedef ac_float<mag_w, mag_i, mag_e> mag; template<unsigned N> struct set { enum { sum_w = W + ac::log2_ceil<N>::val, sum_i = (sum_w-W) + I, sum_e = E, sum_s = S}; typedef ac_float<sum_w, sum_i, sum_e> sum; }; typedef ac_fixed<to_fx_w, to_fx_i, to_fx_s> to_ac_fixed_t; typedef ac_int<to_i_w, to_i_s> to_ac_int_t; }; template<AC_FL_T(2)> friend class ac_float; ac_float() { #if defined(AC_DEFAULT_IN_RANGE) #endif } ac_float(const ac_float &op) { m = op.m; e = op.e; } template<AC_FL_T(2)> ac_float(const AC_FL(2) &op, bool assert_on_overflow=false, bool assert_on_rounding=false) { typedef AC_FL(2) fl2_t; enum { ST2 = S|S2, WT2 = W2+(!S2&S), IT2 = I2+(!S2&S), RND = Q!=AC_TRN & Q!=AC_TRN_ZERO & WT2 > W, MAX_EXP2 = fl2_t::MAX_EXP, MIN_EXP2 = fl2_t::MIN_EXP, I_DIFF = IT2-I, MAX_EXP_T = MAX_EXP2 + I_DIFF + RND, MIN_EXP_T = MIN_EXP2 + I_DIFF, MAX_EXP_T_P = MAX_EXP_T < 0 ? ~ MAX_EXP_T : MAX_EXP_T, MIN_EXP_T_P = MIN_EXP_T < 0 ? ~ MIN_EXP_T : MIN_EXP_T, WC_EXP_T = AC_MAX(MAX_EXP_T_P, MIN_EXP_T_P), ET = ac::template nbits<WC_EXP_T>::val + 1 }; typedef ac_fixed<WT2,IT2,ST2> fx2_t; typedef ac_fixed<WT2,I,S> fx_t; fx2_t m2 = op.m; fx_t t; t.set_slc(0, m2.template slc<fx_t::width>(0)); ac_fixed<W+RND,I+RND,S,Q> m_1 = t; bool rnd_ovfl = false; if(RND) { rnd_ovfl = !m_1[W] & m_1[W-1]; m_1[W-1] = m_1[W-1] & !rnd_ovfl; m_1[W-2] = m_1[W-2] | rnd_ovfl; } m.set_slc(0, m_1.template slc<W>(0)); if(fx_t::width > W && assert_on_rounding) AC_ASSERT(m == t, "Loss of precision due to Rounding in ac_float constructor"); ac_int<ET,true> exp = !m ? ac_int<ET,true> (0) : ac_int<ET,true> (op.e + I_DIFF + (RND & rnd_ovfl)); adjust(exp, false, assert_on_overflow); } ac_float(const ac_fixed<W,I,S> &m2, const ac_int<E,true> &e2, bool normalize=true) { m = m2; if(E) { if(!m) e = 0; else { e = e2; if(normalize) m.normalize(e); } } } template<int WFX, int IFX, bool SFX, int E2> ac_float(const ac_fixed<WFX,IFX,SFX> &m2, const ac_int<E2,true> &e2, bool normalize=true) { enum { WF2 = WFX+!SFX, IF2 = IFX+!SFX }; ac_float<WF2,IF2,E2> f(ac_fixed<WF2,IF2,true>(m2), e2, normalize); *this = f; } template<int WFX, int IFX, bool SFX, ac_q_mode QFX, ac_o_mode OFX> ac_float(const ac_fixed<WFX,IFX,SFX,QFX,OFX> &op, bool normalize=true) { enum { U2S = !SFX, WT2 = WFX+U2S, IT2 = IFX+U2S, RND = QFX!=AC_TRN & QFX!=AC_TRN_ZERO & WT2 > W, I_DIFF = IT2-I, MAX_EXP_T = -(I_DIFF + RND), MIN_EXP_T = AC_MAX(MIN_EXP - I_DIFF, -WT2+1), MAX_EXP_T_P = MAX_EXP_T < 0 ? ~ MAX_EXP_T : MAX_EXP_T, MIN_EXP_T_P = MIN_EXP_T < 0 ? ~ MIN_EXP_T : MIN_EXP_T, WC_EXP_T = AC_MAX(MAX_EXP_T_P, MIN_EXP_T_P), ET = ac::template nbits<WC_EXP_T>::val + 1 }; ac_float<WT2,IT2,ET> f(op, ac_int<ET,true>(0), normalize); *this = f; } template<int WI, bool SI> ac_float(const ac_int<WI,SI> &op) { *this = ac_fixed<WI,WI,SI>(op); } inline ac_float( bool b ) { *this = (ac_int<1,false>) b; } inline ac_float( char b ) { *this = (ac_int<8,true>) b; } inline ac_float( signed char b ) { *this = (ac_int<8,true>) b; } inline ac_float( unsigned char b ) { *this = (ac_int<8,false>) b; } inline ac_float( signed short b ) { *this = (ac_int<16,true>) b; } inline ac_float( unsigned short b ) { *this = (ac_int<16,false>) b; } inline ac_float( signed int b ) { *this = (ac_int<32,true>) b; } inline ac_float( unsigned int b ) { *this = (ac_int<32,false>) b; } inline ac_float( signed long b ) { *this = (ac_int<ac_private::long_w,true>) b; } inline ac_float( unsigned long b ) { *this = (ac_int<ac_private::long_w,false>) b; } inline ac_float( Slong b ) { *this = (ac_int<64,true>) b; } inline ac_float( Ulong b ) { *this = (ac_int<64,false>) b; } // Explicit conversion functions to ac_int and ac_fixed inline typename rt_unary::to_ac_fixed_t to_ac_fixed() const { typename rt_unary::to_ac_fixed_t r = m; r <<= e; return r; } inline typename rt_unary::to_ac_int_t to_ac_int() const { return to_ac_fixed().to_ac_int(); } // Explicit conversion functions to C built-in types ------------- inline int to_int() const { return to_ac_int().to_int(); } inline unsigned to_uint() const { return to_ac_int().to_uint(); } inline long to_long() const { return (signed long) to_ac_int().to_int64(); } inline unsigned long to_ulong() const { return (unsigned long) to_ac_int().to_uint64(); } inline Slong to_int64() const { return to_ac_int().to_int64(); } inline Ulong to_uint64() const { return to_ac_int().to_uint64(); } inline float to_float() const { return ldexpf(m.to_double(), exp()); } inline double to_double() const { return ldexp(m.to_double(), exp()); } const ac_fixed<W,I,S> mantissa() const { return m; } const ac_int<E,true> exp() const { return e; } bool normalize() { bool normalized = operator !() || !S && m[W-1] || S && (m[W-1] ^ m[W-2]); if(E && !normalized) normalized = m.normalize(e); return normalized; } template <int ET> void adjust(ac_int<ET,true> new_e, bool normalize, bool assert_on_overflow) { if(E >= ET) { e = new_e; if(E && normalize) m.normalize(e); } else { ac_int<E,false> offset = 0; offset[E-1] = 1; ac_int<ET+1,true> e_s = new_e + offset; if(e_s < 0) { m >>= (MIN_EXP - new_e); // can a full barrel-shifter be avoided ??? e = MIN_EXP; } else { // break down: bits( (1<<E) -1 + W-1 ) + 1 is max bit for normalization // other bits can be tested separetely ac_int<ET,false> e_u = e_s; if(ET && normalize) m.normalize(e_u); e_u -= offset; if(e_u[ET-1] | !(e_u >> (E-1))) // what about E == 0 or ET == 0 ??? e = e_u; else { e = MAX_EXP; m = m < 0 ? value<AC_VAL_MIN>(m) : value<AC_VAL_MAX>(m); if(assert_on_overflow) AC_ASSERT(0, "OVERFLOW ON ASSIGNMENT TO AC_FLOAT"); } } } } ac_float( double d, bool assert_on_overflow=false, bool assert_on_rounding=false ) { enum { I_EXT = AC_MAX(I,1), W_EXT = ac_private::ac_float_cdouble_t::width + I_EXT - 1, }; ac_private::ac_float_cdouble_t t = ac_private::double_to_ac_float(d); ac_float r(t, assert_on_overflow, assert_on_rounding); *this = r; } ac_float( float f, bool assert_on_overflow=false, bool assert_on_rounding=false ) { enum { I_EXT = AC_MAX(I,1), W_EXT = ac_private::ac_float_cfloat_t::width + I_EXT - 1, }; ac_private::ac_float_cfloat_t t = ac_private::float_to_ac_float(f); ac_float r(t, assert_on_overflow, assert_on_rounding); *this = r; } template<AC_FL_T(2)> typename rt< AC_FL_TV0(2) >::mult operator *(const AC_FL(2) &op2) const { typename rt< AC_FL_TV0(2) >::mult r(m*op2.m, exp()+op2.exp(), false); return r; } template<AC_FL_T(2)> bool compare(const AC_FL(2) &op2, bool *gt) const { typedef ac_fixed<W2,I,S2> fx2_t; typedef typename ac_fixed<W,I,S>::template rt_T< fx2_t >::logic fx_t; typedef ac_fixed<fx_t::width,fx_t::i_width,false> fxu_t; fx2_t op2_m_0; op2_m_0.set_slc(0, op2.m.template slc<W2>(0)); fx_t op1_m = m; fx_t op2_m = op2_m_0; int e_dif = exp() - op2.exp() + I - I2; bool op2_m_neg = op2_m[fx_t::width-1]; fx_t out_bits = op2_m ^ ((op2_m_neg & e_dif < 0) ? ~fx_t(0) : fx_t(0)); out_bits &= ~(fxu_t(~fxu_t(0)) << e_dif); op2_m >>= e_dif; bool overflow = e_dif < 0 & !!out_bits | op2_m_neg ^ op2_m[fx_t::width-1]; *gt = overflow & op2_m_neg | !overflow & op1_m > op2_m; bool eq = op1_m == op2_m & !overflow & !out_bits; return eq; } template<AC_FL_T(2), AC_FL_T(R)> void plus_minus(const AC_FL(2) &op2, AC_FL(R) &r, bool sub=false) const { typedef AC_FL(R) r_type; enum { IT = AC_MAX(I,I2) }; typedef ac_fixed<W, IT, S> fx1_t; typedef ac_fixed<W2, IT, S2> fx2_t; typedef typename fx1_t::template rt_T< ac_fixed<WR,IT,SR> >::logic fx1t_t; typedef typename fx2_t::template rt_T< ac_fixed<WR,IT,SR> >::logic fx2t_t; typedef typename fx1t_t::template rt_T<fx2t_t>::plus mt_t; typedef ac_fixed<mt_t::width+1,mt_t::i_width,SR> t1_t; typedef ac_fixed<mt_t::width+2,mt_t::i_width,SR> t2_t; typedef ac_fixed<t2_t::width,IR,SR> r1_t; enum { MAX_EXP2 = AC_FL(2)::MAX_EXP, MIN_EXP2 = AC_FL(2)::MIN_EXP, I_DIFF = mt_t::i_width - IR, MAX_EXP_T = AC_MAX(MAX_EXP, MAX_EXP2) + I_DIFF, MIN_EXP_T = AC_MIN(MIN_EXP, MIN_EXP2) + I_DIFF, MAX_EXP_T_P = MAX_EXP_T < 0 ? ~ MAX_EXP_T : MAX_EXP_T, MIN_EXP_T_P = MIN_EXP_T < 0 ? ~ MIN_EXP_T : MIN_EXP_T, WC_EXP_T = AC_MAX(MAX_EXP_T_P, MIN_EXP_T_P), ET = ac::template nbits<WC_EXP_T>::val + 1 }; ac_fixed<mt_t::width, I+1, mt_t::sign> op1_m_0 = m; mt_t op1_m = 0; op1_m.set_slc(0, op1_m_0.template slc<mt_t::width>(0)); int op1_e = exp() + I-IT + (SR&!S); ac_fixed<mt_t::width, I2+1, mt_t::sign> op2_m_0 = op2.m; mt_t op2_m = 0; op2_m.set_slc(0, op2_m_0.template slc<mt_t::width>(0)); if(sub) op2_m = -op2_m; int op2_e = op2.exp() + I2-IT + (SR&!S2); bool op1_zero = operator !(); bool op2_zero = !op2; int e_dif = op1_e - op2_e; bool e1_lt_e2 = e_dif < 0; e_dif = (op1_zero | op2_zero) ? 0 : e1_lt_e2 ? -e_dif : e_dif; mt_t op_sl = e1_lt_e2 ? op1_m : op2_m; // Sticky bits are bits shifted out, leaving out the MSB mt_t sticky_bits = op_sl; sticky_bits &= ~((~t1_t(0)) << e_dif); bool sticky_bit = !!sticky_bits; bool msb_shifted_out = (bool) t1_t(op_sl).template slc<1>(e_dif); op_sl >>= e_dif; op1_m = e1_lt_e2 ? op_sl : op1_m; op2_m = e1_lt_e2 ? op2_m : op_sl; t1_t t1 = op1_m; t1 += op2_m; t1[0] = msb_shifted_out; bool shift_r_1 = false; //t1[t1_t::width-1] != t1[t1_t::width-2]; sticky_bit |= shift_r_1 & t1[0]; t1 >>= shift_r_1; t2_t t2 = t1; t2[0] = sticky_bit; r1_t r1; r1.set_slc(0, t2.template slc<t2_t::width>(0)); r_type r_t; r_t.m = (ac_fixed<WR,IR,SR,QR>) r1; // t2; This could overflow if !SR&ST ac_int<ET,true> r_e = op1_zero ? op2_e : (op2_zero ? op1_e : AC_MAX(op1_e, op2_e)); r_e = ac_int<1,true>(!op1_zero | !op2_zero) & (r_e + shift_r_1 + I_DIFF); r_t.adjust(r_e, true, false); r.m = r_t.m; r.e = r_t.e; } template<AC_FL_T(1), AC_FL_T(2)> ac_float add(const AC_FL(1) &op1, const AC_FL(2) &op2) { op1.plus_minus(op2, *this); return *this; } template<AC_FL_T(1), AC_FL_T(2)> ac_float sub(const AC_FL(1) &op1, const AC_FL(2) &op2) { op1.plus_minus(op2, *this, true); return *this; } typename rt_unary::neg abs() const { typedef typename rt_unary::neg r_t; r_t r; r.m = is_neg() ? -m : r_t::mant_t(m); r.e = e; return r; } #ifdef __AC_FLOAT_ENABLE_ALPHA // These will be changed!!! For now only enable to explore integration with ac_complex template<AC_FL_T(2)> typename rt< AC_FL_TV0(2) >::plus operator +(const AC_FL(2) &op2) const { typename rt< AC_FL_TV0(2) >::plus r; plus_minus(op2, r); return r; } template<AC_FL_T(2)> typename rt< AC_FL_TV0(2) >::minus operator -(const AC_FL(2) &op2) const { typename rt< AC_FL_TV0(2) >::minus r; plus_minus(op2, r, true); return r; } #endif template<AC_FL_T(2)> typename rt< AC_FL_TV0(2) >::div operator /(const AC_FL(2) &op2) const { typename rt< AC_FL_TV0(2) >::div r(m/op2.m, exp()-op2.exp()); return r; } template<AC_FL_T(2)> ac_float operator +=(const AC_FL(2) &op2) { ac_float r; plus_minus(op2, r); *this = r; } template<AC_FL_T(2)> ac_float operator -=(const AC_FL(2) &op2) { ac_float r; plus_minus(op2, r, true); *this = r; } template<AC_FL_T(2)> ac_float operator *=(const AC_FL(2) &op2) { *this = *this * op2; } template<AC_FL_T(2)> ac_float operator /=(const AC_FL(2) &op2) { *this = *this / op2; } ac_float operator + () const { return *this; } typename rt_unary::neg operator - () const { typename rt_unary::neg r; r.m = -m; r.e = e; return r; } bool operator ! () const { return !m; } // Shift -------------------------------------------------------------------- template<int WI, bool SI> typename rt_i<WI,SI>::lshift operator << ( const ac_int<WI,SI> &op2 ) const { typename rt_i<WI,SI>::lshift r; r.m = m; r.e = e + op2; return r; } template<int WI, bool SI> typename rt_i<WI,SI>::rshift operator >> ( const ac_int<WI,SI> &op2 ) const { typename rt_i<WI,SI>::rshift r; r.m = m; r.e = e - op2; return r; } // Shift assign ------------------------------------------------------------- template<int WI, bool SI> ac_float &operator <<= ( const ac_int<WI,SI> &op2 ) { *this = operator << (op2); return *this; } template<int WI, bool SI> ac_float &operator >>= ( const ac_int<WI,SI> &op2 ) { *this = operator >> (op2); return *this; } template<AC_FL_T(2)> bool operator == (const AC_FL(2) &f) const { bool gt; return compare(f, &gt); } template<AC_FL_T(2)> bool operator != (const AC_FL(2) &f) const { return !operator == (f); } template<AC_FL_T(2)> bool operator < (const AC_FL(2) &f) const { bool gt; bool eq = compare(f, &gt); return !(eq | gt); } template<AC_FL_T(2)> bool operator >= (const AC_FL(2) &f) const { return !operator < (f); } template<AC_FL_T(2)> bool operator > (const AC_FL(2) &f) const { bool gt; compare(f, &gt); return gt; } template<AC_FL_T(2)> bool operator <= (const AC_FL(2) &f) const { return !operator > (f); } inline std::string to_string(ac_base_mode base_rep, bool sign_mag = false, bool hw=true) const { // TODO: printing decimal with exponent if(!hw) { ac_fixed<W,0,S> mantissa; mantissa.set_slc(0, m.template slc<W>(0)); std::string r = mantissa.to_string(base_rep, sign_mag); r += "e2"; r += (e + I).to_string(base_rep, sign_mag | base_rep == AC_DEC); return r; } else { std::string r = m.to_string(base_rep, sign_mag); if(base_rep != AC_DEC) r += "_"; r += "e2"; if(base_rep != AC_DEC) r += "_"; if(E) r += e.to_string(base_rep, sign_mag | base_rep == AC_DEC); else r += "0"; return r; } } inline static std::string type_name() { const char *tf[] = {"false", "true" }; const char *q[] = {"AC_TRN", "AC_RND", "AC_TRN_ZERO", "AC_RND_ZERO", "AC_RND_INF", "AC_RND_MIN_INF", "AC_RND_CONV" }; std::string r = "ac_float<"; r += ac_int<32,true>(W).to_string(AC_DEC) + ','; r += ac_int<32,true>(I).to_string(AC_DEC) + ','; r += ac_int<32,true>(E).to_string(AC_DEC) + ','; r += tf[S]; r += ','; r += q[Q]; r += '>'; return r; } template<ac_special_val V> inline ac_float &set_val() { m.template set_val<V>(); if(V == AC_VAL_MIN) e.template set_val<AC_VAL_MAX>(); else if(V == AC_VAL_QUANTUM) e.template set_val<AC_VAL_MIN>(); else e.template set_val<V>(); return *this; } }; namespace ac_private { template<typename T> bool ac_fpclassify(T x, bool &inf) { bool nan = !(x==x); if(!nan) { T d = x - x; inf = !(d==d); } return nan; } inline ac_float_cdouble_t double_to_ac_float(double d) { typedef ac_float_cdouble_t r_t; #ifndef __SYNTHESIS__ bool inf; bool nan = ac_fpclassify(d, inf); if(nan) AC_ASSERT(0, "In conversion from double to ac_float: double is NaN"); else if(inf) AC_ASSERT(0, "In conversion from double to ac_float: double is Infinite"); #endif r_t::exp_t exp; r_t::mant_t mant = ac::frexp_d(d, exp); return r_t(mant, exp, false); } inline ac_float_cfloat_t float_to_ac_float(float f) { typedef ac_float_cfloat_t r_t; #ifndef __SYNTHESIS__ bool inf; bool nan = ac_fpclassify(f, inf); if(nan) AC_ASSERT(0, "In conversion from float to ac_float: float is NaN"); else if(inf) AC_ASSERT(0, "In conversion from float to ac_float: float is Infinite"); #endif r_t::exp_t exp; r_t::mant_t mant = ac::frexp_f(f, exp); return r_t(mant, exp, false); } }; namespace ac { template<typename T> struct ac_float_represent { typedef typename ac_fixed_represent<T>::type fx_t; typedef ac_float<fx_t::width+!fx_t::sign,fx_t::i_width+!fx_t::sign,1,fx_t::q_mode> type; }; template<> struct ac_float_represent<float> { typedef ac_private::ac_float_cfloat_t type; }; template<> struct ac_float_represent<double> { typedef ac_private::ac_float_cdouble_t type; }; } namespace ac_private { // with T == ac_float template< AC_FL_T0(2) > struct rt_ac_float_T< AC_FL0(2) > { typedef AC_FL0(2) fl2_t; template< AC_FL_T0() > struct op1 { typedef AC_FL0() fl_t; typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult; typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus; typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus; typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2; typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic; typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div; typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2; }; }; // with T == ac_fixed template<int WFX, int IFX, bool SFX> struct rt_ac_float_T< ac_fixed<WFX,IFX,SFX> > { // For now E2 > 0 enum { E2 = 1, S2 = true, W2 = WFX + !SFX, I2 = IFX + !SFX }; typedef AC_FL0(2) fl2_t; template< AC_FL_T0() > struct op1 { typedef AC_FL0() fl_t; typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult; typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus; typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus; typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2; typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic; typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div; typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2; }; }; // with T == ac_int template<int WI, bool SI> struct rt_ac_float_T< ac_int<WI,SI> > { // For now E2 > 0 enum { E2 = 1, S2 = true, I2 = WI + !SI, W2 = I2 }; typedef AC_FL0(2) fl2_t; template< AC_FL_T0() > struct op1 { typedef AC_FL0() fl_t; typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult; typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus; typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus; typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2; typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic; typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div; typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2; }; }; // Multiplication is optimizable, general operator +/- is not yet supported template<typename T> struct rt_ac_float_T< c_type<T> > { // For now E2 > 0 enum { SCT = c_type_params<T>::S, S2 = true, W2 = c_type_params<T>::W + !SCT, I2 = c_type_params<T>::I + !SCT, E2 = AC_MAX(1, c_type_params<T>::E) }; typedef AC_FL0(2) fl2_t; template< AC_FL_T0() > struct op1 { typedef AC_FL0() fl_t; typedef typename fl_t::template rt< AC_FL_TV0(2) >::mult mult; typedef typename fl_t::template rt< AC_FL_TV0(2) >::plus plus; typedef typename fl_t::template rt< AC_FL_TV0(2) >::minus minus; typedef typename fl2_t::template rt< AC_FL_TV0() >::minus minus2; typedef typename fl_t::template rt< AC_FL_TV0(2) >::logic logic; typedef typename fl_t::template rt< AC_FL_TV0(2) >::div div; typedef typename fl2_t::template rt< AC_FL_TV0() >::div div2; }; }; } // Stream -------------------------------------------------------------------- #ifndef __SYNTHESIS__ template<AC_FL_T()> inline std::ostream& operator << (std::ostream &os, const AC_FL() &x) { os << x.to_string(AC_DEC); return os; } #endif #define FL_BIN_OP_WITH_CTYPE(BIN_OP, C_TYPE, RTYPE) \ template< AC_FL_T() > \ inline typename AC_FL()::template rt_T2<C_TYPE>::RTYPE operator BIN_OP ( C_TYPE c_op, const AC_FL() &op) { \ typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \ return fl2_t(c_op).operator BIN_OP (op); \ } \ template< AC_FL_T() > \ inline typename AC_FL()::template rt_T<C_TYPE>::RTYPE operator BIN_OP ( const AC_FL() &op, C_TYPE c_op) { \ typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \ return op.operator BIN_OP (fl2_t(c_op)); \ } #define FL_REL_OP_WITH_CTYPE(REL_OP, C_TYPE) \ template< AC_FL_T() > \ inline bool operator REL_OP ( const AC_FL() &op, C_TYPE op2) { \ typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \ return op.operator REL_OP (fl2_t(op2)); \ } \ template< AC_FL_T() > \ inline bool operator REL_OP ( C_TYPE op2, const AC_FL() &op) { \ typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \ return fl2_t(op2).operator REL_OP (op); \ } #define FL_ASSIGN_OP_WITH_CTYPE_2(ASSIGN_OP, C_TYPE) \ template< AC_FL_T() > \ inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, C_TYPE op2) { \ typedef typename ac::template ac_float_represent<C_TYPE>::type fl2_t; \ return op.operator ASSIGN_OP (fl2_t(op2)); \ } #define FL_OPS_WITH_CTYPE(C_TYPE) \ FL_BIN_OP_WITH_CTYPE(*, C_TYPE, mult) \ FL_BIN_OP_WITH_CTYPE(+, C_TYPE, plus) \ FL_BIN_OP_WITH_CTYPE(-, C_TYPE, minus) \ FL_BIN_OP_WITH_CTYPE(/, C_TYPE, div) \ \ FL_REL_OP_WITH_CTYPE(==, C_TYPE) \ FL_REL_OP_WITH_CTYPE(!=, C_TYPE) \ FL_REL_OP_WITH_CTYPE(>, C_TYPE) \ FL_REL_OP_WITH_CTYPE(>=, C_TYPE) \ FL_REL_OP_WITH_CTYPE(<, C_TYPE) \ FL_REL_OP_WITH_CTYPE(<=, C_TYPE) \ \ FL_ASSIGN_OP_WITH_CTYPE_2(+=, C_TYPE) \ FL_ASSIGN_OP_WITH_CTYPE_2(-=, C_TYPE) \ FL_ASSIGN_OP_WITH_CTYPE_2(*=, C_TYPE) \ FL_ASSIGN_OP_WITH_CTYPE_2(/=, C_TYPE) #define FL_SHIFT_OP_WITH_INT_CTYPE(BIN_OP, C_TYPE, RTYPE) \ template< AC_FL_T() > \ inline typename AC_FL()::template rt_i< ac_private::c_type_params<C_TYPE>::W, ac_private::c_type_params<C_TYPE>::S >::RTYPE operator BIN_OP ( const AC_FL() &op, C_TYPE i_op) { \ typedef typename ac::template ac_int_represent<C_TYPE>::type i_t; \ return op.operator BIN_OP (i_t(i_op)); \ } #define FL_SHIFT_ASSIGN_OP_WITH_INT_CTYPE(ASSIGN_OP, C_TYPE) \ template< AC_FL_T() > \ inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, C_TYPE i_op) { \ typedef typename ac::template ac_int_represent<C_TYPE>::type i_t; \ return op.operator ASSIGN_OP (i_t(i_op)); \ } #define FL_SHIFT_OPS_WITH_INT_CTYPE(C_TYPE) \ FL_SHIFT_OP_WITH_INT_CTYPE(>>, C_TYPE, rshift) \ FL_SHIFT_OP_WITH_INT_CTYPE(<<, C_TYPE, lshift) \ FL_SHIFT_ASSIGN_OP_WITH_INT_CTYPE(>>=, C_TYPE) \ FL_SHIFT_ASSIGN_OP_WITH_INT_CTYPE(<<=, C_TYPE) #define FL_OPS_WITH_INT_CTYPE(C_TYPE) \ FL_OPS_WITH_CTYPE(C_TYPE) \ FL_SHIFT_OPS_WITH_INT_CTYPE(C_TYPE) // --------------------------------------- End of Macros for Binary Operators with C Floats // Binary Operators with C Floats -------------------------------------------- FL_OPS_WITH_CTYPE(float) FL_OPS_WITH_CTYPE(double) FL_OPS_WITH_INT_CTYPE(bool) FL_OPS_WITH_INT_CTYPE(char) FL_OPS_WITH_INT_CTYPE(signed char) FL_OPS_WITH_INT_CTYPE(unsigned char) FL_OPS_WITH_INT_CTYPE(short) FL_OPS_WITH_INT_CTYPE(unsigned short) FL_OPS_WITH_INT_CTYPE(int) FL_OPS_WITH_INT_CTYPE(unsigned int) FL_OPS_WITH_INT_CTYPE(long) FL_OPS_WITH_INT_CTYPE(unsigned long) FL_OPS_WITH_INT_CTYPE(Slong) FL_OPS_WITH_INT_CTYPE(Ulong) // -------------------------------------- End of Binary Operators with C Floats // Macros for Binary Operators with ac_int -------------------------------------------- #define FL_BIN_OP_WITH_AC_INT_1(BIN_OP, RTYPE) \ template< AC_FL_T(), int WI, bool SI> \ inline typename AC_FL()::template rt_T2< ac_int<WI,SI> >::RTYPE operator BIN_OP ( const ac_int<WI,SI> &i_op, const AC_FL() &op) { \ typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \ return fl2_t(i_op).operator BIN_OP (op); \ } #define FL_BIN_OP_WITH_AC_INT_2(BIN_OP, RTYPE) \ template< AC_FL_T(), int WI, bool SI> \ inline typename AC_FL()::template rt_T2< ac_int<WI,SI> >::RTYPE operator BIN_OP ( const AC_FL() &op, const ac_int<WI,SI> &i_op) { \ typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \ return op.operator BIN_OP (fl2_t(i_op)); \ } #define FL_BIN_OP_WITH_AC_INT(BIN_OP, RTYPE) \ FL_BIN_OP_WITH_AC_INT_1(BIN_OP, RTYPE) \ FL_BIN_OP_WITH_AC_INT_2(BIN_OP, RTYPE) #define FL_REL_OP_WITH_AC_INT(REL_OP) \ template< AC_FL_T(), int WI, bool SI> \ inline bool operator REL_OP ( const AC_FL() &op, const ac_int<WI,SI> &op2) { \ typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \ return op.operator REL_OP (fl2_t(op2)); \ } \ template< AC_FL_T(), int WI, bool SI> \ inline bool operator REL_OP ( ac_int<WI,SI> &op2, const AC_FL() &op) { \ typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \ return fl2_t(op2).operator REL_OP (op); \ } #define FL_ASSIGN_OP_WITH_AC_INT(ASSIGN_OP) \ template< AC_FL_T(), int WI, bool SI> \ inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, const ac_int<WI,SI> &op2) { \ typedef typename ac::template ac_float_represent< ac_int<WI,SI> >::type fl2_t; \ return op.operator ASSIGN_OP (fl2_t(op2)); \ } // -------------------------------------------- End of Macros for Binary Operators with ac_int // Binary Operators with ac_int -------------------------------------------- FL_BIN_OP_WITH_AC_INT(*, mult) FL_BIN_OP_WITH_AC_INT(+, plus) FL_BIN_OP_WITH_AC_INT(-, minus) FL_BIN_OP_WITH_AC_INT(/, div) FL_REL_OP_WITH_AC_INT(==) FL_REL_OP_WITH_AC_INT(!=) FL_REL_OP_WITH_AC_INT(>) FL_REL_OP_WITH_AC_INT(>=) FL_REL_OP_WITH_AC_INT(<) FL_REL_OP_WITH_AC_INT(<=) FL_ASSIGN_OP_WITH_AC_INT(+=) FL_ASSIGN_OP_WITH_AC_INT(-=) FL_ASSIGN_OP_WITH_AC_INT(*=) FL_ASSIGN_OP_WITH_AC_INT(/=) FL_ASSIGN_OP_WITH_AC_INT(%=) // -------------------------------------- End of Binary Operators with ac_int // Macros for Binary Operators with ac_fixed -------------------------------------------- #define FL_BIN_OP_WITH_AC_FIXED_1(BIN_OP, RTYPE) \ template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \ inline typename AC_FL()::template rt_T2< ac_fixed<WF,IF,SF> >::RTYPE operator BIN_OP ( const ac_fixed<WF,IF,SF,QF,OF> &f_op, const AC_FL() &op) { \ typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \ return fl2_t(f_op).operator BIN_OP (op); \ } #define FL_BIN_OP_WITH_AC_FIXED_2(BIN_OP, RTYPE) \ template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \ inline typename AC_FL()::template rt_T2< ac_fixed<WF,IF,SF> >::RTYPE operator BIN_OP ( const AC_FL() &op, const ac_fixed<WF,IF,SF,QF,OF> &f_op) { \ typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \ return op.operator BIN_OP (fl2_t(f_op)); \ } #define FL_BIN_OP_WITH_AC_FIXED(BIN_OP, RTYPE) \ FL_BIN_OP_WITH_AC_FIXED_1(BIN_OP, RTYPE) \ FL_BIN_OP_WITH_AC_FIXED_2(BIN_OP, RTYPE) #define FL_REL_OP_WITH_AC_FIXED(REL_OP) \ template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \ inline bool operator REL_OP ( const AC_FL() &op, const ac_fixed<WF,IF,SF,QF,OF> &op2) { \ typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \ return op.operator REL_OP (fl2_t(op2)); \ } \ template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \ inline bool operator REL_OP ( ac_fixed<WF,IF,SF,QF,OF> &op2, const AC_FL() &op) { \ typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \ return fl2_t(op2).operator REL_OP (op); \ } #define FL_ASSIGN_OP_WITH_AC_FIXED(ASSIGN_OP) \ template< AC_FL_T(), int WF, int IF, bool SF, ac_q_mode QF, ac_o_mode OF> \ inline AC_FL() &operator ASSIGN_OP ( AC_FL() &op, const ac_fixed<WF,IF,SF,QF,OF> &op2) { \ typedef typename ac::template ac_float_represent< ac_fixed<WF,IF,SF> >::type fl2_t; \ return op.operator ASSIGN_OP (fl2_t(op2)); \ } // -------------------------------------------- End of Macros for Binary Operators with ac_fixed // Binary Operators with ac_fixed -------------------------------------------- FL_BIN_OP_WITH_AC_FIXED(*, mult) FL_BIN_OP_WITH_AC_FIXED(+, plus) FL_BIN_OP_WITH_AC_FIXED(-, minus) FL_BIN_OP_WITH_AC_FIXED(/, div) FL_REL_OP_WITH_AC_FIXED(==) FL_REL_OP_WITH_AC_FIXED(!=) FL_REL_OP_WITH_AC_FIXED(>) FL_REL_OP_WITH_AC_FIXED(>=) FL_REL_OP_WITH_AC_FIXED(<) FL_REL_OP_WITH_AC_FIXED(<=) FL_ASSIGN_OP_WITH_AC_FIXED(+=) FL_ASSIGN_OP_WITH_AC_FIXED(-=) FL_ASSIGN_OP_WITH_AC_FIXED(*=) FL_ASSIGN_OP_WITH_AC_FIXED(/=) // -------------------------------------- End of Binary Operators with ac_fixed // Global templatized functions for easy initialization to special values template<ac_special_val V, AC_FL_T()> inline AC_FL() value( AC_FL() ) { AC_FL() r; return r.template set_val<V>(); } namespace ac { // function to initialize (or uninitialize) arrays template<ac_special_val V, AC_FL_T() > inline bool init_array( AC_FL() *a, int n) { AC_FL0() t = value<V>(*a); for(int i=0; i < n; i++) a[i] = t; return true; } } /////////////////////////////////////////////////////////////////////////////// #if (defined(_MSC_VER) && !defined(__EDG__)) #pragma warning( pop ) #endif #if defined(__clang__) #pragma clang diagnostic pop #endif #ifdef __AC_NAMESPACE } #endif #endif // __AC_FLOAT_H
<filename>lib/helpers/debounce.tsx export function debounce (fn, ms) { let timeout; return function (...args) { const fnCall = () => { fn.apply(this, args) } clearTimeout(timeout); timeout = setTimeout(fnCall, ms) return timeout }; }
<filename>tests/unit/time.test.js const { convertTime12to24, normalizeTime, normalizeAMPM, } = require('../../src/time.js'); describe('time.js', () => { describe('convertTime12to24', () => { it('should convert 12 AM/PM correctly', () => { expect(convertTime12to24('12:00', 'PM')).toBe('12:00'); expect(convertTime12to24('12:00', 'AM')).toBe('00:00'); }); it('should convert time in the hh:mm format', () => { expect(convertTime12to24('05:06', 'PM')).toBe('17:06'); expect(convertTime12to24('07:19', 'AM')).toBe('07:19'); }); it('should convert time in the hh:mm:ss format', () => { expect(convertTime12to24('01:02:34', 'PM')).toBe('13:02:34'); expect(convertTime12to24('02:04:54', 'AM')).toBe('02:04:54'); }); }); describe('normalizeAMPM', () => { it('should convert am format correctly', () => { expect(normalizeAMPM('am')).toBe('AM'); expect(normalizeAMPM('pm')).toBe('PM'); expect(normalizeAMPM('AM')).toBe('AM'); expect(normalizeAMPM('PM')).toBe('PM'); }); it('should convert a.m. format correctly', () => { expect(normalizeAMPM('a.m.')).toBe('AM'); expect(normalizeAMPM('p.m.')).toBe('PM'); expect(normalizeAMPM('A.M.')).toBe('AM'); expect(normalizeAMPM('P.M.')).toBe('PM'); }); }); describe('normalizeTime', () => { it('should add seconds if they are missing', () => { expect(normalizeTime('12:34')).toBe('12:34:00'); }); it('should add a leading 0 to the hours if missing', () => { expect(normalizeTime('1:23:45')).toBe('01:23:45'); }); it('should not alter an already normalized string', () => { expect(normalizeTime('12:34:56')).toBe('12:34:56'); }); }); });
/* * Copyright 2002-2021 the original author or 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 * * 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. */ package org.springframework.http.client.reactive; import org.springframework.http.HttpStatusCode; import org.springframework.http.ReactiveHttpInputMessage; import org.springframework.http.ResponseCookie; import org.springframework.util.MultiValueMap; import org.springframework.util.ObjectUtils; /** * Represents a client-side reactive HTTP response. * * @author <NAME> * @author <NAME> * @since 5.0 */ public interface ClientHttpResponse extends ReactiveHttpInputMessage { /** * Return an id that represents the underlying connection, if available, * or the request for the purpose of correlating log messages. * @since 5.3.5 */ default String getId() { return ObjectUtils.getIdentityHexString(this); } /** * Return the HTTP status code as an {@link HttpStatusCode}. * @return the HTTP status as {@code HttpStatusCode} value (never {@code null}) */ HttpStatusCode getStatusCode(); /** * Return the HTTP status code as an integer. * @return the HTTP status as an integer value * @since 5.0.6 * @see #getStatusCode() * @deprecated as of 6.0, in favor of {@link #getStatusCode()} */ @Deprecated int getRawStatusCode(); /** * Return a read-only map of response cookies received from the server. */ MultiValueMap<String, ResponseCookie> getCookies(); }
#!/bin/bash set -e cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"/../ echo "=== test-baseline.sh ===" isort --check-only -rc src/flwr_experimental/baseline && echo "- isort: done" && black -q --check src/flwr_experimental/baseline && echo "- black: done" && # mypy is covered by test.sh pylint src/flwr_experimental/baseline && echo "- pylint: done" && pytest -q src/flwr_experimental/baseline && echo "- pytest: done" && echo "- All Python checks passed"
'use strict' /* global winston */ const Redis = require('ioredis') const _ = require('lodash') /** * Redis module * * @param {Object} appconfig Application config * @return {Redis} Redis instance */ module.exports = (appconfig) => { let rd = null if (_.isArray(appconfig.redis)) { rd = new Redis.Cluster(appconfig.redis, { scaleReads: 'master', redisOptions: { lazyConnect: false } }) } else { rd = new Redis(_.defaultsDeep(appconfig.redis), { lazyConnect: false }) } // Handle connection errors rd.on('error', (err) => { winston.error('Failed to connect to Redis instance(s). [err-1]') return err }) rd.on('node error', (err) => { winston.error('Failed to connect to Redis instance(s). [err-2]') return err }) return rd }
#!/bin/bash <<EOF Portfolio \ Tools \ Python \ Impression Image Tool A simple bootstrap script responsible for running the impression image tool, and ensuring that the virtual environment is created and provisioned EOF CURRENT_SCRIPT_DIRECTORY=${CURRENT_SCRIPT_DIRECTORY:-$(dirname $(realpath $0))} export SHARED_SCRIPTS_PATH=${SHARED_SCRIPTS_PATH:-$(realpath $CURRENT_SCRIPT_DIRECTORY/../../../Docker/scripts)} export CURRENT_SCRIPT_FILENAME=${CURRENT_SCRIPT_FILENAME:-$(basename $0)} export CURRENT_SCRIPT_FILENAME_BASE=${CURRENT_SCRIPT_FILENAME%.*} source "$SHARED_SCRIPTS_PATH/shared-functions.sh" write_header PYTHON_VIRTUALENV_PATH=$CURRENT_DIRECTORY/venv write_success "imagetool" "done"
<filename>services/GameServices/removePlayerFromGame.js 'use strict'; const gameSchema = require('../../schema/GameSchema'); const removePlayerFromGame = function (gameId, playerId) { console.log('Game service - removePlayerFromGame - begin'); return new Promise((resolve, reject) => { gameSchema.findById(gameId).exec(function(err, game) { // Test if game exist if (err || game === null) { console.log('Game service - removePlayerFromGame - error game not found'); resolve({ status: 'error', message: 'game_not_found' }); } else { // Test game status if (game.status !== 'init') { console.log('Game service - removePlayerFromGame - error can\'t leave game with this status: ' + game.status); resolve({ status: 'error', message: 'wrong_game_status' }); } else { // Test if player is in the game if (!game.players.includes(playerId)) { console.log('Game service - removePlayerFromGame - error player not found'); resolve({ status: 'error', message: 'player_not_in_game' }); } else { let playerIndex = game.players.indexOf(playerId); game.players.splice(playerIndex, 1); game.save(); resolve({ status: 'success', message: 'player_removed' }); } } } }); }); }; module.exports = removePlayerFromGame;
import * as vscode from "vscode"; import { globalStateGet, globalStateUpdate } from "@microsoft/teamsfx-core"; import { ExtTelemetry } from "../telemetry/extTelemetry"; import { TelemetryEvent } from "../telemetry/extTelemetryEvents"; import * as StringResources from "../resources/Strings.json"; const SURVEY_URL = "https://aka.ms/teams-toolkit-survey"; enum ExtensionSurveyStateKeys { DoNotShowAgain = "survey/doNotShowAgain", RemindMeLater = "survey/remindMeLater", DisableSurveyForTime = "survey/disableSurveyForTime", } const TIME_TO_DISABLE_SURVEY = 1000 * 60 * 60 * 24 * 7 * 12; // 4 weeks const TIME_TO_SHOW_SURVEY = 1000 * 60 * 7; // 7 minutes const SAMPLE_PERCENTAGE = 25; // 25 percent for public preview export class ExtensionSurvey { private context: vscode.ExtensionContext; private timeToShowSurvey: number; private timeToDisableSurvey: number; private checkSurveyInterval?: NodeJS.Timeout; private showSurveyTimeout?: NodeJS.Timeout; private needToShow = false; constructor( context: vscode.ExtensionContext, timeToShowSurvey?: number, samplePercentage?: number, timeToDisableSurvey?: number ) { this.context = context; this.timeToShowSurvey = timeToShowSurvey ? timeToShowSurvey : TIME_TO_SHOW_SURVEY; const randomSample: number = Math.floor(Math.random() * 100) + 1; if (randomSample <= (samplePercentage ? samplePercentage : SAMPLE_PERCENTAGE)) { this.needToShow = true; } this.timeToDisableSurvey = timeToDisableSurvey ? timeToDisableSurvey : TIME_TO_DISABLE_SURVEY; } public async activate(): Promise<void> { if (this.needToShow && !this.checkSurveyInterval) { this.checkSurveyInterval = setInterval(() => { if (!this.shouldShowBanner()) { return; } if (!this.showSurveyTimeout && ExtTelemetry.hasSentTelemetry) { this.showSurveyTimeout = setTimeout(() => this.showSurvey(), this.timeToShowSurvey); } }, 2000); } } public shouldShowBanner(): boolean { const doNotShowAgain = globalStateGet(ExtensionSurveyStateKeys.DoNotShowAgain, false); if (doNotShowAgain) { return false; } const currentTime = Date.now(); const remindMeLaterTime = globalStateGet(ExtensionSurveyStateKeys.RemindMeLater, 0); if (remindMeLaterTime > currentTime) { return false; } const disableSurveyForTime = globalStateGet(ExtensionSurveyStateKeys.DisableSurveyForTime, 0); if (disableSurveyForTime > currentTime) { return false; } return true; } public async showSurvey(): Promise<void> { const extension = vscode.extensions.getExtension("TeamsDevApp.ms-teams-vscode-extension"); if (!extension) { return; } const extensionVersion = extension.packageJSON.version || "unknown"; const take = { title: StringResources.vsc.survey.takeSurvey.title, run: async (): Promise<void> => { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.Survey, { message: StringResources.vsc.survey.takeSurvey.message, }); vscode.commands.executeCommand( "vscode.open", vscode.Uri.parse( `${SURVEY_URL}?o=${encodeURIComponent(process.platform)}&v=${encodeURIComponent( extensionVersion )}` ) ); const disableSurveyForTime = Date.now() + this.timeToDisableSurvey; await globalStateUpdate( ExtensionSurveyStateKeys.DisableSurveyForTime, disableSurveyForTime ); }, }; const remind = { title: StringResources.vsc.survey.remindMeLater.title, run: async (): Promise<void> => { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.Survey, { message: StringResources.vsc.survey.remindMeLater.message, }); }, }; const never = { title: StringResources.vsc.survey.dontShowAgain.title, run: async (): Promise<void> => { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.Survey, { message: StringResources.vsc.survey.dontShowAgain.message, }); await globalStateUpdate(ExtensionSurveyStateKeys.DoNotShowAgain, true); }, }; const selection = await vscode.window.showInformationMessage( StringResources.vsc.survey.banner.title, take, remind, never ); if (this.showSurveyTimeout) { clearTimeout(this.showSurveyTimeout); this.showSurveyTimeout = undefined; } if (selection) { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.Survey, { message: StringResources.vsc.survey.banner.message, }); await selection.run(); } else { ExtTelemetry.sendTelemetryEvent(TelemetryEvent.Survey, { message: StringResources.vsc.survey.cancelMessage, }); } } }
function formatAttributeLabels(array $attributeLabels): string { // Sort the attribute labels alphabetically ksort($attributeLabels); $formattedString = ''; // Iterate through the sorted attribute labels and build the formatted string foreach ($attributeLabels as $attribute => $description) { $formattedString .= ucfirst($attribute) . ': ' . $description . PHP_EOL; } return $formattedString; } // Example usage $attributeLabels = [ 'id_asig' => 'Id Asig', 'name' => 'Name', 'age' => 'Age', 'gender' => 'Gender', ]; echo formatAttributeLabels($attributeLabels);
import { DecodeUint32 } from "./Decode"; import { EncodeUint32 } from "./Encode"; export enum ObjectClass { INVALID = -1, CKO_DATA = 0x00000000, CKO_CERTIFICATE = 0x00000001, CKO_PUBLIC_KEY = 0x00000002, CKO_PRIVATE_KEY = 0x00000003, CKO_SECRET_KEY = 0x00000004, CKO_HW_FEATURE = 0x00000005, CKO_DOMAIN_PARAMETERS = 0x00000006, CKO_MECHANISM = 0x00000007, CKO_OTP_KEY = 0x00000008, CKO_VENDOR_DEFINED = 0x80000000, } export async function DecodeObjectClass(raw?: Uint8Array): Promise<ObjectClass | undefined> { let parsed: number | undefined; try { parsed = await DecodeUint32(raw); } catch (err) { console.error(err); return ObjectClass.INVALID; } if (parsed === undefined) { return ObjectClass.INVALID; } switch (parsed) { case ObjectClass.INVALID: case ObjectClass.CKO_DATA: case ObjectClass.CKO_CERTIFICATE: case ObjectClass.CKO_PUBLIC_KEY: case ObjectClass.CKO_PRIVATE_KEY: case ObjectClass.CKO_SECRET_KEY: case ObjectClass.CKO_HW_FEATURE: case ObjectClass.CKO_DOMAIN_PARAMETERS: case ObjectClass.CKO_MECHANISM: case ObjectClass.CKO_OTP_KEY: case ObjectClass.CKO_VENDOR_DEFINED: return parsed as ObjectClass; default: console.error(`invalid object class: ${parsed}`); return ObjectClass.INVALID; } } export function EncodeObjectClass(cl?: ObjectClass): Promise<Uint8Array | undefined> { if (cl === ObjectClass.INVALID) { throw new Error("cannot encode invalid object class"); } return EncodeUint32(cl as (number | undefined)); }
<reponame>grambas/snake-game<gh_stars>0 package de.hshannover.inform.dunkleit.gruppe12.mainmenu; import javax.swing.SwingUtilities; import de.hshannover.inform.dunkleit.gruppe12.mainmenu.gui.MainMenuFrame; import de.hshannover.inform.dunkleit.gruppe12.mainmenu.gui.MainMenuGUIController; import de.hshannover.inform.dunkleit.gruppe12.snake.SnakeConsts; /** * Enthält Einstiegspunkt des Programms * * @author dierschke */ public class MainMenuStarter { /** * Einstiegsfunktion erstellt das Hauptfenster des Hauptmenüs * * @param args Übergabeparameter (nicht genutzt) */ public static void main(String[] args) { // Hauptmenu anzeigen SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainMenuGUIController controller = new MainMenuGUIController(); MainMenuFrame view = new MainMenuFrame(MainMenuConsts.MAIN_TITLE); // Spiele hinzufuegen controller.addGame(SnakeConsts.GAME_IDENTIFIER, SnakeConsts.GAME_TITLE); controller.setView(view); view.setController(controller); controller.showMainMenu(); } }); } }
from collections import defaultdict def return_default(): return 0 def dd(): return defaultdict(return_default) CHALLENGE_DAY = "10" REAL = open(CHALLENGE_DAY + ".txt").read() SAMPLE = open(CHALLENGE_DAY + ".sample").read() SAMPLE_EXPECTED = 35 # SAMPLE_EXPECTED = def parse_lines(raw): # Groups. # split = raw.split("\n\n") # return list(map(lambda group: group.split("\n"), split)) split = raw.split("\n") # return split # raw # return list(map(lambda l: l.split(" "), split)) # words. return list(map(int, split)) # return list(map(lambda l: l.strip(), split)) # beware leading / trailing WS #123 less and is OK # it's device is 3 + max of my adapters # My seat has jolt of 0 def solve(raw): parsed = parse_lines(raw) # Debug here to make sure parsing is good. ret = 0 max_joltage = max(parsed) + 3 parsed.sort() here = 0 diffs = [0, 0, 0, 0] for i in range(len(parsed)): diff = parsed[i] - here assert diff != 0 assert diff <= 3 diffs[diff] += 1 here = parsed[i] return diffs[1] * (diffs[3] + 1) return ret def test_parsing(lines): if isinstance(lines, list): for i in range(min(5, len(lines))): print(lines[i]) elif isinstance(lines, dict) or isinstance(lines, defaultdict): nd = {} for k in list(lines.keys())[0: 5]: print("\"" + k + "\": " + str(lines[k])) test_parsing(parse_lines(SAMPLE)) print("^^^^^^^^^PARSED SAMPLE SAMPLE^^^^^^^^^") sample = solve(SAMPLE) if SAMPLE_EXPECTED is None: print("*** SKIPPING SAMPLE! ***") else: assert sample == SAMPLE_EXPECTED print("*** SAMPLE PASSED ***") solved = solve(REAL) print("SOLUTION: ", solved) import pandas as pd df=pd.DataFrame([str(solved)]) df.to_clipboard(index=False,header=False) print("COPIED TO CLIPBOARD") # assert solved
#!/bin/bash -xe # Copyright (C) 2011-2013 OpenStack 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. HOSTNAME=$1 SUDO=${SUDO:-true} THIN=${THIN:-true} ALL_MYSQL_PRIVS=${ALL_MYSQL_PRIVS:-false} GIT_BASE=${GIT_BASE:-git://git.openstack.org} sudo hostname $HOSTNAME if [ -n "$HOSTNAME" ] && ! grep -q $HOSTNAME /etc/hosts ; then echo "127.0.1.1 $HOSTNAME" | sudo tee -a /etc/hosts fi echo $HOSTNAME > /tmp/image-hostname.txt sudo mv /tmp/image-hostname.txt /etc/image-hostname.txt if [ ! -f /etc/redhat-release ]; then # Cloud provider apt repos break us - so stop using them LSBDISTID=$(lsb_release -is) LSBDISTCODENAME=$(lsb_release -cs) if [ "$LSBDISTID" == "Ubuntu" ] ; then sudo dd of=/etc/apt/sources.list <<EOF # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME main restricted deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-updates main restricted deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-updates main restricted ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME universe deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME universe deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-updates universe deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME multiverse deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-updates multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-updates multiverse ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. deb http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-backports main restricted universe multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ $LSBDISTCODENAME-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu $LSBDISTCODENAME-security main restricted deb-src http://security.ubuntu.com/ubuntu $LSBDISTCODENAME-security main restricted deb http://security.ubuntu.com/ubuntu $LSBDISTCODENAME-security universe deb-src http://security.ubuntu.com/ubuntu $LSBDISTCODENAME-security universe deb http://security.ubuntu.com/ubuntu $LSBDISTCODENAME-security multiverse deb-src http://security.ubuntu.com/ubuntu $LSBDISTCODENAME-security multiverse EOF fi fi # Fedora image doesn't come with wget if [ -f /usr/bin/yum ]; then sudo yum -y install wget fi wget https://git.openstack.org/cgit/openstack-infra/system-config/plain/install_puppet.sh sudo bash -xe install_puppet.sh sudo git clone --depth=1 $GIT_BASE/openstack-infra/system-config.git \ /root/system-config sudo /bin/bash /root/system-config/install_modules.sh set +e if [ -z "$NODEPOOL_SSH_KEY" ] ; then sudo puppet apply --detailed-exitcodes --color=false \ --modulepath=/root/system-config/modules:/etc/puppet/modules \ -e "class {'openstack_project::single_use_slave': sudo => $SUDO, thin => $THIN, all_mysql_privs => $ALL_MYSQL_PRIVS, }" PUPPET_RET_CODE=$? else sudo puppet apply --detailed-exitcodes --color=false \ --modulepath=/root/system-config/modules:/etc/puppet/modules \ -e "class {'openstack_project::single_use_slave': install_users => false, sudo => $SUDO, thin => $THIN, all_mysql_privs => $ALL_MYSQL_PRIVS, ssh_key => '$NODEPOOL_SSH_KEY', }" PUPPET_RET_CODE=$? fi # Puppet doesn't properly return exit codes. Check here the values that # indicate failure of some sort happened. 0 and 2 indicate success. if [ "$PUPPET_RET_CODE" -eq "4" ] || [ "$PUPPET_RET_CODE" -eq "6" ] ; then exit $PUPPET_RET_CODE fi set -e # The puppet modules should install unbound. Set up some nameservers. cat >/tmp/forwarding.conf <<EOF forward-zone: name: "." forward-addr: 114.114.114.114 EOF sudo mv /tmp/forwarding.conf /etc/unbound/ sudo chown root:root /etc/unbound/forwarding.conf sudo chmod a+r /etc/unbound/forwarding.conf # HPCloud has selinux enabled by default, Rackspace apparently not. # Regardless, apply the correct context. if [ -x /sbin/restorecon ] ; then sudo chcon system_u:object_r:named_conf_t:s0 /etc/unbound/forwarding.conf fi # Overwrite /etc/resolv.conf at boot sudo dd of=/etc/rc.local <<EOF #!/bin/bash set -o xtrace # Some providers inject dynamic network config statically. Work around this # for DNS nameservers. This is expected to fail on some nodes so remove -e. set +e sed -i -e 's/^\(DNS[0-9]*=[.0-9]\+\)/#\1/g' /etc/sysconfig/network-scripts/ifcfg-* set -e echo 'nameserver 127.0.0.1' > /etc/resolv.conf exit 0 EOF # hpcloud has started mounting ephemeral /dev/vdb at /mnt. # devstack-gate wants to partition the ephemeral disk, add some swap # and mount it at /opt. get rid of the mount. # # note this comes down from the cloud-init metadata; which we setup to # ignore below. sudo sed -i '/^\/dev\/vdb/d' /etc/fstab # Make all cloud-init data sources match rackspace- only attempt to look # at ConfigDrive, not at metadata service. This is not needed if there # is no cloud-init if [ -d /etc/cloud/cloud.cfg.d ] ; then sudo dd of=/etc/cloud/cloud.cfg.d/95_real_datasources.cfg <<EOF datasource_list: [ ConfigDrive, None ] EOF fi # reset cloud-init sudo rm -rf /var/lib/cloud/instances sudo bash -c "echo 'include: /etc/unbound/forwarding.conf' >> /etc/unbound/unbound.conf" if [ -e /etc/init.d/unbound ] ; then sudo /etc/init.d/unbound restart elif [ -e /usr/lib/systemd/system/unbound.service ] ; then sudo systemctl restart unbound else echo "Can't discover a method to restart \"unbound\"" exit 1 fi # Make sure DNS works. dig git.openstack.org # Cache all currently known gerrit repos. sudo mkdir -p /opt/git sudo -i python /opt/nodepool-scripts/cache_git_repos.py $GIT_BASE # We don't always get ext4 from our clouds, mount ext3 as ext4 on the next # boot (eg when this image is used for testing). sudo sed -i 's/ext3/ext4/g' /etc/fstab # Remove additional sources used to install puppet or special version of pypi. # We do this because leaving these sources in place causes every test that # does an apt-get update to hit those servers which may not have the uptime # of our local mirrors. OS_FAMILY=$(facter osfamily) if [ "$OS_FAMILY" == "Debian" ] ; then sudo rm -f /etc/apt/sources.list.d/* sudo apt-get update elif [ "$OS_FAMILY" == "RedHat" ] ; then # Can't delete * in yum.repos.d since all of the repos are listed there. # Be specific instead. if [ -f /etc/yum.repos.d/puppetlabs.repo ] ; then sudo rm -f /etc/yum.repos.d/puppetlabs.repo fi fi # Remove cron jobs # We create fresh servers for these hosts, and they are used once. They don't # need to do things like update the locatedb or the mandb or rotate logs # or really any of those things. We only want code running here that we want # here. sudo rm -f /etc/cron.{monthly,weekly,daily,hourly,d}/* # Install Zuul into a virtualenv # This is in /usr instead of /usr/local due to this bug on precise: # https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/839588 git clone /opt/git/openstack-infra/zuul /tmp/zuul sudo virtualenv /usr/zuul-env sudo -H /usr/zuul-env/bin/pip install /tmp/zuul sudo rm -fr /tmp/zuul # Create a virtualenv for zuul-swift-logs # This is in /usr instead of /usr/local due to this bug on precise: # https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/839588 sudo -H virtualenv /usr/zuul-swift-logs-env sudo -H /usr/zuul-swift-logs-env/bin/pip install --proxy http://127.0.0.1:8081 python-magic argparse \ requests glob2 # Create a virtualenv for os-testr (which contains subunit2html) # this is in /usr instead of /usr/loca/ due to this bug on precise: # https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/839588 sudo -H virtualenv /usr/os-testr-env sudo -H /usr/os-testr-env/bin/pip install --proxy http://127.0.0.1:8081 os-testr
module Qernel # Represents slots whose +conversion+ adjusts dynamically to fill whatever # remains from the other slots on the node. This ensures that the # cumulative conversion of all the slots add up to 1.0. # # Used for: # # * Output slots whose carrier is "loss". # * Slots which have a truthy "flexible" attribute. # class Slot::Elastic < Slot # Public: Creates a new Elastic slot. # # Raises a Qernel::Slot::Elastic::TooManyElasticSlots if the node # already has an elastic slot with the same direction. # def initialize(*) super if siblings.any? { |s| s.kind_of?(Slot::Elastic) } raise TooManyElasticSlots.new(self) end end # Public: Dynamically calculates +conversion+ so that all of the slots sum # to 1.0. # # Returns a float. # def conversion fetch(:conversion) do others = inelastic_siblings.sum(&:conversion) # Don't break the laws of thermodynamics; conversion may not be # negative. others > 1.0 ? 0.0 : 1.0 - others end end # Public: Returns the sibling slots to be considered when calculating the # conversion. Override in a subclass if you need to ignore certain # carriers itn some calculations. # # Returns an array of Slots # def inelastic_siblings siblings end # Internal: Raised when trying to add a second elastic slot to a # node. class TooManyElasticSlots < RuntimeError def initialize(slot) @slot = slot end def message other = @slot.siblings.detect do |sibling| sibling.kind_of?(Slot::Elastic) end <<-MESSAGE.squish! Node #{ @slot.node.inspect } already has an elastic slot (#{ other.inspect }); you cannot add #{ @slot.inspect }. MESSAGE end end end # Slot::Elastic end # Qernel
<reponame>oueya1479/OpenOLAT /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.modules.reminder.manager; import java.io.InputStream; import java.io.OutputStream; import org.olat.core.util.xml.XStreamHelper; import org.olat.modules.reminder.ReminderRule; import org.olat.modules.reminder.model.ImportExportReminder; import org.olat.modules.reminder.model.ImportExportReminders; import org.olat.modules.reminder.model.ReminderRuleImpl; import org.olat.modules.reminder.model.ReminderRules; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.security.ExplicitTypePermission; /** * * Initial date: 25 mars 2019<br> * @author srosse, <EMAIL>, http://www.frentix.com * */ public class ReminderRulesXStream { private static final XStream ruleXStream = XStreamHelper.createXStreamInstance(); static { Class<?>[] types = new Class[] { ReminderRule.class, ReminderRuleImpl.class, ReminderRules.class, ImportExportReminders.class, ImportExportReminder.class }; ruleXStream.addPermission(new ExplicitTypePermission(types)); ruleXStream.alias("rule", ReminderRuleImpl.class); ruleXStream.alias("rules", ReminderRules.class); ruleXStream.alias("reminders", ImportExportReminders.class); ruleXStream.alias("reminder", ImportExportReminder.class); } public static ReminderRules toRules(String rulesXml) { return (ReminderRules)ruleXStream.fromXML(rulesXml); } public static ReminderRules toRules(InputStream in) { return (ReminderRules)ruleXStream.fromXML(in); } public static String toXML(ReminderRules rules) { return ruleXStream.toXML(rules); } public static void toXML(ImportExportReminders reminders, OutputStream out) { ruleXStream.toXML(reminders, out); } public static ImportExportReminders fromXML(InputStream in) { return (ImportExportReminders)ruleXStream.fromXML(in); } }
import numpy as np arr = np.zeros((3, 3, 3)) print(arr)
<gh_stars>0 package main.java.game; import java.util.*; public class GameBoard { //instance variable private int height; private int width; private String[][] gameBoard; private Set<Integer> availableIndexes; private Set<Integer> unavailableIndexes; /** * getter for marked indexes set * * @return */ public Set<Integer> getUnavailableIndexes() { return unavailableIndexes; } /** * getter for free indexes set * * @return */ public Set<Integer> getAvailableIndexes() { return availableIndexes; } /** * constructor * * @param height height of board * @param width width of board */ public GameBoard(int height, int width) { this.width = width; this.height = height; this.availableIndexes = new HashSet<>(); this.unavailableIndexes = new HashSet<>(); this.gameBoard = initializeBoard(new String[height][width]); } /** * initializes game board with '*' * * @param array array to initialize * @return */ private String[][] initializeBoard(String[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { array[i][j] = "* "; availableIndexes.add(i * array[0].length + j); } } return array; } /** * remove used index from set of available indexes so it could not be chosen again. * * @param index what index to remove */ public void removeUsedIndex(int index) { if (availableIndexes.contains(index)) { availableIndexes.remove(index); } } /** * remove used set of indexes from set of available indexes so it could not be chosen again. * * @param set set of indexes to remove */ public void removeAllUsedIndex(Set<Integer> set) { if (set != null) { for (int index : set) { removeUsedIndex(index); } } } /** * given number for etc 0-99 in board of 10x10 translate ut to clolumn height * * @param index what index to convert * @return index converted to height */ public int indexToHeightConverotr(int index) { return index / width; } /** * given number for etc 0-99 in board of 10x10 translate ut to clolumn width. * * @param index what index to convert * @return index converted to width */ public int indexToWidthConverotr(int index) { return index % height; } /** * prints the board */ public void printGameBoard() { for (int i = 0; i < gameBoard.length; i++) { for (int j = 0; j < gameBoard[0].length; j++) { System.out.print(gameBoard[i][j]); } System.out.print("\n"); } } /** * get free (unused) index * * @return */ public int getRandomIndex() { int size = availableIndexes.size(); int item = new Random().nextInt(size); List<Integer> newTemArray = new ArrayList<Integer>(availableIndexes); return newTemArray.get(item); } /** * given index palce mark of ship on board :'s' for submarine ,'d' for destroyer,'c' for cruiser,'a' for aircraft. * * @param index index needed to be marked on gameboard. * @param mark 'a' ,'c','d','s' according to ships type */ public void placeMarkOnBoard(int index, String mark) { int height = indexToHeightConverotr(index); int width = indexToWidthConverotr(index); gameBoard[height][width] = mark; removeUsedIndex(index); unavailableIndexes.add(index); } /** * given set of indexes and mark it places the mark on all of the sets indexes on gameboard. * * @param listToMark indexes needed to be marked * @param mark 'a' ,'c','d','s' according to ships type */ public void placeMarkSetOnBoard(Set<Integer> listToMark, String mark) { for (int index : listToMark) { placeMarkOnBoard(index, mark); } } ///////////ships and submarine operation /** * given current index and numbersToGenerate,generates set of new indexes in ascending order for row * * @param currentIndex index to start from * @param numbersToGenerate number of indexes to geneerate including current index * @return set of generated indexes */ public Set<Integer> generateAscRowIndexes(int currentIndex, int numbersToGenerate) { Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < numbersToGenerate; i++) { set.add(currentIndex + i); } return set; } /** * given current index and numbersToGenerate,generates set of new indexes in descending order for row * * @param currentIndex index to start from * @param numbersToGenerate number of indexes to geneerate including current index * @return set of generated indexes */ public Set<Integer> generateDescRowIndexes(int currentIndex, int numbersToGenerate) { Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < numbersToGenerate; i++) { set.add(currentIndex - i); } return set; } /** * given current index and numbersToGenerate,generates set of new indexes in ascending order for column,jumps * are by width between each new generated index * * @param currentIndex index to start from * @param numbersToGenerate number of indexes to geneerate including current index * @return set of generated indexes */ public Set<Integer> generateAscColumnIndexes(int currentIndex, int numbersToGenerate) { Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < numbersToGenerate; i++) { set.add(currentIndex + i * width); } return set; } /** * given current index and numbersToGenerate,generates set of new indexes in descending order for column,jumps * are by width between each new generated index * * @param currentIndex index to start from * @param numbersToGenerate number of indexes to geneerate including current index * @return set of generated indexes */ public Set<Integer> generateDescColumnIndexes(int currentIndex, int numbersToGenerate) { Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < numbersToGenerate; i++) { set.add(currentIndex - i * width); } return set; } /** * places ship horizontal at first it tries from the index to its left left of the board, if failed it tries to its right * if placed remove its neighbours because adjacent ships are not allowed. * * @param currentIndex free index * @param marksNumber number of marks on board * @param mark 'a' ,'c','d','s' according to ships type * @return if succeeded true otherwise false */ public boolean placeHorizontal(int currentIndex, int marksNumber, String mark) { boolean isPlaced = false; int widthIndex = indexToWidthConverotr(currentIndex); ///is on same row ,try to mark from cuurrent index to marksnumber time to the left if ((widthIndex - marksNumber + 1 >= 0) && (!isPlaced)) { Set<Integer> leftRowSet = generateDescRowIndexes(currentIndex, marksNumber); Set<Integer> neighbours = new HashSet<>(); for (int index : leftRowSet) { neighbours.addAll(getAdjacentIndexes(index)); neighbours.removeAll(leftRowSet); } ///check indexes neighbors are not ships(marked) if ((getAvailableIndexes().containsAll(leftRowSet)) && (!checkIfsomeContained(neighbours, getUnavailableIndexes()))) { isPlaced = true; ///mark to the left vertical placeMarkSetOnBoard(leftRowSet, mark); } } ///is on same row ,try to mark from cuurrent index to marksnumber time to the right if ((widthIndex + marksNumber - 1 < width) && (!isPlaced)) { Set<Integer> rightRowSet = generateAscRowIndexes(currentIndex, marksNumber); Set<Integer> neighbours = new HashSet<>(); for (int index : rightRowSet) { neighbours.addAll(getAdjacentIndexes(index)); neighbours.removeAll(rightRowSet); } if ((getAvailableIndexes().containsAll(rightRowSet)) && (!checkIfsomeContained(neighbours, getUnavailableIndexes()))) { isPlaced = true; ///mark to the left vertical placeMarkSetOnBoard(rightRowSet, mark); } } return isPlaced; } /** * check if one of 'contained' elements are in 'set' ,if its return true, otherwise return false. * * @param set set of integers we want to check if contains one of 'contained' elements. * @param contained set of integers we want to check if cintained in 'set' * @return */ public boolean checkIfsomeContained(Set<Integer> set, Set<Integer> contained) { for (int index : contained) { if (set.contains(index)) { return true; } } return false; } /** * given an index get all of its neighbours indexes. * * @param currentIndex index we want to get its neighbors * @return set of neighbours indexes */ public Set<Integer> getAdjacentIndexes(int currentIndex) { Set<Integer> set = new HashSet<>(); int widthIndex = indexToWidthConverotr(currentIndex); int heightIndex = indexToHeightConverotr(currentIndex); if ((indexToWidthConverotr(currentIndex + 1) == widthIndex + 1) && (widthIndex + 1 <= width)) { set.add(currentIndex + 1); } if ((indexToWidthConverotr(currentIndex - 1) == widthIndex - 1) && (widthIndex - 1 >= 0)) { set.add(currentIndex - 1); } if ((indexToHeightConverotr(currentIndex + width) == heightIndex + 1) && (heightIndex + 1 <= height)) { set.add(currentIndex + width); } if ((indexToHeightConverotr(currentIndex - width) == heightIndex - 1) && (heightIndex - 1 >= 0)) { set.add(currentIndex - width); } //////////////corners if ((indexToWidthConverotr(currentIndex + 1 + width) == widthIndex + 1) && (indexToHeightConverotr(currentIndex + 1 + width) == heightIndex + 1) && (widthIndex + 1 <= height) && (heightIndex + 1 <= height)) { set.add(currentIndex + 1 + width); } if ((indexToWidthConverotr(currentIndex - 1 + width) == widthIndex - 1) && (indexToHeightConverotr(currentIndex - 1 + width) == heightIndex + 1) && (heightIndex + 1 <= height) && (widthIndex - 1 >= 0)) { set.add(currentIndex - 1 + width); } if ((indexToWidthConverotr(currentIndex - 1 - width) == widthIndex - 1) && (indexToHeightConverotr(currentIndex - 1 - width) == heightIndex - 1) && (widthIndex - 1 >= 0) && (heightIndex - 1 >= 0)) { set.add(currentIndex - 1 - width); } if ((indexToWidthConverotr(currentIndex + 1 - width) == widthIndex + 1) && (indexToHeightConverotr(currentIndex + 1 - width) == heightIndex - 1) && (heightIndex - 1 >= 0) && (widthIndex + 1 <= width)) { set.add(currentIndex + 1 - width); } return set; } /** * places ship vertical at first it tries from the index to top of the board, if failed it tries to bottom * if placed remove its neighbours because adjacent ships are not allowed. * * @param currentIndex free index * @param marksNumber number of marks on board * @param mark 'a' ,'c','d','s' according to ships type * @return if succeeded true otherwise false */ public boolean placeVertical(int currentIndex, int marksNumber, String mark) { boolean isPlaced = false; int heightIndex = indexToHeightConverotr(currentIndex); ///is on same row ,try to mark from cuurrent index to marksnumber time to the top if ((heightIndex + (-marksNumber + 1) * width >= 0) && (!isPlaced)) { Set<Integer> topRowSet = generateDescColumnIndexes(currentIndex, marksNumber); Set<Integer> neighbours = new HashSet<>(); for (int index : topRowSet) { neighbours.addAll(getAdjacentIndexes(index)); neighbours.removeAll(topRowSet); } ///check indexes neighbors are not ships(marked) if ((getAvailableIndexes().containsAll(topRowSet)) && (!checkIfsomeContained(neighbours, getUnavailableIndexes()))) { isPlaced = true; ///mark to the left vertical placeMarkSetOnBoard(topRowSet, mark); removeAllUsedIndex(neighbours); } } ///is on same row ,try to mark from cuurrent index to marksnumber time to the bottom direction(of the board,ascending on height index) if ((heightIndex + (marksNumber - 1) * width < height * width) && (!isPlaced)) { Set<Integer> bottomRowSet = generateAscColumnIndexes(currentIndex, marksNumber); Set<Integer> neighbours = new HashSet<>(); for (int index : bottomRowSet) { neighbours.addAll(getAdjacentIndexes(index)); } ///check indexes neighbors are not ships(marked) if (getAvailableIndexes().containsAll(bottomRowSet) && (!checkIfsomeContained(neighbours, getUnavailableIndexes()))) { isPlaced = true; ///mark to the left vertical placeMarkSetOnBoard(bottomRowSet, mark); } } return isPlaced; } /** * place ship randomly on board ,chooses 0 or 1 ,if succeeded returns true otherwise if failed * coin is having xor operation in which it gets its opposite value (0 or 1) * * @param currentIndex free index * @param marksNumber number of marks on board * @param mark 'a' ,'c','d','s' according to ships type * @return if succeeded true otherwise false */ public boolean placeRandomVerticalOrHorizontal(int currentIndex, int marksNumber, String mark) { int coin = flipACoin(); if (placeVerticalOrHorizontal(currentIndex, marksNumber, mark, coin)) { return true; } else { ///0 xor 1 =1 and 1 xor 1 =0 we get the opposite coin = coin ^ 1; if (placeVerticalOrHorizontal(currentIndex, marksNumber, mark, coin)) { return true; } else { return false; } } } /** * place a ship in vertical or horizontal position on board. * * @param currentIndex free index to start * @param marksNumber size of ship:1,2,3,4 * @param mark 'a' ,'c','d','s' according to ships type * @param coin 1 or 0 * @return if succeeded true otherwise false */ public boolean placeVerticalOrHorizontal(int currentIndex, int marksNumber, String mark, int coin) { boolean result; if (coin == 0) { result = placeVertical(currentIndex, marksNumber, mark); } else//its 1 { result = placeHorizontal(currentIndex, marksNumber, mark); } return result; } /** * place submarine on board */ public void placeSubmarine() { int freeIndex = getRandomIndex(); Set<Integer> neighbours = getAdjacentIndexes(freeIndex); if (!checkIfsomeContained(neighbours, getUnavailableIndexes())) { placeMarkOnBoard(freeIndex, "s "); } else { placeSubmarine(); } } /** * place carrier on board */ public void placeCarrier() { int freeIndex = getRandomIndex(); if (!placeRandomVerticalOrHorizontal(freeIndex, 4, "a ")) placeCarrier(); } /** * place carrier on board */ public void placeCruiser() { int freeIndex = getRandomIndex(); if (!placeRandomVerticalOrHorizontal(freeIndex, 3, "c ")) placeCruiser(); } /** * place carrier on board */ public void placeDestroyer() { int freeIndex = getRandomIndex(); if (!placeRandomVerticalOrHorizontal(freeIndex, 2, "d ")) placeDestroyer(); } /** * reurn randomly 1 or 0 * * @return */ public int flipACoin() { return (int) Math.round(Math.random()); } }
from unittest import TestCase from quiz10 import cuenta class TestCuenta(TestCase): def test_deposito(self): a = cuenta () self.assertEqual(a.deposito(300), 500) def test_retiro(self): a = cuenta () self.assertEqual(a.retiro(300), 500)
// Descrição: Arquivo responsável pela lógica das rotas do cliente const mongoose = require('mongoose') const Cliente = mongoose.model('Cliente') const Usuario = mongoose.model('Usuario') const Pedido = mongoose.model('Pedido') const Produto = mongoose.model('Produto') const Variacao = mongoose.model('Variacao') class ClienteController { // ------------------------------------------------------------ ADMIN ------------------------------------------------------------- // GET / async index(req, res, next) { try { // offset - Quando tem que pular para mostrar um conteudo da pagina const offset = Number(req.query.offset) || 0 // limit - Quanto quer mostrar na pagina const limit = Number(req.query.limit) || 30 const clientes = await Cliente.paginate( { loja: req.query.loja }, { offset, limit, populate: { path: "usuario", select: "-salt -hash" } } ); return res.send({ clientes }) } catch (e) { next(e) } } // GET /search/:search/pedidos async searchPedidos(req, res, next) { const { offset, limit, loja } = req.query; try { const search = new RegExp(req.params.search, "i"); const clientes = await Cliente.find({ loja, $text: { $search: search, $diacriticSensitive: false } }); const pedidos = await Pedido.paginate( { loja, cliente: { $in: clientes.map(item => item._id) } }, { offset, limit, populate: ["cliente", "pagamento", "entrega"] } ); pedidos.docs = await Promise.all(pedidos.docs.map(async (pedido) => { pedido.carrinho = await Promise.all(pedido.carrinho.map(async (item) => { item.produto = await Produto.findById(item.produto); item.variacao = await Variacao.findById(item.variacao); return item; })); return pedido; })); return res.send({ pedidos }); } catch (e) { next(e); } } // GET /search/:search async search(req, res, next) { // offset - Quando tem que pular para mostrar um conteudo da pagina const offset = Number(req.query.offset) || 0; // limit - Quanto quer mostrar na pagina const limit = Number(req.query.limit) || 30; const search = new RegExp(req.params.search, "i"); try { const clientes = await Cliente.paginate( { loja: req.query.loja, $or: [ { $text: { $search: search, $diacriticSensitive: false } }, { telefones: { $regex: search } } ] }, { offset, limit, populate: { path: "usuario", select: "-salt -hash" } } ); return res.send({ clientes }) } catch (e) { next(e) } } // GET /admin/:id async showAdmin(req, res, next) { try { // Faz a busca pelo cliente com os dados passados const cliente = await Cliente.findOne({ _id: req.params.id, loja: req.query.loja }).populate({ path: "usuario", select: "-salt -hash" }) return res.send({ cliente }) } catch (e) { next(e) } } // PUT /admin/:id async updateAdmin(req, res, next) { // Pega os dados no body const { nome, cpf, email, telefones, endereco, dataDeNascimento } = req.body; try { // Faz a busca pelo cliente const cliente = await Cliente.findById(req.params.id).populate({ path: "usuario", select: "-salt -hash" }) // Se valores existirem atualiza valores if (nome) { cliente.usuario.nome = nome cliente.nome = nome } if (email) cliente.usuario.email = email if (cpf) cliente.cpf = cpf if (telefones) cliente.telefones = telefones if (endereco) cliente.endereco = endereco if (dataDeNascimento) cliente.dataDeNascimento = dataDeNascimento // Salva os dados await cliente.usuario.save() await cliente.save() return res.send({ cliente }) } catch (e) { next(e) } } // GET /admin/:id/pedidos async showPedidosCliente(req, res, next) { const { offset, limit, loja } = req.query; try { const pedidos = await Pedido.paginate( { loja, cliente: req.params.id }, { offset: Number(offset || 0), limit: Number(limit || 30), populate: ["cliente", "pagamento", "entrega"] } ); pedidos.docs = await Promise.all(pedidos.docs.map(async (pedido) => { pedido.carrinho = await Promise.all(pedido.carrinho.map(async (item) => { item.produto = await Produto.findById(item.produto); item.variacao = await Variacao.findById(item.variacao); return item; })); return pedido; })); return res.send({ pedidos }); } catch (e) { next(e); } } // -------------------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------- CLIENTES ----------------------------------------------------------- // GET /:id async show(req, res, next) { try { const cliente = await Cliente.findOne({ usuario: req.payload.id, loja: req.query.loja }).populate({ path: "usuario", select: "-salt -hash" }) return res.send({ cliente }) } catch (e) { next(e) } } // POST / async store(req, res, next) { // Pega os dados no body const { nome, cpf, email, telefones, endereco, dataDeNascimento, password } = req.body const { loja } = req.query // Cria um novo usuario e verifica a senha const usuario = new Usuario({ nome, email, loja }) usuario.setSenha(password) // Cria um novo cliente linkando com o novo usuario const cliente = new Cliente({ nome, cpf, telefones, endereco, loja, dataDeNascimento, usuario: usuario._id }) try { // Salva os dados await usuario.save() await cliente.save() return res.send({ cliente: Object.assign({}, cliente._doc, { email: usuario.email }) }) } catch (e) { next(e) } } // PUT /:id async update(req, res, next) { // Pega os dados no body const { nome, cpf, email, telefones, endereco, dataDeNascimento, password } = req.body try { // Faz a busca pelo cliente const cliente = await Cliente.findOne({ usuario: req.payload.id }).populate('usuario') if (!cliente) return res.send({ error: 'Cliente não existe!!' }) // Se valores existirem atualiza valores if (nome) { cliente.usuario.nome = nome cliente.nome = nome } if (email) cliente.usuario.email = email if (password) cliente.usuario.password = password if (cpf) cliente.cpf = cpf if (telefones) cliente.telefones = telefones if (endereco) cliente.endereco = endereco if (dataDeNascimento) cliente.dataDeNascimento = dataDeNascimento // Salva os dados await cliente.save() cliente.usuario = { email: cliente.usuario.email, _id: cliente.usuario._id, permissao: cliente.usuario.permissao } return res.send({ cliente }) } catch (e) { next(e) } } // DELETE /:id async remove(req, res, next) { try { const cliente = await Cliente.findOne({ usuario: req.payload.id }).populate("usuario") // Remove a opção de login await cliente.usuario.remove() // Muda para deletado o status, mas o dono da loja ainda consegue ver o registro do cliente cliente.deletado = true // Salva os dados await cliente.save() return res.send({ deletado: true }) } catch (e) { next(e) } } // -------------------------------------------------------------------------------------------------------------------------------- } module.exports = ClienteController
package engine import "errors" var ( ErrNotFound = errors.New("not found") ErrReadOnlyTx = errors.New("cannot execute a write operation in a read only transaction") )
import styles from './styles'; import combineStyles from '../internal/combine-styles'; const root = overrideStyle => combineStyles(styles.root, overrideStyle); const itemContainer = (rowHeight, enableLightbox, overrideStyle) => { let style = combineStyles(styles.itemContainer, { height: rowHeight }); if (enableLightbox) { style = combineStyles(style, { cursor: 'pointer' }); } return combineStyles(style, overrideStyle); }; const item = (rowHeight, overrideStyle) => ( combineStyles(combineStyles(styles.item, { height: rowHeight }), overrideStyle) ); const colorPlaceholder = (color, originalWidth, originalHeight, rowHeight, overrideStyle) => { const width = (originalWidth * rowHeight) / originalHeight; const style = combineStyles(styles.item, { backgroundColor: color, width, height: rowHeight }); return combineStyles(style, overrideStyle); }; export default { root, itemContainer, item, colorPlaceholder };
<filename>nw-apps/REPL-GUI/src/config-and-ui.js var gui = require('nw.gui'); win = gui.Window.get(); var nativeMenuBar = new gui.Menu({ type: "menubar" }); try { nativeMenuBar.createMacBuiltin("My App", { hideEdit: false, hideWindow: true }); win.menu = nativeMenuBar; } catch (ex) { console.log(ex.message); } reload_On_Changes = function() { var path = './'; var fs = require('fs'); fs.watch(path, function() { if (location) location.reload(); }); } //util methods var newWindow = function() { var gui = require('nw.gui'); var new_win = gui.Window.get(window.open(document.location.href)) } //setup
<filename>src/main/java/model/OrderDetail.java package model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.hibernate.annotations.Index; @Entity @Table(name = "`order_detail`") @JsonIgnoreProperties(ignoreUnknown = true) public class OrderDetail implements Serializable { private static final long serialVersionUID = 1; @Id @GeneratedValue @Column(name = "`order_detail_key`") private Long orderDetailKey; @OneToOne @JoinColumn(name = "`order_key`") @Index(name = "order_key_idx") private Order order; @Column(name = "`meal_name`") private String mealName; @Column(name = "`meal_price`") private Integer mealPrice; @Column(name = "`created_at`") private Long createdAt; @Column(name = "`modified_at`") @Index(name = "modified_at_idx") private Long modifiedAt; @Column(name = "`is_archived`") @Index(name = "is_archived_idx") private boolean isArchived; public OrderDetail() { super(); } public Long getOrderDetailKey() { return orderDetailKey; } public void setOrderDetailKey(Long orderDetailKey) { this.orderDetailKey = orderDetailKey; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public String getMealName() { return mealName; } public void setMealName(String mealName) { this.mealName = mealName; } public Integer getMealPrice() { return mealPrice; } public void setMealPrice(Integer mealPrice) { this.mealPrice = mealPrice; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } public Long getModifiedAt() { return modifiedAt; } public void setModifiedAt(Long modifiedAt) { this.modifiedAt = modifiedAt; } public boolean isArchived() { return isArchived; } public void setArchived(boolean isArchived) { this.isArchived = isArchived; } }
/* * Copyright(C) 2020 The Android Open Source Project * * 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" (short)0IS, * 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 com.android.javacard.keymaster; import javacard.framework.Util; import javacard.security.CryptoException; import javacard.security.Key; import javacard.security.MessageDigest; import javacard.security.Signature; import javacardx.crypto.Cipher; public class KMRsa2048NoDigestSignature extends Signature { public static final byte ALG_RSA_SIGN_NOPAD = (byte) 0x65; public static final byte ALG_RSA_PKCS1_NODIGEST = (byte) 0x66; private byte algorithm; private Cipher inst; public KMRsa2048NoDigestSignature(byte alg) { algorithm = alg; inst = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false); } @Override public void init(Key key, byte b) throws CryptoException { inst.init(key, b); } @Override public void init(Key key, byte b, byte[] bytes, short i, short i1) throws CryptoException { inst.init(key, b, bytes, i, i1); } @Override public void setInitialDigest(byte[] bytes, short i, short i1, byte[] bytes1, short i2, short i3) throws CryptoException { } @Override public byte getAlgorithm() { return algorithm; } @Override public byte getMessageDigestAlgorithm() { return MessageDigest.ALG_NULL; } @Override public byte getCipherAlgorithm() { return algorithm; } @Override public byte getPaddingAlgorithm() { return Cipher.PAD_NULL; } @Override public short getLength() throws CryptoException { return 0; } @Override public void update(byte[] bytes, short i, short i1) throws CryptoException { // HAL accumulates the data and send it at finish operation. } @Override public short sign(byte[] bytes, short i, short i1, byte[] bytes1, short i2) throws CryptoException { padData(bytes, i, i1, KMAndroidSEProvider.getInstance().tmpArray, (short) 0); return inst.doFinal(KMAndroidSEProvider.getInstance().tmpArray, (short) 0, (short) 256, bytes1, i2); } @Override public short signPreComputedHash(byte[] bytes, short i, short i1, byte[] bytes1, short i2) throws CryptoException { return 0; } @Override public boolean verify(byte[] bytes, short i, short i1, byte[] bytes1, short i2, short i3) throws CryptoException { //Verification is handled inside HAL return false; } @Override public boolean verifyPreComputedHash(byte[] bytes, short i, short i1, byte[] bytes1, short i2, short i3) throws CryptoException { //Verification is handled inside HAL return false; } private void padData(byte[] buf, short start, short len, byte[] outBuf, short outBufStart) { if (!isValidData(buf, start, len)) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } Util.arrayFillNonAtomic(outBuf, (short) outBufStart, (short) 256, (byte) 0x00); if (algorithm == ALG_RSA_SIGN_NOPAD) { // add zero to right } else if (algorithm == ALG_RSA_PKCS1_NODIGEST) {// 0x00||0x01||PS||0x00 outBuf[0] = 0x00; outBuf[1] = 0x01; Util.arrayFillNonAtomic(outBuf, (short) 2, (short) (256 - len - 3), (byte) 0xFF); outBuf[(short) (256 - len - 1)] = 0x00; } else { CryptoException.throwIt(CryptoException.ILLEGAL_USE); } Util.arrayCopyNonAtomic(buf, start, outBuf, (short) (256 - len), len); } private boolean isValidData(byte[] buf, short start, short len) { if (algorithm == ALG_RSA_SIGN_NOPAD) { if (len > 256) { return false; } } else { // ALG_RSA_PKCS1_NODIGEST if (len > 245) { return false; } } return true; } }
# baidu.py class BaiduIndex: def fetch_index_data(self): # Code to fetch index data from Baidu search engine return "Baidu index data" # sogou.py class SogouIndex: def fetch_index_data(self): # Code to fetch index data from Sogou search engine return "Sogou index data" # toutiao.py class ToutiaoIndex: def fetch_index_data(self): # Code to fetch index data from Toutiao search engine return "Toutiao index data"
#!/bin/bash nodename="localhost.localdomain/redisnode2" docker stop $nodename exit 0
import argparse import os, os.path import json import logging class cmdOptions(): pass def __parse_cmd_args(options_namespace): arg_parser = argparse.ArgumentParser( description='A tool to manage differential file uploads to an Amazon Glacier repository') arg_parser.add_argument("-i", '--account-id', help='The AWS ID of the account that owns the specified vault') arg_parser.add_argument("-p", '--aws-profile', help='If supplied, the "--profile" switch will be passed to the AWS CLI for credential \ management.') arg_parser.add_argument("-d", '--database', help='The database name to connect to.') arg_parser.add_argument("-v", '--debug', help='If passed, the default logging level will be set to DEBUG.', action='store_true') arg_parser.add_argument("-l", '--logging-dir', help='The log will be stored in this directory, if passed.', default=os.path.expanduser('~')) arg_parser.add_argument("-c", '--config-file', help='Loads options from a config file.', default=os.path.expanduser("~/.cupo.json")) subparsers = arg_parser.add_subparsers( help="Run cupo *option* --help for more info on each command.", dest="subparser_name") arg_parser_backup = subparsers.add_parser('backup', help="Execute incremental backup of a directory to an Amazon Glacier \ vault, and prune any outdated archives.") arg_parser_backup.add_argument("-b", '--backup_directory', help='The top directory to back up', metavar='top_dir') arg_parser_backup.add_argument("-n", '--vault_name', help='The name of the vault to upload the archive to') arg_parser_backup.add_argument('--no-backup', help='If passed, the backup operation will not take place, going straight to the \ maintenance operations', action='store_true') arg_parser_backup.add_argument('--no-prune', help='If passed, the process of finding and removing old archives will not take place.', action='store_true') arg_parser_backup.add_argument('--dummy-upload', help='If passed, the archives will not be uploaded, but a dummy AWS URI and archive \ ID will be generated. Use for testing only.', action='store_true') arg_parser_backup.add_argument("--temp-dir", help="If passed, the specified directory will be used to store temporary upload and \ download chunks. Use when the drive with the default tempdir has little \ available space") arg_parser_backup.add_argument("-x", "--max-files", help="If passed, the maximum amount of files that should exist in a single archive\ before a subsequent archive is created to continue backing up the directory.\ Use with directories with large numbers of files") arg_parser_retrieve = subparsers.add_parser('retrieve', help="Retrieve a directory tree from the specified vault and download \ it to the local system.") arg_parser_retrieve.add_argument("-n", '--vault_name', help='The name of the vault to download from.') arg_parser_retrieve.add_argument("-r", '--top_path', help="The relative directory of the top directory to download. Use --list for a \ list of directories available.") arg_parser_retrieve.add_argument('--download_location', help="The local directory to download the file tree to.") arg_parser_retrieve.add_argument("--temp-dir", help="If passed, the specified directory will be used to store temporary upload and \ download chunks. Use when the drive with the default tempdir has little \ available space") arg_parser_retrieve.add_argument('--list', help="Print a list of the directories available for download.", action='store_true', dest="list_uploaded_archives") arg_parser_new_vault = subparsers.add_parser('new-vault', help="Add a new vault to the specified Glacier account, and register \ it with the local database.") arg_parser_new_vault.add_argument('new_vault_name', help='The name of the new vault to create.') arg_parser_new_config = subparsers.add_parser('sample-config', help="Create a sample configuration file that can be passed to Cupo \ by --config-file.") arg_parser_new_config.add_argument('sample_file_location', help='The path and filename for the generated \ config file.') args = arg_parser.parse_args(namespace=options_namespace) def __load_config_file_args(config_file_path, options_namespace): with open(config_file_path) as conf_f: config_opts = json.load(conf_f) for k in config_opts.viewkeys(): # Don't overwrite options that have been explicitly set on the command line if not hasattr(options_namespace, k) or not getattr(options_namespace, k): # Add the config option to the global options object setattr(options_namespace, k, config_opts[k]) def parse_args(): # Creating a separate object so that both argparse'd switches and config file # options can be accessed from the same object cmd_opts = cmdOptions() __parse_cmd_args(cmd_opts) if hasattr(cmd_opts, "config_file") and cmd_opts.config_file: print "Config file:", cmd_opts.config_file if os.path.exists(cmd_opts.config_file): __load_config_file_args(cmd_opts.config_file, cmd_opts) else: logging.error( "Config file does not exist. Use '--config-file' to specify a location or create a file at ~/.cupo.json") exit(1) if not hasattr(cmd_opts, "aws_profile"): setattr(cmd_opts, "aws_profile", None) return cmd_opts def create_config_file(file_location): config_opts = {"database": "", "vault_name": "", "account_id": "", "aws_profile": "", "debug": False, "logging_dir": "", "backup_directory": "", "temp_dir":"", "max_files": 999 } with open(file_location, "w") as f: json.dump(config_opts, f, indent=4, separators=(",", ": "))
# ----------------------------------------------------------------------------- # # Package : denque # Version : 1.5.0 # Source repo : https://github.com/invertase/denque # Tested on : RHEL 8.3 # Script License: Apache License, Version 2 or later # Maintainer : BulkPackageSearch Automation <sethp@us.ibm.com> # # Disclaimer: This script has been tested in root mode on given # ========== platform using the mentioned version of the package. # It may not work as expected with newer versions of the # package and/or distribution. In such case, please # contact "Maintainer" of this script. # # ---------------------------------------------------------------------------- PACKAGE_NAME=denque PACKAGE_VERSION=1.5.0 PACKAGE_URL=https://github.com/invertase/denque yum -y update && yum install -y yum-utils nodejs nodejs-devel nodejs-packaging npm python38 python38-devel ncurses git gcc gcc-c++ libffi libffi-devel ncurses git jq make cmake yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/8.3Server/ppc64le/appstream/ yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/8.3Server/ppc64le/baseos/ yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/7Server/ppc64le/optional/ yum install -y firefox liberation-fonts xdg-utils && npm install n -g && n latest && npm install -g npm@latest && export PATH="$PATH" && npm install --global yarn grunt-bump xo testem acorn OS_NAME=`python3 -c "os_file_data=open('/etc/os-release').readlines();os_info = [i.replace('PRETTY_NAME=','').strip() for i in os_file_data if i.startswith('PRETTY_NAME')];print(os_info[0])"` HOME_DIR=`pwd` if ! git clone $PACKAGE_URL $PACKAGE_NAME; then echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------" echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/clone_fails echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Clone_Fails" > /home/tester/output/version_tracker exit 0 fi cd $HOME_DIR/$PACKAGE_NAME git checkout $PACKAGE_VERSION PACKAGE_VERSION=$(jq -r ".version" package.json) # run the test command from test.sh if ! npm install && npm audit fix && npm audit fix --force; then echo "------------------$PACKAGE_NAME:install_fails-------------------------------------" echo "$PACKAGE_URL $PACKAGE_NAME" echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_Fails" exit 0 fi cd $HOME_DIR/$PACKAGE_NAME if ! npm test; then echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------" echo "$PACKAGE_URL $PACKAGE_NAME" echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_success_but_test_Fails" exit 0 else echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------" echo "$PACKAGE_URL $PACKAGE_NAME" echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success" exit 0 fi
package m.co.rh.id.anavigator.example; import android.app.Activity; import android.os.Handler; import android.os.Looper; import android.view.View; import android.view.ViewGroup; import m.co.rh.id.anavigator.StatefulView; import m.co.rh.id.anavigator.component.INavigator; import m.co.rh.id.anavigator.component.RequireNavigator; public class SplashPage extends StatefulView<Activity> implements RequireNavigator { private transient INavigator mNavigator; @Override public void provideNavigator(INavigator navigator) { mNavigator = navigator; // example simple timer, show 3 seconds then out Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { // The retry is done in provideNavigator instead of initState // this is because if saveState is enabled, this page will be restored // and provideNavigator will be executed but not initState // if this is not invoked then the screen will stuck on SplashPage mNavigator.retry(true); // splash showed to user and done }, 3000); } @Override protected View createView(Activity activity, ViewGroup container) { return activity.getLayoutInflater().inflate(R.layout.page_splash, container, false); } @Override public void dispose(Activity activity) { super.dispose(activity); mNavigator = null; } }
from rest_framework import serializers class AQHeaderSerializer(serializers.Serializer): BatteryVoltage = serializers.FloatField(required=False) COFinal = serializers.FloatField(required=False) COOffset = serializers.FloatField(required=False) COPrescaled = serializers.FloatField(required=False) COScaled = serializers.FloatField(required=False) COSerialNumber = serializers.IntegerField(required=False) COSlope = serializers.FloatField(required=False) COStatus = serializers.CharField(required=False) GasProtocol = serializers.IntegerField(required=False) GasStatus = serializers.CharField(required=False) Humidity = serializers.FloatField(required=False) Latitude = serializers.FloatField(required=False) Longitude = serializers.FloatField(required=False) Name = serializers.CharField(required=False) NO2Final = serializers.FloatField(required=False) NO2Offset = serializers.FloatField(required=False) NO2Prescaled = serializers.FloatField(required=False) NO2Scaled = serializers.FloatField(required=False) NO2SerialNumber = serializers.IntegerField(required=False) NO2Slope = serializers.FloatField(required=False) NO2Status = serializers.CharField(required=False) NOFinal = serializers.FloatField(required=False) NOOffset = serializers.FloatField(required=False) NOPrescaled = serializers.FloatField(required=False) NOScaled = serializers.FloatField(required=False) NOSerialNumber = serializers.IntegerField(required=False) NOSlope = serializers.FloatField(required=False) NOStatus = serializers.CharField(required=False) O3Final = serializers.FloatField(required=False) O3Offset = serializers.FloatField(required=False) O3Prescaled = serializers.FloatField(required=False) O3Scaled = serializers.FloatField(required=False) O3SerialNumber = serializers.IntegerField(required=False) O3Slope = serializers.FloatField(required=False) O3Status = serializers.CharField(required=False) OtherInfo = serializers.CharField(required=False) P1 = serializers.IntegerField(required=False) P2 = serializers.IntegerField(required=False) P3 = serializers.IntegerField(required=False) PodFeaturetype = serializers.IntegerField(required=False) Pressure = serializers.FloatField(required=False) SO2Final = serializers.FloatField(required=False) SO2Offset = serializers.FloatField(required=False) SO2Prescaled = serializers.FloatField(required=False) SO2Scaled = serializers.FloatField(required=False) SO2SerialNumber = serializers.IntegerField(required=False) SO2Slope = serializers.FloatField(required=False) SO2Status = serializers.CharField(required=False) StationID = serializers.IntegerField(required=False) Temperature = serializers.FloatField(required=False) Timestamp = serializers.CharField(required=False) # The inner list in the following serialisation is actually '[integer, float]' # but that's not specified here because I can't see any way to do so. # e.g. saying child=serializers.FloatField() results in the integer # being promoted to a float class AQDataSerializer(serializers.Serializer): Header = AQHeaderSerializer() Readings = serializers.ListField( child=serializers.ListField(min_length=2, max_length=2) ) SensorType = serializers.CharField() # date_from, date_to, Description are not necessarily populated # in all entries, hence required=False class AQConfigSerializer(serializers.Serializer): acp_id = serializers.CharField(source='StationID') acp_lat = serializers.FloatField(source='Latitude') acp_lng = serializers.FloatField(source='Longitude') date_from = serializers.CharField(required=False) date_to = serializers.CharField(required=False) Description = serializers.CharField(required=False) FeedID = serializers.CharField() Latitude = serializers.FloatField() Longitude = serializers.FloatField() Name = serializers.CharField() SensorTypes = serializers.ListField(child=serializers.CharField()) StationID = serializers.CharField() class AQListSerializer(serializers.Serializer): aq_list = AQConfigSerializer(many=True)
<reponame>bensallen/zackup class HostConfig < ActiveRecord::Base belongs_to :host belongs_to :config_item validates_uniqueness_of :config_item_id, :scope => :host_id,:message => "This settings is already set for this host" def name item = self.config_item if item return item.name else return 'empty' end end def parent_name item = ConfigItem.find(self.config_item.parent_id) if item return item.name else return 'empty' end end def configurable? item = self.config_item if item return item.configurable else return nil end end def display_type item = self.config_item if item return item.display_type else return 'empty' end end end
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Button } from 'nr1'; import { add, sub, getDaysInMonth, endOfMonth, startOfMonth, getISODay } from 'date-fns'; import { Day } from '.'; const MONTHS = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; export default class Calendar extends PureComponent { constructor(props) { super(props); const today = new Date(); const convertedDate = this.convertDate(today); this.state = { ...convertedDate }; } convertDate = date => { return { currentDate: date, currentMonth: date.getMonth(), currentYear: date.getFullYear(), firstDayOfMonth: getISODay(startOfMonth(date)), daysInCurrentMonth: getDaysInMonth(date), lastDayOfMonth: getISODay(endOfMonth(date)) }; }; handlePreviousMonth = () => { const { currentDate } = this.state; const convertedDate = this.convertDate(sub(currentDate, { months: 1 })); this.setState({ ...convertedDate }); }; handleNextMonth = () => { const { currentDate } = this.state; const convertedDate = this.convertDate(add(currentDate, { months: 1 })); this.setState({ ...convertedDate }); }; render() { const daysComponents = []; const { slo } = this.props; const { currentYear, currentMonth, firstDayOfMonth, lastDayOfMonth, daysInCurrentMonth } = this.state; Array.from({ length: firstDayOfMonth - 1 }).forEach((_, index) => daysComponents.push(<div key={`${index}-1`} className="day-container" />) ); Array.from({ length: daysInCurrentMonth }).forEach((_, index) => { daysComponents.push( <Day key={index} date={new Date(currentYear, currentMonth, index + 1)} slo={slo} /> ); }); if (lastDayOfMonth > 0) { Array.from({ length: 7 - lastDayOfMonth }).forEach((_, index) => daysComponents.push( <div key={`${index}-2`} className="day-container" /> ) ); } return ( <div className="calendar-container"> <div className="calendar"> <div className="calendar__month"> <Button onClick={this.handlePreviousMonth} type={Button.TYPE.NORMAL} > Previous </Button> <div> {MONTHS[this.state.currentMonth]} {this.state.currentYear} </div> <Button onClick={this.handleNextMonth} type={Button.TYPE.NORMAL}> Next </Button> </div> <div className="calendar__weekdays"> <div>Monday</div> <div>Tuesday</div> <div>Wednesday</div> <div>Thursday</div> <div>Friday</div> <div>Saturday</div> <div>Sunday</div> </div> <div className="calendar__days">{daysComponents}</div> </div> </div> ); } } Calendar.propTypes = { slo: PropTypes.object.isRequired };
import { atom, useRecoilState } from 'recoil'; export const currentFiltersJsonState = atom<string>({ key: 'currentFiltersJsonState', default: ('') }); export const useFilterState = () => { const [filters, setFilters] = useRecoilState(currentFiltersJsonState); const updateFilters = (newFilters: string) => { setFilters(newFilters); }; return { filters, updateFilters }; };
<reponame>georgelam6/SLECS<gh_stars>0 #pragma once #include <unordered_map> #include <array> #include <cassert> #include "ECSCommon.h" class IComponentArray { public: virtual ~IComponentArray() = default; virtual void EntityDestroyed(EntityHandle ent) = 0; }; template <typename T> class ComponentArray : public IComponentArray { private: std::array<T, MAX_COMPONENTS> m_componentArray; std::unordered_map<EntityHandle, size_t> m_entityToIndexMap; std::unordered_map<size_t, EntityHandle> m_indexToEntityMap; size_t m_size; public: inline void InsertData(EntityHandle ent, T component) { assert(m_entityToIndexMap.find(ent) == m_entityToIndexMap.end() && "Component added to same entity more than once."); size_t newIndex = m_size; m_entityToIndexMap[ent] = newIndex; m_indexToEntityMap[newIndex] = ent; m_componentArray[newIndex] = component; ++m_size; } inline void RemoveData(EntityHandle ent) { assert(m_entityToIndexMap.find(ent) != m_entityToIndexMap.end() && "Removing non-existent component."); size_t indexOfRemovedEntity = m_entityToIndexMap[ent]; size_t indexOfLastElement = m_size - 1; m_componentArray[indexOfRemovedEntity] = m_componentArray[indexOfLastElement]; EntityHandle entityOfLastElement = m_indexToEntityMap[indexOfLastElement]; m_entityToIndexMap[entityOfLastElement] = indexOfRemovedEntity; m_indexToEntityMap[indexOfRemovedEntity] = entityOfLastElement; m_entityToIndexMap.erase(ent); m_indexToEntityMap.erase(indexOfLastElement); --m_size; } inline T& GetData(EntityHandle ent) { assert(m_entityToIndexMap.find(ent) != m_entityToIndexMap.end() && "Retrieving non-existent component."); return m_componentArray[m_entityToIndexMap[ent]]; } inline void EntityDestroyed(EntityHandle ent) override { if (m_entityToIndexMap.find(ent) != m_entityToIndexMap.end()) { RemoveData(ent); } } };
<reponame>drkitty/cyder from itertools import chain, imap, groupby import re from dhcp_objects import (Option, Group, Host, Parameter, Pool, Allow, Deny, Subnet, ) key_table = [(Option, 'options'), (Group, 'groups'), (Host, 'hosts'), (Parameter, 'parameters'), (Pool, 'pools'), (Allow, 'allow'), (Deny, 'deny'), (Subnet, 'subnets'), ('mac', 'mac'), ('start', 'start'), ('end', 'end'), ('fqdn', 'fqdn'), ('match' , 'match')] def get_key(obj): for o, k in key_table: if obj is o: return k raise Exception("key {0} was not found".format(obj)) def prepare_arguments(attrs, exclude_list=None, **kwargs): exclude_list = exclude_list or [] new_kwargs = {} dicts = [d for d in attrs if type(d) is dict] kwargs.update(dict(chain(*map(lambda x: x.items(), dicts)))) attrs = [a for a in attrs if not (type(a) is dict)] for k, g in groupby(sorted(attrs, key=type), type): key = get_key(k) kwargs[key] = list(g) if not key in exclude_list else list(g)[0] return dict(new_kwargs.items() + kwargs.items()) mac_match = "(([0-9a-fA-F]){2}:){5}([0-9a-fA-F]){2}$" is_mac = re.compile(mac_match) is_ip = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
#!/bin/bash set -euo pipefail echo "#############################" echo "# LOAD MODULES" type module >& /dev/null || source /mnt/software/Modules/current/init/bash module purge module load git module load gcc/4.9.2 CCACHE_BASEDIR=$PWD module load ccache/3.3.4 module load boost/1.60 module load ninja/1.7.1 module load cmake/3.2.2 module load hdf5-tools/1.8.14 module load zlib/1.2.8 module load htslib/1.3.1 echo "#############################" echo "# PRE-BUILD HOOK" echo "## Check formatting" ./tools/check-formatting --all (cd libcpp && git clean -xdf) (cd pbbam && git clean -xdf) echo "#############################" echo "# BUILD" rm -rf build mkdir -p build cd build cmake \ -DCMAKE_BUILD_TYPE=ReleaseWithAssert \ -DHDF5_ROOT=$HDF5_DIR \ -GNinja \ .. sed -i -e 's@/-I@/ -I@g' build.ninja ninja cd .. echo "#############################" echo "# TEST" export PATH=$PWD/build:$PATH mkdir -p test-reports module purge module load gcc/4.9.2 module load hdf5-tools/1.8.14 module load zlib/1.2.8-cloudflare module load htslib/1.3.1 module load samtools module load cram/0.7 #make -f cram.mk \ # XUNIT="--xunit-file=$PWD/test-reports/blasr-cram_xunit.xml" \ # cramfast make -f cram.mk \ cramfast exit $?
<filename>pkg/store/transport.go<gh_stars>1-10 package store import ( "github.com/opencars/wanted/pkg/model" ) // Transport is a wrapper for slice of WantedVehicle. type Transport []model.Vehicle // Len is the number of elements in the collection. func (t Transport) Len() int { return len(t) } // Less reports whether the element with // index i should sort before the element with index j. func (t Transport) Less(i, j int) bool { return t[i].CheckSum < t[j].CheckSum } // Swap swaps the elements with indexes i and j. func (t Transport) Swap(i, j int) { t[i], t[j] = t[j], t[i] } // Search returns id of element, which has specified ID. // Transport array should be pre-sorted. // // Uses binary-search algorithm under the hood. // More about algorithm: https://en.wikipedia.org/wiki/Binary_search_algorithm. func (t Transport) Search(id string) int { return t.search(0, len(t), id) } func (t Transport) search(from, to int, id string) int { pivot := (to-from)/2 + from if to-from <= 0 { return -1 } if id == t[pivot].CheckSum { return pivot } if id > t[pivot].CheckSum { return t.search(pivot+1, to, id) } return t.search(from, pivot, id) }
#!/bin/bash . path.sh python3 tfsr/tfsr/data/save_speech_data.py \ --path-base=$DATA_PATH \ --prep-data-shard=10 \ --prep-data-name=timit \ --path-vocab=egs/data/timit_61.vocab \ --feat-type=graves13 \ --feat-dim=123 \ --path-train-json=train_61.json \ --path-valid-json=valid_61.json \ --path-test-json=test_61.json \ --path-wrt-tfrecord=tfrecord_graves \ --prep-data-unit=word \ --decoding-from-npy=True
#!/usr/bin/env bash source $(dirname $0)/common.sh if [ $# -gt 0 ]; then $kafka_home/bin/kafka-console-producer.sh --topic $1 --broker-list $all_brokers else echo "Usage: "$(basename $0)" <topic>" fi
<gh_stars>10-100 /* * Copyright (c) 2016 ARM Limited. All rights reserved. */ #ifndef TEST_NS_NVM_HELPER_H #define TEST_NS_NVM_HELPER_H #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> bool test_ns_nvm_helper_write(); bool test_ns_nvm_helper_read(); bool test_ns_nvm_helper_delete(); bool test_ns_nvm_helper_concurrent_requests(); bool test_ns_nvm_helper_platform_error(); bool test_ns_nvm_helper_platform_error_in_write(); #ifdef __cplusplus } #endif #endif // TEST_NS_NVM_HELPER_H
<reponame>NischalKash/Ruby_Assignment_1 def sorted_squares(a) a.map! { |num| num**2 }.sort end def move_zeros(a) c = a.count a.delete(0) zero_count = c - a.count a.fill(0, a.size, zero_count) end def group_anagrams(a) res = Hash.new{ |h,k| h[k] = Array.new } # puts res a.each do |s| sorted_str = s.chars.sort.join # puts sorted_str if res[sorted_str] res[sorted_str] << s else res[sorted_str] = [s] end end res.values end # Part 2 # @param [Object] str def reverse_words(str) str = str.strip.gsub(/\s\s+/, ' ') words_list = str.split(' ') words_list = words_list.reverse # puts words_list.inspect res = [] words_list.each do |word| # puts word vowel_str = '' word.chars.to_a.each do |ch| # puts ch if ch =~ /[aeiouAEIOU]/ vowel_str << ch # puts ch word = word.delete(ch) # puts word end end word += vowel_str res << word end res_str = res.join(' ') res_str.downcase end def highest_frequency_word(s) words_list = s.gsub(Regexp.union(['!', '?', ',', '\'', ';', '.']), ' ').split.map(&:downcase) # puts words_list res = Hash.new{} words_list.each do |word| if res[word] res[word] += 1 else res[word] = 1 end end max_freq = 1 max_freq_word = words_list[0] res.each do |name, values| if values > max_freq max_freq_word = name max_freq = values end end max_freq_word #res.max_by{ |k,v| v }[0] end # @param [Object] s # @return [TrueClass, FalseClass] def palindrome?(s) if s == '' return true end str = s.gsub(/[^0-9a-zA-Z ]/i, '') str = str.gsub(/\s+/, "").downcase i = 0 j = str.length - 1 while i < j return false if str[i] != str[j] i += 1 j -= 1 end true end class Beverage def initialize(name, price) raise ArgumentError, 'Argument is nil or ""' unless name != nil && name != '' raise ArgumentError, 'Argument is nil or <0' unless price != nil && price >= 0 @name = name @price = '%0.2f' % price end attr_accessor :name attr_accessor :price # @return [String] def formatted_price res = '' res_list = Array.new res_list = @price.to_s.split('.') res_list = res_list.map(&:to_i) if (res_list[0] == 0 && res_list[1] == 0) || (res_list.count == 1 && res_list[0] == 0) res = "Free" else if res_list.count == 1 || (res_list.count == 2 && res_list[1] == 0) if res_list[0] > 1 res = res_list[0].to_s + ' dollars only' else res = res_list[0].to_s + ' dollar only' end elsif res_list[0] == 0 and res_list.count == 2 if res_list[1] > 1 #puts res_list[1] res = res_list[1].to_s + ' cents only' else #puts res_list[1] res = res_list[1].to_s + ' cent only' end else if res_list[0] == 0 res = '' elsif res_list[0] > 1 res = res_list[0].to_s + ' dollars ' else res = res_list[0].to_s + ' dollar ' end if res_list[1] == 0 res = res elsif res_list[1] > 1 res = res != '' ? res + 'and ' + res_list[1].to_s + ' cents only' : res + res_list[1].to_s + ' cents only' else res = res != '' ? res + 'and ' + res_list[1].to_s + ' cent only' : res + res_list[1].to_s + ' cent only' end end end end end puts sorted_squares([-4, -1, 0, 3, 10]).inspect puts move_zeros([1, 0, 2, 8, 0, 0, 7]).inspect puts group_anagrams(['elbow', 'cried', 'below', 'cider']).inspect puts reverse_words(' hello world! ') puts highest_frequency_word('How Are a!re you Doing?') puts palindrome?('popa') b2 = Beverage.new('Mocha Latte',0) puts b2.formatted_price