text
stringlengths
1
1.05M
<filename>src/contexts/navigation/GalleryNavigationProvider.tsx import { createContext, ReactNode, useContext, useEffect, useMemo, useState } from 'react'; import { FADE_TIME_MS } from 'components/FadeTransitioner/FadeTransitioner'; import { useRouter } from 'next/router'; import { useTrack } from 'contexts/analytics/AnalyticsContext'; type GalleryNavigationContextType = { historyStackLength: number; historyStack: string[] }; const GalleryNavigationContext = createContext<GalleryNavigationContextType | undefined>(undefined); function useGalleryNavigationContext() { const value = useContext(GalleryNavigationContext); if (!value) { throw new Error('Missing GalleryNavigationContext somewhere above this component.'); } return value; } type Props = { children: ReactNode; }; export function GalleryNavigationProvider({ children }: Props) { const [historyStackLength, setHistoryStackLength] = useState(0); const { asPath } = useRouter(); // This is a flattened list of all the paths the user has visited. Nothing gets popped off, unlike the browser history. const [historyStack, setHistoryStack] = useState<string[]>([]); const track = useTrack(); useEffect(() => { // history setHistoryStack((stack) => [...stack, asPath]); // analytics track('Page view', { path: asPath }); }, [asPath, track]); useEffect(() => { const originalPushState = window.history.pushState; window.history.pushState = (...args) => { // This function is here to fix a scroll jank issue with the TransitionGroups // Scroll restoration from Next.JS seems to work fine out of the box without // the transition group. Upon a transition, the scroll position jumps to the top // of the page even though the height hasn't changed. // // To solve the above issue, upon a navigation push // We get the current scroll position (the correct one), and then // we listen for the jank scroll (this should happen exactly once) // We then scroll back to the saved scroll position caught a few ms ago. function setupScrollJankFix() { let scrollY = window.scrollY; function handleScroll() { /** * !!! WARNING !!! * * This is quite possibly one of the worst crimes I've committed to date. * * THE LONG-TERM PLAN is to have a context that keeps track of the user's * scroll position at various pages, and we can toss this file and its window * location madness. * * Now for the explanation.... * * We currently have a hack that overrides the browser's own attempt to * place the user at their intended scroll position to prevent jank that * coincides with our fade transition. * * Unfortunately, we end up shooting ourselves in the foot if the user * hasn't scrolled at all. If the user doesn't scroll and they navigate * to another page, the browser doesn't try to restore their scroll, * and we end up overriding the subsequent *active* scroll made by the * user themselves. More specifically: * 1) User scroll at 0 * 2) User navigates to another page * 3) User arrives at 0 * 4) User begins scrolling * 5) Our hack rejects their scroll, restores scroll back to 0 * 6) User experiences jank and is thrown back to the top of the page * 7) User possibly experiences motion sickness * * THE FIX: disable our hack if the user is sufficiently close to * the top of the page. * * THE CAVEAT: we don't want to intervene if scrollY is exactly 0, because * that signals that the browser is actively pushing the user to the next page, * and we DO want to block that default behavior – otherwise the jump occurs * before the transition begins. Thus the `window.scrollY > 0` condition. */ if (window.scrollY > 0 && window.scrollY <= 25) { window.removeEventListener('scroll', handleScroll); return; } window.scrollTo({ top: scrollY }); // This exists to delay Next.JS built in scroll restoration. // // Without this bit, the scroll restoration happens as soon as the // animation starts. This means the user will see a scroll event // happen even though the previous page hasn't fully been covered // by the white overlay. // // Once the animation kicks off, we want to have the user land // at the top of the next page. setTimeout(() => { window.scrollTo({ top: 0 }); }, FADE_TIME_MS); scrollY = window.scrollY; window.removeEventListener('scroll', handleScroll); } window.addEventListener('scroll', handleScroll); } setupScrollJankFix(); originalPushState.bind(window.history)(...args); setHistoryStackLength(window.history.state.idx ?? 0); }; function handlePopState() { const originalScrollTo = window.scrollTo; // This part exists to delay Next.JS built in scroll restoration. // // Without this bit, the scroll restoration happens as soon as the // animation starts. This means the user will see a scroll event // happen even though the previous page hasn't fully been covered // by the white overlay. // // We can fix this by intercepting the Next.JS scroll restoration // when they call popState, and delaying the actual call until // the animation is where we want it to be. // @ts-expect-error We're getting too raw here window.scrollTo = (...args) => { setTimeout(() => { // @ts-expect-error We're getting too raw here originalScrollTo(...args); }, FADE_TIME_MS); window.scrollTo = originalScrollTo; }; setHistoryStackLength(window.history.state.idx ?? 0); } window.addEventListener('popstate', handlePopState); return () => { window.history.pushState = originalPushState; window.removeEventListener('popstate', handlePopState); }; }, []); const value = useMemo<GalleryNavigationContextType>( () => ({ historyStackLength, historyStack, }), [historyStackLength, historyStack] ); return ( <GalleryNavigationContext.Provider value={value}>{children}</GalleryNavigationContext.Provider> ); } export function useCanGoBack() { const { historyStackLength } = useGalleryNavigationContext(); return historyStackLength > 0; } export function useHistoryStack() { const { historyStack } = useGalleryNavigationContext(); return historyStack; }
# Copyright 2020 The DDSP Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Library of pretrained models for use in perceptual loss functions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import tensorflow.compat.v1 as tf import tensorflow.compat.v2 as tf2 tfkl = tf2.keras.layers class UntrainedModel(object): """Base class that wrap any pretrained model.""" def __init__(self, name=''): self._name = name @property def name(self): return self._name @property def variable_scope(self): return self._name def __call__(self, audio, training): with tf.variable_scope(self.variable_scope, reuse=tf.AUTO_REUSE): outputs = self.get_outputs(audio, training) return outputs def get_outputs(self, audio, training): """Returns the output of the model, usually an embedding.""" raise NotImplementedError def trainable_variables(self): return tf.trainable_variables(scope=self.variable_scope) def crepe_keras_model(model_capacity: str, mode: str, activation='relu'): _capacity_multiplier = { 'tiny': 4, 'small': 8, 'medium': 16, 'large': 24, 'full': 32 }[model_capacity] mode_cls = 'pitch_idx_classifier' mode_reg = 'pitch_idx_regressor' assert mode in [mode_cls, mode_reg] model = tf.keras.Sequential() k = tf.keras.layers # short-cut for readability layer_ids = [1, 2, 3, 4, 5, 6] filters = [n * _capacity_multiplier for n in [32, 4, 4, 4, 8, 16]] widths = [512, 64, 64, 64, 64, 64] # note that unlike original crepe, there's no stride of (4, 1) at layer=1 # because we need 250 f0 prediction per second strides = [(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)] model.add(k.Reshape((64000, 1, 1), input_shape=(64000,))) for l, f, w, s in zip(layer_ids, filters, widths, strides): model.add( k.Conv2D( f, (w, 1), strides=s, padding='same', name='conv%d' % l)) model.add(k.BatchNormalization(name='conv%d-BN' % l)) model.add(k.Activation(activation, name='%s-%d' % (activation, l))) model.add( k.MaxPool2D( pool_size=(2, 1), strides=None, padding='valid', name='conv%d-maxpool' % l)) model.add(k.Dropout(0.25, name='conv%d-dropout' % l)) if mode == mode_cls: model.add(k.Conv2D(360, (4, 1), padding='same', activation='sigmoid', name='dense_alternative')) # (batch, 1000, 1, 360) model.add(k.Reshape((1000, 360), name='classifier')) # (batch, 1000, 360) elif mode == mode_reg: model.add(k.Conv2D(1, (4, 1), padding='same', activation='sigmoid', name='dense_alternative')) # (batch, 1000, 1, 1) model.add(k.Lambda(lambda x: 400.0 * x - 20.0)) # now [-20, 380] model.add(k.Reshape((1000, 1), name='regressor')) # (batch, 1000, 1) return model class Crepe(tfkl.Layer): """Crepe model modified for 4-second (64000 sample) audio Paper: https://arxiv.org/pdf/1802.06182.pdf Adapted from: https://github.com/marl/crepe/blob/master/crepe/core.py """ def __init__(self, model_capacity, activation_layer, name=None): super(Crepe, self).__init__(self, name=name) self._model_capacity = model_capacity self._capacity_multiplier = { 'tiny': 4, 'small': 8, 'medium': 16, 'large': 24, 'full': 32 }[model_capacity] self._activation_layer = activation_layer self._layers = self._build_layers() def _build_layers(self): """Returns layers in the CREPE model.""" layers = [] k = tf.keras.layers # short-cut for readability layer_ids = [1, 2, 3, 4, 5, 6] filters = [n * self._capacity_multiplier for n in [32, 4, 4, 4, 8, 16]] widths = [512, 64, 64, 64, 64, 64] # note that unlike original crepe, there's no stride of (4, 1) at layer=1 # because we need 250 f0 prediction per second strides = [(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)] for l, f, w, s in zip(layer_ids, filters, widths, strides): layers.append( k.Conv2D( f, (w, 1), strides=s, padding='same', activation='relu', name='conv%d' % l)) layers.append(k.BatchNormalization(name='conv%d-BN' % l)) layers.append( k.MaxPool2D( pool_size=(2, 1), strides=None, padding='valid', name='conv%d-maxpool' % l)) layers.append(k.Dropout(0.25, name='conv%d-dropout' % l)) # layers.append(k.Permute((2, 1, 3), name='transpose')) # layers.append(k.Flatten(name='flatten')) # layers.append(k.Dense(360, activation='sigmoid', name='classifier')) layers.append(k.Conv2D(360, (4, 1), padding='same', activation='sigmoid', name='dense_alternative')) layers.append(k.Reshape((1000, 360), name='classifier')) return layers def call(self, audio, training=False): # returns a dict of tensors, from layer name to layer activations. assert audio.shape[1] == 64000, audio.shape y = audio for _ in range(2): y = tf.expand_dims(y, axis=-1) # [batch, length, 1, 1] activation_dict = {} for layer in self._layers: if 'BN' in layer.name or 'dropout' in layer.name: y = layer(y, training=training) else: y = layer(y) activation_dict[layer.name] = y return activation_dict # final shape: (batch, 1000, 360) class TrainableCREPE(UntrainedModel): """CREPE model.""" def __init__(self, model_capacity='tiny', activation_layer='classifier', name='crepe'): super(TrainableCREPE, self).__init__(name=name) self._model_capacity = model_capacity self._activation_layer = activation_layer self._model = None def _build_model(self): """Builds the CREPE model.""" self._model = Crepe( self._model_capacity, self._activation_layer, name=self._name) def __call__(self, audio, training): return self.get_outputs(audio, training) def get_outputs(self, audio, training): """Returns the embeddings. Args: audio: tensors of shape [batch, length=64000]. Returns: activations of shape [batch, depth] """ if self._model is None: self._build_model() batch_size = tf.shape(audio)[0] # TODO(gcj): relax this constraint by modifying the model to generate # outputs at every time point. activation_dict = self._model(audio, training) if self._activation_layer not in activation_dict: raise ValueError( 'activation layer {} not found, valid keys are {}'.format( self._activation_layer, sorted(activation_dict.keys()))) outputs = activation_dict.get(self._activation_layer) # outputs = tf.reshape(outputs, [batch_size, -1]) # post-processing to compute cent and hz should happen outside hereafter. return outputs """ Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= reshape (Reshape) (None, 64000, 1, 1) 0 _________________________________________________________________ conv1 (Conv2D) (None, 64000, 1, 128) 65664 _________________________________________________________________ conv1-BN (BatchNormalization (None, 64000, 1, 128) 512 _________________________________________________________________ conv1-maxpool (MaxPooling2D) (None, 32000, 1, 128) 0 _________________________________________________________________ conv1-dropout (Dropout) (None, 32000, 1, 128) 0 _________________________________________________________________ conv2 (Conv2D) (None, 32000, 1, 16) 131088 _________________________________________________________________ conv2-BN (BatchNormalization (None, 32000, 1, 16) 64 _________________________________________________________________ conv2-maxpool (MaxPooling2D) (None, 16000, 1, 16) 0 _________________________________________________________________ conv2-dropout (Dropout) (None, 16000, 1, 16) 0 _________________________________________________________________ conv3 (Conv2D) (None, 16000, 1, 16) 16400 _________________________________________________________________ conv3-BN (BatchNormalization (None, 16000, 1, 16) 64 _________________________________________________________________ conv3-maxpool (MaxPooling2D) (None, 8000, 1, 16) 0 _________________________________________________________________ conv3-dropout (Dropout) (None, 8000, 1, 16) 0 _________________________________________________________________ conv4 (Conv2D) (None, 8000, 1, 16) 16400 _________________________________________________________________ conv4-BN (BatchNormalization (None, 8000, 1, 16) 64 _________________________________________________________________ conv4-maxpool (MaxPooling2D) (None, 4000, 1, 16) 0 _________________________________________________________________ conv4-dropout (Dropout) (None, 4000, 1, 16) 0 _________________________________________________________________ conv5 (Conv2D) (None, 4000, 1, 32) 32800 _________________________________________________________________ conv5-BN (BatchNormalization (None, 4000, 1, 32) 128 _________________________________________________________________ conv5-maxpool (MaxPooling2D) (None, 2000, 1, 32) 0 _________________________________________________________________ conv5-dropout (Dropout) (None, 2000, 1, 32) 0 _________________________________________________________________ conv6 (Conv2D) (None, 2000, 1, 64) 131136 _________________________________________________________________ conv6-BN (BatchNormalization (None, 2000, 1, 64) 256 _________________________________________________________________ conv6-maxpool (MaxPooling2D) (None, 1000, 1, 64) 0 _________________________________________________________________ conv6-dropout (Dropout) (None, 1000, 1, 64) 0 _________________________________________________________________ dense_alternative (Conv2D) (None, 1000, 1, 360) 92520 _________________________________________________________________ classifier (Reshape) (None, 1000, 360) 0 ================================================================= Total params: 487,096 Trainable params: 486,552 Non-trainable params: 544 _________________________________________________________________ """
<filename>app/components/SidebarMenu/index.js<gh_stars>1-10 import React from 'react'; import PropTypes from 'prop-types'; import SidebarMenuStyle from './style'; import Settings from './Settings'; import Messages from './Messages'; import Notifications from './Notifications'; export function SidebarMenu({ global }) { let template = <Settings />; if (global.toggles.sidebar.itemActived === 'Message') { template = <Messages />; } if (global.toggles.sidebar.itemActived === 'Notification') { template = <Notifications />; } return <SidebarMenuStyle id="sidebar">{template}</SidebarMenuStyle>; } SidebarMenu.propTypes = { global: PropTypes.object, }; export default SidebarMenu;
public class Student { // instance variables int rollNum; String name; int age; // Constructor public Student(int rollNum, String name, int age) { this.rollNum = rollNum; this.name = name; this.age = age; } // display student details public void display() { System.out.println("Roll Num: " + rollNum); System.out.println("Name: " + name); System.out.println("Age: " + age); } }
<filename>src/main/java/patterns/proxy/withinterface/SayHelloClass.java package patterns.proxy.withinterface; public class SayHelloClass implements SayHelloInterface { public static final String REPLY_PREFIX = "Hello "; @Override public String sayHello(String name) { return REPLY_PREFIX + name; } }
<filename>code/iaas/service-discovery/server/src/main/java/io/cattle/platform/servicediscovery/deployment/impl/DefaultDeploymentUnitInstance.java package io.cattle.platform.servicediscovery.deployment.impl; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.model.Service; import io.cattle.platform.core.model.ServiceExposeMap; import io.cattle.platform.engine.process.impl.ProcessCancelException; import io.cattle.platform.object.process.StandardProcess; import io.cattle.platform.object.resource.ResourcePredicate; import io.cattle.platform.process.common.util.ProcessUtils; import io.cattle.platform.servicediscovery.api.constants.ServiceDiscoveryConstants; import io.cattle.platform.servicediscovery.api.util.ServiceDiscoveryUtil; import io.cattle.platform.servicediscovery.deployment.AbstractInstanceUnit; import io.cattle.platform.servicediscovery.deployment.DeploymentUnitInstance; import io.cattle.platform.servicediscovery.deployment.impl.DeploymentManagerImpl.DeploymentServiceContext; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; public class DefaultDeploymentUnitInstance extends AbstractInstanceUnit { protected String instanceName; public DefaultDeploymentUnitInstance(DeploymentServiceContext context, String uuid, Service service, String instanceName, Instance instance, Map<String, String> labels, String launchConfigName) { super(context, uuid, service, launchConfigName); this.instanceName = instanceName; this.instance = instance; if (this.instance != null) { exposeMap = context.exposeMapDao.findInstanceExposeMap(this.instance); } } @Override public boolean isError() { return this.instance != null && this.instance.getRemoved() != null; } @Override protected void removeUnitInstance() { if (!(instance.getState().equals(CommonStatesConstants.REMOVED) || instance.getState().equals( CommonStatesConstants.REMOVING))) { try { context.objectProcessManager.scheduleStandardProcessAsync(StandardProcess.REMOVE, instance, null); } catch (ProcessCancelException e) { context.objectProcessManager.scheduleProcessInstanceAsync(InstanceConstants.PROCESS_STOP, instance, ProcessUtils.chainInData(new HashMap<String, Object>(), InstanceConstants.PROCESS_STOP, InstanceConstants.PROCESS_REMOVE)); } } } @Override public DeploymentUnitInstance create(Map<String, Object> deployParams) { if (createNew()) { Map<String, Object> launchConfigData = populateLaunchConfigData(deployParams); Pair<Instance, ServiceExposeMap> instanceMapPair = context.exposeMapDao.createServiceInstance(launchConfigData, service, this.instanceName); this.instance = instanceMapPair.getLeft(); this.exposeMap = instanceMapPair.getRight(); } if (instance.getState().equalsIgnoreCase(CommonStatesConstants.REQUESTED)) { context.objectProcessManager.scheduleStandardProcessAsync(StandardProcess.CREATE, instance, null); } if (exposeMap.getState().equalsIgnoreCase(CommonStatesConstants.REQUESTED)) { context.objectProcessManager.scheduleStandardProcessAsync(StandardProcess.CREATE, exposeMap, null); } this.instance = context.objectManager.reload(this.instance); return this; } @SuppressWarnings("unchecked") protected Map<String, Object> populateLaunchConfigData(Map<String, Object> deployParams) { Map<String, Object> launchConfigData = ServiceDiscoveryUtil.buildServiceInstanceLaunchData(service, deployParams, launchConfigName, context.allocatorService); launchConfigData.put("name", this.instanceName); Object labels = launchConfigData.get(InstanceConstants.FIELD_LABELS); if (labels != null) { String overrideHostName = ((Map<String, String>) labels) .get(ServiceDiscoveryConstants.LABEL_OVERRIDE_HOSTNAME); if (StringUtils.equalsIgnoreCase(overrideHostName, "container_name")) { launchConfigData.put(InstanceConstants.FIELD_HOSTNAME, this.instanceName); } } return launchConfigData; } @Override public boolean createNew() { return this.instance == null; } @Override public DeploymentUnitInstance waitForStartImpl() { this.instance = context.resourceMonitor.waitFor(this.instance, new ResourcePredicate<Instance>() { @Override public boolean evaluate(Instance obj) { return InstanceConstants.STATE_RUNNING.equals(obj.getState()); } }); return this; } @Override protected boolean isStartedImpl() { return context.objectManager.reload(this.instance).getState().equalsIgnoreCase(InstanceConstants.STATE_RUNNING); } @Override public void waitForNotTransitioning() { if (this.instance != null) { this.instance = context.resourceMonitor.waitForNotTransitioning(this.instance); } } }
<gh_stars>0 import React from 'react'; // Pages import Lobby from 'modules/user/view/pages/Lobby'; import { Route } from 'react-router-dom'; const UserRoutes = (): JSX.Element[] => [ <Route path="/" key="lobby" exact component={Lobby} />, ]; export default UserRoutes;
<reponame>Lloret82/work-with const router = require("express").Router() const apiRoutes = require("./api") const htmlRoutes = require("./html") // const withAuth = require('../utils/auth'); // const User = require('../models/user'); router.use("/api", apiRoutes) router.use("/", htmlRoutes) //upload function router.get("/upload", async (req, res) => { res.render("upload") }) module.exports = router
<gh_stars>0 export * from './unsupportedOperationError';
import React from 'react' import { Link } from 'gatsby' import PropTypes from 'prop-types' import styled from 'styled-components' import LoginButton from './login' const Container = styled.div` display: grid; grid-template-columns: 1fr 26px; margin: 0 1rem 0 1rem; max-width: 768px; padding: 0.75rem 0 1rem 0; border-bottom: 1px solid #32374C; @media (min-width: 768px) { & { margin: 0 auto; } } ` const Title = styled.h1` grid-column-start: 1; margin: 0; text-align: left; font-size: 1.5rem; ` const StyledLink = styled(Link)` color: #addb67; ` const Header = ({ siteTitle }) => ( <Container> <Title> <StyledLink to="/"> {siteTitle} </StyledLink> </Title> <LoginButton /> </Container> ) Header.propTypes = { siteTitle: PropTypes.string.isRequired } export default Header
python train.py \ --mode 'multi_kpcn' \ --input_channels 34 \ --hidden_channels 100 \ --num_layer 9 \ --eps 0.00316 \ --do_val \ --lr 1e-5 \ --epochs 40 \ --loss 'L1' \ --data_dir '/root/kpcn_data/kpcn_data/data'
export * from './cepMask' export * from './cpfMask' export * from './cnpjMask' export * from './cpfCnpjMask' export * from './phoneMask'
<gh_stars>0 package springcourse.exercises.exercise4; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import springcourse.exercises.exercise4.model.Book; import springcourse.exercises.exercise4.model.Member; import java.util.Collection; /** * @author <NAME> * @since 3/24/14 */ public class Main { private static Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); Library library = applicationContext.getBean(Library.class); // Commended code 1 /*Collection<Book> allBooks = library.getAllBooks(); Assert.assertNotNull(allBooks); Assert.assertTrue(allBooks.size() >= 5); logger.info("There are {} books", allBooks.size());*/ // Commended code 2 /*Collection<Member> allMembers = library.getAllMembers(); Assert.assertNotNull(allMembers); Assert.assertTrue(allMembers.size() >= 3); logger.info("There are {} members", allMembers.size());*/ } }
<gh_stars>0 import React from 'react' import Helmet from 'react-helmet' export default ({ description = '<NAME> | Full-Stack Developer', lang = 'en', meta = '', keywords = [], title = '' }) => { return ( <Helmet htmlAttributes={{ lang, }} title={title} meta={[ { name: 'description', content: description, }, { property: 'og:title', content: title, }, { property: 'og:description', content: description, }, { property: 'og:type', content: 'website', }, { name: 'twitter:card', content: 'summary', }, { name: 'twitter:creator', content: '<NAME>', }, { name: 'twitter:title', content: title, }, { name: 'twitter:description', content: description, }, ] .concat( keywords && keywords.length > 0 ? { name: 'keywords', content: keywords.join(', '), } : [] ) .concat(meta)} /> ) }
func calculateAverageScore(_ scores: [Int]) -> Double { guard !scores.isEmpty else { return 0 } let sum = scores.reduce(0, +) return Double(sum) / Double(scores.count) } // Test cases let testScores1 = [85, 90, 92, 88, 78] let testScores2: [Int] = [] print(calculateAverageScore(testScores1)) // Output: 86.6 print(calculateAverageScore(testScores2)) // Output: 0.0
function searchTree(node, query) { if (node.value == query) { return true; } if (!node.left && !node.right) { return false; } return searchTree(node.left, query) || searchTree(node.right, query); }
#!/bin/bash set -e set -u if [ -e ../../configure.sh ]; then source ../../configure.sh elif [ -e ../configure.sh ]; then source ../configure.sh elif [ -e ./configure.sh ]; then source ./configure.sh else echo "Error: Could not find 'configure.sh'!" exit 1 fi if [[ $# -ne 1 ]]; then echo "Usage: mount.sh <image ID>" exit 1 fi if check_number $1; then echo "Usage: mount.sh <image ID>" exit 1 fi IID=${1} if check_root; then echo "Error: This script requires root privileges!" exit 1 fi echo "----Running----" WORK_DIR=`get_vm ${IID}` IMAGE=`get_fs ${IID}` IMAGE_DIR=`get_fs_mount ${IID}` DEVICE=/dev/mapper/loop0p1 echo "----Adding Device File----" #/usr/bin/qemu-nbd --connect=/dev/${NBD} "${IMAGE}" kpartx -a -v "${IMAGE}" sleep 1 echo "----Making image directory----" [[ ! -e "${IMAGE_DIR}" ]] && mkdir "${IMAGE_DIR}" echo "----Mounting----" #sudo /bin/mount /dev/nbd0p1 "${IMAGE_DIR}" mount "${DEVICE}" "${IMAGE_DIR}"
package com.vxml.tag; public class MenuTag extends DoNothingTag { }
import { getDocumentLocaleSettings, getLanguage, merge, validateFormatValue } from './common.js'; function formatPositiveInteger(value, descriptor, useGrouping) { value = Math.floor(value); if (!useGrouping) { return value.toString(); } const valueStr = '' + value; let ret = ''; const groupSizes = Array.isArray(descriptor.groupSize) ? descriptor.groupSize : [descriptor.groupSize]; let currentGroupSizeIndex = -1; const maxGroupSizeIndex = groupSizes.length - 1; let currentGroupSize = 0; let groupEnd = valueStr.length; while (groupEnd > 0) { if (currentGroupSizeIndex < maxGroupSizeIndex) { currentGroupSize = groupSizes[++currentGroupSizeIndex]; } let chunk = null; if (currentGroupSize === 0) { chunk = valueStr.substring(0, groupEnd); } else { const groupStart = groupEnd - currentGroupSize; chunk = valueStr.substring(groupStart, groupEnd); } // not first or only chunk if (groupEnd !== valueStr.length) { ret = descriptor.symbols.group + ret; } ret = chunk + ret; groupEnd -= chunk.length; } return ret; } function validateFormatOptions(options) { options = options || {}; options.useGrouping = options.useGrouping !== false; if (options.style !== 'decimal' && options.style !== 'percent') { options.style = 'decimal'; } options.minimumFractionDigits = validateInteger( 'minimumFractionDigits', options.minimumFractionDigits, 0, 0, 20 ); options.maximumFractionDigits = validateInteger( 'maximumFractionDigits', options.maximumFractionDigits, Math.max(options.minimumFractionDigits, 3), 0, 20 ); if (options.minimumFractionDigits > options.maximumFractionDigits) { throw new RangeError('maximumFractionDigits value is out of range.'); } return options; } function validateInteger(name, value, defaultValue, min, max) { if (value === undefined || value === null) { value = defaultValue; } if (typeof value === 'string') { value = parseInt(value); } if (isNaN(value) || typeof value !== 'number' || (min !== undefined && value < min) || (max !== undefined && value > max)) { throw new RangeError(name + ' value is out of range.'); } return value; } export function getNumberDescriptor() { const language = getLanguage(); const subtags = language.split('-'); const baseLanguage = subtags[0]; let negativePattern = '-{number}'; if (baseLanguage === 'ar') { negativePattern = '{number}-'; } let percentPattern = '{number} %'; let percentNegativePattern = '-{number} %'; switch (baseLanguage) { case 'es': case 'hi': case 'ja': case 'pt': case 'zh': percentPattern = '{number}%'; percentNegativePattern = '-{number}%'; break; case 'tr': percentPattern = '%{number}'; percentNegativePattern = '-%{number}'; break; } let decimalSymbol = '.'; let groupSymbol = ','; switch (baseLanguage) { case 'da': case 'de': case 'es': case 'nl': case 'pt': case 'tr': decimalSymbol = ','; groupSymbol = '.'; break; case 'fr': case 'sv': decimalSymbol = ','; groupSymbol = ' '; break; } switch (language) { case 'es-mx': decimalSymbol = '.'; groupSymbol = ','; break; } const descriptor = { groupSize: 3, patterns: { decimal: { positivePattern: '{number}', negativePattern: negativePattern }, percent: { positivePattern: percentPattern, negativePattern: percentNegativePattern } }, symbols: { decimal: decimalSymbol, group: groupSymbol, negative: '-', percent: '%' } }; const settings = getDocumentLocaleSettings(); if (settings.overrides.number) { merge(descriptor, settings.overrides.number); } return descriptor; } function formatDecimal(value, options) { const descriptor = getNumberDescriptor(); value = validateFormatValue(value); options = validateFormatOptions(options); const isNegative = value < 0; value = Math.abs(value); const strValue = new Intl.NumberFormat( 'en-US', { maximumFractionDigits: options.maximumFractionDigits, minimumFractionDigits: options.minimumFractionDigits, useGrouping: false } ).format(value); let ret = formatPositiveInteger(parseInt(strValue), descriptor, options.useGrouping); const decimalIndex = strValue.indexOf('.'); if (decimalIndex > -1) { ret += descriptor.symbols.decimal + strValue.substr(decimalIndex + 1); } const pattern = isNegative ? descriptor.patterns.decimal.negativePattern : descriptor.patterns.decimal.positivePattern; ret = pattern.replace('{number}', ret); if (isNegative) { ret = ret.replace('-', descriptor.symbols.negative); } return ret; } export function formatNumber(value, options) { if (options && options.style === 'percent') { return formatPercent(value, options); } return formatDecimal(value, options); } export function formatPercent(value, options) { const descriptor = getNumberDescriptor(); value = validateFormatValue(value); const isNegative = (value < 0); value = Math.abs(value) * 100; const dec = formatDecimal(value, options); let percent = isNegative ? descriptor.patterns.percent.negativePattern : descriptor.patterns.percent.positivePattern; percent = percent.replace('{number}', dec); percent = percent.replace('%', descriptor.symbols.percent); if (isNegative) { percent = percent.replace('-', descriptor.symbols.negative); } return percent; } export function parseNumber(value) { if (value === undefined || value === null) { return 0; } const descriptor = getNumberDescriptor(); value = value.replace( new RegExp('\\s|[' + descriptor.symbols.group + ']', 'g'), '' ); if (value === '') { return 0; } let ret = ''; let negative = false; let hasDecimal = false; let breakout = false; for (let i = 0; i < value.length; i++) { let c = value.charAt(i); switch (c) { case descriptor.symbols.decimal: ret += !hasDecimal ? '.' : ''; hasDecimal = true; break; case descriptor.symbols.negative: case '(': case ')': negative = true; break; default: c = parseInt(c); if (!isNaN(c) && c >= 0 && c <= 9) { ret += c; } else { breakout = true; } } if (breakout) { break; } } if (ret.length === 0) { return NaN; } ret = parseFloat(ret); if (negative) { ret = ret * -1; } return ret; }
<filename>parameters-backend/parameters-backend-elasticsearch/src/main/java/be/kwakeroni/parameters/backend/es/api/ElasticSearchCriteria.java package be.kwakeroni.parameters.backend.es.api; import org.json.JSONObject; /** * (C) 2017 <NAME> */ public interface ElasticSearchCriteria { public void inGroup(String groupName); public void addParameterMatch(String parameter, String value); public void addParameterNotMatch(String parameter, String value); public void addParameterComparison(String parameter, String operator, Object value); public void addComplexFilter(JSONObject filter); public JSONObject toJSONObject(); }
#!/bin/bash # This script calculates simple interest given principal, # annual rate of interest and time period in years. # Do not use this in production. Sample purpose only. # Author: Upkar Lidder (IBM) # Additional Authors: # derekfkw # Input: # p, principal amount # t, time period in years # r, annual rate of interest # Output: # simple interest = p*t*r echo "Enter the principal:" read p echo "Enter rate of interest per year:" read r echo "Enter time period in years:" read t s=`expr $p \* $t \* $r / 100` echo "The simple interest is: " echo $s
<reponame>Jorch72/MagicArsenal /* * MIT License * * Copyright (c) 2018 <NAME> (Falkreon) and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.elytradev.marsenal.client; import java.util.HashSet; import java.util.Set; import com.elytradev.marsenal.ArsenalConfig; import com.elytradev.marsenal.MagicArsenal; import com.elytradev.marsenal.Proxy; import com.elytradev.marsenal.block.IItemVariants; import com.elytradev.marsenal.capability.IMagicResources; import com.elytradev.marsenal.capability.impl.MagicResources; import com.elytradev.marsenal.client.codex.XMLResourceLoader; import com.elytradev.marsenal.entity.EntityFrostShard; import com.elytradev.marsenal.entity.EntityWillOWisp; import com.elytradev.marsenal.gui.ContainerCodex; import com.elytradev.marsenal.item.ArsenalItems; import com.elytradev.marsenal.item.IMetaItemModel; import com.elytradev.marsenal.item.ISpellFocus; import com.elytradev.marsenal.item.ItemCodex; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; public class ClientProxy extends Proxy { public static MagicResources scrambleTargets = new MagicResources(); @Override public void preInit() { Emitter.register("healingSphere", HealingSphereEmitter.class); Emitter.register("drainLife", DrainLifeEmitter.class); Emitter.register("infuseLife", InfuseLifeEmitter.class); Emitter.register("disruption", DisruptionEmitter.class); Emitter.register("spellGather", SpellGatherEmitter.class); Emitter.register("magmaBlast", MagmaBlastEmitter.class); Emitter.register("lightning", LightningEmitter.class); Emitter.register("coalesce", CoalesceEmitter.class); Emitter.registerWorldEmitter("chaosorb", ChaosOrbEmitter.class); Emitter.registerWorldEmitter("radiantbeacon", RadiantBeaconEmitter.class); RenderingRegistry.registerEntityRenderingHandler(EntityFrostShard.class, RenderFrostShard::new); RenderingRegistry.registerEntityRenderingHandler(EntityWillOWisp.class, RenderWillOWisp::new); //Unsatisfactory behavior. Using WorldEmitter. //ClientRegistry.bindTileEntitySpecialRenderer(TileEntityChaosOrb.class, new RenderChaosOrb()); XMLResourceLoader.getInstance().preInit(); } @Override public void init() { } @SubscribeEvent public void registerItemModels(ModelRegistryEvent event) { for(Item item : ArsenalItems.itemsForModels()) { if (item instanceof ItemCodex) { ResourceLocation loc = Item.REGISTRY.getNameForObject(item); for(int i=0; i<ContainerCodex.CODEX_PAGES.size()+100; i++) { //TODO: This will break eventually! ModelLoader.setCustomModelResourceLocation(item, i, new ModelResourceLocation(loc, "inventory")); } ModelLoader.setCustomModelResourceLocation(item, 9000, new ModelResourceLocation(loc, "inventory")); //"Simple" book meta continue; } if (item instanceof IMetaItemModel) { String[] models = ((IMetaItemModel)item).getModelLocations(); for(int i=0; i<models.length; i++) { ModelLoader.setCustomModelResourceLocation(item, i, new ModelResourceLocation(new ResourceLocation(MagicArsenal.MODID, models[i]), "inventory")); } } else { NonNullList<ItemStack> variantList = NonNullList.create(); item.getSubItems(MagicArsenal.TAB_MARSENAL, variantList); ResourceLocation loc = Item.REGISTRY.getNameForObject(item); if (variantList.size()==1) { registerModelVariant(new ItemStack(item), loc); //ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(loc, "inventory")); } else { for(ItemStack subItem : variantList) { registerModelVariant(subItem, loc); //ModelLoader.setCustomModelResourceLocation(item, subItem.getItemDamage(), new ModelResourceLocation(loc, "variant="+subItem.getItemDamage())); } } } } } private void registerModelVariant(ItemStack stack, ResourceLocation loc) { if (stack.getItem() instanceof ItemBlock && ((ItemBlock)stack.getItem()).getBlock() instanceof IItemVariants) { Block b = ((ItemBlock)stack.getItem()).getBlock(); String variant = ((IItemVariants)b).getVariantFromItem(stack); ModelLoader.setCustomModelResourceLocation(stack.getItem(), stack.getItemDamage(), new ModelResourceLocation(loc, variant)); } else { ModelLoader.setCustomModelResourceLocation(stack.getItem(), stack.getItemDamage(), new ModelResourceLocation(loc, "variant="+stack.getItemDamage())); } } private static void drawBar(int x, int y, int width, int height, int cur, int total, int bg, int fg) { float percent = cur/(float)total; int barWidth = (int)(width*percent); if (barWidth>width) barWidth = width; Gui.drawRect(x, y, x+width, y+height, bg); if (barWidth>0) { Gui.drawRect(x, y, x+barWidth, y+height, fg); } } private static void checkForResources(EntityLivingBase caster, ItemStack stack, Set<ResourceLocation> set) { if (stack==null || stack.isEmpty()) return; if (stack.getItem() instanceof ISpellFocus) { ((ISpellFocus)stack.getItem()).addResources(caster, stack, set); } } @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.END) return; if (Minecraft.getMinecraft().player==null) return; ParticleEmitters.tick(); if (!Minecraft.getMinecraft().player.hasCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null)) return; IMagicResources res = Minecraft.getMinecraft().player.getCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null); //Scramble towards each resource value ClientProxy.scrambleTargets.forEach((resource, val)->{ int oldValue = res.getResource(resource, 0); int dist = Math.abs(val-oldValue); dist /= 2; if (dist<1) dist=1; if (val>oldValue) { res.set(resource, oldValue+dist); } else if (val<oldValue) { res.set(resource, oldValue-dist); } }); //Scramble towards the GCD target res.setMaxCooldown(ClientProxy.scrambleTargets.getMaxCooldown()); int cur = res.getGlobalCooldown(); int target = ClientProxy.scrambleTargets.getGlobalCooldown(); int delta = Math.abs(cur - target) / 2; if (delta<1) delta=1; if (cur<target) { if (res instanceof MagicResources) { ((MagicResources)res)._setGlobalCooldown(cur+delta); } else { res.setGlobalCooldown(cur+delta); } } else if (cur>target) { res.reduceGlobalCooldown(delta); } } @SubscribeEvent public void onRenderScreen(RenderGameOverlayEvent.Post evt) { EntityLivingBase player = Minecraft.getMinecraft().player; if (!player.hasCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null)) return; if (evt.getType()==ElementType.CROSSHAIRS) { IMagicResources res = player.getCapability(MagicArsenal.CAPABILTIY_MAGIC_RESOURCES, null); HashSet<ResourceLocation> relevantResources = new HashSet<ResourceLocation>(); checkForResources(player, player.getHeldItemMainhand(), relevantResources); checkForResources(player, player.getHeldItemOffhand(), relevantResources); int width = evt.getResolution().getScaledWidth(); int height = evt.getResolution().getScaledHeight(); int centerX = width/2; int centerY = height/2; if (res.getGlobalCooldown()>0) { drawBar(centerX-15, centerY+20, 32, 2, res.getGlobalCooldown(), res.getMaxCooldown(), 0xFF333333, 0xFF777777); } if (relevantResources.contains(IMagicResources.RESOURCE_STAMINA) && res.getResource(IMagicResources.RESOURCE_STAMINA, ArsenalConfig.get().resources.maxStamina)<ArsenalConfig.get().resources.maxStamina) { drawBar(centerX-15, centerY+23, 32, 2, res.getResource(IMagicResources.RESOURCE_STAMINA, ArsenalConfig.get().resources.maxStamina), ArsenalConfig.get().resources.maxStamina, 0xFF333333, 0xFF333399); } if (relevantResources.contains(IMagicResources.RESOURCE_RAGE) && res.getResource(IMagicResources.RESOURCE_RAGE, ArsenalConfig.get().resources.maxRage)<ArsenalConfig.get().resources.maxRage) { drawBar(centerX-15, centerY+26, 32, 2, res.getResource(IMagicResources.RESOURCE_RAGE, ArsenalConfig.get().resources.maxRage), ArsenalConfig.get().resources.maxRage, 0xFF333333, 0xFF993333); } } } @SubscribeEvent(priority=EventPriority.LOW) public void onRenderWorldLast(RenderWorldLastEvent event) { ParticleEmitters.draw(event.getPartialTicks(), Minecraft.getMinecraft().player); } }
export PATH=${PATH}:$HOME/.lua:$HOME/.local/bin:${TRAVIS_BUILD_DIR}/install/luarocks/bin bash -x .travis/setup_lua.sh eval `$HOME/.lua/luarocks path`
<reponame>OSWeDev/oswedev import Component from 'vue-class-component'; import { GridItem, GridLayout } from "vue-grid-layout"; import { Prop, Watch } from 'vue-property-decorator'; import ModuleDAO from '../../../../../shared/modules/DAO/ModuleDAO'; import InsertOrDeleteQueryResult from '../../../../../shared/modules/DAO/vos/InsertOrDeleteQueryResult'; import IEditableDashboardPage from '../../../../../shared/modules/DashboardBuilder/interfaces/IEditableDashboardPage'; import DashboardPageVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardPageVO'; import DashboardPageWidgetVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardPageWidgetVO'; import DashboardVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardVO'; import DashboardWidgetVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardWidgetVO'; import VOsTypesManager from '../../../../../shared/modules/VOsTypesManager'; import ConsoleHandler from '../../../../../shared/tools/ConsoleHandler'; import ThrottleHelper from '../../../../../shared/tools/ThrottleHelper'; import VueComponentBase from '../../VueComponentBase'; import { ModuleDashboardPageAction, ModuleDashboardPageGetter } from '../page/DashboardPageStore'; import ChecklistItemModalComponent from '../widgets/checklist_widget/checklist_item_modal/ChecklistItemModalComponent'; import DashboardBuilderWidgetsController from '../widgets/DashboardBuilderWidgetsController'; import CRUDCreateModalComponent from '../widgets/table_widget/crud_modals/create/CRUDCreateModalComponent'; import CRUDUpdateModalComponent from '../widgets/table_widget/crud_modals/update/CRUDUpdateModalComponent'; import './DashboardBuilderBoardComponent.scss'; import DashboardBuilderBoardItemComponent from './item/DashboardBuilderBoardItemComponent'; @Component({ template: require('./DashboardBuilderBoardComponent.pug'), components: { Gridlayout: GridLayout, Griditem: GridItem, Dashboardbuilderboarditemcomponent: DashboardBuilderBoardItemComponent, Crudupdatemodalcomponent: CRUDUpdateModalComponent, Crudcreatemodalcomponent: CRUDCreateModalComponent, Checklistitemmodalcomponent: ChecklistItemModalComponent } }) export default class DashboardBuilderBoardComponent extends VueComponentBase { public static GridLayout_TOTAL_HEIGHT: number = 720; public static GridLayout_TOTAL_ROWS: number = 72; public static GridLayout_ELT_HEIGHT: number = DashboardBuilderBoardComponent.GridLayout_TOTAL_HEIGHT / DashboardBuilderBoardComponent.GridLayout_TOTAL_ROWS; public static GridLayout_TOTAL_WIDTH: number = 1280; public static GridLayout_TOTAL_COLUMNS: number = 128; public static GridLayout_ELT_WIDTH: number = DashboardBuilderBoardComponent.GridLayout_TOTAL_WIDTH / DashboardBuilderBoardComponent.GridLayout_TOTAL_COLUMNS; @ModuleDashboardPageAction private set_page_widget: (page_widget: DashboardPageWidgetVO) => void; @ModuleDashboardPageAction private delete_page_widget: (page_widget: DashboardPageWidgetVO) => void; @ModuleDashboardPageAction private set_Checklistitemmodalcomponent: (Checklistitemmodalcomponent: ChecklistItemModalComponent) => void; @ModuleDashboardPageAction private set_Crudupdatemodalcomponent: (Crudupdatemodalcomponent: CRUDUpdateModalComponent) => void; @ModuleDashboardPageAction private set_Crudcreatemodalcomponent: (Crudcreatemodalcomponent: CRUDCreateModalComponent) => void; @ModuleDashboardPageGetter private get_widgets_invisibility: { [w_id: number]: boolean }; @Prop() private dashboard_page: DashboardPageVO; @Prop() private dashboard_pages: DashboardPageVO[]; @Prop() private dashboard: DashboardVO; @Prop({ default: null }) private selected_widget: DashboardPageWidgetVO; @Prop({ default: true }) private editable: boolean; private elt_height: number = DashboardBuilderBoardComponent.GridLayout_ELT_HEIGHT; private col_num: number = DashboardBuilderBoardComponent.GridLayout_TOTAL_COLUMNS; private max_rows: number = DashboardBuilderBoardComponent.GridLayout_TOTAL_ROWS; private widgets: DashboardPageWidgetVO[] = []; private editable_dashboard_page: IEditableDashboardPage = null; private throttled_rebuild_page_layout = ThrottleHelper.getInstance().declare_throttle_without_args(this.rebuild_page_layout.bind(this), 200); get widgets_by_id(): { [id: number]: DashboardWidgetVO } { return VOsTypesManager.getInstance().vosArray_to_vosByIds(DashboardBuilderWidgetsController.getInstance().sorted_widgets); } get draggable(): boolean { return this.editable; } get resizable(): boolean { return this.editable; } public async update_layout_widget(widget: DashboardPageWidgetVO) { if ((!this.editable_dashboard_page) || (!this.editable_dashboard_page.layout)) { await this.rebuild_page_layout(); return; } let i = this.editable_dashboard_page.layout.findIndex((w) => w['id'] == widget.id); if (!i) { await this.rebuild_page_layout(); return; } this.editable_dashboard_page.layout[i] = widget; } @Watch("dashboard_page", { immediate: true }) private async onchange_dbdashboard() { if (!this.dashboard_page) { this.editable_dashboard_page = null; return; } if ((!this.editable_dashboard_page) || (this.editable_dashboard_page.id != this.dashboard_page.id)) { await this.throttled_rebuild_page_layout(); } } private mounted() { DashboardBuilderWidgetsController.getInstance().add_widget_to_page_handler = this.add_widget_to_page.bind(this); this.set_Checklistitemmodalcomponent(this.$refs['Checklistitemmodalcomponent'] as ChecklistItemModalComponent); this.set_Crudupdatemodalcomponent(this.$refs['Crudupdatemodalcomponent'] as CRUDUpdateModalComponent); this.set_Crudcreatemodalcomponent(this.$refs['Crudcreatemodalcomponent'] as CRUDCreateModalComponent); } @Watch('get_widgets_invisibility', { deep: true }) private async onchange_get_widgets_invisibility() { this.throttled_rebuild_page_layout(); } private async rebuild_page_layout() { let widgets = await ModuleDAO.getInstance().getVosByRefFieldIds<DashboardPageWidgetVO>( DashboardPageWidgetVO.API_TYPE_ID, 'page_id', [this.dashboard_page.id]); widgets = widgets ? widgets.filter((w) => !this.get_widgets_invisibility[w.id]) : null; this.widgets = widgets; /** * Si on a une sélection qui correpond au widget qu'on est en train de recharger, on modifie aussi le lien */ if (this.selected_widget && this.selected_widget.id) { let page_widget = this.widgets.find((w) => w.id == this.selected_widget.id); this.set_page_widget(page_widget); this.select_widget(page_widget); } this.editable_dashboard_page = Object.assign({ layout: this.widgets }, this.dashboard_page); } private async add_widget_to_page(widget: DashboardWidgetVO) { if (!this.dashboard_page) { return; } let self = this; self.snotify.async( self.label('DashboardBuilderBoardComponent.add_widget_to_page.start'), () => new Promise(async (resolve, reject) => { let page_widget = new DashboardPageWidgetVO(); page_widget.page_id = self.dashboard_page.id; page_widget.widget_id = widget.id; let max_weight: number = 0; self.widgets.forEach((w) => { if (w.weight >= max_weight) { max_weight = w.weight + 1; } }); page_widget.weight = max_weight; page_widget.w = widget.default_width; page_widget.h = widget.default_height; let max_y = 0; if (self.editable_dashboard_page.layout && self.editable_dashboard_page.layout.length) { self.editable_dashboard_page.layout.forEach((item) => max_y = Math.max(max_y, item.y + item.h)); } page_widget.x = 0; page_widget.y = max_y; page_widget.background = widget.default_background; try { if (DashboardBuilderWidgetsController.getInstance().widgets_options_constructor[widget.name]) { let options = DashboardBuilderWidgetsController.getInstance().widgets_options_constructor[widget.name](); page_widget.json_options = JSON.stringify(options); } } catch (error) { ConsoleHandler.getInstance().error(error); } let insertOrDeleteQueryResult: InsertOrDeleteQueryResult = await ModuleDAO.getInstance().insertOrUpdateVO(page_widget); if ((!insertOrDeleteQueryResult) || (!insertOrDeleteQueryResult.id)) { reject({ body: self.label('DashboardBuilderBoardComponent.add_widget_to_page.ko'), config: { timeout: 10000, showProgressBar: true, closeOnClick: false, pauseOnHover: true, }, }); return; } // On reload les widgets self.widgets = await ModuleDAO.getInstance().getVosByRefFieldIds<DashboardPageWidgetVO>( DashboardPageWidgetVO.API_TYPE_ID, 'page_id', [self.dashboard_page.id]); page_widget = self.widgets.find((w) => w.id == insertOrDeleteQueryResult.id); self.editable_dashboard_page = Object.assign({ layout: self.widgets }, self.dashboard_page); self.set_page_widget(page_widget); self.select_widget(page_widget); resolve({ body: self.label('DashboardBuilderBoardComponent.add_widget_to_page.ok'), config: { timeout: 10000, showProgressBar: true, closeOnClick: false, pauseOnHover: true, }, }); }) ); } private async resizedEvent(i, newH, newW, newHPx, newWPx) { if (!this.widgets) { return; } let widget = this.widgets.find((w) => w.i == i); if (!widget) { ConsoleHandler.getInstance().error("resizedEvent:on ne retrouve pas le widget"); return; } widget.h = newH; widget.w = newW; await ModuleDAO.getInstance().insertOrUpdateVO(widget); this.set_page_widget(widget); } private async movedEvent(i, newX, newY) { if (!this.widgets) { return; } let widget = this.widgets.find((w) => w.i == i); if (!widget) { ConsoleHandler.getInstance().error("movedEvent:on ne retrouve pas le widget"); return; } widget.x = newX; widget.y = newY; await ModuleDAO.getInstance().insertOrUpdateVO(widget); this.set_page_widget(widget); } private async delete_widget(page_widget: DashboardPageWidgetVO) { let self = this; // On demande confirmation avant toute chose. // si on valide, on lance la suppression self.snotify.confirm(self.label('DashboardBuilderBoardComponent.delete_widget.body'), self.label('DashboardBuilderBoardComponent.delete_widget.title'), { timeout: 10000, showProgressBar: true, closeOnClick: false, pauseOnHover: true, buttons: [ { text: self.t('YES'), action: async (toast) => { self.$snotify.remove(toast.id); self.snotify.async( self.label('DashboardBuilderBoardComponent.delete_widget.start'), () => new Promise(async (resolve, reject) => { try { await ModuleDAO.getInstance().deleteVOs([page_widget]); let i = 0; for (; i < self.widgets.length; i++) { let w = self.widgets[i]; if (w.i == page_widget.i) { break; } } self.widgets.splice(i, 1); self.delete_page_widget(page_widget); self.select_widget(null); // On reload les widgets await self.throttled_rebuild_page_layout(); resolve({ body: self.label('DashboardBuilderBoardComponent.delete_widget.ok'), config: { timeout: 10000, showProgressBar: true, closeOnClick: false, pauseOnHover: true, }, }); } catch (error) { reject({ body: error, config: { timeout: 10000, showProgressBar: true, closeOnClick: false, pauseOnHover: true, }, }); } }) ); }, bold: false }, { text: self.t('NO'), action: (toast) => { self.$snotify.remove(toast.id); } } ] }); } private select_widget(page_widget) { this.$emit('select_widget', page_widget); } private select_page(page) { this.$emit('select_page', page); } // private select_widget_and_stop(event, page_widget) { // event.stopPropagation(); // this.$emit('select_widget', page_widget); // } }
import calendar def days_in_month(year, month): return calendar.monthrange(year, month)[1]
package converter import com.wordnik.swagger.annotations.ApiModelProperty import com.wordnik.swagger.converter.ModelConverters import com.wordnik.swagger.core.util.JsonSerializer import org.joda.time.LocalDate import org.junit.runner.RunWith import org.scalatest.FlatSpec import org.scalatest.junit.JUnitRunner import org.scalatest.matchers.ShouldMatchers import scala.annotation.meta.field @RunWith(classOf[JUnitRunner]) class JodaLocalDateConverterTest extends FlatSpec with ShouldMatchers { it should "read a generic model" in { val models = ModelConverters.readAll(classOf[ModelWithJodaLocalDate]) models.size should be(1) val model = models.head val nameProperty = model.properties("name") nameProperty.`type` should be("string") nameProperty.position should be(2) nameProperty.description should be(Some("name of the model")) val dateTimeProperty = model.properties("createdAt") dateTimeProperty.`type` should be("Date") dateTimeProperty.position should be(1) dateTimeProperty.required should be(true) dateTimeProperty.description should be(Some("creation localDate")) println(JsonSerializer.asJson(models.head)) } } case class ModelWithJodaLocalDate( @(ApiModelProperty@field)(value = "name of the model", position = 2) name: String, @(ApiModelProperty@field)(value = "creation localDate", required = true, position = 1) createdAt: LocalDate)
#!/bin/bash brew install git brew install python pip install -U pip sudo -H pip install ansible sudo -H pip install prudentia
#!/usr/bin/env bash echo password: cluFn7wTiGryunymYOu4RcffSxQluehd echo run nmap -p 31000-32000 127.0.0.1 \| awk -F '\$1 ~ /^[0-9]+/ {print $1,$2,$3}' echo enumerate, running 'openssl s_client -ign_eof -connect 127.0.0.1:$PORT' echo feed the current password to this connection and see which one returns the value ssh -p 2220 bandit16@bandit.labs.overthewire.org << EOF openssl s_client -ign_eof -connect 127.0.0.1:31790 cluFn7wTiGryunymYOu4RcffSxQluehd EOF
#!/bin/bash echo "temporary placeholder" function cf_labels_service() { echo "temporary stubbed" } export -f cf_labels_service
<gh_stars>1-10 import * as t from "io-ts"; import { RpcFilterRequest } from "./filterRequest"; // TODO: This types are incorrect. See: https://geth.ethereum.org/docs/rpc/pubsub // Actually, the logs filter is not of the same type as eth_newFilter export interface RpcSubscribe { request: RpcFilterRequest; } export type RpcSubscribeRequest = t.TypeOf<typeof rpcSubscribeRequest>; export const rpcSubscribeRequest = t.keyof( { newHeads: null, newPendingTransactions: null, logs: null, }, "RpcSubscribe" );
<gh_stars>1-10 package org.josql; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.josql.evaluators.ExecuteOnEvaluator; import org.josql.evaluators.GroupByClauseEvaluator; import org.josql.evaluators.HavingClauseEvaluator; import org.josql.evaluators.LimitClauseEvaluator; import org.josql.evaluators.OrderByClauseEvaluator; import org.josql.evaluators.QueryEvaluator; import org.josql.evaluators.SelectClauseEvaluator; import org.josql.evaluators.WhereClauseEvaluator; import org.josql.exceptions.QueryExecutionException; import org.josql.utils.Timer; public class QueryExecutor { private Query query; private List<Object> objs; private Class<?> objClass; private Map<Object, Object> executeOnFunctions; private ColumnValuesExtractor columnExtractor; private Stack<QueryEvaluator> evaluators; /** * Create a new QueryExecutor for executing a JoSQL query * @param _query the JoSQL Query object * @param _objs The list of objects to execute the query on. * @param _objClass the type of the objects */ public QueryExecutor(final Query _query, final List<Object> _objs, final Class<?> _objClass) { query = _query; objs = _objs; objClass = _objClass; executeOnFunctions = query.getExecuteOnFunctions(); } /** * Execute this query on the specified objects. * @throws QueryExecutionException If the query cannot be executed. */ public void execute() throws QueryExecutionException { if ((objs == null) && (objClass != null)) { throw new QueryExecutionException ("List of objects must be non-null when an object class is specified."); } if ((objClass == null) && (objs == null)) { objs = Query.nullQueryList; } Timer timer = query.getQueryResults().getTimeEvaluator().newTimer("Query executed in"); timer.start(); init(); executeStack(); timer.stop(); } private void init() { query.allObjects = objs; evaluators = new Stack<QueryEvaluator>(); // See if we have any expressions that are to be executed on // the complete set. evaluators.push(new ExecuteOnEvaluator(executeOnFunctions, objs, Query.ALL)); evaluators.push(new WhereClauseEvaluator()); // See if we have any functions that are to be executed on the results... evaluators.push(new ExecuteOnEvaluator(executeOnFunctions, query.getQueryResults().getResults(), Query.RESULTS)); columnExtractor = new ColumnValuesExtractor(query, query.cols); if (query.grouper != null) { evaluators.push(new GroupByClauseEvaluator(query.grouper, columnExtractor)); // If we have a "having" clause execute it here... evaluators.push(new HavingClauseEvaluator()); }else{ // Now perform the order by. evaluators.push(new OrderByClauseEvaluator()); // Finally, if we have a limit clause, restrict the set of objects returned... evaluators.push(new LimitClauseEvaluator()); evaluators.push(new SelectClauseEvaluator(query.cols, columnExtractor)); } } private void executeStack() throws QueryExecutionException { Iterator<QueryEvaluator> it = evaluators.iterator(); while(it.hasNext()) { it.next().evaluate(query); } } }
public static String createVisibilityStorePrefix(String packageName, String databaseName) { return "AppSearchImpl.createPrefix(" + packageName + ", " + databaseName + ")"; }
import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { ChatRoom } from '../../../models'; import { t, roomTypes } from '../../../utils'; import resetSelection from '../resetSelection'; import { fireGlobalEvent } from '../../../ui-utils'; Template.createActivityInstructions.helpers({ roomName() { const room = ChatRoom.findOne(Session.get('openedRoom')); return room && roomTypes.getRoomName(room.t, room); }, selectedMessages() { return Template.instance().selectedMessages.get(); }, errorMessage() { return Template.instance().errorMessage.get(); }, }); Template.createActivityInstructions.events({ 'click .js-cancel-activity, click .mail-messages__instructions--selected'(e, t) { t.reset(true); }, 'click .js-send-activity'(e, instance) { const { selectedMessages, selectedMessagesHtml } = instance; const subject = instance.$('[name="subject"]').val(); if (!selectedMessages.get().length) { instance.errorMessage.set(t('Mail_Message_No_messages_selected_select_all')); return false; } const messages = Object.values(selectedMessagesHtml); const sortedByDate = messages.sort((a, b) => a.timestamp - b.timestamp); const renderMessage = function(message) { return ` <tr> <td>${ message.time }</td> <td>${ message.wholeName }</td> <td>${ message.body }</td> </tr> `; }; const html = ` <br /> <table style='border:none' cellspacing='5' cellpadding='5' border='0'> ${ sortedByDate.map(renderMessage).join('') } </table> <span></span> `; const elem = document.createElement('div'); elem.innerHTML = html; elem.querySelectorAll('.copyonly').forEach((r) => r.remove()); const body = elem.innerHTML; fireGlobalEvent('create-activity', { subject, body }); instance.reset(true); $('.js-close').click(); }, }); Template.createActivityInstructions.onRendered(function() { const { selectedMessages, selectedMessagesHtml } = this; $('.messages-box .message').on('click', function() { const { id } = this; const messages = selectedMessages.get(); if ($(this).hasClass('selected')) { delete selectedMessagesHtml[id]; selectedMessages.set(messages.filter((message) => message !== id)); } else { const wholeName = this.querySelector('.user').innerText; const time = this.querySelector('time').getAttribute('title'); const timestamp = +this.getAttribute('data-timestamp'); const body = this.querySelector('.body').innerHTML; selectedMessagesHtml[id] = { wholeName, time, timestamp, body }; selectedMessages.set(messages.concat(id)); } }); }); Template.createActivityInstructions.onCreated(function() { resetSelection(true); this.selectedMessages = new ReactiveVar([]); this.selectedMessagesHtml = {}; this.errorMessage = new ReactiveVar(''); this.reset = (bool) => { this.selectedMessages.set([]); this.selectedMessagesHtml = {}; this.errorMessage.set(''); resetSelection(bool); }; }); Template.createActivityInstructions.onDestroyed(function() { Template.instance().reset(false); });
from __future__ import print_function, unicode_literals import tensorflow as tf import numpy as np import scipy.misc import os import argparse import operator import csv import cv2 from moviepy.editor import VideoFileClip from nets.ColorHandPose3DNetwork import ColorHandPose3DNetwork from utils.general import detect_keypoints, trafo_coords, plot_hand, plot_hand_2d, plot_hand_3d from pose.DeterminePositions import * from pose.utils.FingerPoseEstimate import FingerPoseEstimate # Variables to be used # TODO: Check how to pass parameters through fl_image function. Remove global variables image_tf = None threshold = None known_finger_poses = None network_elements = None output_txt_path = None reqd_pose_name = None def parse_args(): parser = argparse.ArgumentParser(description = 'Process frames in a video of a particular pose') parser.add_argument('video_path', help = 'Path of video', type = str) # This part needs improvement. Currently, pose_no is position_id present in FingerDataFormation.py parser.add_argument('pose_no', help = 'Pose to classify at', type = int) parser.add_argument('--output-path', dest = 'output_path', type = str, default = None, help = 'Path of folder where to store the text output') parser.add_argument('--thresh', dest = 'threshold', help = 'Threshold of confidence level(0-1)', default = 0.45, type = float) args = parser.parse_args() return args def prepare_paths(video_path, output_txt_path): video_path = os.path.abspath(video_path) if output_txt_path is None: output_txt_path = os.path.split(video_path)[0] else: output_txt_path = os.path.abspath(output_txt_path) if not os.path.exists(output_txt_path): os.mkdir(output_txt_path) file_name = os.path.basename(video_path).split('.')[0] output_video_path = os.path.join(output_txt_path, '{}_save.mp4'.format(file_name)) output_txt_path = os.path.join(output_txt_path, '{}.csv'.format(file_name)) if not os.path.exists(output_txt_path): open(output_txt_path, 'w').close() return video_path, output_txt_path, output_video_path def prepare_network(): # network input image_tf = tf.placeholder(tf.float32, shape = (1, 240, 320, 3)) hand_side_tf = tf.constant([[1.0, 1.0]]) # Both left and right hands included evaluation = tf.placeholder_with_default(True, shape = ()) # build network net = ColorHandPose3DNetwork() hand_scoremap_tf, image_crop_tf, scale_tf, center_tf,\ keypoints_scoremap_tf, keypoint_coord3d_tf = net.inference(image_tf, hand_side_tf, evaluation) # Start TF gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.8) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) # initialize network net.init(sess) return sess, image_tf, keypoint_coord3d_tf, scale_tf, center_tf, keypoints_scoremap_tf def process_video_frame(video_frame): video_frame = video_frame[:, :, :3] video_frame = scipy.misc.imresize(video_frame, (240, 320)) image_v = np.expand_dims((video_frame.astype('float') / 255.0) - 0.5, 0) keypoint_coord3d_tf, scale_tf, center_tf, keypoints_scoremap_tf = network_elements keypoint_coord3d_v, scale_v, center_v, keypoints_scoremap_v = sess.run([keypoint_coord3d_tf, scale_tf, center_tf, keypoints_scoremap_tf], feed_dict = {image_tf: image_v}) keypoints_scoremap_v = np.squeeze(keypoints_scoremap_v) keypoint_coord3d_v = np.squeeze(keypoint_coord3d_v) # post processing coord_hw_crop = detect_keypoints(np.squeeze(keypoints_scoremap_v)) coord_hw = trafo_coords(coord_hw_crop, center_v, scale_v, 256) plot_hand_2d(coord_hw, video_frame) score_label = process_keypoints(keypoint_coord3d_v) if score_label is not None: font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(video_frame, score_label, (10, 200), font, 1.0, (255, 0, 0), 2, cv2.LINE_AA) return video_frame def process_keypoints(keypoint_coord3d_v): fingerPoseEstimate = FingerPoseEstimate(keypoint_coord3d_v) fingerPoseEstimate.calculate_positions_of_fingers(print_finger_info = False) obtained_positions = determine_position(fingerPoseEstimate.finger_curled, fingerPoseEstimate.finger_position, known_finger_poses, threshold) score_label = None if len(obtained_positions) > 0: max_pose_label = max(obtained_positions.items(), key=operator.itemgetter(1))[0] if obtained_positions[max_pose_label] >= threshold and max_pose_label == reqd_pose_name: score_label = max_pose_label with open(output_txt_path, 'a') as fid: list_entry = [entry for sublist in keypoint_coord3d_v for entry in sublist] csv_writer = csv.writer(fid) csv_writer.writerow(list_entry) return score_label if __name__ == '__main__': args = parse_args() threshold = args.threshold * 10 video_path, output_txt_path, output_video_path = prepare_paths(args.video_path, args.output_path) known_finger_poses = create_known_finger_poses() reqd_pose_name = get_position_name_with_pose_id(args.pose_no, known_finger_poses) sess, image_tf, keypoint_coord3d_tf, scale_tf, center_tf, keypoints_scoremap_tf = prepare_network() network_elements = [keypoint_coord3d_tf, scale_tf, center_tf, keypoints_scoremap_tf] video_clip = VideoFileClip(video_path) white_clip = video_clip.fl_image(process_video_frame) #NOTE: this function expects color images!! white_clip.write_videofile(output_video_path, audio=False)
#!/bin/bash ##This is just a random incomplete unimportant example of the actual "payload for the server" echo "************PRINT SOME TEXT***************\n" echo "Hello World!!!" echo "\n" echo "Resources:" echo "\n" echo "Addresses:" echo "$(ifconfig)" echo "\n"
def Fibonacci(n): a = 0 b = 1 if n<0: print("Incorrect input") elif n==0: return a elif n==1: return b else: for i in range(2,n+1): c = a + b a = b b = c return b # Driver program print(Fibonacci(10))
# Work around ModSecurity not supporting optional includes on NGiNX # Note: we are careful here to not assume the existance of the "plugins" # directory. It is being introduced with version 4 of CRS. for suffix in "config" "before" "after"; do if [ -n "$(find /opt/owasp-crs -path "/opt/owasp-crs/plugins/*-${suffix}.conf")" ]; then # enable if there are config files sed -i -E "s/^#\s*(.+-${suffix}\.conf)/\1/" /etc/modsecurity.d/setup.conf else # disable if there are no config files sed -i -E "s/^([^#]+-${suffix}\.conf)/# \1/" /etc/modsecurity.d/setup.conf fi done
package voot.oauth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.util.Assert; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; public class CachedRemoteTokenServices implements DecisionResourceServerTokenServices { private static final Logger LOG = LoggerFactory.getLogger(CachedRemoteTokenServices.class); private final Map<String, CachedOAuth2Authentication> authentications = new ConcurrentHashMap<>(); private final long duration; private final DecisionResourceServerTokenServices tokenServices; public CachedRemoteTokenServices(DecisionResourceServerTokenServices tokenServices, long durationMilliseconds, long expiryIntervalCheckMilliseconds) { this.tokenServices = tokenServices; Assert.isTrue( durationMilliseconds > 0 && durationMilliseconds < 1000 * 60 * 61, "durationMilliseconds must be between 0 and 3660000"); Assert.isTrue( expiryIntervalCheckMilliseconds > 0 && expiryIntervalCheckMilliseconds < 1000 * 60 * 61, "expiryIntervalCheckMilliseconds must be between 0 and 3660000"); this.duration = durationMilliseconds; newSingleThreadScheduledExecutor().scheduleAtFixedRate(this::clearExpiredAuthentications, 0, expiryIntervalCheckMilliseconds, TimeUnit.MILLISECONDS); } @Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { CachedOAuth2Authentication cachedAuthentication = authentications.get(accessToken); long now = System.currentTimeMillis(); if (cachedAuthentication != null && cachedAuthentication.timestamp + duration > now) { LOG.debug("Returning OAuth2Authentication from cache {}", cachedAuthentication.authentication); return cachedAuthentication.authentication; } OAuth2Authentication oAuth2Authentication = tokenServices.loadAuthentication(accessToken); //will not happen, but just to ensure this does not cause memory problems int size = authentications.size(); if (size < 10000) { LOG.debug("Putting OAuth2Authentication in cache {} current size: {}", oAuth2Authentication, size + 1); authentications.put(accessToken, new CachedOAuth2Authentication(now, oAuth2Authentication)); } return oAuth2Authentication; } @Override public OAuth2AccessToken readAccessToken(String accessToken) { return tokenServices.readAccessToken(accessToken); } private void clearExpiredAuthentications() { try { long now = System.currentTimeMillis(); authentications.forEach((accessToken, authentication) -> { if (authentication.timestamp + duration < now) { LOG.debug("Removing expired authentication with access token {}", accessToken); authentications.remove(accessToken); } }); } catch (Throwable t) { LOG.error("Error in clearExpiredAuthentications", t); //we don't rethrow as this would stop the subsequent scheduled clearing } } @Override public boolean canHandle(String accessToken) { return tokenServices.canHandle(accessToken); } private class CachedOAuth2Authentication { long timestamp; OAuth2Authentication authentication; public CachedOAuth2Authentication(long timestamp, OAuth2Authentication authentication) { this.timestamp = timestamp; this.authentication = authentication; } } }
from os.path import abspath class BaseOpts: def __init__(self, verbose_make, jobs, configure_dir, install_dir, mono_source_root, mxe_prefix): self.verbose_make = verbose_make self.jobs = jobs self.configure_dir = configure_dir self.install_dir = install_dir self.mono_source_root = mono_source_root self.mxe_prefix = mxe_prefix def runtime_opts_from_args(args): return BaseOpts( verbose_make=args.verbose_make, jobs=args.jobs, configure_dir=abspath(args.configure_dir), install_dir=abspath(args.install_dir), mono_source_root=abspath(args.mono_sources), mxe_prefix=args.mxe_prefix )
class BankAccount: def __init__(self): self.balance = 0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: print("Insufficient funds") else: self.balance -= amount def check_balance(self): return self.balance def calculate_interest(self, rate): interest = self.balance * rate return interest
#!/bin/sh rm -rf .terraform terraform --version terraform init -backend-config "bucket=tfstate-poc" -backend-config "region=sa-east-1" -backend-config "key=vpc" if [[ $(terraform workspace list | grep 'production' | wc -l ) = 0 ]]; then terraform workspace new production fi terraform workspace select production
#!/usr/bin/env bash cd $(dirname $0) export K8S_HOME=$(readlink -m "../") source "$K8S_HOME/DEPLOY.variables" VAGRANT_DEPLOY_HOME="../build/deploy" VAGRANT_SRC_HOME="." VAGRANT_BOX_NAME="\"yuhubs.k8s.vbox\/${K8S_VAGRANT_BOX_BASENAME}\"" convert_array() { local -n args=$1 local result="\[" local count=0 for e in ${args[@]}; do if [ $count -gt 0 ]; then result="${result}, " fi result="${result}\"$e\"" count=$(($count+1)) done result="${result}\]" echo "$result" } cp_script_files() { local src_dir=$1 local dest_dir=$2 local script_files=($src_dir/*.sh) for file in ${script_files[@]}; do file=${file##*/} cp -f "$src_dir/$file" "$dest_dir/$file" chmod a+x "$dest_dir/$file" done } categories=("Services" "Ingresses") for cat in ${categories[@]}; do VAGRANT_SRC_DIR="${VAGRANT_SRC_HOME}/$cat" VAGRANT_DEST_DIR="${VAGRANT_DEPLOY_HOME}/$cat" case "$cat" in "Ingresses") NODE_NAMES=("${K8S_INGRESS_NODE_NAMES[@]}"); NODE_IPS=("${K8S_INGRESS_NODE_IPS[@]}"); ;; *) NODE_NAMES=("${K8S_SERVICE_NODE_NAMES[@]}"); NODE_IPS=("${K8S_SERVICE_NODE_IPS[@]}"); ;; esac NODE_NAMES_ARRAY=$(convert_array NODE_NAMES) NODE_IPS_ARRAY=$(convert_array NODE_IPS) mkdir -p "$VAGRANT_DEST_DIR" sed \ -e "s/\[\"<node_names>\"\]/${NODE_NAMES_ARRAY}/" \ -e "s/\[\"<node_ips>\"\]/${NODE_IPS_ARRAY}/" \ -e "s/\"<vagrant_box_name>\"/${VAGRANT_BOX_NAME}/" \ "$VAGRANT_SRC_DIR/Vagrantfile.tmpl" \ >"$VAGRANT_DEST_DIR/Vagrantfile" cp_script_files \ "$VAGRANT_SRC_DIR" \ "$VAGRANT_DEST_DIR/.." done
<reponame>RobertArtioli/phaser /** * @author <NAME> <<EMAIL>> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Positions the Game Object so that the bottom of its bounds aligns with the given coordinate. * * @function Phaser.Display.Bounds.SetBottom * @since 3.0.0 * * @generic {Phaser.GameObjects.GameObject} G - [gameObject,$return] * * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object that will be re-positioned. * @param {number} value - The coordinate to position the Game Object bounds on. * * @return {Phaser.GameObjects.GameObject} The Game Object that was positioned. */ var SetBottom = function (gameObject, value) { gameObject.y = (value - gameObject.height) + (gameObject.height * gameObject.originY); return gameObject; }; module.exports = SetBottom;
import numpy as np import tensorflow as tf from keras.models import Sequential from keras.layers import Dense, Dropout # define model model = Sequential() model.add(Dense(128, activation='relu', input_shape=(input_dim,))) model.add(Dropout(0.5)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) # compile model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # train model model.fit(X_train, y_train, batch_size=32, epochs=10, validation_data=(X_test, y_test)) # evaluate model score = model.evaluate(X_test, y_test, batch_size=32)
#!/bin/bash while true; do ./r > input # 生成随机数据 ./a < input > output.a ./b < input > output.b diff output.a output.b # 文件比较 if [ $? -ne 0 ] ; then break; fi # 判断返回值 done
import { html, PolymerElement } from '@polymer/polymer'; import './subscribe-form-footer'; class FooterRel extends PolymerElement { static get template() { return html ` <style include="shared-styles flex flex-alignment"> :host { border-top: 1px solid var(--border-light-color); border-bottom: 1px solid var(--border-light-color); margin: 0 20px 0 20px; overflow: auto; overflow-y: hidden; padding: 10px 0; color: var(--footer-text-color); display: grid; grid-gap: 16px; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); } .col-heading { font-size: 14px; font-weight: 500; line-height: 21px; margin-top: 25px; margin-bottom: 10px; } .nav { list-style: none; margin: 0; padding: 0; } a { color: var(--footer-text-color); padding-bottom: 2px; text-decoration: none; pointer-events: all; } li { display: list-item; line-height: 25px; pointer-events: none; } li:hover { text-decoration: underline; } @media (min-width: 768px) { :host { margin: 15px 0; padding: 30px 0; } .col-heading { font-size: 18px; margin-top: 0; } } </style> {% for footerRel in footerRelBlock %} <div class="col" layout vertical wrap flex-auto> <div class="col-heading">{$ footerRel.title $}</div> <ul class="nav"> {% for link in footerRel.links %} <li> <a href="{$ link.url $}" {% if link.newtab %} target="_blank" rel="noopener noreferrer" {% endif %} >{$ link.name $}</a > </li> {% endfor %} </ul> </div> {% endfor %} <div class="col" layout vertical flex-auto wrap> <div class="col-heading">{$ subscribe $}</div> <span>{$ subscribeNote $}</span> <subscribe-form-footer></subscribe-form-footer> </div> `; } static get is() { return 'footer-rel'; } } window.customElements.define(FooterRel.is, FooterRel); //# sourceMappingURL=footer-rel.js.map
// Copyright 2020 // // 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 bean import ( "context" "reflect" "strings" "github.com/astaxie/beego/core/logs" "github.com/astaxie/beego/client/orm" "github.com/astaxie/beego/core/bean" ) // DefaultValueFilterChainBuilder only works for InsertXXX method, // But InsertOrUpdate and InsertOrUpdateWithCtx is more dangerous than other methods. // so we won't handle those two methods unless you set includeInsertOrUpdate to true // And if the element is not pointer, this filter doesn't work type DefaultValueFilterChainBuilder struct { factory bean.AutoWireBeanFactory compatibleWithOldStyle bool // only the includeInsertOrUpdate is true, this filter will handle those two methods includeInsertOrUpdate bool } // NewDefaultValueFilterChainBuilder will create an instance of DefaultValueFilterChainBuilder // In beego v1.x, the default value config looks like orm:default(xxxx) // But the default value in 2.x is default:xxx // so if you want to be compatible with v1.x, please pass true as compatibleWithOldStyle func NewDefaultValueFilterChainBuilder(typeAdapters map[string]bean.TypeAdapter, includeInsertOrUpdate bool, compatibleWithOldStyle bool) *DefaultValueFilterChainBuilder { factory := bean.NewTagAutoWireBeanFactory() if compatibleWithOldStyle { newParser := factory.FieldTagParser factory.FieldTagParser = func(field reflect.StructField) *bean.FieldMetadata { if newParser != nil && field.Tag.Get(bean.DefaultValueTagKey) != "" { return newParser(field) } else { res := &bean.FieldMetadata{} ormMeta := field.Tag.Get("orm") ormMetaParts := strings.Split(ormMeta, ";") for _, p := range ormMetaParts { if strings.HasPrefix(p, "default(") && strings.HasSuffix(p, ")") { res.DftValue = p[8 : len(p)-1] } } return res } } } for k, v := range typeAdapters { factory.Adapters[k] = v } return &DefaultValueFilterChainBuilder{ factory: factory, compatibleWithOldStyle: compatibleWithOldStyle, includeInsertOrUpdate: includeInsertOrUpdate, } } func (d *DefaultValueFilterChainBuilder) FilterChain(next orm.Filter) orm.Filter { return func(ctx context.Context, inv *orm.Invocation) []interface{} { switch inv.Method { case "Insert", "InsertWithCtx": d.handleInsert(ctx, inv) break case "InsertOrUpdate", "InsertOrUpdateWithCtx": d.handleInsertOrUpdate(ctx, inv) break case "InsertMulti", "InsertMultiWithCtx": d.handleInsertMulti(ctx, inv) break } return next(ctx, inv) } } func (d *DefaultValueFilterChainBuilder) handleInsert(ctx context.Context, inv *orm.Invocation) { d.setDefaultValue(ctx, inv.Args[0]) } func (d *DefaultValueFilterChainBuilder) handleInsertOrUpdate(ctx context.Context, inv *orm.Invocation) { if d.includeInsertOrUpdate { ins := inv.Args[0] if ins == nil { return } pkName := inv.GetPkFieldName() pkField := reflect.Indirect(reflect.ValueOf(ins)).FieldByName(pkName) if pkField.IsZero() { d.setDefaultValue(ctx, ins) } } } func (d *DefaultValueFilterChainBuilder) handleInsertMulti(ctx context.Context, inv *orm.Invocation) { mds := inv.Args[1] if t := reflect.TypeOf(mds).Kind(); t != reflect.Array && t != reflect.Slice { // do nothing return } mdsArr := reflect.Indirect(reflect.ValueOf(mds)) for i := 0; i < mdsArr.Len(); i++ { d.setDefaultValue(ctx, mdsArr.Index(i).Interface()) } logs.Warn("%v", mdsArr.Index(0).Interface()) } func (d *DefaultValueFilterChainBuilder) setDefaultValue(ctx context.Context, ins interface{}) { err := d.factory.AutoWire(ctx, nil, ins) if err != nil { logs.Error("try to wire the bean for orm.Insert failed. "+ "the default value is not set: %v, ", err) } }
def infixToPostfix(infix): # list of allowed operators operators = ["+", "-", "*", "/"] # output stack postfix = [] # operator stack opStack = [] # iterate through the input for token in infix: # variable representing the token tok = str(token) # if the token is an operand if tok not in operators: # append it to the output postfix.append(tok) # if the token is an operator else: # while the operator stack isn't empty # and the top of stack operator # isn't a left parenthesis while len(opStack) != 0 and opStack[-1] != "(": # if the operator has higher precedence, # append it to the output if precedence(token) > precedence(opStack[-1]): postfix.append(opStack.pop()) else: break # push the operator to the stack opStack.append(tok) # pop the remaining operator onto the output while len(opStack) != 0: postfix.append(opStack.pop()) # return the postfix expression return postfix def precedence(token): # assign the precedence value to the token prec = { "+": 1, "-": 1, "*": 2, "/": 2 } # return the precedence return prec[token]
# Agrega atributos relacionados con la sintaxis # uso add_scope_att_hc_parent.sh {$BIOSCOPE | $BIOSCOPED} WORKING_DIR=$1 # Agrego hc parent echo "$0: Adding syntax atributtes..." #cat $SRC/scripts/add_scope_att_hc_parent.sql | sqlite3 $WORKING_DIR/bioscope.db 2>/dev/null python $SRC/scripts/add_scope_att_hc_parent.py $WORKING_DIR
package dev.fiki.forgehax.main.mods.misc; import com.google.common.base.Strings; import com.google.common.collect.Sets; import dev.fiki.forgehax.api.cmd.argument.Arguments; import dev.fiki.forgehax.api.cmd.settings.collections.SimpleSettingSet; import dev.fiki.forgehax.api.common.PriorityEnum; import dev.fiki.forgehax.api.event.SubscribeListener; import dev.fiki.forgehax.api.mod.Category; import dev.fiki.forgehax.api.mod.ToggleMod; import dev.fiki.forgehax.api.modloader.RegisterMod; import dev.fiki.forgehax.asm.events.packet.PacketInboundEvent; import dev.fiki.forgehax.asm.events.packet.PacketOutboundEvent; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.CCustomPayloadPacket; import net.minecraft.network.play.server.SCustomPayloadPlayPacket; import java.util.Scanner; @RegisterMod( name = "PayloadSpoofer", description = "Will cancel packets sent by some mods", category = Category.MISC ) public class PayloadSpoofer extends ToggleMod { private final SimpleSettingSet<String> channels = newSimpleSettingSet(String.class) .name("channels") .description("Payload channels to block") .supplier(Sets::newHashSet) .argument(Arguments.newStringArgument() .label("channel") .build()) .build(); private boolean isBlockedPacket(String channel, PacketBuffer buffer) { if (channels.contains(channel)) { return true; } else if ("REGISTER".equals(channel)) { Scanner scanner = new Scanner(new String(buffer.array())); scanner.useDelimiter("\\u0000"); if (scanner.hasNext()) { String next = scanner.next(); return !Strings.isNullOrEmpty(next) && channels.contains(next); } } return false; } @SubscribeListener(priority = PriorityEnum.HIGHEST) public void onIncomingPacket(PacketInboundEvent event) { if (event.getPacket() instanceof SCustomPayloadPlayPacket) { String channel = ((SCustomPayloadPlayPacket) event.getPacket()).getName().toString(); PacketBuffer packetBuffer = ((SCustomPayloadPlayPacket) event.getPacket()).getData(); if (isBlockedPacket(channel, packetBuffer)) { event.setCanceled(true); } } } @SubscribeListener(priority = PriorityEnum.HIGHEST) public void onOutgoingPacket(PacketOutboundEvent event) { if (event.getPacket() instanceof CCustomPayloadPacket) { String channel = ((CCustomPayloadPacket) event.getPacket()).getName().toString(); PacketBuffer packetBuffer = ((CCustomPayloadPacket) event.getPacket()).getInternalData(); if (isBlockedPacket(channel, packetBuffer)) { event.setCanceled(true); } } } }
#!/bin/sh machines=$(azure vm list sballHadoopMachinesWest | grep running | awk '{ print $3 }' | xargs) for m in $machines do azure vm deallocate sballHadoopMachinesWest $m done
// // VHCAnnouncement.h // VHCIM // // Created by vhall on 2019/2/15. // Copyright © 2019 vhall. All rights reserved. // #import "VHCMsg.h" NS_ASSUME_NONNULL_BEGIN @interface VHCAnnouncement : VHCMsg @end NS_ASSUME_NONNULL_END
<gh_stars>10-100 /************************************************************************** * * Copyright 2016 Novartis Institutes for BioMedical Research Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *************************************************************************/ #include "Wrapper_auto_H5DS.h" /* H5_HLDLL herr_t H5DSattach_scale( hid_t did, hid_t dsid, unsigned int idx); */ SEXP R_H5DSattach_scale(SEXP R_did, SEXP R_dsid, SEXP R_idx){ int vars_protected=0; hid_t did = SEXP_to_longlong(R_did, 0); hid_t dsid = SEXP_to_longlong(R_dsid, 0); unsigned int idx = SEXP_to_longlong(R_idx, 0); herr_t return_val = H5DSattach_scale(did, dsid, idx); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL herr_t H5DSdetach_scale( hid_t did, hid_t dsid, unsigned int idx); */ SEXP R_H5DSdetach_scale(SEXP R_did, SEXP R_dsid, SEXP R_idx){ int vars_protected=0; hid_t did = SEXP_to_longlong(R_did, 0); hid_t dsid = SEXP_to_longlong(R_dsid, 0); unsigned int idx = SEXP_to_longlong(R_idx, 0); herr_t return_val = H5DSdetach_scale(did, dsid, idx); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL ssize_t H5DSget_label( hid_t did, unsigned int idx, char *label, size_t size); */ SEXP R_H5DSget_label(SEXP R_did, SEXP R_idx, SEXP R_label, SEXP R_size){ int vars_protected=0; R_label = PROTECT(duplicate(R_label)); vars_protected++; hid_t did = SEXP_to_longlong(R_did, 0); unsigned int idx = SEXP_to_longlong(R_idx, 0); char* label; if(XLENGTH(R_label) == 0) { label = NULL; } else { label = R_alloc(strlen(CHAR(STRING_ELT(R_label, 0))) + 1, 1); strcpy(label, CHAR(STRING_ELT(R_label, 0))); } size_t size = SEXP_to_longlong(R_size, 0); ssize_t return_val = H5DSget_label(did, idx, label, size); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; if(label==NULL) { R_label = PROTECT(NEW_CHARACTER(0)); vars_protected++; } else { R_label = PROTECT(mkString(label)); vars_protected++; } SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 2)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SET_VECTOR_ELT(__ret_list, 1, R_label); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 2)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_STRING_ELT(__ret_list_names, 1, mkChar("label")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL int H5DSget_num_scales( hid_t did, unsigned int dim); */ SEXP R_H5DSget_num_scales(SEXP R_did, SEXP R_dim){ int vars_protected=0; hid_t did = SEXP_to_longlong(R_did, 0); unsigned int dim = SEXP_to_longlong(R_dim, 0); int return_val = H5DSget_num_scales(did, dim); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL ssize_t H5DSget_scale_name( hid_t did, char *name, size_t size); */ SEXP R_H5DSget_scale_name(SEXP R_did, SEXP R_name, SEXP R_size){ int vars_protected=0; R_name = PROTECT(duplicate(R_name)); vars_protected++; hid_t did = SEXP_to_longlong(R_did, 0); char* name; if(XLENGTH(R_name) == 0) { name = NULL; } else { name = R_alloc(strlen(CHAR(STRING_ELT(R_name, 0))) + 1, 1); strcpy(name, CHAR(STRING_ELT(R_name, 0))); } size_t size = SEXP_to_longlong(R_size, 0); ssize_t return_val = H5DSget_scale_name(did, name, size); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; if(name==NULL) { R_name = PROTECT(NEW_CHARACTER(0)); vars_protected++; } else { R_name = PROTECT(mkString(name)); vars_protected++; } SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 2)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SET_VECTOR_ELT(__ret_list, 1, R_name); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 2)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_STRING_ELT(__ret_list_names, 1, mkChar("name")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL htri_t H5DSis_attached( hid_t did, hid_t dsid, unsigned int idx); */ SEXP R_H5DSis_attached(SEXP R_did, SEXP R_dsid, SEXP R_idx){ int vars_protected=0; hid_t did = SEXP_to_longlong(R_did, 0); hid_t dsid = SEXP_to_longlong(R_dsid, 0); unsigned int idx = SEXP_to_longlong(R_idx, 0); htri_t return_val = H5DSis_attached(did, dsid, idx); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL htri_t H5DSis_scale( hid_t did); */ SEXP R_H5DSis_scale(SEXP R_did){ int vars_protected=0; hid_t did = SEXP_to_longlong(R_did, 0); htri_t return_val = H5DSis_scale(did); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL herr_t H5DSset_label( hid_t did, unsigned int idx, const char *label); */ SEXP R_H5DSset_label(SEXP R_did, SEXP R_idx, SEXP R_label){ int vars_protected=0; hid_t did = SEXP_to_longlong(R_did, 0); unsigned int idx = SEXP_to_longlong(R_idx, 0); const char* label = CHAR(STRING_ELT(R_label, 0)); herr_t return_val = H5DSset_label(did, idx, label); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); } /* H5_HLDLL herr_t H5DSset_scale( hid_t dsid, const char *dimname); */ SEXP R_H5DSset_scale(SEXP R_dsid, SEXP R_dimname){ int vars_protected=0; hid_t dsid = SEXP_to_longlong(R_dsid, 0); const char* dimname = CHAR(STRING_ELT(R_dimname, 0)); herr_t return_val = H5DSset_scale(dsid, dimname); SEXP R_return_val= R_NilValue; R_return_val = PROTECT(ScalarInteger64_or_int(return_val)); vars_protected++; SEXP __ret_list; PROTECT(__ret_list = allocVector(VECSXP, 1)); SET_VECTOR_ELT(__ret_list, 0, R_return_val); SEXP __ret_list_names; PROTECT(__ret_list_names = allocVector(STRSXP, 1)); SET_STRING_ELT(__ret_list_names, 0, mkChar("return_val")); SET_NAMES(__ret_list, __ret_list_names); vars_protected += 2; UNPROTECT(vars_protected); return(__ret_list); }
<filename>Source/Photon/Photon-cpp/inc/Punchthrough/Puncher.h #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace Photon { namespace Internal { namespace Punchthrough { class PunchConn; class SocketImplementation; namespace Forwards { class StunMsgType; struct SockaddrIn; class PunchConnState; } } } namespace Punchthrough { class PunchListener; class RelayClient; class Puncher { public: Puncher(RelayClient* pRelayClient, const Common::Logger& logger); virtual ~Puncher(void); bool init(PunchListener* pPunchListener); void clear(void); bool startPunch(int remoteID); bool sendDirect(const Common::JVector<nByte>& buffer, int targetID, bool fallbackRelay); int sendDirect(const Common::JVector<nByte>& buffer, const Common::JVector<int>& targetIDs, bool fallbackRelay); bool processRelayPackage(const Common::JVector<nByte>& packet, int relayRemoteID); void service(void); private: const Internal::Punchthrough::Forwards::SockaddrIn* getEndpoint(int remoteID); bool getIsPunch(const Common::JVector<nByte>& packet); bool processPackage(const Common::JVector<nByte>& packet, bool relay, const Internal::Punchthrough::Forwards::SockaddrIn& directRemoteAddr, int relayRemoteID); bool processPunchPackage(const Common::JVector<nByte>& packet, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); void socketService(void); // working with mConnections container bool hasConnection(int remoteID) const; Internal::Punchthrough::PunchConn* findConnection(int remoteID); Internal::Punchthrough::PunchConn* insertConnection(const Internal::Punchthrough::PunchConn& conn); bool removeConnection(int remoteID); void setConnectionState(Internal::Punchthrough::PunchConn& conn, Internal::Punchthrough::Forwards::PunchConnState state); // :: Handlers void handlerOffer(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingIntern, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingExtern); void handlerAnswer(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingIntern, const Internal::Punchthrough::Forwards::SockaddrIn& addrIncomingExtern); void handlerPing(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); void handlerPong(int idIncoming, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); // :: Senders bool sendOffer(int remoteid); bool sendAnswer(int remoteid); bool sendPing(Internal::Punchthrough::PunchConn& conn); bool sendPong(Internal::Punchthrough::PunchConn& conn, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr); bool sendStunRelay(int remoteid, Internal::Punchthrough::Forwards::StunMsgType stunMsgType, const nByte* pMsgID); bool sendStunDirect(const Internal::Punchthrough::PunchConn& conn, const Internal::Punchthrough::Forwards::SockaddrIn& remoteAddr, Internal::Punchthrough::Forwards::StunMsgType stunMsgType, const nByte* pMsgID); bool sendRelay(const Common::JVector<nByte>& buffer, const Common::JVector<int>& targetIDs); // :: Builders Common::JVector<nByte> buildMsgBindingRequest(void); Common::JVector<nByte> buildStunImplementation(const Internal::Punchthrough::PunchConn* pConn, nByte id, Internal::Punchthrough::Forwards::StunMsgType stunMsgType, const nByte* pMsgID); // :: EndPoint Utils const Internal::Punchthrough::Forwards::SockaddrIn& getLocalEndpoint(void); void aquireExternalEndpoint(void); static const Common::JString addrToStr(const Internal::Punchthrough::Forwards::SockaddrIn& addr); Internal::Punchthrough::SocketImplementation* mpSocket; RelayClient* mpRelayClient; PunchListener* mpPunchListener; Common::Logger mLogger; Common::Helpers::UniquePointer<Internal::Punchthrough::Forwards::SockaddrIn> mupClientExternAddr; bool mValidExternalAddr; // Connections Common::Helpers::UniquePointer<Common::JVector<Internal::Punchthrough::PunchConn> > mupConnections; static const nByte mMsgBindingID[12]; static const nByte mMsgRequestID[12]; static const nByte mMsgResponseID[12]; static const nByte mUserMsgByte0; }; } } }
#!/bin/bash #SBATCH --job-name=ViT #SBATCH --gres=gpu:4 #SBATCH --cpus-per-task=10 #SBATCH --partition=a100 source activate pytorch python train.py \ --name cifar10_vit_b_32_seed_1 \ --dataset cifar10 \ --model_type ViT-B_32 \ --pretrained_dir checkpoint/ViT-B_32.npz \ --output_dir output_models/cifar10/ViT-B_32/Run1 \ --seed 1 \ --gradient_accumulation_steps 4
# Import necessary modules import hashlib # Create a string string = "Hello, World!" # Create the SHA256 object with the string string_hash = hashlib.sha256(string.encode('utf-8')) # Print out the resulting SHA256 hash print("SHA256 hash of '" + string + "' is: \n" + string_hash.hexdigest())
REM FILE NAME: log_swch.sql REM LOCATION: System Monitoring\Reports REM FUNCTION: Provide info on logs for last 24 hour since last log switch REM TESTED ON: 8.0.4.1, 8.1.5, 8.1.7, 9.0.1 REM PLATFORM: non-specific REM REQUIRES: v$log_history, v$archived_log REM REM This is a part of the Knowledge Xpert for Oracle Administration library. REM Copyright (C) 2001 Quest Software REM All rights reserved. REM REM******************** Knowledge Xpert for Oracle Administration ******************** COLUMN thread# format 999 heading 'Thrd#' COLUMN sequence# format 99999 heading 'Seq#' COLUMN first_change# heading 'SCN Low#' COLUMN next_change# heading 'SCN High#' COLUMN archive_name format a50 heading 'Log File' COLUMN first_time format a20 heading 'Switch Time' COLUMN name format a30 heading 'Archive Log' SET lines 132 @title132 "Log Switch History Report" SPOOL rep_out\log_swch REM SELECT a.recid, a.thread#, a.sequence#, a.first_change#, a.next_change#, TO_CHAR (a.first_time, 'DD-MON-YYYY HH24:MI:SS') first_time, x.NAME FROM v$log_history a, v$archived_log x WHERE a.first_time > (SELECT b.first_time - 1 FROM v$log_history b WHERE b.next_change# = (SELECT MAX (c.next_change#) FROM v$log_history c)) AND a.recid = x.sequence#(+); SPOOL off SET lines 80 CLEAR columns TTITLE off
#include <stdio.h> #include <string.h> int main(void) { char str[80] = "This is an example string"; char *token, longest[20]; int length = 0; token = strtok(str, " "); while( token != NULL ) { int curlength = strlen(token); if(curlength > length){ length = curlength; // Copy the current token into longest strcpy(longest, token); } // Get the next token token = strtok(NULL, " "); } printf("Longest word is %s with length %d \n", longest, length); return 0; }
require 'spec_helper' # spec for CommandExecutor module Fusuma describe CommandExecutor do describe 'execute' do subject { command_executor.execute } let(:vector) { Swipe.new(10, 5) } let(:command_executor) { CommandExecutor.new(3, vector) } let(:set_command) do allow(Config).to receive(:command) .with(anything) .and_return('test_command') end let(:unset_command) do allow(Config).to receive(:command) .with(anything) .and_return(nil) end let(:set_shortcut) do allow(Config).to receive(:shortcut) .with(anything) .and_return('test+key') end let(:unset_shortcut) do allow(Config).to receive(:shortcut) .with(anything) .and_return(nil) end context 'with command' do before do unset_shortcut end context 'with valid condition' do before do set_command end it 'should execute command' do expect_any_instance_of(described_class) .to receive(:`) .with('test_command') subject end end context 'with invalid condition' do before do unset_command end it 'should NOT execute command' do expect_any_instance_of(described_class) .not_to receive(:`) .with('test_command') subject end end end context 'with shortcut' do before do unset_command end context 'with valid condition' do before do set_shortcut end it 'should return' do expect_any_instance_of(described_class) .to receive(:`) .with('xdotool key test+key') subject end end context 'with invalid condition' do before do unset_shortcut end it 'should NOT execute shortcut' do expect_any_instance_of(described_class) .not_to receive(:`) .with('xdotool key test+key') subject end end end context 'when any command or shortcut are not assigned' do before do unset_command unset_shortcut end it 'should NOT execute command' do expect_any_instance_of(described_class) .not_to receive(:`) .with(%q('echo "Command is not assigned"')) subject end end end end end
package com.sjcdigital.sjcedu.robot.model.entities; /** * * @author pedro-hos * */ public class Escola { private String nome; private String codigo; private String depAdministrativa; private Endereco endereco; private ComplexGestaoEscolar complexGestaoEscolar; private PraticaPedagogica praticaPedagogica; private InfraestruturaBasica infraestruturaBasica; private EspacoAprendizagemEquip EspacoAprendizagemEquip; private Organizacao organizacao; private ParticipacaoSaeb participacaoSaeb; private IdebValores idebValores; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDepAdministrativa() { return depAdministrativa; } public void setDepAdministrativa(String depAdministrativa) { this.depAdministrativa = depAdministrativa; } public Endereco getEndereco() { return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } public ComplexGestaoEscolar getComplexGestaoEscolar() { return complexGestaoEscolar; } public void setComplexGestaoEscolar(ComplexGestaoEscolar complexGestaoEscolar) { this.complexGestaoEscolar = complexGestaoEscolar; } public PraticaPedagogica getPraticaPedagogica() { return praticaPedagogica; } public void setPraticaPedagogica(PraticaPedagogica praticaPedagogica) { this.praticaPedagogica = praticaPedagogica; } public InfraestruturaBasica getInfraestruturaBasica() { return infraestruturaBasica; } public void setInfraestruturaBasica(InfraestruturaBasica infraestruturaBasica) { this.infraestruturaBasica = infraestruturaBasica; } public EspacoAprendizagemEquip getEspacoAprendizagemEquip() { return EspacoAprendizagemEquip; } public void setEspacoAprendizagemEquip(EspacoAprendizagemEquip espacoAprendizagemEquip) { EspacoAprendizagemEquip = espacoAprendizagemEquip; } public Organizacao getOrganizacao() { return organizacao; } public void setOrganizacao(Organizacao organizacao) { this.organizacao = organizacao; } public ParticipacaoSaeb getParticipacaoSaeb() { return participacaoSaeb; } public void setParticipacaoSaeb(ParticipacaoSaeb participacaoSaeb) { this.participacaoSaeb = participacaoSaeb; } public IdebValores getIdebValores() { return idebValores; } public void setIdebValores(IdebValores idebValores) { this.idebValores = idebValores; } }
<reponame>nkclear/reset_html<filename>_src/js/plugins.js<gh_stars>0 //--------------------------------------------------- //01. ロールオーバーIE6,7,8 or フェードオーバー //02. Auto_blank //03. Heightline //04. Easytabs //05. Jquery.easing.plugin //06. アルファオーバーのみ(置換画像無し).opover //07. ブラウザ判別 //08. 初期設定 // opover/#pagetop //--------------------------------------------------- //ロールオーバー IE6/IE7/IE8ノーマル 画像名_off,_on $(function() { var ua = navigator.userAgent; var isIE = ua.match(/msie/i), isIE6 = ua.match(/msie [6.]/i), isIE7 = ua.match(/msie [7.]/i), isIE8 = ua.match(/msie [8.]/i), isIE9 = ua.match(/msie [9.]/i), isIE10 = ua.match(/msie [10.]/i); //スマホタブレット時OFF if (navigator.userAgent.indexOf('iPhone') > 0 || navigator.userAgent.indexOf('iPad') > 0 || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('Android') > 0) { }else{ //pagetop var topBtn = $('#pagetop img'); topBtn.hide(); //スクロールが100に達したらボタン表示 $(window).scroll(function () { if ($(this).scrollTop() > 100) { topBtn.fadeIn(); } else { topBtn.fadeOut(); } }); $("#pagetop img").click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); //IE判定-統一する場合は下記の1行コメントアウト if(isIE6||isIE7||isIE8){ function smartRollover() { if(document.getElementsByTagName) { var images = document.getElementsByTagName("img"); for(var i=0; i < images.length; i++) { if(images[i].getAttribute("src").match("_off.")) { images[i].onmouseover = function() { this.setAttribute("src", this.getAttribute("src").replace("_off.", "_on.")); } images[i].onmouseout = function() { this.setAttribute("src", this.getAttribute("src").replace("_on.", "_off.")); } } } } } if(window.addEventListener) { window.addEventListener("load", smartRollover, false); } else if(window.attachEvent) { window.attachEvent("onload", smartRollover); } //IE判定-統一する場合は下記の括弧コメントアウト } //ロールオーバー モダンブラウザ、フェードバージョン else{ var targetImgs = $('img'); targetImgs.each(function() { if(this.src.match('_off')) { this.rollOverImg = new Image(); this.rollOverImg.src = this.getAttribute("src").replace("_off", "_on"); $(this.rollOverImg).css({position: 'absolute', opacity: 0}); $(this).before(this.rollOverImg); $(this.rollOverImg).mousedown(function(){ $(this).stop().animate({opacity: 0}, {duration: 0, queue: false}); }); $(this.rollOverImg).hover(function(){ $(this).animate({opacity: 1}, {duration: 400, queue: false}); }, function(){ $(this).animate({opacity: 0}, {duration: 400, queue: false}); }); } }); } } }); //▲▲▲▲▲▲▲▲▲▲ロールオーバー IE6/IE7/IE8ノーマル (function () { var e; var t = function () {}; var n = ["assert", "clear", "count", "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed", "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd", "table", "time", "timeEnd", "timeStamp", "trace", "warn"]; var r = n.length; var i = window.console = window.console || {}; while (r--) { e = n[r]; if (!i[e]) { i[e] = t; } } })(); //_blank var $a = $('a'); var domain = location.hostname; for(var i = -1, n = $a.length, href, $this; ++i < n;) { $this = $($a[i]); href = $this.attr('href'); if( $this.attr('target') !== '_blank' && (domain !== href.split('/')[2] && href.match(/^http:\/\//) || href.match(/^https:\/\//)) || href.match(/\.pdf$/) || $this.hasClass('download') ) { $this.attr('target', '_blank'); } } /*!--------------------------------------------------------------------------* * * jquery.heightLine.js * * MIT-style license. * * 2013 <NAME> * http://www.to-r.net * *--------------------------------------------------------------------------*/ ;(function($){ $.fn.heightLine = function(){ var target = this,fontSizeChangeTimer,windowResizeId= Math.random(); var heightLineObj = { op : { "maxWidth" : 10000, "minWidth" : 0, "fontSizeCheck" : false }, setOption : function(op){ this.op = $.extend(this.op,op); }, destroy : function(){ target.css("height",""); }, create : function(op){ var self = this, maxHeight = 0, windowWidth = $(window).width(); self.setOption(op); if( windowWidth<=self.op.maxWidth && windowWidth>=self.op.minWidth ){ target.each(function(){ if($(this).outerHeight()>maxHeight){ maxHeight = $(this).outerHeight(); } }).each(function(){ var height = maxHeight - parseInt($(this).css("padding-top")) - parseInt($(this).css("padding-bottom")); $(this).height(height); }); } }, refresh : function(op){ this.destroy(); this.create(op); }, removeEvent :function(){ $(window).off("resize."+windowResizeId); target.off("destroy refresh"); clearInterval(fontSizeChangeTimer); } } if(typeof arguments[0] === "string" && arguments[0] === "destroy"){ target.trigger("destroy"); }else if(typeof arguments[0] === "string" && arguments[0] === "refresh"){ target.trigger("refresh"); }else{ heightLineObj["create"](arguments[0]); $(window).on("resize."+windowResizeId,function(){ heightLineObj["refresh"](); }); target.on("destroy",function(){ heightLineObj["removeEvent"](); heightLineObj["destroy"](); }).on("refresh",function(){ heightLineObj["refresh"](); }); if(heightLineObj.op.fontSizeCheck){ if($("#fontSizeChange").length<=0){ var fontSizeChange = $("<span id='fontSizeChange'></span>").css({ width:0, height:"1em", position:"absolute", left:0, top:0 }).appendTo("body"); } var defaultFontSize = $("#fontSizeChange").height(); fontSizeChangeTimer = setInterval(function(){ if(defaultFontSize != $("#fontSizeChange").height()){ heightLineObj["refresh"](); } },100); } } return target; } })(jQuery); /* * jQuery.appear * https://github.com/bas2k/jquery.appear/ * http://code.google.com/p/jquery-appear/ * * Copyright (c) 2009 <NAME> * Copyright (c) 2012 <NAME> * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) */ (function($) { $.fn.appear = function(fn, options) { var settings = $.extend({ //arbitrary data to pass to fn data: undefined, //call fn only on the first appear? one: true, // X & Y accuracy accX: 0, accY: 0 }, options); return this.each(function() { var t = $(this); //whether the element is currently visible t.appeared = false; if (!fn) { //trigger the custom event t.trigger('appear', settings.data); return; } var w = $(window); //fires the appear event when appropriate var check = function() { //is the element hidden? if (!t.is(':visible')) { //it became hidden t.appeared = false; return; } //is the element inside the visible window? var a = w.scrollLeft(); var b = w.scrollTop(); var o = t.offset(); var x = o.left; var y = o.top; var ax = settings.accX; var ay = settings.accY; var th = t.height(); var wh = w.height(); var tw = t.width(); var ww = w.width(); if (y + th + ay >= b && y <= b + wh + ay && x + tw + ax >= a && x <= a + ww + ax) { //trigger the custom event if (!t.appeared) t.trigger('appear', settings.data); } else { //it scrolled out of view t.appeared = false; } }; //create a modified fn with some additional logic var modifiedFn = function() { //mark the element as visible t.appeared = true; //is this supposed to happen only once? if (settings.one) { //remove the check w.unbind('scroll', check); var i = $.inArray(check, $.fn.appear.checks); if (i >= 0) $.fn.appear.checks.splice(i, 1); } //trigger the original fn fn.apply(this, arguments); }; //bind the modified fn to the element if (settings.one) t.one('appear', settings.data, modifiedFn); else t.bind('appear', settings.data, modifiedFn); //check whenever the window scrolls w.scroll(check); //check whenever the dom changes $.fn.appear.checks.push(check); //check now (check)(); }); }; //keep a queue of appearance checks $.extend($.fn.appear, { checks: [], timeout: null, //process the queue checkAll: function() { var length = $.fn.appear.checks.length; if (length > 0) while (length--) ($.fn.appear.checks[length])(); }, //check the queue asynchronously run: function() { if ($.fn.appear.timeout) clearTimeout($.fn.appear.timeout); $.fn.appear.timeout = setTimeout($.fn.appear.checkAll, 20); } }); //run checks when these methods are called $.each(['append', 'prepend', 'after', 'before', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'remove', 'css', 'show', 'hide'], function(i, n) { var old = $.fn[n]; if (old) { $.fn[n] = function() { var r = old.apply(this, arguments); $.fn.appear.run(); return r; } } }); })(jQuery); //jQuery Easing jQuery.easing.jswing=jQuery.easing.swing; jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,a,c,b,d){return jQuery.easing[jQuery.easing.def](e,a,c,b,d)},easeInQuad:function(e,a,c,b,d){return b*(a/=d)*a+c},easeOutQuad:function(e,a,c,b,d){return-b*(a/=d)*(a-2)+c},easeInOutQuad:function(e,a,c,b,d){if((a/=d/2)<1)return b/2*a*a+c;return-b/2*(--a*(a-2)-1)+c},easeInCubic:function(e,a,c,b,d){return b*(a/=d)*a*a+c},easeOutCubic:function(e,a,c,b,d){return b*((a=a/d-1)*a*a+1)+c},easeInOutCubic:function(e,a,c,b,d){if((a/=d/2)<1)return b/ 2*a*a*a+c;return b/2*((a-=2)*a*a+2)+c},easeInQuart:function(e,a,c,b,d){return b*(a/=d)*a*a*a+c},easeOutQuart:function(e,a,c,b,d){return-b*((a=a/d-1)*a*a*a-1)+c},easeInOutQuart:function(e,a,c,b,d){if((a/=d/2)<1)return b/2*a*a*a*a+c;return-b/2*((a-=2)*a*a*a-2)+c},easeInQuint:function(e,a,c,b,d){return b*(a/=d)*a*a*a*a+c},easeOutQuint:function(e,a,c,b,d){return b*((a=a/d-1)*a*a*a*a+1)+c},easeInOutQuint:function(e,a,c,b,d){if((a/=d/2)<1)return b/2*a*a*a*a*a+c;return b/2*((a-=2)*a*a*a*a+2)+c},easeInSine:function(e, a,c,b,d){return-b*Math.cos(a/d*(Math.PI/2))+b+c},easeOutSine:function(e,a,c,b,d){return b*Math.sin(a/d*(Math.PI/2))+c},easeInOutSine:function(e,a,c,b,d){return-b/2*(Math.cos(Math.PI*a/d)-1)+c},easeInExpo:function(e,a,c,b,d){return a==0?c:b*Math.pow(2,10*(a/d-1))+c},easeOutExpo:function(e,a,c,b,d){return a==d?c+b:b*(-Math.pow(2,-10*a/d)+1)+c},easeInOutExpo:function(e,a,c,b,d){if(a==0)return c;if(a==d)return c+b;if((a/=d/2)<1)return b/2*Math.pow(2,10*(a-1))+c;return b/2*(-Math.pow(2,-10*--a)+2)+c}, easeInCirc:function(e,a,c,b,d){return-b*(Math.sqrt(1-(a/=d)*a)-1)+c},easeOutCirc:function(e,a,c,b,d){return b*Math.sqrt(1-(a=a/d-1)*a)+c},easeInOutCirc:function(e,a,c,b,d){if((a/=d/2)<1)return-b/2*(Math.sqrt(1-a*a)-1)+c;return b/2*(Math.sqrt(1-(a-=2)*a)+1)+c},easeInElastic:function(e,a,c,b,d){e=1.70158;var f=0,g=b;if(a==0)return c;if((a/=d)==1)return c+b;f||(f=d*0.3);if(g<Math.abs(b)){g=b;e=f/4}else e=f/(2*Math.PI)*Math.asin(b/g);return-(g*Math.pow(2,10*(a-=1))*Math.sin((a*d-e)*2*Math.PI/f))+c},easeOutElastic:function(e, a,c,b,d){e=1.70158;var f=0,g=b;if(a==0)return c;if((a/=d)==1)return c+b;f||(f=d*0.3);if(g<Math.abs(b)){g=b;e=f/4}else e=f/(2*Math.PI)*Math.asin(b/g);return g*Math.pow(2,-10*a)*Math.sin((a*d-e)*2*Math.PI/f)+b+c},easeInOutElastic:function(e,a,c,b,d){e=1.70158;var f=0,g=b;if(a==0)return c;if((a/=d/2)==2)return c+b;f||(f=d*0.3*1.5);if(g<Math.abs(b)){g=b;e=f/4}else e=f/(2*Math.PI)*Math.asin(b/g);if(a<1)return-0.5*g*Math.pow(2,10*(a-=1))*Math.sin((a*d-e)*2*Math.PI/f)+c;return g*Math.pow(2,-10*(a-=1))*Math.sin((a* d-e)*2*Math.PI/f)*0.5+b+c},easeInBack:function(e,a,c,b,d,f){if(f==undefined)f=1.70158;return b*(a/=d)*a*((f+1)*a-f)+c},easeOutBack:function(e,a,c,b,d,f){if(f==undefined)f=1.70158;return b*((a=a/d-1)*a*((f+1)*a+f)+1)+c},easeInOutBack:function(e,a,c,b,d,f){if(f==undefined)f=1.70158;if((a/=d/2)<1)return b/2*a*a*(((f*=1.525)+1)*a-f)+c;return b/2*((a-=2)*a*(((f*=1.525)+1)*a+f)+2)+c},easeInBounce:function(e,a,c,b,d){return b-jQuery.easing.easeOutBounce(e,d-a,0,b,d)+c},easeOutBounce:function(e,a,c,b,d){return(a/= d)<1/2.75?b*7.5625*a*a+c:a<2/2.75?b*(7.5625*(a-=1.5/2.75)*a+0.75)+c:a<2.5/2.75?b*(7.5625*(a-=2.25/2.75)*a+0.9375)+c:b*(7.5625*(a-=2.625/2.75)*a+0.984375)+c},easeInOutBounce:function(e,a,c,b,d){if(a<d/2)return jQuery.easing.easeInBounce(e,a*2,0,b,d)*0.5+c;return jQuery.easing.easeOutBounce(e,a*2-d,0,b,d)*0.5+b*0.5+c}}); $(function(){ //pagetop var topBtn = $('#pagetop'); topBtn.hide(); //スクロールが100に達したらボタン表示 $(window).scroll(function () { if ($(this).scrollTop() > 100) { topBtn.fadeIn(); } else { topBtn.fadeOut(); } }); $("#pagetop").click(function () { $('body,html').animate({ scrollTop: 0 }, 300,"easeInOutCubic"); return false; }); }); $(document).ready(function() { $('.item_top').each(function() { $(this).appear(function() { $(this).delay(250).animate({ opacity : 1, top : "0px" }, 1000, 'easeOutExpo'); }); }); $('.item_bottom').each(function() { $(this).appear(function() { $(this).delay(300).animate({ opacity : 1, bottom : "0px" }, 1000, 'easeOutExpo'); }); }); $('.item_left').each(function() { $(this).appear(function() { $(this).delay(250).animate({ opacity : 1, left : "0px" }, 1000, 'easeOutExpo'); }); }); $('.item_right').each(function() { $(this).appear(function() { $(this).delay(250).animate({ opacity : 1, right : "0px" }, 1000, 'easeOutExpo'); }); }); $('.item_fade_in').each(function() { $(this).appear(function() { $(this).delay(250).animate({ opacity : 1, right : "0px" }, 1000, 'easeOutExpo'); }); }); });
<reponame>Darian1996/mercyblitz-gp-public package com.darian.oopdesignpattern.observer; import java.util.Observable; /*** * 观察者模式 Demo * Observable 是一个维护有序的 Observer 集合 , Subject、Publisher * Observer = consumer = Subscriber */ public class ObserverDemo { public static void main(String[] args) { // JDk 存在观察者模式的实现。 MyObservable observable = new MyObservable(); observable.addObserver((o, arg) -> { System.out.println("观察者 1:邮件订阅:" + arg); }); observable.addObserver((o, arg) -> { System.out.println("观察者 2:邮件订阅:" + arg); }); observable.addObserver((o, arg) -> { System.out.println("观察者 3:邮件订阅:" + arg); }); // 调整变化 observable.setChanged(); // 通知变化到所有观察者 observable.notifyObservers("邮件通知:Hello, World"); } private static class MyObservable extends Observable{ // 子类提升方法从 protected 到 public @Override public synchronized void setChanged() { super.setChanged(); } } }
package com.example.nhl; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.util.SparseArray; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.nhl.activities.AddUserActivity; import com.example.nhl.model.User; import com.example.nhl.network.NetworkService; import com.google.android.gms.vision.Frame; import com.google.android.gms.vision.text.TextBlock; import com.google.android.gms.vision.text.TextRecognizer; import java.util.ArrayList; import java.util.List; import java.util.Objects; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class PhotoActivity extends AppCompatActivity { ImageView imageView; TextView textView; private static final int CAMERA_REQUEST = 1888; private static final int MY_CAMERA_PERMISSION_CODE = 100; @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); } @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo); imageView = findViewById(R.id.imageViewTextImage); imageView.setDrawingCacheEnabled(true); textView = findViewById(R.id.textViewFromImage); if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE); } else { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_CAMERA_PERMISSION_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show(); Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQUEST); } else { Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) { int orientation = getResources().getConfiguration().orientation; int degress = 0; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.w("test","dont touch degrees"); } else { degress = 90; } Matrix matrix = new Matrix(); matrix.postRotate(degress); Bitmap photo = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data"); assert photo != null; Bitmap finalBitmap = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); imageView.setImageBitmap(finalBitmap); goToAddUser(); } } public void goToAddUser(){ Intent intent = new Intent(this, AddUserActivity.class); intent.putExtra("name", getTextFromImage()); startActivity(intent); } public String getTextFromImage() { Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build(); if (!textRecognizer.isOperational()) { Toast.makeText(getApplicationContext(), "could not have text", Toast.LENGTH_SHORT).show(); } else { Frame frame = new Frame.Builder().setBitmap(bitmap).build(); SparseArray<TextBlock> items = textRecognizer.detect(frame); StringBuilder sb = new StringBuilder(); for (int i = 0; i < items.size(); i++) { TextBlock item = items.valueAt(i); sb.append(item.getValue()); sb.append("\n"); } return sb.toString(); } return ""; } }
require_relative '../pcmk_common' Puppet::Type.type(:pcmk_property).provide(:default) do desc 'A base resource definition for a pacemaker property' ### overloaded methods def create property = @resource[:property] node = @resource[:node] value = @resource[:value] cmd = "property set" if not_empty_string(@resource[:force]) cmd += " --force" end if not_empty_string(node) cmd += " --node #{node}" end cmd += " #{property}=#{value}" ret = pcs('create', @resource[:property], cmd, @resource[:tries], @resource[:try_sleep]) Puppet.debug("property create: #{cmd} -> #{ret}") return ret end def destroy property = @resource[:property] node = @resource[:node] cmd = "property unset" if not_empty_string(node) cmd += " --node #{node}" end cmd += " #{property}" ret = pcs('delete', @resource[:property], cmd, @resource[:tries], @resource[:try_sleep]) Puppet.debug("property destroy: #{cmd} -> #{ret}") return ret end def exists? property = @resource[:property] node = @resource[:node] cmd = "property show | grep #{property}" if not_empty_string(node) cmd += " | grep #{node}" end cmd += " > /dev/null 2>&1" ret = pcs('show', @resource[:property], cmd, @resource[:tries], @resource[:try_sleep]) Puppet.debug("property exists: #{cmd} -> #{ret}") return ret == false ? false : true end end
<reponame>code-check/github-api package codecheck.github package operations import exceptions._ import models._ import org.scalatest.FunSpec import scala.concurrent.Await class LabelOpSpec extends FunSpec with api.Constants { val number = 1 val gName = generateRandomWord describe("removeAllLabels") { it("should succeed") { val result = Await.result(api.removeAllLabels(user, userRepo, number), TIMEOUT) assert(result.length == 0) } } describe("addLabel") { it("should succeed") { val result = Await.result(api.addLabels(user, userRepo, number, "bug"), TIMEOUT) assert(result.length == 1) val label = result.head assert(label.name == "bug") assert(label.url.length > 0) assert(label.color.length == 6) } } describe("replaceLabels") { it("should succeed") { val result = Await.result(api.replaceLabels(user, userRepo, number, "duplicate", "invalid"), TIMEOUT) assert(result.length == 2) assert(result.filter(_.name == "duplicate").length == 1) assert(result.filter(_.name == "invalid").length == 1) } } describe("removeLabel") { it("should succeed") { val result = Await.result(api.removeLabel(user, userRepo, number, "duplicate"), TIMEOUT) assert(result.length == 1) val result2 = Await.result(api.removeLabel(user, userRepo, number, "invalid"), TIMEOUT) assert(result2.length == 0) } } describe("listLabels") { it("listLabels should succeed") { Await.result(api.addLabels(user, userRepo, number, "invalid"), TIMEOUT) val result = Await.result(api.listLabels(user, userRepo, number), TIMEOUT) assert(result.length == 1) val label = result.head assert(label.name == "invalid") assert(label.url.length > 0) assert(label.color.length == 6) } } describe("listLabelDefs") { it("should succeed") { val result = Await.result(api.listLabelDefs(user, userRepo), TIMEOUT) assert(result.length > 0) val label = result.head assert(label.name.length > 0) assert(label.url.length > 0) assert(label.color.length == 6) } } describe("getLabelDef") { it("should succeed") { Await.result(api.getLabelDef(user, userRepo, "question"), TIMEOUT).map { label => assert(label.name == "question") assert(label.url.length > 0) assert(label.color == "cc317c") } } it("should be None") { assert(Await.result(api.getLabelDef(user, userRepo, "hoge"), TIMEOUT).isEmpty) } } describe("createLabelDef") { it("should succeed") { val input = LabelInput(gName, "cc317c") val label = Await.result(api.createLabelDef(user, userRepo, input), TIMEOUT) assert(label.name == gName) assert(label.url.length > 0) assert(label.color == "cc317c") } it("again should fail") { val input = LabelInput(gName, "cc317c") try { val label = Await.result(api.createLabelDef(user, userRepo, input), TIMEOUT) fail } catch { case e: GitHubAPIException => assert(e.error.errors.length == 1) assert(e.error.errors.head.code == "already_exists") } } } describe("updateLabelDef") { it("should succeed") { val input = LabelInput(gName, "84b6eb") val label = Await.result(api.updateLabelDef(user, userRepo, gName, input), TIMEOUT) assert(label.name == gName) assert(label.url.length > 0) assert(label.color == "84b6eb") } } describe("removeLabelDef") { it("should succeed") { val result = Await.result(api.removeLabelDef(user, userRepo, gName), TIMEOUT) assert(result) } it("removeLabelDef again should fail") { try { val result = Await.result(api.removeLabelDef(user, userRepo, gName), TIMEOUT) fail } catch { case e: NotFoundException => assert(e.error.errors.length == 0) } } } }
import { ContainerCreateOptions } from 'dockerode' export interface User { id?: number name?: string email?: string password?: string } export interface Deploy { id?: number nameProject?: string secret?: string email?: string local?: boolean host?: string port?: number apiIdFk?: number userIdFk?: number } export interface Container { id?: number order?: number config?: ContainerCreateOptions deployIdFk?: number userIdFk?: number }
<filename>frontend/src/filters/index.ts /* * Copyright (c) 2020-2021 - for information on the respective copyright owner * see the NOTICE file and/or the repository at * https://github.com/hyperledger-labs/business-partner-agent * * SPDX-License-Identifier: Apache-2.0 */ import Vue from "vue"; import moment from "moment"; /** * @function formatDate * Converts a date to an 'YYYY-MM-DD' formatted string * @param {Date, String, Long} value A date object * @returns {String} A string representation of `value` */ export function formatDate(value) { if (value) { return moment(value).format("YYYY-MM-DD"); } } /** * @function formatDateLong * Converts a date to an 'YYYY-MM-DD HH:mm' formatted string * @param {Date, String, Long} value A date object * @returns {String} A string representation of `value` */ export function formatDateLong(value) { if (value) { return moment(value).format("YYYY-MM-DD HH:mm"); } } export function credentialTag(credDefinitionId) { if (!credDefinitionId) return ""; const pos = credDefinitionId.lastIndexOf(":"); return credDefinitionId.slice(Math.max(0, pos + 1)); } export function capitalize(string) { return string && string !== "" ? string.replace(/\w\S*/g, (w) => w.replace(/^\w/, (c) => c.toUpperCase())) : ""; } // Define Global Vue Filters // // {{ expression | filter }} // Vue.filter("formatDate", formatDate); Vue.filter("formatDateLong", formatDateLong); Vue.filter("credentialTag", credentialTag); Vue.filter("capitalize", capitalize);
#!/usr/bin/env bash osism apply bootstrap osism apply homer # NOTE: comment the following lines if Ceph is used sudo pvcreate /dev/sdb sudo vgcreate cinder-volumes /dev/sdb osism apply iscsi osism apply common osism apply haproxy osism apply elasticsearch osism apply kibana osism apply openvswitch osism apply memcached osism apply redis osism apply etcd osism apply mariadb osism apply phpmyadmin osism apply rabbitmq osism apply keystone osism apply horizon osism apply placement osism apply glance osism apply neutron osism apply nova osism apply cinder osism apply ironic osism apply openstackclient osism apply --environment custom bootstrap-openstack
<gh_stars>1-10 /* globals locale */ 'use strict'; var utils = {}; utils.prettyDate = time => { const date = new Date((time || '')); const diff = (((new Date()).getTime() - date.getTime()) / 1000); const dayDiff = Math.floor(diff / 86400); if (isNaN(dayDiff) || dayDiff < 0) { return 'just now'; } return dayDiff === 0 && ( diff < 60 && locale.get('popup_msg_1') || diff < 120 && locale.get('popup_msg_2') || diff < 3600 && locale.get('popup_msg_3_format').replace('%d', Math.floor(diff / 60)) || diff < 7200 && locale.get('popup_msg_4') || diff < 86400 && Math.floor(diff / 3600) + ' ' + locale.get('popup_msg_5')) || dayDiff === 1 && locale.get('popup_msg_6') || dayDiff < 7 && locale.get('popup_msg_7_format').replace('%d', dayDiff) || dayDiff < 7 * 7 && locale.get('popup_msg_8_format').replace('%d', Math.ceil(dayDiff / 7)) || dayDiff < 7 * 4 * 3 && locale.get('popup_msg_9_format').replace('%d', Math.ceil(dayDiff / 7 / 4)) || locale.get('popup_date_format') .replace('%dd', date.getDate()) .replace('%yy', date.getFullYear().toString()) .replace('%mm', [ locale.get('popup_msg_10'), locale.get('popup_msg_11'), locale.get('popup_msg_12'), locale.get('popup_msg_13'), locale.get('popup_msg_14'), locale.get('popup_msg_15'), locale.get('popup_msg_16'), locale.get('popup_msg_17'), locale.get('popup_msg_18'), locale.get('popup_msg_19'), locale.get('popup_msg_20'), locale.get('popup_msg_21') ][date.getMonth()]); };
#!/bin/sh DIR=$HOME/.koala KOALA=$DIR/bin/koala.sh BIN=/usr/local/bin/koala cat ../src/info.txt echo "[*] Koala Toolkit Upgrade" echo "[*] Uninstall current version" docker container kill afigueir/koala docker container rm afigueir/koala docker image rm afigueir/koala docker image rm kalilinux/kali-rolling rm -rf $BIN rm -rf $DIR echo "[*] Git clone lxndrfgrd/koala" git clone https://github.com/afigueir/koala.git $DIR echo "[*] Install scripts in /usr/local/bin" chmod +x $KOALA && ln -sf $KOALA $BIN
describe('eslint-sagui-bug', function () { it('should work', function () { }) })
import { Test, TestingModule } from '@nestjs/testing'; import { CellService } from '../cell.service'; import { CellRepository } from '../cell.repository'; import { HttpService } from '@nestjs/common'; import { BlockService } from '../../block/block.service'; import { AddressService } from '../../address/address.service'; import { mockCellsResult, page, lockHash, step,mockTransactionResult, mockGetTxHistoriesResult } from './cell.data.spec'; import { CkbService } from '../../ckb/ckb.service'; describe('CellService', () => { let cellService; let cellRepository; let ckbService; // mock reposity const mockCellRepository = () => ({ queryCellsByLockHash: jest.fn(), }); // 1-mock httpService class HttpServiceMock {} const HttpServiceProvider = { provide: HttpService, useClass: HttpServiceMock, }; // 2-mock blockService class BlockServiceMock {} const BlockServiceProvider = { provide: BlockService, useClass: BlockServiceMock, }; // 3- mock AddressService class AddressServiceMock {} const AddressServiceProvider = { provide: AddressService, useClass: AddressServiceMock, }; // 4- mock CKBService const mockCKBService = () => ({ getCKB: ()=> { return { rpc: { getHeaderByNumber: blockNumber => Promise.resolve({ timestamp: '100' }), getTransaction: txHash => Promise.resolve(mockTransactionResult) } }; } }); const CKBServiceProvider = { provide: CkbService, // useClass: CKBServiceMock, useFactory: mockCKBService, }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ CellService, { provide: CellRepository, useFactory: mockCellRepository, }, HttpServiceProvider, BlockServiceProvider, AddressServiceProvider, CKBServiceProvider, ], }).compile(); cellService = await module.get<CellService>(CellService); cellRepository = await module.get<CellRepository>(CellRepository); ckbService = await module.get<CkbService>(CkbService); }); describe('get tx histories by lockScript', () => { it('get tx histories by lockScript', async () => { cellRepository.queryCellsByLockHash.mockResolvedValue(mockCellsResult); const result = await cellService.getTxHistoriesByLockHash( lockHash, step, page, ); expect(result).toEqual(mockGetTxHistoriesResult); expect(cellRepository.queryCellsByLockHash).toHaveBeenCalledWith( lockHash, step, page, ); }); }); });
<gh_stars>0 class Sort { def sort(xs: Array[Int]): Array[Int] = if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter ( x => pivot > x)), xs filter ( x => pivot == x), sort(xs filter ( x => pivot < x))) } }
class PantriesController < ApplicationController before_action :authenticate_user! before_action :set_pantry, only: %i[ edit update destroy ] # GET /pantries or /pantries.json def index user = User.find(current_user.id) @pantry = user.try(:pantry) if @pantry redirect_to pantry_path(@pantry.id) else redirect_to new_pantry_path end end # GET /pantries/1 or /pantries/1.json def show user = User.find(current_user.id) @pantry = user.pantry end # GET /pantries/new def new @pantry = Pantry.new end # GET /pantries/1/edit def edit end # POST /pantries or /pantries.json def create @pantry = Pantry.new(pantry_params) respond_to do |format| if @pantry.save current_user.update(pantry_id: @pantry.id) format.html { redirect_to pantry_url(@pantry), notice: "Pantry was successfully created." } format.json { render :show, status: :created, location: @pantry } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @pantry.errors, status: :unprocessable_entity } end end end # PATCH/PUT /pantries/1 or /pantries/1.json def update respond_to do |format| if @pantry.update(pantry_params) format.html { redirect_to pantry_url(@pantry), notice: "Pantry was successfully updated." } format.json { render :show, status: :ok, location: @pantry } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @pantry.errors, status: :unprocessable_entity } end end end # DELETE /pantries/1 or /pantries/1.json def destroy @pantry.destroy respond_to do |format| format.html { redirect_to pantries_url, notice: "Pantry was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_pantry puts "PARAMS PANTRY" puts params @pantry = Pantry.find(params[:id]) end # Only allow a list of trusted parameters through. def pantry_params params.fetch(:pantry, {}).permit(:user_id, :name) end end
<gh_stars>0 /****************************************************************************** * Copyright 2011 Kitware Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "MidasResourceDescTable.h" #include "midasUtils.h" /** Constructor */ QTableWidgetDescriptionItem::QTableWidgetDescriptionItem(const char* text, QTableWidgetDescriptionItem::Options options) { /*if ( options & Tooltip ) { this->setToolTip( text ); }*/ this->setText(text); if( options & Bold ) { QFont boldfont; boldfont.setBold(true); this->setFont(boldfont); } if( !(options & Editable) ) { this->setFlags(~ Qt::ItemFlags(Qt::ItemIsEditable) ); } /*if ( options & AlignLeft ) { this->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); } else { this->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); }*/ } void MidasResourceDescTable::contextMenuEvent(QContextMenuEvent* e) { emit midasTableWidgetContextMenu(e); }
#!/bin/bash # Add your languages to this array, with spaces in between - Example: languages=("en" "es" "zh") declare -a languages=("en") # 1. Get the current working directory cwd=${PWD##*/} # 2. Generate this bot to capture all microservices cd ../ ./botengine --generate $cwd cd $cwd # 3. Update the .pot file template for all languages pybabel extract -o ./locale/messages.pot -c NOTE: -s ../.$cwd # 4. Loop through every language and update the .po file for i in "${languages[@]}" do if [ ! -d "./locale/$i/LC_MESSAGES" ]; then # 4a. Initialize the new language directory .po file echo "" echo "Initializing the new language directory : $i" pybabel init -D 'messages' -i ./locale/messages.pot -d ./locale -l $i else # 4b. Update the existing language directory .po file echo "" echo "Updating the existing language directory .po file : $i" pybabel update -D 'messages' -i ./locale/messages.pot -d ./locale -l $i fi # 5. Compile the .po file into the .mo file pybabel compile -D 'messages' -d ./locale -l $i -i ./locale/$i/LC_MESSAGES/messages.po -f done
gpu=$1 fweight=$2 initlr=$3 name=$(echo icm_supervised_box3dpixel_v11_fw_${fweight}_lr_${initlr}) CUDA_VISIBLE_DEVICES=$gpu python train_icm_supervised.py Box3dReachPixel-v11 /z/dianchen/v11 --cos_forward --init_lr $initlr --forward_weight $fweight --tfmodel_path "/z/dianchen/tfmodel_box3d/$name.pkl" --tfboard_path "/z/dianchen/tfboard_box3d/$name"
#ifndef SliceOptions_h #define SliceOptions_h #include <iostream> #include <string> #include <vector> #include <SinglyLinkedList.h> #include <AstInterface.h> class ArrangeNestingOrder; class LoopNestFusion; class LoopBlocking; class LoopPar; class CopyArrayOperator; class AstNodePtr; class LoopTransformInterface; class ROSE_DLL_API LoopTransformOptions { public: class OptRegistryType { std::string name, expl; public: virtual void operator ()(LoopTransformOptions &opt, unsigned& index, const std::vector<std::string>& argv)=0; OptRegistryType( const std::string &s1, const std::string &s2) : name(s1), expl(s2) {} std::string GetName() const { return name; } std::string GetExpl() const { return expl; } virtual ~OptRegistryType() {} }; private: static LoopTransformOptions *inst; SinglyLinkedListWrap <OptRegistryType*> reg; ArrangeNestingOrder *icOp; LoopNestFusion *fsOp; LoopBlocking *bkOp; LoopPar * parOp; CopyArrayOperator* cpOp; unsigned cacheline, reuseDist, splitlimit, defaultblocksize, parblocksize; LoopTransformOptions(); virtual ~LoopTransformOptions(); public: static LoopTransformOptions* GetInstance () ; void PrintUsage(std::ostream& stream) const ; void RegisterOption( OptRegistryType* t); LoopBlocking* GetBlockSel() const { return bkOp; } LoopPar* GetParSel() const { return parOp; } CopyArrayOperator* GetCopyArraySel() const { return cpOp; } ArrangeNestingOrder* GetInterchangeSel() const { return icOp; } LoopNestFusion* GetFusionSel() const { return fsOp; } unsigned GetCacheLineSize() const { return cacheline; } unsigned GetReuseDistance() const { return reuseDist; } unsigned GetTransAnalSplitLimit() const { return splitlimit; } unsigned GetDefaultBlockSize() const { return defaultblocksize; } unsigned GetParBlockSize() const { return parblocksize; } void SetDefaultBlockSize(unsigned size) { defaultblocksize = size; } void SetParBlockSize(unsigned size) { parblocksize = size; } bool DoDynamicTuning() const; unsigned GetDynamicTuningIndex() const; typedef enum {NO_OPT = 0, LOOP_NEST_OPT = 1, INNER_MOST_OPT = 2, MULTI_LEVEL_OPT = 3, LOOP_OPT = 3, DATA_OPT = 4, LOOP_DATA_OPT = 7, PAR_OPT=8, PAR_LOOP_OPT=11, PAR_LOOP_DATA_OPT=15} OptType; OptType GetOptimizationType(); void SetOptions (const std::vector<std::string>& argvList, std::vector<std::string>* known_opt=0); void SetBlockSel( LoopBlocking* sel); void SetParSel( LoopPar* sel); void SetCopySel( CopyArrayOperator* sel); void SetInterchangeSel( ArrangeNestingOrder* sel); void SetFusionSel( LoopNestFusion* sel); void SetCacheLineSize( unsigned sel) { cacheline = sel; } void SetReuseDistance( unsigned sel) { reuseDist = sel; } void SetTransAnalSplitLimit( unsigned sel) { splitlimit = sel; } }; #endif
<gh_stars>0 package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 场景(如消费/核身)消息上报接口 * * @author auto create * @since 1.0, 2021-07-23 15:19:34 */ public class AlipayCommerceKidsMsgSceneSendModel extends AlipayObject { private static final long serialVersionUID = 1373469718324963972L; /** * 业务码 */ @ApiField("biz_code") private String bizCode; /** * operator_name:刷脸行为人,如学生或教职工,必填;school_name:学校名称,必填;school_stdcode:学校外标,必填;link:如alipays://platformapi/startapp?appId=xxxx,必填;memo:备注信息,必填;target_userid:消息接入人uid,必填;operator_userid:刷脸行为人UID,必填; contact_info:联系信息,必填; */ @ApiField("biz_data") private String bizData; /** * 业务真实发生时间,如核身时间点,消费支付时间点。格式要求yyyy-MM-dd HH:mm:ss */ @ApiField("biz_time") private String bizTime; /** * 外部业务唯一编号,重复报错 */ @ApiField("out_biz_no") private String outBizNo; /** * 业务类型,确定数据使用场景。就餐提醒:school_facepay、离校提醒:school_entrance_out、入校提醒:school_entrance_in,考勤提醒:school_sign */ @ApiField("template_code") private String templateCode; /** * 模板版本号,默认为1.0 */ @ApiField("template_code_version") private String templateCodeVersion; public String getBizCode() { return this.bizCode; } public void setBizCode(String bizCode) { this.bizCode = bizCode; } public String getBizData() { return this.bizData; } public void setBizData(String bizData) { this.bizData = bizData; } public String getBizTime() { return this.bizTime; } public void setBizTime(String bizTime) { this.bizTime = bizTime; } public String getOutBizNo() { return this.outBizNo; } public void setOutBizNo(String outBizNo) { this.outBizNo = outBizNo; } public String getTemplateCode() { return this.templateCode; } public void setTemplateCode(String templateCode) { this.templateCode = templateCode; } public String getTemplateCodeVersion() { return this.templateCodeVersion; } public void setTemplateCodeVersion(String templateCodeVersion) { this.templateCodeVersion = templateCodeVersion; } }
import requests import sqlite3 # Establish a connection to the database conn = sqlite3.connect('database.db') # Fetch data from API data = requests.get("https://api.example.com/v1/resources").json() # Store the data in the database c = conn.cursor() c.execute("CREATE TABLE IF NOT EXISTS data (data_id INTEGER PRIMARY KEY, data_name TEXT, data_value TEXT)") for item in data: c.execute("INSERT INTO data (data_name, data_value) VALUES (?,?)", (item['name'], item['value'])) # Commit changes and close the connection conn.commit() conn.close()
json.extract! user, :id json.username user.the_username json.name user.the_name json.avatar user.the_avatar json.url user.the_url
<filename>algorithm/300/373-kSmallestPairs.go //给定两个以 升序排列 的整数数组 nums1 和 nums2 , 以及一个整数 k 。 // // 定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2 。 // // 请找到和最小的 k 个数对 (u1,v1), (u2,v2) ... (uk,vk) 。 // // // // 示例 1: // // //输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 //输出: [1,2],[1,4],[1,6] //解释: 返回序列中的前 3 对数: // [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] // // // 示例 2: // // //输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 //输出: [1,1],[1,1] //解释: 返回序列中的前 2 对数: //  [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] // // // 示例 3: // // //输入: nums1 = [1,2], nums2 = [3], k = 3 //输出: [1,3],[2,3] //解释: 也可能序列中所有的数对都被返回:[1,3],[2,3] // // // // // 提示: // // // 1 <= nums1.length, nums2.length <= 10⁵ // -10⁹ <= nums1[i], nums2[i] <= 10⁹ // nums1 和 nums2 均为升序排列 // 1 <= k <= 1000 // // Related Topics 数组 堆(优先队列) 👍 307 👎 0 package algorithm_300 import "container/heap" func kSmallestPairs(nums1 []int, nums2 []int, k int) [][]int { var res [][]int var n, m = len(nums1), len(nums2) var h = &hp{nil, nums1, nums2} for i := 0; i < k && i < n; i++ { h.data = append(h.data, index{i, 0}) } for h.Len() > 0 && len(res) < k { num := heap.Pop(h) res = append(res, []int{nums1[num.(index).i], nums2[num.(index).j]}) if num.(index).j+1 < m { heap.Push(h, index{num.(index).i, num.(index).j + 1}) } } return res } type index struct { i, j int } type hp struct { data []index nums1, nums2 []int } func (h hp) Len() int { return len(h.data) } func (h hp) Less(i, j int) bool { return h.nums1[h.data[i].i]+h.nums2[h.data[i].j] < h.nums1[h.data[j].i]+h.nums2[h.data[j].j] } func (h hp) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] } func (h *hp) Push(x interface{}) { h.data = append(h.data, x.(index)) } func (h *hp) Pop() interface{} { old := h.data n := len(old) x := old[n-1] h.data = old[0 : n-1] return x }
def reverse_string(string): return string[::-1]
############################################################################# ## ## Copyright (C) 2013 Riverbank Computing Limited. ## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:LGPL$ ## Commercial Usage ## Licensees holding valid Qt Commercial licenses may use this file in ## accordance with the Qt Commercial License Agreement provided with the ## Software or, alternatively, in accordance with the terms contained in ## a written agreement between you and Nokia. ## ## GNU Lesser General Public License Usage ## Alternatively, this file may be used under the terms of the GNU Lesser ## General Public License version 2.1 as published by the Free Software ## Foundation and appearing in the file LICENSE.LGPL included in the ## packaging of this file. Please review the following information to ## ensure the GNU Lesser General Public License version 2.1 requirements ## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ## ## In addition, as a special exception, Nokia gives you certain additional ## rights. These rights are described in the Nokia Qt LGPL Exception ## version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ## ## GNU General Public License Usage ## Alternatively, this file may be used under the terms of the GNU ## General Public License version 3.0 as published by the Free Software ## Foundation and appearing in the file LICENSE.GPL included in the ## packaging of this file. Please review the following information to ## ensure the GNU General Public License version 3.0 requirements will be ## met: http://www.gnu.org/copyleft/gpl.html. ## ## If you have questions regarding the use of this file, please contact ## Nokia at <EMAIL>. ## $QT_END_LICENSE$ ## ############################################################################# import sys from PyQt5.QtGui import QColor, QFont from PyQt5.QtWidgets import QMessageBox, QWidget class Colors(object): # Colors: sceneBg1 = QColor(91, 91, 91) sceneBg1Line = QColor(114, 108, 104) sceneBg2 = QColor(0, 0, 0) sceneLine = QColor(255, 255, 255) paperBg = QColor(100, 100, 100) menuTextFg = QColor(255, 0, 0) buttonBgLow = QColor(255, 255, 255, 90) buttonBgHigh = QColor(255, 255, 255, 20) buttonText = QColor(255, 255, 255) tt_green = QColor(166, 206, 57) fadeOut = QColor(206, 246, 117, 0) heading = QColor(190, 230, 80) contentColor = "<font color='#eeeeee'>" glVersion = "Not detected!" # Guides: stageStartY = 8 stageHeight = 536 stageStartX = 8 stageWidth = 785 contentStartY = 22 contentHeight = 510 # Properties: noTicker = False noRescale = False noAnimations = False noBlending = False noScreenSync = False fullscreen = False usePixmaps = False useLoop = False showBoundingRect = False showFps = False noAdapt = False noWindowMask = True useButtonBalls = False useEightBitPalette = False noTimerUpdate = False noTickerMorph = False adapted = False verbose = False pause = True fps = 100 menuCount = 18 animSpeed = 1.0 benchmarkFps = -1.0 tickerLetterCount = 80; tickerMoveSpeed = 0.4 tickerMorphSpeed = 2.5 tickerText = ".EROM ETAERC .SSEL EDOC" rootMenuName = "PyQt Examples" @staticmethod def contentFont(): font = QFont() font.setStyleStrategy(QFont.PreferAntialias) if sys.platform == 'darwin': font.setPixelSize(14) font.setFamily('Arial') else: font.setPixelSize(13) font.setFamily('Verdana') return font @staticmethod def headingFont(): font = QFont() font.setStyleStrategy(QFont.PreferAntialias) font.setPixelSize(23) font.setBold(True) font.setFamily('Verdana') return font; @staticmethod def buttonFont(): font = QFont() font.setStyleStrategy(QFont.PreferAntialias) font.setPixelSize(11) font.setFamily('Verdana') return font @staticmethod def tickerFont(): font = QFont() font.setStyleStrategy(QFont.PreferAntialias) if sys.platform == 'darwin': font.setPixelSize(11) font.setBold(True) font.setFamily('Arial') else: font.setPixelSize(10) font.setBold(True) font.setFamily('sans serif') return font @classmethod def debug(cls, *args): if cls.verbose: sys.stderr.write("%s\n" % " ".join([str(arg) for arg in args])) @classmethod def parseArgs(cls, argv): # Some arguments should be processed before others. Handle them now. if "-verbose" in argv: cls.verbose = True # Handle the rest of the arguments. They may override attributes # already set. for s in argv: if s == "-no-ticker": cls.noTicker = True elif s.startswith("-ticker"): cls.noTicker = not bool(parseFloat(s, "-ticker")) elif s == "-no-animations": cls.noAnimations = True elif s.startswith("-animations"): cls.noAnimations = not bool(parseFloat(s, "-animations")) elif s == "-no-adapt": # Don't adapt the animations based on the actual performance. cls.noAdapt = True elif s == "-low": cls.setLowSettings() elif s == "-no-rescale": cls.noRescale = True elif s == "-use-pixmaps": cls.usePixmaps = True elif s == "-fullscreen": cls.fullscreen = True elif s == "-show-br": cls.showBoundingRect = True elif s == "-show-fps": cls.showFps = True elif s == "-no-blending": cls.noBlending = True elif s == "-no-sync": cls.noScreenSync = True elif s.startswith("-menu"): cls.menuCount = int(parseFloat(s, "-menu")) elif s.startswith("-use-timer-update"): cls.noTimerUpdate = not bool(parseFloat(s, "-use-timer-update")) elif s.startswith("-pause"): cls.pause = bool(parseFloat(s, "-pause")) elif s == "-no-ticker-morph": cls.noTickerMorph = True elif s == "-use-window-mask": cls.noWindowMask = False elif s == "-use-loop": cls.useLoop = True elif s == "-use-8bit": cls.useEightBitPalette = True elif s.startswith("-8bit"): cls.useEightBitPalette = bool(parseFloat(s, "-8bit")) elif s == "-use-balls": cls.useButtonBalls = True elif s.startswith("-ticker-letters"): cls.tickerLetterCount = int(parseFloat(s, "-ticker-letters")) elif s.startswith("-ticker-text"): cls.tickerText = parseText(s, "-ticker-text") elif s.startswith("-ticker-speed"): cls.tickerMoveSpeed = parseFloat(s, "-ticker-speed") elif s.startswith("-ticker-morph-speed"): cls.tickerMorphSpeed = parseFloat(s, "-ticker-morph-speed") elif s.startswith("-animation-speed"): cls.animSpeed = parseFloat(s, "-animation-speed") elif s.startswith("-fps"): cls.fps = int(parseFloat(s, "-fps")) elif s.startswith("-h") or s.startswith("-help"): QMessageBox.warning(None, "Arguments", "Usage: qtdemo.py [-verbose] [-no-adapt] " "[-fullscreen] [-ticker[0|1]] " "[-animations[0|1]] [-no-blending] [-no-sync] " "[-use-timer-update[0|1]] [-pause[0|1]] " "[-use-window-mask] [-no-rescale] [-use-pixmaps] " "[-show-fps] [-show-br] [-8bit[0|1]] [-menu<int>] " "[-use-loop] [-use-balls] [-animation-speed<float>] " "[-fps<int>] [-low] [-ticker-letters<int>] " "[-ticker-speed<float>] [-no-ticker-morph] " "[-ticker-morph-speed<float>] [-ticker-text<string>]") sys.exit(0) cls.postConfigure() @classmethod def setLowSettings(cls): cls.noTicker = True cls.noTimerUpdate = True cls.fps = 30 cls.usePixmaps = True cls.noAnimations = True cls.noBlending = True @classmethod def postConfigure(cls): if not cls.noAdapt: w = QWidget() if w.depth() < 16: cls.useEightBitPalette = True cls.adapted = True cls.debug("- Adapt: Color depth less than 16 bit. Using 8 bit palette") def parseFloat(argument, name): try: value = float(parseText(argument, name)) except ValueError: value = 0.0 return value def parseText(argument, name): if len(name) == len(argument): QMessageBox.warning(None, "Arguments", "No argument number found for %s. Remember to put name and " "value adjacent! (e.g. -fps100)") sys.exit(0) return argument[len(name):]
<reponame>quintel/etengine # frozen_string_literal: true module Qernel module MeritFacade # Extracts marginal costs from a node to be used to set their placement # in the merit order. class MarginalCostSorter def cost(node, config) config.type == :flex ? :null : node.marginal_costs end end end end
#!/bin/bash set -e # fail fast if [[ ${credentials:-x} == "x" ]]; then echo "No \$credentials provided, entering self-test mode." if [[ -f /.firstrun ]]; then echo Still starting PostgreSQL, waiting... sleep 5 fi credentials=$(cat /config/credentials.json) fi echo Sanity testing ${service_plan_image:-${image:-PostgreSQL}} with $credentials uri=$(echo $credentials | jq -r '.uri // .credentials.uri // ""') : ${uri:?missing from binding credentials} username=$( echo "$uri" | sed 's|[[:blank:]]*postgres://\([^:]\+\):\([^@]\+\)@\([^:]\+\):\([^/]\+\)\/\(.*\)[[:blank:]]*|\1|' ) password=$( echo "$uri" | sed 's|[[:blank:]]*postgres://\([^:]\+\):\([^@]\+\)@\([^:]\+\):\([^/]\+\)\/\(.*\)[[:blank:]]*|\2|' ) host=$( echo "$uri" | sed 's|[[:blank:]]*postgres://\([^:]\+\):\([^@]\+\)@\([^:]\+\):\([^/]\+\)\/\(.*\)[[:blank:]]*|\3|' ) port=$( echo "$uri" | sed 's|[[:blank:]]*postgres://\([^:]\+\):\([^@]\+\)@\([^:]\+\):\([^/]\+\)\/\(.*\)[[:blank:]]*|\4|' ) dbname=$( echo "$uri" | sed 's|[[:blank:]]*postgres://\([^:]\+\):\([^@]\+\)@\([^:]\+\):\([^/]\+\)\/\(.*\)[[:blank:]]*|\5|' ) wait=${wait_til_running:-60} echo "Waiting for $uri to be ready (max ${wait}s)" for ((n=0; n<$wait; n++)); do pg_isready -h $host -p $port -d $dbname if [[ $? == 0 ]]; then echo "Postgres is ready" break fi print . sleep 1 done pg_isready -h $host -p $port -d $dbname if [[ $? != 0 ]]; then echo "Postgres not running" exit 1 fi wait=${wait_til_running:-60} echo "Waiting for $uri database to exist (max ${wait}s)" for ((n=0; n<$wait; n++)); do psql ${uri} -c 'DROP TABLE IF EXISTS sanitytest;' if [[ $? == 0 ]]; then echo "Database is ready" break fi print . sleep 1 done psql ${uri} -c 'DROP TABLE IF EXISTS sanitytest;' if [[ $? != 0 ]]; then echo "Database not running" exit 1 fi set -x psql ${uri} -c 'CREATE TABLE sanitytest(value text);' psql ${uri} -c "INSERT INTO sanitytest VALUES ('storage-test');" psql ${uri} -c 'SELECT value FROM sanitytest;' | grep 'storage-test' || { echo Could not store and retrieve value in cluster! exit 1 }
#!/bin/bash source /home/luban/.bashrc source /etc/profile source /home/luban/miniconda3/bin/activate base cd ../../../ weight_file=./weights/voc_aspp_b_2_left_last_1259 eval_folder=./eval/voc_aspp_b_2_left_last_1259 for((i=5000;i<=200000;i+=5000));do weight=$weight_file/ssd300_VOC_$i.pth save_folder=$eval_folder/$i mkdir -p $save_folder echo $weight echo $save_folder python eval_aspp.py --model_type="aspp_b_2_left_last" --trained_model=$weight --save_folder=$save_folder --rate="1,2,5,9" done #python eval_aspp.py --trained_model="./weights/voc_aspp_1259/VOC.pth" --save_folder="./eval/voc_aspp-1259/"
//=========================================== // Lumina-DE source code // Copyright (c) 2014-2015, <NAME> // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #ifdef __FreeBSD__ #include "LuminaOS.h" #include <unistd.h> #include <sys/types.h> #include <sys/sysctl.h> #include <QDebug> //can't read xbrightness settings - assume invalid until set static int screenbrightness = -1; static int audiovolume = -1; QString LOS::OSName(){ return "FreeBSD"; } //OS-specific prefix(s) // NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in QString LOS::LuminaShare(){ return (L_SHAREDIR+"/lumina-desktop/"); } //Install dir for Lumina share files QString LOS::AppPrefix(){ return "/usr/local/"; } //Prefix for applications QString LOS::SysPrefix(){ return "/usr/"; } //Prefix for system //OS-specific application shortcuts (*.desktop files) QString LOS::ControlPanelShortcut(){ return "/usr/local/share/applications/pccontrol.desktop"; } //system control panel QString LOS::AppStoreShortcut(){ return "/usr/local/share/applications/appcafe.desktop"; } //graphical app/pkg manager //OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; ) QStringList LOS::RSSFeeds(){ QStringList feeds; feeds << "FreeBSD News Feed::::https://www.freebsd.org/news/rss.xml"; feeds << "TrueOS News Feed::::https://www.trueos.org/feed/"; return feeds; } // ==== ExternalDevicePaths() ==== QStringList LOS::ExternalDevicePaths(){ //Returns: QStringList[<type>::::<filesystem>::::<path>] //Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN] QStringList devs = LUtils::getCmdOutput("mount"); //Now check the output for(int i=0; i<devs.length(); i++){ if(devs[i].startsWith("/dev/")){ devs[i].replace("\t"," "); QString type = devs[i].section(" on ",0,0); type.remove("/dev/"); //Determine the type of hardware device based on the dev node if(type.startsWith("da")){ type = "USB"; } else if(type.startsWith("ada")){ type = "HDRIVE"; } else if(type.startsWith("mmsd")){ type = "SDCARD"; } else if(type.startsWith("cd")||type.startsWith("acd")){ type="DVD"; } else{ type = "UNKNOWN"; } //Now put the device in the proper output format devs[i] = type+"::::"+devs[i].section("(",1,1).section(",",0,0)+"::::"+devs[i].section(" on ",1,50).section("(",0,0).simplified(); }else{ //invalid device - remove it from the list devs.removeAt(i); i--; } } //Also add info about anything in the "/media" directory QDir media("/media"); QFileInfoList list = media.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Type | QDir::Name); //qDebug() << "Media files found:" << list.length(); for(int i=0; i<list.length(); i++){ //qDebug() << "Found media entry:" << list[i].fileName(); if(list[i].isDir()){ devs << "UNKNOWN::::::::/media/"+list[i].fileName(); }else if(list[i].fileName().endsWith(".desktop")){ QString type = list[i].fileName().section(".desktop",0,-2); //Determine the type of hardware device based on the dev node if(type.startsWith("da")){ type = "USB"; } else if(type.startsWith("ada")){ type = "HDRIVE"; } else if(type.startsWith("mmsd")){ type = "SDCARD"; } else if(type.startsWith("cd")||type.startsWith("acd")){ type="DVD"; } else{ type = "UNKNOWN"; } devs << type+"::::::::/media/"+list[i].fileName(); } } return devs; } //Read screen brightness information int LOS::ScreenBrightness(){ //First run a quick check to ensure this is not a VirtualBox VM (no brightness control) static int goodsys = -1; //This will not change over time - only check/set once if(goodsys<0){ //Make sure we are not running in VirtualBox (does not work in a VM) QStringList info = LUtils::getCmdOutput("pciconf -lv"); if( info.filter("VirtualBox", Qt::CaseInsensitive).isEmpty() ){ goodsys = 1; } else{ goodsys = 0; } //not a good system } if(goodsys<=0){ return -1; } //not a good system //Returns: Screen Brightness as a percentage (0-100, with -1 for errors) if( !LUtils::isValidBinary("xbrightness") ){ return -1; } //incomplete install //Now perform the standard brightness checks if(screenbrightness==-1){ //memory value if(QFile::exists(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness")){ //saved file value int val = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness").join("").simplified().toInt(); screenbrightness = val; } } //If it gets to this point, then we have a valid (but new) installation if(screenbrightness<0){ screenbrightness = 100; } //default value for systems return screenbrightness; } //Set screen brightness void LOS::setScreenBrightness(int percent){ if(percent == -1){ return; } //This is usually an invalid value passed directly to the setter //ensure bounds if(percent<0){percent=0;} else if(percent>100){ percent=100; } //Run the command(s) bool success = false; // - try hardware setting first (TrueOS || or intel_backlight) bool remoteSession = !QString(getenv("PICO_CLIENT_LOGIN")).isEmpty(); /*if( LUtils::isValidBinary("pc-sysconfig") && !remoteSession){ //Use TrueOS tool (direct sysctl control) QString ret = LUtils::getCmdOutput("pc-sysconfig", QStringList() <<"setscreenbrightness "+QString::number(percent)).join(""); success = ret.toLower().contains("success"); qDebug() << "Set hardware brightness:" << percent << success; }*/ if( !success && LUtils::isValidBinary("intel_backlight") && !remoteSession){ //Use the intel_backlight utility (only for Intel mobo/hardware?) if(0== LUtils::runCmd("intel_backlight", QStringList() <<QString::number(percent)) ){ //This utility does not report success/failure - run it again to get the current value and ensure it was set properly success = (percent == LUtils::getCmdOutput("intel_backlight").join("").section("%",0,0).section(":",1,1).simplified().toInt() ); } } // - if hardware brightness does not work, use software brightness if(!success && LUtils::isValidBinary("xbrightness") ){ QString cmd = "xbrightness %1"; float pf = percent/100.0; //convert to a decimel cmd = cmd.arg( QString::number( int(65535*pf) ) ); success = (0 == LUtils::runCmd(cmd) ); } //Save the result for later if(!success){ screenbrightness = -1; } else{ screenbrightness = percent; } LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentxbrightness", QStringList() << QString::number(screenbrightness), true); } //Read the current volume int LOS::audioVolume(){ //Returns: audio volume as a percentage (0-100, with -1 for errors) int out = audiovolume; if(out < 0){ //First time session check: Load the last setting for this user QString info = LUtils::readFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentvolume").join(""); if(!info.isEmpty()){ out = info.simplified().toInt(); audiovolume = out; //reset this internal flag return out; } } bool remoteSession = !QString(getenv("PICO_CLIENT_LOGIN")).isEmpty(); if(remoteSession){ QStringList info = LUtils::getCmdOutput("pactl list short sinks"); qDebug() << "Got PA sinks:" << info; out = 50; //TEMPORARY - still need to write up the info parsing audiovolume = out; }else{ //probe the system for the current volume (other utils could be changing it) QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines if(!info.isEmpty()){ int L = info.section(":",1,1).toInt(); int R = info.section(":",2,2).toInt(); if(L>R){ out = L; } else{ out = R; } if(out != audiovolume){ //Volume changed by other utility: adjust the saved value as well LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentvolume", QStringList() << QString::number(out), true); } audiovolume = out; } } return out; } //Set the current volume void LOS::setAudioVolume(int percent){ if(percent<0){percent=0;} else if(percent>100){percent=100;} bool remoteSession = !QString(getenv("PICO_CLIENT_LOGIN")).isEmpty(); if(remoteSession){ LUtils::runCmd(QString("pactl set-sink-volume @DEFAULT_SINK@ ")+QString::number(percent)+"%"); }else{ QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines if(!info.isEmpty()){ int L = info.section(":",1,1).toInt(); int R = info.section(":",2,2).toInt(); int diff = L-R; if((percent == L) && (L==R)){ return; } //already set to that volume if(diff<0){ R=percent; L=percent+diff; } //R Greater else{ L=percent; R=percent-diff; } //L Greater or equal //Check bounds if(L<0){L=0;}else if(L>100){L=100;} if(R<0){R=0;}else if(R>100){R=100;} //Run Command LUtils::runCmd("mixer vol "+QString::number(L)+":"+QString::number(R)); } } audiovolume = percent; //save for checking later LUtils::writeFile(QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/.currentvolume", QStringList() << QString::number(percent), true); } //Change the current volume a set amount (+ or -) void LOS::changeAudioVolume(int percentdiff){ bool remoteSession = !QString(getenv("PICO_CLIENT_LOGIN")).isEmpty(); if(remoteSession){ LUtils::runCmd(QString("pactl set-sink-volume @DEFAULT_SINK@ ")+((percentdiff>0)?"+" : "") + QString::number(percentdiff)+"%"); }else{ QString info = LUtils::getCmdOutput("mixer -S vol").join(":").simplified(); //ignores any other lines if(!info.isEmpty()){ int L = info.section(":",1,1).toInt() + percentdiff; int R = info.section(":",2,2).toInt() + percentdiff; //Check bounds if(L<0){L=0;}else if(L>100){L=100;} if(R<0){R=0;}else if(R>100){R=100;} //Run Command LUtils::runCmd("mixer vol "+QString::number(L)+":"+QString::number(R)); } } } //Check if a graphical audio mixer is installed bool LOS::hasMixerUtility(){ return QFile::exists("/usr/local/bin/pc-mixer"); } //Launch the graphical audio mixer utility void LOS::startMixerUtility(){ QProcess::startDetached("pc-mixer -notray"); } //Check for user system permission (shutdown/restart) bool LOS::userHasShutdownAccess(){ //User needs to be a part of the operator group to be able to run the shutdown command QStringList groups = LUtils::getCmdOutput("id -Gn").join(" ").split(" "); return groups.contains("operator"); } bool LOS::systemPerformingUpdates(){ return (QProcess::execute("pgrep -F /tmp/.updateInProgress")==0); //this is 0 if updating right now } //Return the details of any updates which are waiting to apply on shutdown QString LOS::systemPendingUpdates(){ if(QFile::exists("/tmp/.trueos-update-staged")){ return LUtils::readFile("/tmp/.trueos-update-staged").join("\n"); } else{ return ""; } } //System Shutdown void LOS::systemShutdown(bool skipupdates){ //start poweroff sequence if(skipupdates){QProcess::startDetached("shutdown -po now"); } else{ QProcess::startDetached("shutdown -p now"); } } //System Restart void LOS::systemRestart(bool skipupdates){ //start reboot sequence bool activeupdates = (LUtils::getCmdOutput("sysrc -n trueos_active_update").join("").simplified()=="YES"); if(skipupdates){ QProcess::startDetached("shutdown -ro now"); }else{ if(activeupdates && LUtils::isValidBinary("pc-updatemanager") && LOS::systemPendingUpdates().isEmpty()){ QProcess::startDetached("pc-updatemanager startupdate"); } else{ QProcess::startDetached("shutdown -r now"); } } } //Check for suspend support bool LOS::systemCanSuspend(){ QString state = LUtils::getCmdOutput("sysctl -n hw.acpi.suspend_state").join("").simplified(); bool ok = LUtils::getCmdOutput("sysctl -n hw.acpi.supported_sleep_state").join("").split(" ",QString::SkipEmptyParts).contains(state); /*bool ok = QFile::exists("/usr/local/bin/pc-sysconfig"); if(ok){ ok = LUtils::getCmdOutput("pc-sysconfig systemcansuspend").join("").toLower().contains("true"); }*/ return ok; } //Put the system into the suspend state void LOS::systemSuspend(){ QString state = LUtils::getCmdOutput("sysctl -n hw.acpi.suspend_state").join("").simplified(); //QProcess::startDetached("pc-sysconfig suspendsystem"); QProcess::startDetached("acpiconf", QStringList() << "-s" << state ); } //Battery Availability bool LOS::hasBattery(){ int val = LUtils::getCmdOutput("apm -l").join("").toInt(); return (val >= 0 && val <= 100); } //Battery Charge Level int LOS::batteryCharge(){ //Returns: percent charge (0-100), anything outside that range is counted as an error int charge = LUtils::getCmdOutput("apm -l").join("").toInt(); if(charge > 100){ charge = -1; } //invalid charge return charge; } //Battery Charging State bool LOS::batteryIsCharging(){ return (LUtils::getCmdOutput("apm -a").join("").simplified() == "1"); } //Battery Time Remaining int LOS::batterySecondsLeft(){ //Returns: estimated number of seconds remaining return LUtils::getCmdOutput("apm -t").join("").toInt(); } //File Checksums QStringList LOS::Checksums(QStringList filepaths){ //Return: checksum of the input file QStringList info = LUtils::getCmdOutput("md5 \""+filepaths.join("\" \"")+"\""); for(int i=0; i<info.length(); i++){ if( !info[i].contains(" = ") ){ info.removeAt(i); i--; } else{ //Strip out the extra information info[i] = info[i].section(" = ",1,1); } } return info; } //file system capacity QString LOS::FileSystemCapacity(QString dir) { //Return: percentage capacity as give by the df command QStringList mountInfo = LUtils::getCmdOutput("df \"" + dir+"\""); QString::SectionFlag skipEmpty = QString::SectionSkipEmpty; //we take the 5th word on the 2 line QString capacity = mountInfo[1].section(" ",4,4, skipEmpty); return capacity; } QStringList LOS::CPUTemperatures(){ //Returns: List containing the temperature of any CPU's ("50C" for example) static QStringList vars = QStringList(); QStringList temps; if(vars.isEmpty()){ temps = LUtils::getCmdOutput("sysctl -i dev.cpu").filter(".temperature:"); //try direct readings first if(temps.isEmpty()){ temps = LUtils::getCmdOutput("sysctl -i hw.acpi").filter(".temperature:"); } // then try acpi values }else{ temps = LUtils::getCmdOutput("sysctl "+vars.join(" ")); vars.clear(); } temps.sort(); for(int i=0; i<temps.length(); i++){ if(temps[i].contains(".acpi.") || temps[i].contains(".cpu")){ vars << temps[i].section(":",0,0); //save this variable for later checks temps[i] = temps[i].section(":",1,5).simplified(); //only pull out the value, not the variable }else{ //non CPU temperature - skip it temps.removeAt(i); i--; } } /*}else{ //Already have the known variables - use the library call directly (much faster) for(int i=0; i<vars.length(); i++){ float result[1000]; size_t len = sizeof(result); if(0 != sysctlbyname(vars[i].toLocal8Bit(), result, &len, NULL, 0)){ continue; } //error returned //result[len] = '\0'; //make sure to null-terminate the output QString res; for(int r=0; r<((int) len); r++){ res.append(QString::number(result[r])); } temps << res; qDebug() << "Temp Result:" << vars[i] << res << result << len; } }*/ return temps; } int LOS::CPUUsagePercent(){ //Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors) //Calculate the percentage based on the kernel information directly - no extra utilities QStringList result = LUtils::getCmdOutput("sysctl -n kern.cp_times").join("").split(" "); static QStringList last = QStringList(); if(last.isEmpty()){ last = result; return 0; } //need two ticks before it works properly double tot = 0; int cpnum = 0; for(int i=4; i<result.length(); i+=5){ //The values come in blocks of 5 per CPU: [user,nice,system,interrupt,idle] cpnum++; //the number of CPU's accounted for (to average out at the end) //qDebug() <<"CPU:" << cpnum; long sum = 0; //Adjust/all the data to correspond to diffs from the previous check for(int j=0; j<5; j++){ QString tmp = result[i-j]; result[i-j] = QString::number(result[i-j].toLong()-last[i-j].toLong()); //need the difference between last run and this one sum += result[i-j].toLong(); last[i-j] = tmp; //make sure to keep the original value around for the next run } //Calculate the percentage used for this CPU (100% - IDLE%) tot += 100.0L - ( (100.0L*result[i].toLong())/sum ); //remember IDLE is the last of the five values per CPU } return qRound(tot/cpnum); } int LOS::MemoryUsagePercent(){ //SYSCTL: vm.stats.vm.v_<something>_count QStringList info = LUtils::getCmdOutput("sysctl -n vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count"); if(info.length()<3){ return -1; } //error in fetching information //List output: [total, wired, active] double perc = 100.0* (info[1].toLong()+info[2].toLong())/(info[0].toDouble()); return qRound(perc); } QStringList LOS::DiskUsage(){ //Returns: List of current read/write stats for each device QStringList info = LUtils::getCmdOutput("iostat -dx -c 2 -w 0.1 -t IDE -t SCSI -t da"); //Note: This returns the statistics *twice*: the first set is average for entire system // - the second set is the actual average stats over that 0.1 second if(info.length()<6){ return QStringList(); } //nothing from command QStringList labs = info[1].split(" ",QString::SkipEmptyParts); QStringList out; QString fmt = "%1: %2 %3"; for(int i=(info.length()/2)+2; i<info.length(); i++){ //skip the first data entry , just labels info[i].replace("\t"," "); if(i==1){ labs = info[i].split(" ", QString::SkipEmptyParts); }//the labels for each column else{ QStringList data = info[i].split(" ",QString::SkipEmptyParts); //data[0] is always the device //qDebug() << "Data Line:" << data; if(data.length()>2 && labs.length()>2){ out << fmt.arg(data[0], data[1]+" "+labs[1], data[2]+" "+labs[2]); } } } return out; } #endif
package cn.cerc.jui.parts; import java.util.ArrayList; import java.util.List; import cn.cerc.jbean.core.AbstractHandle; import cn.cerc.jmis.page.IMenuBar; public class RightMenus extends AbstractHandle { private List<IMenuBar> items = new ArrayList<>(); public List<IMenuBar> getItems() { return items; } public void setItems(List<IMenuBar> items) { this.items = items; } }
#!/bin/bash -e pushd ../services/sql_demo docker-compose -f docker-compose-dev.yml build popd ./make_service_ova.sh sql_demo
package com.example.mert.stoktakip.activities; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.SparseArray; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.example.mert.stoktakip.R; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.vision.CameraSource; import com.google.android.gms.vision.Detector; import com.google.android.gms.vision.barcode.Barcode; import com.google.android.gms.vision.barcode.BarcodeDetector; import java.io.IOException; public class BarkodOkuyucuActivity extends AppCompatActivity { SurfaceView surfaceView; String[] permissions = {Manifest.permission.CAMERA}; private static final int REQUEST_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_barkod_okuyucu); surfaceView = findViewById(R.id.surface_view); createCameraResource(); } private void createCameraResource() { BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build(); final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector) .setAutoFocusEnabled(true) .setRequestedPreviewSize(1600, 1024) .build(); surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { if (ActivityCompat.checkSelfPermission(BarkodOkuyucuActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(BarkodOkuyucuActivity.this, permissions, REQUEST_CODE); } try { cameraSource.start(surfaceView.getHolder()); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { cameraSource.stop(); } }); barcodeDetector.setProcessor(new Detector.Processor<Barcode>() { @Override public void release() { } @Override public void receiveDetections(Detector.Detections<Barcode> detections) { final SparseArray<Barcode> barcodes = detections.getDetectedItems(); if (barcodes.size() > 0) { Intent intent = new Intent(); intent.putExtra("barcode", barcodes.valueAt(0)); setResult(CommonStatusCodes.SUCCESS, intent); finish(); } } }); } }
/** * This file holds a JSON object that contains potential dropdown options */ export const dropDownOptions = [ {'id': 0, 'title': 'Administrative Tribunals Support Service of Canada', 'selected': false, 'key': 'department'}, {'id': 1, 'title': 'Agriculture and Agri-Food Canada', 'selected': false, 'key': 'department'}, {'id': 2, 'title': 'Atlantic Canada Opportunities Agency', 'selected': false, 'key': 'department'}, {'id': 3, 'title': 'Auditor General of Canada, Office of the', 'selected': false, 'key': 'department'}, {'id': 4, 'title': 'Canada Border Services Agency', 'selected': false, 'key': 'department'}, {'id': 5, 'title': 'Canada Council for the Arts', 'selected': false, 'key': 'department'}, {'id': 6, 'title': 'Canada Economic Development for Quebec Regions', 'selected': false, 'key': 'department'}, {'id': 7, 'title': 'Canada Energy Regulator', 'selected': false, 'key': 'department'}, {'id': 8, 'title': 'Canada Industrial Relations Board', 'selected': false, 'key': 'department'}, {'id': 9, 'title': 'Canada Mortgage and Housing Corporation', 'selected': false, 'key': 'department'}, {'id': 10, 'title': 'Canada Revenue Agency', 'selected': false, 'key': 'department'}, {'id': 11, 'title': 'Canada School of Public Service', 'selected': false, 'key': 'department'}, {'id': 12, 'title': 'Canadian Air Transport Security Authority', 'selected': false, 'key': 'department'}, {'id': 13, 'title': 'Canadian Commercial Corporation', 'selected': false, 'key': 'department'}, {'id': 14, 'title': 'Canadian Dairy Commission', 'selected': false, 'key': 'department'}, {'id': 15, 'title': 'Canadian Food Inspection Agency', 'selected': false, 'key': 'department'}, {'id': 16, 'title': 'Canadian Grain Commission', 'selected': false, 'key': 'department'}, {'id': 17, 'title': 'Canadian Heritage', 'selected': false, 'key': 'department'}, {'id': 18, 'title': 'Canadian Human Rights Commission', 'selected': false, 'key': 'department'}, {'id': 19, 'title': 'Canadian Institutes of Health Research', 'selected': false, 'key': 'department'}, {'id': 20, 'title': 'Canadian Intergovernmental Conference Secretariat', 'selected': false, 'key': 'department'}, {'id': 21, 'title': 'Canadian Museum for Human Rights', 'selected': false, 'key': 'department'}, {'id': 22, 'title': 'Canadian Museum of History', 'selected': false, 'key': 'department'}, {'id': 23, 'title': 'Canadian Museum of Nature', 'selected': false, 'key': 'department'}, {'id': 24, 'title': 'Canadian Northern Economic Development Agency', 'selected': false, 'key': 'department'}, {'id': 25, 'title': 'Canadian Nuclear Safety Commission', 'selected': false, 'key': 'department'}, {'id': 26, 'title': 'Canadian Radio-television and Telecommunications Commission', 'selected': false, 'key': 'department'}, {'id': 27, 'title': 'Canadian Space Agency', 'selected': false, 'key': 'department'}, {'id': 28, 'title': 'Canadian Tourism Commission', 'selected': false, 'key': 'department'}, {'id': 29, 'title': 'Canadian Transportation Agency', 'selected': false, 'key': 'department'}, {'id': 30, 'title': 'Civilian Review and Complaints Commission for the RCMP', 'selected': false, 'key': 'department'}, {'id': 31, 'title': 'Copyright Board Canada', 'selected': false, 'key': 'department'}, {'id': 32, 'title': 'Correctional Service Canada', 'selected': false, 'key': 'department'}, {'id': 33, 'title': 'Courts Administration Service', 'selected': false, 'key': 'department'}, {'id': 34, 'title': 'Defence Construction Canada', 'selected': false, 'key': 'department'}, {'id': 35, 'title': 'Defence Research and Development Canada (DRDC)', 'selected': false, 'key': 'department'}, {'id': 36, 'title': 'Employment and Social Development Canada', 'selected': false, 'key': 'department'}, {'id': 37, 'title': 'Environment and Climate Change Canada', 'selected': false, 'key': 'department'}, {'id': 38, 'title': 'Farm Products Council of Canada', 'selected': false, 'key': 'department'}, {'id': 39, 'title': 'Federal Court', 'selected': false, 'key': 'department'}, {'id': 40, 'title': 'Federal Court of Appeal', 'selected': false, 'key': 'department'}, {'id': 41, 'title': 'Federal Economic Development Agency for Southern Ontario', 'selected': false, 'key': 'department'}, {'id': 42, 'title': 'Federal Public Sector Labour Relations and Employment Board', 'selected': false, 'key': 'department'}, {'id': 43, 'title': 'Finance Canada', 'selected': false, 'key': 'department'}, {'id': 44, 'title': 'Financial Consumer Agency of Canada', 'selected': false, 'key': 'department'}, {'id': 45, 'title': 'Fisheries and Oceans Canada', 'selected': false, 'key': 'department'}, {'id': 46, 'title': 'Global Affairs Canada', 'selected': false, 'key': 'department'}, {'id': 47, 'title': 'Health Canada', 'selected': false, 'key': 'department'}, {'id': 48, 'title': 'House of Commons', 'selected': false, 'key': 'department'}, {'id': 49, 'title': 'Immigration and Refugee Board of Canada', 'selected': false, 'key': 'department'}, {'id': 50, 'title': 'Immigration, Refugees and Citizenship Canada', 'selected': false, 'key': 'department'}, {'id': 51, 'title': 'Impact Assessment Agency of Canada', 'selected': false, 'key': 'department'}, {'id': 52, 'title': 'Indigenous and Northern Affairs Canada', 'selected': false, 'key': 'department'}, {'id': 53, 'title': 'Indigenous Services Canada', 'selected': false, 'key': 'department'}, {'id': 54, 'title': 'Infrastructure Canada', 'selected': false, 'key': 'department'}, {'id': 55, 'title': 'Ingenium', 'selected': false, 'key': 'department'}, {'id': 56, 'title': 'Innovation, Science and Economic Development Canada', 'selected': false, 'key': 'department'}, {'id': 57, 'title': 'International Development Research Centre', 'selected': false, 'key': 'department'}, {'id': 58, 'title': 'International Joint Commission', 'selected': false, 'key': 'department'}, {'id': 59, 'title': 'Justice Canada', 'selected': false, 'key': 'department'}, {'id': 60, 'title': 'Laurentian Pilotage Authority Canada', 'selected': false, 'key': 'department'}, {'id': 61, 'title': 'Library and Archives Canada', 'selected': false, 'key': 'department'}, {'id': 62, 'title': 'Library of Parliament', 'selected': false, 'key': 'department'}, {'id': 63, 'title': 'Military Grievances External Review Committee', 'selected': false, 'key': 'department'}, {'id': 64, 'title': 'Military Police Complaints Commission of Canada', 'selected': false, 'key': 'department'}, {'id': 65, 'title': 'National Arts Centre', 'selected': false, 'key': 'department'}, {'id': 66, 'title': 'National Capital Commission', 'selected': false, 'key': 'department'}, {'id': 67, 'title': 'National Defence', 'selected': false, 'key': 'department'}, {'id': 68, 'title': 'National Film Board of Canada', 'selected': false, 'key': 'department'}, {'id': 69, 'title': 'National Research Council Canada', 'selected': false, 'key': 'department'}, {'id': 70, 'title': 'Natural Resources Canada', 'selected': false, 'key': 'department'}, {'id': 71, 'title': 'Natural Sciences and Engineering Research Council of Canada', 'selected': false, 'key': 'department'}, {'id': 72, 'title': 'Northern Pipeline Agency', 'selected': false, 'key': 'department'}, {'id': 73, 'title': 'Office of the Chief Electoral Officer', 'selected': false, 'key': 'department'}, {'id': 74, 'title': 'Office of the Commissioner for Federal Judicial Affairs Canada', 'selected': false, 'key': 'department'}, {'id': 75, 'title': 'Office of the Commissioner of Official Languages', 'selected': false, 'key': 'department'}, {'id': 76, 'title': 'Office of the Conflict of Interest and Ethics Commissioner', 'selected': false, 'key': 'department'}, {'id': 77, 'title': 'Office of the Information Commissioner of Canada', 'selected': false, 'key': 'department'}, {'id': 78, 'title': 'Office of the Privacy Commissioner of Canada', 'selected': false, 'key': 'department'}, {'id': 79, 'title': 'Office of the Secretary to the Governor General', 'selected': false, 'key': 'department'}, {'id': 80, 'title': 'Office of the Superintendent of Financial Institutions Canada', 'selected': false, 'key': 'department'}, {'id': 81, 'title': 'Pacific Pilotage Authority Canada', 'selected': false, 'key': 'department'}, {'id': 82, 'title': 'Parks Canada', 'selected': false, 'key': 'department'}, {'id': 83, 'title': 'Parliamentary Budget Officer', 'selected': false, 'key': 'department'}, {'id': 84, 'title': 'Parole Board of Canada', 'selected': false, 'key': 'department'}, {'id': 85, 'title': 'Patented Medicine Prices Review Board', 'selected': false, 'key': 'department'}, {'id': 86, 'title': 'Polar Knowledge Canada', 'selected': false, 'key': 'department'}, {'id': 87, 'title': 'PPP Canada', 'selected': false, 'key': 'department'}, {'id': 88, 'title': "Prime Minister's Office", 'selected': false, 'key': 'department'}, {'id': 89, 'title': 'Privy Council Office', 'selected': false, 'key': 'department'}, {'id': 90, 'title': 'Public Health Agency of Canada', 'selected': false, 'key': 'department'}, {'id': 91, 'title': 'Public Prosecution Service of Canada', 'selected': false, 'key': 'department'}, {'id': 92, 'title': 'Public Safety Canada', 'selected': false, 'key': 'department'}, {'id': 93, 'title': 'Public Service Commission', 'selected': false, 'key': 'department'}, {'id': 94, 'title': 'Public Services and Procurement Canada', 'selected': false, 'key': 'department'}, {'id': 95, 'title': 'Royal Canadian Mint', 'selected': false, 'key': 'department'}, {'id': 96, 'title': 'Royal Canadian Mounted Police', 'selected': false, 'key': 'department'}, {'id': 97, 'title': 'Senate of Canada', 'selected': false, 'key': 'department'}, {'id': 98, 'title': 'Shared Services Canada', 'selected': false, 'key': 'department'}, {'id': 99, 'title': 'Social Sciences and Humanities Research Council of Canada', 'selected': false, 'key': 'department'}, {'id': 100, 'title': 'Standards Council of Canada', 'selected': false, 'key': 'department'}, {'id': 101, 'title': 'Statistics Canada', 'selected': false, 'key': 'department'}, {'id': 102, 'title': 'Supreme Court of Canada', 'selected': false, 'key': 'department'}, {'id': 103, 'title': 'Tax Court of Canada', 'selected': false, 'key': 'department'}, {'id': 104, 'title': 'The Federal Bridge Corporation Limited', 'selected': false, 'key': 'department'}, {'id': 105, 'title': 'Transportation Appeal Tribunal of Canada', 'selected': false, 'key': 'department'}, {'id': 106, 'title': 'Transportation Safety Board of Canada', 'selected': false, 'key': 'department'}, {'id': 107, 'title': 'Transport Canada', 'selected': false, 'key': 'department'}, {'id': 108, 'title': 'Treasury Board of Canada Secretariat', 'selected': false, 'key': 'department'}, {'id': 109, 'title': 'Veterans Affairs Canada', 'selected': false, 'key': 'department'}, {'id': 110, 'title': 'Veterans Review and Appeal Board', 'selected': false, 'key': 'department'}, {'id': 111, 'title': 'Western Economic Diversification Canada', 'selected': false, 'key': 'department'}, {'id': 112, 'title': 'Women and Gender Equality Canada', 'selected': false, 'key': 'department'} ]
function fibonacciSequence(n) { let sequence = [0, 1] for (let i = 2; i < n; i++) { sequence[i] = sequence[i-1] + sequence[i-2] } return sequence; } console.log(fibonacciSequence(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
from nltk.util import ngrams sentence = "This is a sentence." n = 3 grams = list(ngrams(sentence.split(), n)) for gram in grams: print(gram) # Output: ('This', 'is', 'a') ('is', 'a', 'sentence.')
<filename>Viewer/ecflowUI/src/CommandOutput.cpp //============================================================================ // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // //============================================================================ #include "CommandOutput.hpp" #include "CommandOutputDialog.hpp" #include "VConfig.hpp" CommandOutputHandler* CommandOutputHandler::instance_=nullptr; //=============================================== // // CommandOutput // //============================================== CommandOutput::CommandOutput(QString cmd,QString cmdDef,QDateTime runTime) : enabled_(true), command_(cmd), commandDef_(cmdDef), runTime_(runTime), status_(RunningStatus) { } void CommandOutput::appendOutput(QString txt,int maxSize,bool& trimmed) { output_+=txt; trimmed=false; if(output_.size() > maxSize) { output_=output_.right(maxSize-100); trimmed=true; } } void CommandOutput::appendError(QString txt,int maxSize,bool& trimmed) { error_+=txt; trimmed=false; if(error_.size() > maxSize) { error_=error_.right(maxSize-100); trimmed=true; } } QString CommandOutput::statusStr() const { static QString finishedStr("finished"); static QString failedStr("failed"); static QString runningStr("running"); switch(status_) { case FinishedStatus: return finishedStr; case FailedStatus: return failedStr; case RunningStatus: return runningStr; default: return QString(); } return QString(); } QColor CommandOutput::statusColour() const { static QColor redColour(255,0,0); static QColor greenColour(9,160,63); static QColor blackColour(0,0,0); switch(status_) { case CommandOutput::FinishedStatus: return blackColour; case CommandOutput::FailedStatus: return redColour; case CommandOutput::RunningStatus: return greenColour; default: return blackColour; } return blackColour; } //=============================================== // // CommandOutputHandler // //=============================================== CommandOutputHandler::CommandOutputHandler(QObject* parent) : QObject(parent) { showDialogStdOutProp_ = VConfig::instance()->find("view.shellCommand.showPopupOnStdOut"); showDialogStdErrProp_ = VConfig::instance()->find("view.shellCommand.showPopupOnStdErr"); } CommandOutputHandler* CommandOutputHandler::instance() { if(!instance_) instance_=new CommandOutputHandler(nullptr); return instance_; } int CommandOutputHandler::indexOfItem(CommandOutput_ptr item) const { if(!item) return -1; for(int i=0; i < items_.count(); i++) { if(item.get() == items_[i].get()) return i; } return -1; } void CommandOutputHandler::appendOutput(CommandOutput_ptr item,QString txt) { if(item) { bool trimmed=false; item->appendOutput(txt,maxOutputSize_,trimmed); if (needToShowStdOut()) { CommandOutputDialog::showDialog(); } if(trimmed==false) Q_EMIT itemOutputAppend(item,txt); else Q_EMIT itemOutputReload(item); } } void CommandOutputHandler::appendError(CommandOutput_ptr item,QString txt) { if(item) { bool trimmed=false; item->appendError(txt,maxErrorSize_,trimmed); if (needToShowStdErr()) { CommandOutputDialog::showDialog(); } if(trimmed==false) Q_EMIT itemErrorAppend(item,txt); else Q_EMIT itemErrorReload(item); } } void CommandOutputHandler::finished(CommandOutput_ptr item) { if(item) { item->setStatus(CommandOutput::FinishedStatus); Q_EMIT itemStatusChanged(item); } } void CommandOutputHandler::failed(CommandOutput_ptr item) { if(item) { item->setStatus(CommandOutput::FailedStatus); Q_EMIT itemStatusChanged(item); if (needToShowStdErr()) { CommandOutputDialog::showDialog(); } } } CommandOutput_ptr CommandOutputHandler::addItem(QString cmd,QString cmdDef,QDateTime runTime, CreateContext context) { if( (needToShowStdOut() && context == StdOutContext) || (needToShowStdErr() && context == StdErrContext) ) { CommandOutputDialog::showDialog(); } CommandOutput_ptr item= CommandOutput_ptr(new CommandOutput(cmd,cmdDef,runTime)); Q_EMIT itemAddBegin(); items_ << item; checkItems(); Q_EMIT itemAddEnd(); return item; } void CommandOutputHandler::checkItems() { Q_ASSERT(maxNum_ >0); while(items_.count() > maxNum_) { Q_ASSERT(items_.count() > 0); CommandOutput_ptr item=items_.first(); item->setEnabled(false); items_.remove(0); } } bool CommandOutputHandler::needToShowStdOut() { return (showDialogStdOutProp_)?(showDialogStdOutProp_->value().toBool()):true; } bool CommandOutputHandler::needToShowStdErr() { return (showDialogStdErrProp_)?(showDialogStdErrProp_->value().toBool()):true; }
<reponame>ayltai/hknews-android<filename>app/src/test/java/com/github/ayltai/hknews/util/DateUtilsTest.java package com.github.ayltai.hknews.util; import java.util.Date; import androidx.test.core.app.ApplicationProvider; import org.junit.Assert; import org.junit.Test; import com.github.ayltai.hknews.UnitTest; public final class DateUtilsTest extends UnitTest { @Test public void testJustNow() { Assert.assertEquals("Just now", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 50000L))); } @Test public void testOneMinuteAgo() { Assert.assertEquals("A minute ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 110000L))); } @Test public void testTwentyMinutesAgo() { Assert.assertEquals("20 minutes ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 1200000L))); } @Test public void testOneHourAgo() { Assert.assertEquals("An hour ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 5000000L))); } @Test public void testThreeHoursAgo() { Assert.assertEquals("3 hours ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 10800000L))); } @Test public void testYesterday() { Assert.assertEquals("Yesterday", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 170000000L))); } @Test public void testFourDaysAgo() { Assert.assertEquals("4 days ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 345600000L))); } @Test public void testOneMonthAgo() { Assert.assertEquals("A month ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 3456000000L))); } @Test public void testNineMonthsAgo() { Assert.assertEquals("9 months ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 23328000000L))); } @Test public void testOneYearAgo() { Assert.assertEquals("A year ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 43200000000L))); } @Test public void testTwoYearsAgo() { Assert.assertEquals("2 years ago", DateUtils.getHumanReadableDate(ApplicationProvider.getApplicationContext(), new Date(System.currentTimeMillis() - 63072000000L))); } }
<reponame>guigallo/mymoney-client const SHOW_ALL = 'SHOW_ALL'; const show = { all: SHOW_ALL, list: 'SHOW_LIST', form: 'SHOW_FORM' }; const ignore = (property, showConst) => property.show === show.all || property.show === showConst ? false : true; const ignoreListProperties = (property) => ignore(property, show.form); const ignoreFormProperties = (property) => ignore(property, show.list); const createProperty = (id, label, type, sum, align, required, show = SHOW_ALL) => ({ id, label, type, sum, align, required, show }); export { show, ignoreListProperties, ignoreFormProperties, createProperty }
package io.github.poulad.hnp.web.data.entity; import io.github.poulad.hnp.story.HackerNewsStory; import io.github.poulad.hnp.story.hn_api.ItemDto; import io.github.poulad.hnp.web.model.DraftEpisodeDto; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; import java.time.Instant; import java.util.Date; import javax.annotation.Nonnull; import javax.annotation.Nullable; @Mapper public interface EntityMapper { @Nonnull EntityMapper INSTANCE = Mappers.getMapper(EntityMapper.class); @Nullable @Mapping(source = "id", target = "storyId") Episode hackerNewsStoryToEpisode(@Nullable HackerNewsStory hackerNewsStory); @Nullable @Mapping(source = "id", target = "episodeId") DraftEpisode episodeToDraftEpisode(@Nullable Episode episode); @Nullable @Mapping(source = "episodeId", target = "id") DraftEpisodeDto draftEpisodeToDraftEpisodeDto(@Nullable DraftEpisode draftEpisode); }
#!/bin/bash set -e set -o pipefail DATABASE_NAME=$1 function create_db { echo "Deploying new PostgreSQL instance in namespace db-postgresql as admin..." oc login -u admin -p admin oc project db-postgresql oc new-app --template=postgresql-persistent --name=${DATABASE_NAME} -p POSTGRESQL_DATABASE=backend -e POSTGRESQL_ADMIN_PASSWORD=somegeneratedpassword -p DATABASE_SERVICE_NAME=${DATABASE_NAME} echo "Done..." } function usage { echo " $0 my-db-name" } if [ -z "$1" ] then echo "No argument supplied... Usage:" usage exit 1 fi create_db
<filename>src/features/filters/components/Filters.js import React from "react"; import { Link, useRouteMatch, useLocation } from "react-router-dom"; import styled from "styled-components"; import { StatefulPopover } from "@malcodeman/react-popover"; import { getParam } from "../../../core/utils"; import { DEFAULT_SUBREDDIT, DEFAULT_LISTING_SORT, DEFAULT_TIME_SORT, } from "../../../core/constants"; import Text from "../../commonComponents/Text"; import ChevronDown from "../../commonAssets/icons/ChevronDown"; const StyledFilters = styled.div` display: flex; align-items: center; justify-content: space-between; position: sticky; top: 54px; z-index: 1; padding: 1rem; margin-top: 54px; height: 60px; color: ${(props) => props.theme.primary}; background-color: ${(props) => `${props.theme.backgroundSecondary}F2`}; `; const Panel = styled.div` display: flex; `; const Filter = styled.div` display: flex; align-items: center; cursor: pointer; margin-right: 1rem; `; const Menu = styled.ul` padding: 0.5rem 0; background-color: #fff; list-style-type: none; margin: 0; `; const MenuItem = styled.li``; const StyledLink = styled(Link)` display: block; color: #06070d; padding: 0.5rem 1rem; cursor: pointer; &:hover { background-color: ${(props) => `${props.theme.brand}33`}; } `; function Filters() { const match = useRouteMatch(); const location = useLocation(); const subreddit = match.params.subreddit || DEFAULT_SUBREDDIT; const { pathname } = location; const listingSort = match.params.listing || DEFAULT_LISTING_SORT; const renderTimeSort = listingSort === "controversial" || listingSort === "top"; const timeSort = getParam("time") || DEFAULT_TIME_SORT; function parseListingSortLabel(listing) { switch (listing) { case "hot": return "What's Hot"; case "new": return "Most recent"; case "controversial": return "Controversial"; case "top": return "Top"; case "rising": return "Rising"; default: return ""; } } function parseTimeSortLabel(listing) { switch (listing) { case "hour": return "Now"; case "day": return "Today"; case "week": return "This week"; case "month": return "This month"; case "year": return "This year"; case "all": return "All Time"; default: return ""; } } return ( <StyledFilters> <Panel> <StatefulPopover content={({ close }) => ( <Menu> <MenuItem onClick={close}> <StyledLink to={`/${subreddit}/hot`}>What's Hot</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`/${subreddit}/new`}>Most recent</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`/${subreddit}/controversial`}> Controversial </StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`/${subreddit}/top`}>Top</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`/${subreddit}/rising`}>Rising</StyledLink> </MenuItem> </Menu> )} > <Filter> <Text size={1} mr={0.5}> {parseListingSortLabel(listingSort)} </Text> <ChevronDown /> </Filter> </StatefulPopover> {renderTimeSort && ( <StatefulPopover content={({ close }) => ( <Menu> <MenuItem onClick={close}> <StyledLink to={`${pathname}?time=hour`}>Hour</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`${pathname}?time=day`}>Day</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`${pathname}?time=week`}>Week</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`${pathname}?time=month`}>Month</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`${pathname}?time=year`}>Year</StyledLink> </MenuItem> <MenuItem onClick={close}> <StyledLink to={`${pathname}?time=all`}>All</StyledLink> </MenuItem> </Menu> )} > <Filter> <Text size={1} mr={0.5}> {parseTimeSortLabel(timeSort)} </Text> <ChevronDown /> </Filter> </StatefulPopover> )} </Panel> </StyledFilters> ); } export default Filters;