text
stringlengths
1
1.05M
package com.creadigol.inshort.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.creadigol.inshort.MainActivity; import com.creadigol.inshort.R; import com.creadigol.inshort.Utils.MyApplication; import com.creadigol.inshort.Utils.PreferenceSettings; /** * Created by ADMIN on 06-Jan-17. */ public class LeftFragment extends Fragment implements View.OnClickListener { ImageView ll_Allnews, ll_Bookmark; TextView tvBookmark, tvAllNews; PreferenceSettings mPreferenceSettings; View rootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_one, container, false); mPreferenceSettings = MyApplication.getInstance().getPreferenceSettings(); ll_Allnews = (ImageView) rootView.findViewById(R.id.allnews); ll_Bookmark = (ImageView) rootView.findViewById(R.id.bookmark); tvBookmark = (TextView) rootView.findViewById(R.id.tvbookmark); tvAllNews = (TextView) rootView.findViewById(R.id.tvallnew); Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar_right); ImageView ivRight = (ImageView) toolbar.findViewById(R.id.ivRight); ivRight.setVisibility(View.VISIBLE); TextView tvToolbar = (TextView) toolbar.findViewById(R.id.tv_toolbar_name); tvToolbar.setText("Setting"); ivRight.setOnClickListener(this); ll_Allnews.setOnClickListener(this); ll_Bookmark.setOnClickListener(this); if (mPreferenceSettings.getBookmark()) { ll_Bookmark.setBackground(getResources().getDrawable(R.drawable.button_click)); ll_Bookmark.setImageDrawable(getResources().getDrawable(R.drawable.bookmarkwhite)); tvBookmark.setTextColor(getResources().getColor(R.color.blue)); } else { ll_Allnews.setBackground(getResources().getDrawable(R.drawable.button_click)); ll_Allnews.setImageDrawable(getResources().getDrawable(R.drawable.newswhite)); tvAllNews.setTextColor(getResources().getColor(R.color.blue)); } return rootView; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ivRight: MainActivity.mViewPager.setCurrentItem(1,true); // MyApplication.isNeeded = false; // Intent upload = new Intent(getActivity(), MainActivity.class); // upload.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // startActivityForResult(upload, 0); // getActivity().overridePendingTransition(R.anim.slide_left_page, R.anim.stable); // getActivity().finish(); break; case R.id.allnews: ll_Allnews.setBackground(getResources().getDrawable(R.drawable.button_click)); ll_Allnews.setImageDrawable(getResources().getDrawable(R.drawable.newswhite)); tvAllNews.setTextColor(getResources().getColor(R.color.blue)); mPreferenceSettings.setBookmark(false); MyApplication.isNeeded = false; Intent allnew = new Intent(getActivity(), MainActivity.class); allnew.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(allnew, 0); getActivity().overridePendingTransition(R.anim.slide_left_page, R.anim.stable); getActivity().finish(); break; case R.id.bookmark: ll_Bookmark.setBackground(getResources().getDrawable(R.drawable.button_click)); ll_Bookmark.setImageDrawable(getResources().getDrawable(R.drawable.bookmarkwhite)); mPreferenceSettings.setBookmark(true); MyApplication.isNeeded = false; tvBookmark.setTextColor(getResources().getColor(R.color.blue)); Intent bookmark = new Intent(getActivity(), MainActivity.class); bookmark.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(bookmark, 0); getActivity().overridePendingTransition(R.anim.slide_left_page, R.anim.stable); getActivity().finish(); break; } } @Override public void onResume() { super.onResume(); rootView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { } return false; } }); getView().setFocusableInTouchMode(true); getView().requestFocus(); rootView.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { MainActivity.mViewPager.setCurrentItem(1,true); // MyApplication.isNeeded = false; // Intent bookmark = new Intent(getActivity(), MainActivity.class); // bookmark.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // startActivityForResult(bookmark, 0); // getActivity().overridePendingTransition(R.anim.slide_left_page, R.anim.stable); // getActivity().finish(); return true; } return false; } }); } }
import * as t from "io-ts"; export const rpcCompilerInput = t.type( { language: t.string, sources: t.any, settings: t.any, }, "RpcCompilerInput" ); export type RpcCompilerInput = t.TypeOf<typeof rpcCompilerInput>; export const rpcCompilerOutput = t.type( { sources: t.any, contracts: t.any, }, "RpcCompilerOutput" ); export type RpcCompilerOutput = t.TypeOf<typeof rpcCompilerOutput>;
<reponame>kostovmichael/react-examples<filename>v16/examples/sentry-get-started/webpack.config.js const HtmlWebpackPlugin = require('html-webpack-plugin'); const SentryCliPlugin = require('@sentry/webpack-plugin'); const path = require('path'); module.exports = { entry: path.resolve(__dirname, './src/index'), output: { path: path.resolve(__dirname, './dist'), filename: '[name].bundle.js', }, devtool: 'source-map', mode: 'development', plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, './src/index.html'), }), new SentryCliPlugin({ include: '.', ignore: ['node_modules', 'webpack.config.js'], org: 'du-lin', project: 'react-examples', release: process.env.SENTRY_RELEASE, validate: true, }), ], devServer: { static: { directory: path.join(__dirname, 'dist'), }, port: 9000, }, resolve: { extensions: ['', '.js', '.jsx'], }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], }, }, }, ], }, optimization: { chunkIds: 'named', splitChunks: { cacheGroups: { vendor: { test: /node_modules/, chunks: 'initial', name: 'vendor', priority: 10, enforce: true, }, }, }, }, };
def find_max(arr): # set initial max as the first value in the array max_val = arr[0] # iterate over all values in the array for val in arr: # if current value is greater than max, update max if val > max_val: max_val = val return max_val
import { TestBed } from '@angular/core/testing'; import { FonctionnaliteService } from './fonctionnalite.service'; describe('FonctionnaliteService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: FonctionnaliteService = TestBed.get(FonctionnaliteService); expect(service).toBeTruthy(); }); });
#!/usr/bin/env bash for CMD in 'dev-server' 'chrome' 'watch' do sleep 2s osascript -e "tell application \"Terminal\" to do script \"cd ${PWD};npm run ${CMD}\"" done
import jmespath def create_cluster(_body, kwargs): # Implementation for creating a cluster return {"id": "cluster-123", "status": "created"} def delete_cluster(_body, kwargs): # Implementation for deleting a cluster return {"id": "cluster-123", "status": "deleted"} def update_cluster(_body, kwargs): # Implementation for updating a cluster return {"id": "cluster-123", "status": "updated"} def queryable(func): def wrapper(dest_func, _body, kwargs): query = kwargs.pop("query", None) ret = func(dest_func, _body, kwargs) try: return jmespath.search(query, ret) if query else ret except jmespath.exceptions.ParseError: # Handle parse error return None def execute_queryable(operation_map, operation_name, **kwargs): if operation_name in operation_map: operation_func = operation_map[operation_name] result = operation_func(None, kwargs) if "query" in kwargs: query = kwargs["query"] try: return jmespath.search(query, result) except jmespath.exceptions.ParseError: # Handle parse error return None else: return result else: return None # Handle invalid operation name
import os from dotenv import load_dotenv from os.path import dirname, join def get_env_variable(variable_name): dotenv_path = join(dirname(__file__), ".env") load_dotenv(dotenv_path=dotenv_path, verbose=True) try: return os.getenv(variable_name) except KeyError: message = "Expected environment variable '{}' not set.".format(variable_name) raise Exception(message) def create_db_url(db_name): return f"sqlite:///{db_name}.db" # import .env variables for DB connection # TODO: Unify these ENV variables by pulling from different dot files def get_env_db_url(env_setting): if env_setting == "development": DB_NAME = get_env_variable("DEV_DB") elif env_setting == "testing": DB_NAME = get_env_variable("TESTING_DB") elif env_setting == "production": DB_NAME = get_env_variable("PROD_DB") return create_db_url(DB_NAME) # DB URLS for each Environment DEV_DB_URL = get_env_db_url("development") TESTING_DB_URL = get_env_db_url("testing") PROD_DB_URL = get_env_db_url("production") class Config(object): # SQLAlchemy settings SQLALCHEMY_DATABASE_URI = DEV_DB_URL SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_ECHO = True # Praetorian SECRET_KEY = os.getenv("SECRET_KEY") JWT_ACCESS_LIFESPAN = {"hours": 24} JWT_REFRESH_LIFESPAN = {"days": 30} # Flask Settings PROPAGATE_EXCEPTIONS = True DEBUG = False TESTING = False class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): SQLALCHEMY_DATABASE_URI = TESTING_DB_URL DEBUG = True TESTING = True class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = PROD_DB_URL DEBUG = False TESTING = False
/* * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glowroot.instrumentation.api; import java.util.Collections; import java.util.Map; /** * A (lazy) supplier of {@link QueryMessage} instances. Needs to be thread safe since transaction * thread creates it, but trace storage (and live viewing) is done in a separate thread. */ public abstract class QueryMessageSupplier { private static final QueryMessageSupplier EMPTY = new QueryMessageSupplier() { @Override public Map<String, ?> get() { return Collections.emptyMap(); } }; /** * Returns the {@code QueryMessage} for a {@link QuerySpan}. * * The {@code QueryMessage} does not need to be thread safe if it is instantiated by the * implementation of this method. */ public abstract Map<String, ?> get(); protected QueryMessageSupplier() {} /** * Creates a {@code QueryMessageSupplier} for the specified {@code prefix} and {@code suffix}. */ public static QueryMessageSupplier create() { return EMPTY; } /** * Creates a {@code QueryMessageSupplier} for the specified {@code prefix}. */ public static QueryMessageSupplier create(final Map<String, ?> detail) { return new QueryMessageSupplier() { @Override public Map<String, ?> get() { return detail; } }; } }
#!/bin/sh ARGS=$1 if [ $# -lt 1 ]; then ARGS="help" fi BASEPATH=$(cd `dirname $0`; pwd) case $ARGS in all) cd $BASEPATH; cp CMakeLists.txt ../; cmake ..; make ;; cleanall) cd $BASEPATH; make clean; rm -rf CMakeFiles/ CMakeCache.txt Makefile util/ tools/ servant/ framework/ test/ cmake_install.cmake *.tgz install_manifest.txt ;; install) cd $BASEPATH; make install ;; help|*) echo "Usage:" echo "$0 help: view help info." echo "$0 all: build all target" echo "$0 install: install framework" echo "$0 cleanall: remove all temp file" ;; esac
<html> <head> <title>Welcome Message</title> </head> <body> <h1>Welcome Message</h1> <form action="/welcome" method="post"> <label for="email">Email:</label> <input type="email" name="email" required> <input type="submit" value="Submit"> </form> </body> </html> <!-- controller code instead of server --> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $email = $_POST['email']; echo "Welcome to our website, $email!"; } ?>
<filename>app/templates/tests/specs/framework/MessageBus.js /*global describe:true, expect:true, it:true, sinon:true */ /*jshint expr:true */ define([ 'MessageBus' ], function(MessageBus) { 'use strict'; describe('MessageBus', function() { describe('#on()', function() { it('should fire a callback when its event is called', function() { var spy = sinon.spy(); MessageBus.on('triggeredEvent', spy); MessageBus.trigger('triggeredEvent'); expect(spy).to.have.been.called; }); it('should fire the callback each time it is called', function() { var spy = sinon.spy(); MessageBus.on('triggeredEvent', spy); MessageBus.trigger('triggeredEvent'); MessageBus.trigger('triggeredEvent'); MessageBus.trigger('triggeredEvent'); expect(spy).to.have.been.calledThrice; }); }); describe('#off()', function() { it('should prevent the callback from firing after it is called', function() { var spy = sinon.spy(); MessageBus.on('triggeredEvent', spy); MessageBus.trigger('triggeredEvent'); MessageBus.off('triggeredEvent'); MessageBus.trigger('triggeredEvent'); MessageBus.trigger('triggeredEvent'); expect(spy).to.have.been.calledOnce; }); }); describe('#trigger()', function() { it('should trigger callbacks attached to listeners', function() { var spy = sinon.spy(); MessageBus.on('triggeredEvent', spy); MessageBus.trigger('triggeredEvent'); expect(spy).to.have.been.called; }); }); describe('#once()', function() { it('should throw an exception', function() { expect(MessageBus.listenTo).to. throw (/Not Implemented/); }); }); describe('#listenTo()', function() { it('should throw an exception', function() { expect(MessageBus.listenTo).to. throw (/Not Implemented/); }); }); describe('#stopListening()', function() { it('should throw an exception', function() { expect(MessageBus.listenTo).to. throw (/Not Implemented/); }); }); }); });
<filename>src/components/hooks/Nonsense.js import React, { createContext, useContext, useCallback } from 'react' import { useLocalStorage } from './useLocalStorage' export const NonsenseContext = createContext([]) export const NonsenseProvider = props => { const [nonsense, setNonsense] = useLocalStorage('nonsense', true) return ( <NonsenseContext.Provider value={[nonsense, setNonsense]}> {props.children} </NonsenseContext.Provider> ) } // Note, this will suspend (useEffect within LocalStorage hook) export function useNonsense () { const [ nonsenseValue, setNonsense ] = useContext(NonsenseContext) const toggleNonsense = useCallback(() => { if (nonsenseValue) setNonsense(false) else setNonsense(true) }, [setNonsense, nonsenseValue]) return { nonsense: nonsenseValue, toggleNonsense } }
#!/bin/bash kubectl create ns argocd kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
#!/usr/bin/env bash # $1 sudu password # requre sudo password if [ "$1" == "" ]; then echo "[warning] require sudo password parameter." exit 1 fi SUDO_PW=$1 # MySQL # usage: $ mysql -u user -h 127.0.0.1 -p echo $SUDO_PW | sudo -S docker run -d --name mysql -p 0.0.0.0:3306:3306 \ -e MYSQL_ROOT_PASSWORD=root \ -e MYSQL_DATABASE=db \ -e MYSQL_USER=user \ -e MYSQL_PASSWORD=pass \ mysql --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci #MongoDB echo $SUDO_PW | sudo -S docker run -d --name mongo -p 127.0.0.1:27017:27017 mongo
<gh_stars>0 import {useState} from 'react' function Counter() { const [count,setCount]=useState(0); const increase=()=>{ setCount(count+1) } const decrease=()=>{ setCount(count-1) } return ( <div> <h1>{count}</h1> <button onClick={increase} >Artır</button> <button onClick={decrease}>Azalt</button> </div> ) } export default Counter
/*------------------------------------------------------------------ * us1060.c - Unit Tests for User Story 1060 - TLS SRP support (Server/Proxy) * * May, 2014 * * Copyright (c) 2014-2016 by cisco Systems, Inc. * All rights reserved. *------------------------------------------------------------------ */ #include <stdio.h> #include <string.h> #ifndef WIN32 #include <unistd.h> #include <pthread.h> #endif #include <est.h> #include <curl/curl.h> #include "test_utils.h" #include "curl_utils.h" #include "st_server.h" #include "st_proxy.h" #include <openssl/ssl.h> #include <openssl/x509v3.h> #ifdef HAVE_CUNIT #include "CUnit/Basic.h" #include "CUnit/Automated.h" #endif #define US1060_SERVER_PORT 31060 #define US1060_SERVER_IP "127.0.0.1" #define US1060_UID "estuser" #define US1060_PWD "<PASSWORD>" #ifndef WIN32 #define US1060_CACERTS "CA/estCA/cacert.crt" #define US1060_TRUST_CERTS "CA/trustedcerts.crt" #define US1060_SERVER_CERTKEY "CA/estCA/private/estservercertandkey.pem" #define US1060_VFILE "US1060/passwd.srpv" #define US1060_EXPLICIT_CERT "US1060/explicit-cert.pem" #define US1060_EXPLICIT_KEY "US1060/explicit-key.pem" #define US1060_SELFSIGN_CERT "US1060/selfsigned-cert.pem" #define US1060_SELFSIGN_KEY "US1060/selfsigned-key.pem" #else #define US1060_CACERTS "CA\\estCA\\cacert.crt" #define US1060_TRUST_CERTS "CA\\trustedcerts.crt" #define US1060_SERVER_CERTKEY "CA\\estCA\\private\\estservercertandkey.pem" #define US1060_VFILE "US1060\\passwd.srpv" #define US1060_EXPLICIT_CERT "US1060\\explicit-cert.pem" #define US1060_EXPLICIT_KEY "US1060\\explicit-key.pem" #define US1060_SELFSIGN_CERT "US1060\\selfsigned-cert.pem" #define US1060_SELFSIGN_KEY "US1060\\selfsigned-key.pem" #endif #define US1060_ENROLL_URL "https://127.0.0.1:31060/.well-known/est/simpleenroll" #define US1060_UIDPWD_GOOD "est<PASSWORD>:est<PASSWORD>" #define US1060_UIDPWD_BAD "estuser:xxx<PASSWORD>" #define US1060_PKCS10_CT "Content-Type: application/pkcs10" #define US1060_PROXY_ENROLL_URL "https://127.0.0.1:41060/.well-known/est/simpleenroll" #define US1060_PROXY_PORT 41060 #define US1060_PKCS10_REQ "MIIChjCCAW4CAQAwQTElMCMGA1UEAxMccmVxIGJ5IGNsaWVudCBpbiBkZW1vIHN0\nZXAgMjEYMBYGA1UEBRMPUElEOldpZGdldCBTTjoyMI<KEY>" static char *log_search_target = NULL; static int search_target_found = 0; static unsigned char *cacerts = NULL; static int cacerts_len = 0; static SRP_VBASE *srpdb = NULL; #ifdef WIN32 CRITICAL_SECTION logger_critical_section; #endif /* * This is a simple callback used to override the default * logging facility in libest. We'll use this to look * for specific debug output. */ static void us1060_logger_stderr (char *format, va_list l) { char t_log[1024]; #ifndef WIN32 flockfile(stderr); #else EnterCriticalSection(&logger_critical_section); #endif if (log_search_target) { vsnprintf(t_log, 1024, format, l); if (strstr(t_log, log_search_target)) { search_target_found = 1; } fprintf(stderr, "%s", t_log); } else { vfprintf(stderr, format, l); } fflush(stderr); #ifndef WIN32 funlockfile(stderr); #else LeaveCriticalSection(&logger_critical_section); #endif } static int us1060_start_server (char *cert, char *key, int no_http_auth, int enable_pop, int enable_srp) { int rv; if (enable_srp) { rv = st_start_srp(US1060_SERVER_PORT, cert, key, "US1060 test realm", US1060_CACERTS, US1060_TRUST_CERTS, "CA/estExampleCA.cnf", enable_pop, US1060_VFILE); } else { rv = st_start(US1060_SERVER_PORT, cert, key, "US1060 test realm", US1060_CACERTS, US1060_TRUST_CERTS, "CA/estExampleCA.cnf", 0, enable_pop, 0); } if (no_http_auth) { st_disable_http_auth(); } return rv; } /* * This routine is called when CUnit initializes this test * suite. This can be used to allocate data or open any * resources required for all the test cases. */ static int us1060_init_suite (void) { int rv; #ifdef WIN32 /* Initialize critical section on Windows*/ InitializeCriticalSection(&logger_critical_section); #endif est_init_logger(EST_LOG_LVL_INFO, &us1060_logger_stderr); /* * Start an instance of the EST server with * automatic enrollment enabled. */ rv = us1060_start_server(US1060_SERVER_CERTKEY, US1060_SERVER_CERTKEY, 0, 0, 1); /* * Start an instance of the proxy with SRP enabled */ rv = st_proxy_start_srp(US1060_PROXY_PORT, US1060_SERVER_CERTKEY, US1060_SERVER_CERTKEY, "US1060 proxy realm", US1060_CACERTS, US1060_TRUST_CERTS, US1060_UID, US1060_PWD, US1060_SERVER_IP, US1060_SERVER_PORT, 0, US1060_VFILE); /* * Read in the CA certificates * Used for client-side API testing */ cacerts_len = read_binary_file(US1060_CACERTS, &cacerts); if (cacerts_len <= 0) { return 1; } srpdb = SRP_VBASE_new(NULL); if (!srpdb) { printf("\nUnable allocate SRP verifier database. Aborting!!!\n"); } if (SRP_VBASE_init(srpdb, US1060_VFILE) != SRP_NO_ERROR) { printf("\nUnable initialize SRP verifier database. Aborting!!!\n"); } return rv; } /* * This routine is called when CUnit uninitializes this test * suite. This can be used to deallocate data or close any * resources that were used for the test cases. */ static int us1060_destroy_suite (void) { if (srpdb) { SRP_VBASE_free(srpdb); } st_stop(); st_proxy_stop(); free(cacerts); return 0; } typedef enum { SRP_OFF, SRP_ON } server_srp_mode; typedef enum { SRP_GOOD, SRP_BAD, SRP_NONE, } client_srp_mode; typedef enum { HTTP_OFF, HTTP_OPTIONAL, HTTP_REQUIRED } server_http_mode; typedef struct { char *test_name; char *curl_cert; char *curl_key; char *curl_http_auth; client_srp_mode curl_srp; server_http_mode server_http; server_srp_mode server_srp; int expected_http_result; } us1060_matrix; /* * This is the unit test matrix for server-side SRP support. Curl is * used as the EST client. Because of this PoP is disabled on the * server for all test cases. We try to cover a variety of configurations * and potential scenarios. The client side variations include: * * curl_cert: The certificate curl uses, which may be NULL * curl_key: The key curl uses, which may be NULL * curl_http_auth: The HTTP auth credentials used by curl. * client_srp_mode: Either GOOD, BAD, NONE. Determines which SRP credentials are used * Curl. * * On the server side we configure the server using the following variations: * * server_http_mode: HTTP auth is required, optional, or disabled. * (optional means it only occurs when TLS auth fails) * server_srp_mode: SRP is either enabled or disabled on the server. * * expected_http_result: This is the expected HTTP status code received on by Curl. * When SRP fails, this results in a failed TLS session. Curl * returns a zero in this case since the HTTP layer can not * communicate. If TLS succeeds, but HTTP auth fails, then * the server should return a HTTP 401 response to the client. * When enrollment succeeds, the server should send a * HTTP 200 response. * * */ static us1060_matrix test_matrix[] = { {"1", NULL, NULL, US1060_UIDPWD_GOOD, SRP_GOOD, HTTP_REQUIRED, SRP_ON, 200}, {"2", NULL, NULL, US1060_UIDPWD_GOOD, SRP_BAD, HTTP_REQUIRED, SRP_ON, 0}, {"3", NULL, NULL, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_REQUIRED, SRP_ON, 200}, {"4", NULL, NULL, US1060_UIDPWD_GOOD, SRP_GOOD, HTTP_OPTIONAL, SRP_ON, 200}, {"5", NULL, NULL, US1060_UIDPWD_GOOD, SRP_BAD, HTTP_OPTIONAL, SRP_ON, 0}, {"6", NULL, NULL, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OPTIONAL, SRP_ON, 200}, {"7", NULL, NULL, US1060_UIDPWD_GOOD, SRP_GOOD, HTTP_OFF, SRP_ON, 200}, {"8", NULL, NULL, US1060_UIDPWD_GOOD, SRP_BAD, HTTP_OFF, SRP_ON, 0}, {"9", NULL, NULL, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OFF, SRP_ON, 401}, {"11", NULL, NULL, US1060_UIDPWD_BAD, SRP_GOOD, HTTP_REQUIRED, SRP_ON, 401}, {"12", NULL, NULL, US1060_UIDPWD_BAD, SRP_BAD, HTTP_REQUIRED, SRP_ON, 0}, {"13", NULL, NULL, US1060_UIDPWD_BAD, SRP_NONE, HTTP_REQUIRED, SRP_ON, 401}, {"14", NULL, NULL, US1060_UIDPWD_BAD, SRP_GOOD, HTTP_OPTIONAL, SRP_ON, 200}, {"15", NULL, NULL, US1060_UIDPWD_BAD, SRP_BAD, HTTP_OPTIONAL, SRP_ON, 0}, {"16", NULL, NULL, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OPTIONAL, SRP_ON, 401}, {"17", NULL, NULL, US1060_UIDPWD_BAD, SRP_GOOD, HTTP_OFF, SRP_ON, 200}, {"18", NULL, NULL, US1060_UIDPWD_BAD, SRP_BAD, HTTP_OFF, SRP_ON, 0}, {"19", NULL, NULL, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OFF, SRP_ON, 401}, {"21", NULL, NULL, US1060_UIDPWD_GOOD, SRP_GOOD, HTTP_REQUIRED, SRP_OFF, 0}, {"22", NULL, NULL, US1060_UIDPWD_GOOD, SRP_BAD, HTTP_REQUIRED, SRP_OFF, 0}, {"23", NULL, NULL, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_REQUIRED, SRP_OFF, 200}, {"24", NULL, NULL, US1060_UIDPWD_GOOD, SRP_GOOD, HTTP_OPTIONAL, SRP_OFF, 0}, {"25", NULL, NULL, US1060_UIDPWD_GOOD, SRP_BAD, HTTP_OPTIONAL, SRP_OFF, 0}, {"26", NULL, NULL, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OPTIONAL, SRP_OFF, 200}, {"27", NULL, NULL, US1060_UIDPWD_GOOD, SRP_GOOD, HTTP_OFF, SRP_OFF, 0}, {"28", NULL, NULL, US1060_UIDPWD_GOOD, SRP_BAD, HTTP_OFF, SRP_OFF, 0}, {"29", NULL, NULL, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OFF, SRP_OFF, 401}, {"31", NULL, NULL, US1060_UIDPWD_BAD, SRP_GOOD, HTTP_REQUIRED, SRP_OFF, 0}, {"32", NULL, NULL, US1060_UIDPWD_BAD, SRP_BAD, HTTP_REQUIRED, SRP_OFF, 0}, {"33", NULL, NULL, US1060_UIDPWD_BAD, SRP_NONE, HTTP_REQUIRED, SRP_OFF, 401}, {"34", NULL, NULL, US1060_UIDPWD_BAD, SRP_GOOD, HTTP_OPTIONAL, SRP_OFF, 0}, {"35", NULL, NULL, US1060_UIDPWD_BAD, SRP_BAD, HTTP_OPTIONAL, SRP_OFF, 0}, {"36", NULL, NULL, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OPTIONAL, SRP_OFF, 401}, {"37", NULL, NULL, US1060_UIDPWD_BAD, SRP_GOOD, HTTP_OFF, SRP_OFF, 0}, {"38", NULL, NULL, US1060_UIDPWD_BAD, SRP_BAD, HTTP_OFF, SRP_OFF, 0}, {"39", NULL, NULL, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OFF, SRP_OFF, 401}, {"40", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_REQUIRED, SRP_ON, 200}, {"41", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_REQUIRED, SRP_ON, 401}, {"42", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OPTIONAL, SRP_ON, 200}, {"43", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OPTIONAL, SRP_ON, 200}, {"44", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OFF, SRP_ON, 200}, {"45", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OFF, SRP_ON, 200}, {"46", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_REQUIRED, SRP_OFF, 200}, {"47", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_REQUIRED, SRP_OFF, 401}, {"48", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OPTIONAL, SRP_OFF, 200}, {"49", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OPTIONAL, SRP_OFF, 200}, {"50", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OFF, SRP_OFF, 200}, {"51", US1060_EXPLICIT_CERT, US1060_EXPLICIT_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OFF, SRP_OFF, 200}, {"60", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_REQUIRED, SRP_ON, 0}, {"61", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_REQUIRED, SRP_ON, 0}, {"62", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OPTIONAL, SRP_ON, 0}, {"63", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OPTIONAL, SRP_ON, 0}, {"64", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OFF, SRP_ON, 0}, {"65", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OFF, SRP_ON, 0}, {"66", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_REQUIRED, SRP_OFF, 0}, {"67", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_REQUIRED, SRP_OFF, 0}, {"68", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OPTIONAL, SRP_OFF, 0}, {"69", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OPTIONAL, SRP_OFF, 0}, {"70", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_GOOD, SRP_NONE, HTTP_OFF, SRP_OFF, 0}, {"71", US1060_SELFSIGN_CERT, US1060_SELFSIGN_KEY, US1060_UIDPWD_BAD, SRP_NONE, HTTP_OFF, SRP_OFF, 0}, }; /* * This is our worker for each entry in the test matrix above. * We read the configuration from the entry, configure the * server and client as needed, and attempt a simple enroll * using Curl as the client. * The argument i is the index of the entry in the table above. */ static void us1060_test_matrix_item (int i) { long rv; LOG_FUNC_NM ; printf("\nRunning matrix test %s\n", test_matrix[i].test_name); /* * Stop the server and restart it to make sure * it's in the correct mode. */ st_stop(); SLEEP(1); if (test_matrix[i].server_srp == SRP_ON) { rv = us1060_start_server(US1060_SERVER_CERTKEY, US1060_SERVER_CERTKEY, 0, 0, 1); } else { rv = us1060_start_server(US1060_SERVER_CERTKEY, US1060_SERVER_CERTKEY, 0, 0, 0); } CU_ASSERT(rv == 0); /* * Set the server HTTP auth configuration */ switch (test_matrix[i].server_http) { case HTTP_OFF: st_disable_http_auth(); break; case HTTP_OPTIONAL: st_enable_http_auth(); st_set_http_auth_optional(); break; case HTTP_REQUIRED: st_enable_http_auth(); st_set_http_auth_required(); break; } switch (test_matrix[i].curl_srp) { case SRP_GOOD: rv = curl_http_post_srp(US1060_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, test_matrix[i].curl_http_auth, NULL, CURLAUTH_BASIC, NULL, "srp_user", "srp_pwd", NULL, NULL); break; case SRP_BAD: rv = curl_http_post_srp(US1060_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, test_matrix[i].curl_http_auth, NULL, CURLAUTH_BASIC, NULL, "srp_user", "<PASSWORD>", NULL, NULL); break; case SRP_NONE: /* * Some of the SRP disabled test cases use a client * certificate. */ if (test_matrix[i].curl_cert) { rv = curl_http_post_certuid(US1060_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, test_matrix[i].curl_http_auth, test_matrix[i].curl_cert, test_matrix[i].curl_key, US1060_CACERTS, NULL); } else { rv = curl_http_post(US1060_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, test_matrix[i].curl_http_auth, US1060_CACERTS, CURLAUTH_BASIC, NULL, NULL, NULL); } break; } CU_ASSERT(rv == test_matrix[i].expected_http_result); if (rv != test_matrix[i].expected_http_result) { printf("\nMatrix test %s failed with rv = %d\n", test_matrix[i].test_name, (int) rv); } } /* * This test case runs all the tests in the matrix */ static void us1060_test0 (void) { int i; int test_cnt = sizeof(test_matrix) / sizeof(test_matrix[0]); for (i = 0; i < test_cnt; i++) { us1060_test_matrix_item(i); } } /* * This test case is verifies the happy path when EST * proxy is configured in SRP mode. The client will attempt * to use SRP. The connection between the proxy and * server does not use SRP. We perform a simple enroll * operation. */ static void us1060_test200 (void) { long rv; LOG_FUNC_NM ; /* * Restart the EST server with SRP disabled */ st_stop(); SLEEP(2); rv = us1060_start_server(US1060_SERVER_CERTKEY, US1060_SERVER_CERTKEY, 0, 0, 0); CU_ASSERT(rv == 0); rv = curl_http_post_srp(US1060_PROXY_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, US1060_UIDPWD_GOOD, NULL, CURLAUTH_BASIC, NULL, "srp_user", "srp_pwd", NULL, NULL); /* * Since we passed in a valid SRP userID/password, * we expect the server to respond with success */ CU_ASSERT(rv == 200); } /* * This test case is verifies the simple enroll fails * when the EST client provides a bad SRP password. * The connection between the proxy and server does not * use SRP. */ static void us1060_test201 (void) { long rv; LOG_FUNC_NM ; rv = curl_http_post_srp(US1060_PROXY_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, US1060_UIDPWD_GOOD, NULL, CURLAUTH_BASIC, NULL, "srp_user", "<PASSWORD>", NULL, NULL); CU_ASSERT(rv == 0); } /* * This test case is verifies the simple enroll fails * when the EST client provides a bad HTTP password * and SRP is used. The connection between the proxy * and server does not use SRP. */ static void us1060_test202 (void) { long rv; LOG_FUNC_NM ; rv = curl_http_post_srp(US1060_PROXY_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, US1060_UIDPWD_BAD, NULL, CURLAUTH_BASIC, NULL, "srp_user", "srp_pwd", NULL, NULL); CU_ASSERT(rv == 401); } /* * This test case is verifies the simple enroll works * when the EST client provides no HTTP password * and SRP is used. The connection between the proxy * and server does not use SRP. HTTP auth is disabled * on the proxy. */ static void us1060_test203 (void) { long rv; LOG_FUNC_NM ; st_proxy_http_disable(1); rv = curl_http_post_srp(US1060_PROXY_ENROLL_URL, US1060_PKCS10_CT, US1060_PKCS10_REQ, NULL, NULL, CURLAUTH_NONE, NULL, "srp_user", "srp_pwd", NULL, NULL); CU_ASSERT(rv == 200); } int us1060_add_suite (void) { #ifdef HAVE_CUNIT CU_pSuite pSuite = NULL; /* add a suite to the registry */ pSuite = CU_add_suite("us1060_tls_srp (server/proxy)", us1060_init_suite, us1060_destroy_suite); if (NULL == pSuite) { CU_cleanup_registry(); return CU_get_error(); } /* * Add the tests to the suite * * ********************IMPORTANT********************* * Do not change the order of these tests. * Some of the tests stop the EST server and restart * it using different certs. If you change the order * then false negatives may occur. * ************************************************** * */ if ((NULL == CU_add_test(pSuite, "TLS-SRP server: matrix master", us1060_test0)) || (NULL == CU_add_test(pSuite, "TLS-SRP proxy: enroll w/SRP", us1060_test200)) || (NULL == CU_add_test(pSuite, "TLS-SRP proxy: enroll bad SRP pwd", us1060_test201)) || (NULL == CU_add_test(pSuite, "TLS-SRP proxy: enroll bad HTTP pwd", us1060_test202)) || (NULL == CU_add_test(pSuite, "TLS-SRP proxy: enroll w/o HTTP auth", us1060_test203))) { CU_cleanup_registry(); return CU_get_error(); } return CUE_SUCCESS; #endif }
package cm.xxx.minos.leetcode; /** * Description: * Author: lishangmin * Created: 2018-09-04 00:27 */ public class DoublyListNode { int val; DoublyListNode next, prev; DoublyListNode(int x) {val = x;} public DoublyListNode(int val, DoublyListNode next, DoublyListNode prev) { this.val = val; this.next = next; this.prev = prev; } public int getVal() { return val; } public void setVal(int val) { this.val = val; } public DoublyListNode getNext() { return next; } public void setNext(DoublyListNode next) { this.next = next; } public DoublyListNode getPrev() { return prev; } public void setPrev(DoublyListNode prev) { this.prev = prev; } }
<filename>velocloud/provider.go<gh_stars>0 package velocloud import ( "context" //"fmt" "log" //"github.com/hashicorp-demoapp/hashicups-client-go" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "terraform-provider-velocloud/velocloud/vcoclient" ) func Provider() *schema.Provider { return &schema.Provider{ Schema: map[string]*schema.Schema{ "username": &schema.Schema{ Type: schema.TypeString, Optional: true, DefaultFunc: schema.EnvDefaultFunc("VCO_USER", nil), Description: "Login user name of Velocloud Orchestrator. this user role requires an enterprise superuser.", }, "password": &schema.Schema{ Type: schema.TypeString, Optional: true, Sensitive: true, DefaultFunc: schema.EnvDefaultFunc("VCO_PASS", nil), Description: "password of the login user.", }, "vco": &schema.Schema{ Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("VCO_HOST", nil), Description: "FQDN of Velocloud Orchestrator.", }, "apikey": &schema.Schema{ Type: schema.TypeString, Optional: true, DefaultFunc: schema.EnvDefaultFunc("VCO_KEY", nil), Description: "API Token of Enteprise level. This attirbute cannot be used at same time as 'username'.", }, }, ResourcesMap: map[string]*schema.Resource{ "velocloud_edge": resourceVeloEdge(), "velocloud_profile": resourceVeloProfile(), "velocloud_firewall": resourceVeloFirewall(), }, DataSourcesMap: map[string]*schema.Resource{ "velocloud_address_gruop": dataSourceVeloAddressGroup(), "velocloud_edge": dataSourceVeloEdge(), "velocloud_license_list": dataSourceVeloLicenseList(), "velocloud_port_gruop": dataSourceVeloPortGroup(), "velocloud_profile": dataSourceVeloProfile(), "velocloud_segment": dataSourceVeloSegment(), }, ConfigureContextFunc: providerConfigure, } } func providerConfigure(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) { vco := d.Get("vco").(string) username := d.Get("username").(string) password := d.Get("password").(string) apikey := d.Get("apikey").(string) // Warning or errors can be collected in a slice type var diags diag.Diagnostics c := vcoclient.NewAPIClient(&vcoclient.Configuration{ UserAgent: "Terraform velocloud Agent/1.0.0/go", BasePath: "https://" + vco + "/portal/", DefaultHeader: make(map[string]string), Idcount: 0, }) if (apikey != "") && (username == "") && (password == "") && (vco != "") { c.AddHeader("Authorization", "Token "+apikey) return c, diags } if (username != "") && (password != "") && (vco != "") && (apikey == "") { log.Println("username authentication") auth := &vcoclient.AuthObject{ Username: username, Password: password, } _, err := c.LoginApi.LoginEnterpriseLogin(nil, *auth) if err != nil { return nil, diag.FromErr(err) } return c, diags } return nil, diag.Errorf("Missing credentials") }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_euro_symbol = void 0; var ic_euro_symbol = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M0 0h24v24H0z", "fill": "none" }, "children": [] }, { "name": "path", "attribs": { "d": "M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15v-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15V9H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3v2h3.06c-.04.33-.06.66-.06 1 0 .34.02.67.06 1H3v2h3.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z" }, "children": [] }] }; exports.ic_euro_symbol = ic_euro_symbol;
#!/bin/bash # # Copyright 2013 Bagher BabaAli, # 2014 Brno University of Technology (Author: Karel Vesely) # # TIMIT, description of the database: # http://perso.limsi.fr/lamel/TIMIT_NISTIR4930.pdf # # Hon and Lee paper on TIMIT, 1988, introduces mapping to 48 training phonemes, # then re-mapping to 39 phonemes for scoring: # http://repository.cmu.edu/cgi/viewcontent.cgi?article=2768&context=compsci # . ./cmd.sh [ -f path.sh ] && . ./path.sh set -e # Acoustic model parameters numLeavesTri1=2500 numGaussTri1=15000 numLeavesMLLT=2500 numGaussMLLT=15000 numLeavesSAT=2500 numGaussSAT=15000 numGaussUBM=400 numLeavesSGMM=7000 numGaussSGMM=9000 feats_nj=10 train_nj=30 decode_nj=5 echo ============================================================================ echo " Petuum DNN Training & Decoding " echo ============================================================================ ./scripts/petuum_dnn.sh --num-jobs-nnet "$train_nj" --cmd "$train_cmd" \ data/train data/lang exp/tri3_ali exp/petuum_dnn echo ============================================================================ echo " Getting Results [see RESULTS file] " echo ============================================================================ bash RESULTS dev bash RESULTS test echo ============================================================================ echo "Finished successfully on" `date` echo ============================================================================ exit 0
/* * Copyright 2017 Danish Maritime Authority. * * 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 net.maritimeconnectivity.pki; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.security.cert.X509Certificate; import java.util.stream.Collectors; import static net.maritimeconnectivity.pki.CertificateHandler.getCertFromPem; import static org.junit.jupiter.api.Assertions.fail; public class TestUtils { public static String getRootCAAlias() { return "urn:mrn:mcl:ca:maritimecloud"; } public static String getMyBoatCertPem() { String certFile = "src/test/resources/Certificate_Myboat.pem"; String contents = loadTxtFile(certFile); return contents; } public static X509Certificate getMyBoatCert() { return getCertFromPem(getMyBoatCertPem()); } public static String getEcdisCertPem() { String certFile = "src/test/resources/Certificate_Ecdis.pem"; String contents = loadTxtFile(certFile); return contents; } public static X509Certificate getEcdisCert() { return getCertFromPem(getEcdisCertPem()); } public static String getTestUserCertPem() { String certFile = "src/test/resources/Certificate_TestUser.pem"; String contents = loadTxtFile(certFile); return contents; } public static X509Certificate getTestUserCert() { return getCertFromPem(getTestUserCertPem()); } public static String loadTxtFile(String path) { try { return Files.lines(Paths.get(path)).collect(Collectors.joining("\n")); } catch (IOException e) { e.printStackTrace(); fail("Loading Certificate from file failed!"); throw new RuntimeException(e); } } }
<gh_stars>1-10 package io.github.rcarlosdasilva.weixin.common.dictionary; import com.google.gson.annotations.SerializedName; /** * 语言 * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public enum Language { /** 简体中文. */ @SerializedName("zh_CN") ZH_CN("zh_CN"), /** 繁体中文TW. */ @SerializedName("zh_TW") ZH_TW("zh_TW"), /** 繁体中文HK. */ @SerializedName("zh_HK") ZH_HK("zh_HK"), /** 英文. */ @SerializedName("en") EN_US("en"), /** 印尼语. */ @SerializedName("id") ID("id"), /** 马来语. */ @SerializedName("ms") MS("ms"), /** 西班牙语. */ @SerializedName("es") ES("es"), /** 韩语. */ @SerializedName("ko") KO("ko"), /** 意大利语. */ @SerializedName("it") IT("it"), /** 日语. */ @SerializedName("ja") JA("ja"), /** 波兰语. */ @SerializedName("pl") PL("pl"), /** 葡萄牙语. */ @SerializedName("pt") PT("pt"), /** 俄语. */ @SerializedName("ru") RU("ru"), /** 泰文. */ @SerializedName("th") TH("th"), /** 越南语. */ @SerializedName("vi") VI("vi"), /** 阿拉伯语. */ @SerializedName("ar") AR("ar"), /** 北印度. */ @SerializedName("hi") HI("hi"), /** 希伯来语. */ @SerializedName("he") HE("he"), /** 土耳其语. */ @SerializedName("tr") TR("tr"), /** 德语. */ @SerializedName("de") DE("de"), /** 法语. */ @SerializedName("fr") FR("fr"); private String text; private Language(String text) { this.text = text; } public String getText() { return text; } @Override public String toString() { return this.text; } }
<reponame>ShaolinDeng/SDK-Android<filename>platform/src/com/iflytek/cyber/platform/CyberCore.java /* * Copyright (C) 2018 iFLYTEK CO.,LTD. * * 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 com.iflytek.cyber.platform; import android.util.Log; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.iflytek.cyber.CyberDelegate; import com.iflytek.cyber.Entities; import com.iflytek.cyber.SpeechController; import com.iflytek.cyber.platform.client.CyberClient; import com.iflytek.cyber.platform.client.CyberOkHttpClient; import java.util.UUID; import okio.BufferedSource; import okio.Source; public class CyberCore { private static final String TAG = "CyberCore"; private final CyberHandler core; private final AttachmentManager attachmentManager = new AttachmentManager(); private final ContextManager contextManager = new ContextManager(); private SpeechController speechController = null; public CyberCore(CyberHandler core) { this.core = core; } public void destroy() { attachmentManager.destroy(); } void setEndpoint(String endpoint) { core.setEndpoint(endpoint); } public void queryAttachment(String cid, CyberDelegate.AttachmentCallback callback) { attachmentManager.query(cid, callback); } public void attachmentReady(String cid, BufferedSource source) { attachmentManager.ready(cid, source); } public void updateContext(String namespace, String name, JsonObject payload) { contextManager.update(namespace, name, payload); } public void removeContext(String namespace, String name) { contextManager.remove(namespace, name); } @Deprecated void setSpeechController(SpeechController speechController) { this.speechController = speechController; } @Deprecated public void startRecognize(Source source, JsonObject initiator) { speechController.start(source, initiator); } @Deprecated public void finishRecognize() { speechController.finish(); } @Deprecated public void cancelRecognize() { CyberOkHttpClient.getClient().cancelEvent(); } void stopCapture() { core.stopCapture(); } void expectSpeech(JsonObject initiator) { core.expectSpeech(initiator); } public void dialogResolved() { core.onDialogResolved(); } public void postEvent(String namespace, String name, JsonObject payload, boolean withContext) { final JsonObject envelope = new JsonObject(); envelope.add("context", withContext ? contextManager.build() : new JsonArray()); envelope.add("event", Entities.newMessage(namespace, name, payload)); CyberOkHttpClient.getClient().postEvent(envelope, null, new CyberClient.EventCallback() { @Override public void onDirective(JsonObject directive) { core.onEventDirective(directive); } @Override public void onFailure(Throwable e) { core.onEventFailure(e); } @Override public void onEnd() { core.onEventEnd(); } }); } public void postEvent(String namespace, String name, JsonObject payload, Source audio) { final String dialogRequestId = UUID.randomUUID().toString(); final JsonObject envelope = new JsonObject(); envelope.add("context", contextManager.build()); envelope.add("event", Entities.newMessage(namespace, name, dialogRequestId, payload)); core.onRecognizeStart(dialogRequestId); CyberOkHttpClient.getClient().postEvent(envelope, audio, new CyberClient.EventCallback() { @Override public void onDirective(JsonObject directive) { core.onRecognizeDirective(dialogRequestId, directive); } @Override public void onFailure(Throwable e) { core.onRecognizeFailure(dialogRequestId, e); } @Override public void onEnd() { core.onRecognizeEnd(dialogRequestId); } }); } @Deprecated public void reportExecutionFailure(String unparsedDirective, String message) { Log.e(TAG, "Directive execute failed: " + message + " - " + unparsedDirective); final JsonObject error = new JsonObject(); error.addProperty("type", "UNEXPECTED_INFORMATION_RECEIVED"); error.addProperty("message", message); final JsonObject payload = new JsonObject(); payload.addProperty("unparsedDirective", unparsedDirective); payload.add("error", error); postEvent("System", "ExceptionEncountered", payload, true); } @Deprecated public void reportException(String unparsedDirective, Throwable t) { Log.e(TAG, "Directive execute error: " + unparsedDirective, t); final JsonObject error = new JsonObject(); error.addProperty("type", "INTERNAL_ERROR"); error.addProperty("message", t.getMessage()); final JsonObject payload = new JsonObject(); payload.addProperty("unparsedDirective", unparsedDirective); payload.add("error", error); postEvent("System", "ExceptionEncountered", payload, true); } @Deprecated public void synchronizeState() { postEvent("System", "SynchronizeState", new JsonObject(), true); } }
import React from "react" import InfoNotice from "./InfoNotice" import XButton from "./XButton" type Props = {onClick: Function} export default function IngestUpdateNotice({onClick}: Props) { return ( <InfoNotice> <p>More data is now available.</p> <p> <button className="bevel-button" onClick={() => onClick(0)}> Refresh </button> </p> <XButton onClick={() => onClick(1)} /> </InfoNotice> ) }
import cupy import numpy as np import time square_diff_kernel = cupy.ElementwiseKernel( 'T x, T y', 'T z', 'z = x*x - y*y', 'square_diff' ) def square_diff(in1, in2): return in1*in1 - in2*in2 def test_cupy_kernel(): # Generate random CuPy arrays a = cupy.random.randint(1, 101, 10**6) b = cupy.random.randint(1, 101, 10**6) # Measure execution time of square_diff_kernel start_time_kernel = time.time() result_gpu = square_diff_kernel(a, b) end_time_kernel = time.time() # Convert CuPy arrays to NumPy arrays for comparison with Python function a_np = cupy.asnumpy(a) b_np = cupy.asnumpy(b) # Measure execution time of square_diff function on equivalent NumPy arrays start_time_python = time.time() result_cpu = square_diff(a_np, b_np) end_time_python = time.time() # Print execution times print("Execution time of square_diff_kernel:", end_time_kernel - start_time_kernel, "seconds") print("Execution time of square_diff function:", end_time_python - start_time_python, "seconds") test_cupy_kernel()
var SOBA = artifacts.require("./SOBA.sol"); module.exports = function(deployer) { deployer.deploy(SOBA); };
#!/bin/sh java -DJNIEASY_LICENSE_DIR=.. -Djava.library.path=. -jar ../JNIEasyExamples.jar
// Based on https://www.typescriptlang.org/docs/handbook/advanced-types.html function padLeft(value, padding) { if (typeof padding === "number") { return Array(padding + 1).join(" ") + value; } if (typeof padding === "string") { return padding + value; } throw new Error("Expected string or number, got '" + padding + "'."); } console.log(padLeft("Hello world", 4)); // returns " Hello world" console.log(padLeft("Hello world", " Yakov says ")); // returns " Yakov says Hello world" console.log(padLeft("Hello world", true)); // runtime error // Change the function signature to catch type error during compile time // function padLeft(value: string, padding: string | number) { // No need to throw an error either
import { DefinitionIdentifier as IDefinitionIdentifier, DefinitionIdentifierPOJO, UUID } from "../../public"; import { Identifiers } from "./identifiers"; import { _internal } from "./utils"; import { Joi } from "./validation"; export abstract class DefinitionIdentifier implements IDefinitionIdentifier { public static readonly [_internal] = { label: "object", schema: Joi.object({ id: Joi.string().uuid().required(), identifiers: Identifiers[_internal].schema, }), }; public readonly id: UUID; public readonly identifiers: Identifiers; public constructor(pojo: DefinitionIdentifierPOJO) { this.id = pojo.id; this.identifiers = new Identifiers(pojo.identifiers); } }
#!/bin/bash rm -rf mos cp -r /opt/mos-components-ci mos pushd mos cp etc/lxc/ha/neutron_vlan_ubuntu/* . ln -s ~/images iso sed -i 's|./actions/prepare-environment.sh|#./actions/prepare-environment.sh|' launch.sh ./launch.sh popd
package org.terracottamc.network.packet.type; /** * Copyright (c) 2021, TerracottaMC * All rights reserved. * * <p> * This project is licensed under the BSD 3-Clause License which * can be found in the root directory of this source tree * * @author Kaooot * @version 1.0 */ public enum ResourcePackDataInfoType { INVALID, ADDON, CACHED, COPY_PROTECTED, BEHAVIOUR, PERSONA_PIECE, RESOURCE, SKINS, WORLD_TEMPLATE, COUNT }
<gh_stars>1-10 package de.lmu.cis.ocrd; public interface Line { int getLineId(); int getPageId(); String getNormalized(); }
<gh_stars>0 class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :set_logged_user, :cors_preflight_check after_filter :cors_set_access_control_headers # For all responses in this controller, return the CORS access control headers. def cors_set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'PUT,DELETE,AUTH,POST, GET, OPTIONS' headers['Access-Control-Allow-Headers'] = '*' headers['Access-Control-Max-Age'] = "1728000" end # If this is a preflight OPTIONS request, then short-circuit the # request, return only the necessary headers and return an empty # text/plain. def cors_preflight_check if request.method == :options headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'PUT,DELETE,AUTH,POST, GET, OPTIONS' headers['Access-Control-Allow-Headers'] = '*' headers['Access-Control-Max-Age'] = '1728000' render :text => '', :content_type => 'text/plain' end end def flushFlashMessages flash.each do |name, msg| flash.delete(:name) end end private def set_logged_user if !(params[:controller].eql? "welcome") and !(params[:controller].eql? "api") and !(params[:controller].eql? "context") if session[:is_user_validated] @@user=User.find_by_id(session[:user_id]) else redirect_to root_url end end end end
def remove_duplicates(string): output = "" for char in string: if char not in output: output += char return output
func configure(with viewModel: AlbumViewModel) { map(old: self.viewModel, new: viewModel) coverImageView.image = UIImage(named: viewModel.coverName) nameLabel.text = viewModel.name artistLabel.text = viewModel.artiste favoriteIcon.isHidden = !viewModel.isFavorite self.viewModel = viewModel } private func map(old: AlbumViewModel?, new: AlbumViewModel) { guard let oldViewModel = old else { // Initial configuration, no need to compare return } if oldViewModel.coverName != new.coverName { coverImageView.image = UIImage(named: new.coverName) } if oldViewModel.name != new.name { nameLabel.text = new.name } if oldViewModel.artiste != new.artiste { artistLabel.text = new.artiste } if oldViewModel.isFavorite != new.isFavorite { favoriteIcon.isHidden = !new.isFavorite } }
package org.multibit.hd.core.services; import org.multibit.hd.core.config.Configurations; import org.multibit.hd.core.events.ShutdownEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Service to provide the following to application API:</p> * <ul> * <li>Configuration persistence after a shutdown hook</li> * </ul> * * @since 0.0.1 */ public class ConfigurationService extends AbstractService { private static final Logger log = LoggerFactory.getLogger(ConfigurationService.class); @Override protected boolean startInternal() { // Do nothing return true; } @Override protected boolean shutdownNowInternal(ShutdownEvent.ShutdownType shutdownType) { log.debug("Persisting current configuration after shutdown"); // We may be in a partial startup situation if (Configurations.currentConfiguration != null) { Configurations.persistCurrentConfiguration(); } // Service can survive a switch return preventCleanupOnSwitch(shutdownType); } }
cat ../Data/tmdb_5000_movies.csv | python ETL_mapper.py | sort -k1 | python ETL_reducer.py > ../Data/processed_movie_data.dat
<filename>offer/src/main/java/com/java/study/answer/zuo/fsenior/class01/Code04_DistinctSubseq.java package com.java.study.answer.zuo.fsenior.class01; import java.util.Arrays; public class Code04_DistinctSubseq { public static int distinctSubseq1(String s) { char[] str = s.toCharArray(); int result = 0; int[] dp = new int[str.length]; Arrays.fill(dp, 1); for (int i = 0; i < str.length; i++) { for (int j = 0; j < i; j++) { if (str[j] != str[i]) { dp[i] += dp[j]; } } result += dp[i]; } return result; } public static int distinctSubseq2(String s) { if (s == null || s.length() == 0) { return 0; } char[] str = s.toCharArray(); int[] dp = new int[str.length]; Arrays.fill(dp, 1); int[] count = new int[26]; int result = 0; for (int i = 0; i < str.length; i++) { int index = str[i] - 'a'; dp[i] += result - count[index]; result += dp[i]; count[index] = count[index] + dp[i]; } return result; } public static int distinctSubseq3(String s) { if (s == null || s.length() == 0) { return 0; } char[] str = s.toCharArray(); int[] count = new int[26]; int result = 0; for (int i = 0; i < str.length; i++) { int index = str[i] - 'a'; int pre = result - count[index] + 1; count[index] += pre; result += pre; } return result; } public static String random(int len, int varible) { int size = (int) (Math.random() * len) + 1; char[] str = new char[size]; for (int i = 0; i < size; i++) { str[i] = (char) ((int) (Math.random() * varible) + 'a'); } return String.valueOf(str); } public static void main(String[] args) { int len = 10; int varible = 5; for (int i = 0; i < 1000000; i++) { String test = random(len, varible); if (distinctSubseq1(test) != distinctSubseq2(test) || distinctSubseq2(test) != distinctSubseq3(test)) { System.out.println("fuck"); } } } }
<filename>example/react/screens/PlaylistScreen.js<gh_stars>0 import React, { useEffect } from 'react' import { StyleSheet, Text, View } from 'react-native' import TrackPlayer, { Capability, State, usePlaybackState, RepeatMode } from 'react-native-track-player' import Player from '../components/Player' import playlistData from '../data/playlist.json' import localTrack from '../resources/pure.m4a' export default function PlaylistScreen() { const playbackState = usePlaybackState() useEffect(() => { TrackPlayer.setupPlayer() TrackPlayer.updateOptions({ stopWithApp: true, capabilities: [ Capability.Play, Capability.Pause, Capability.SkipToNext, Capability.SkipToPrevious, Capability.Stop, ], compactCapabilities: [Capability.Play, Capability.Pause], seekToleranceBefore: 0, seekToleranceAfter: 0, }) }, []) const [playWhenReady, setPlayWhenReady] = React.useState(true) async function togglePlayback() { const currentTrack = await TrackPlayer.getCurrentTrack() if (currentTrack == null) { await TrackPlayer.reset() await TrackPlayer.add(playlistData) await TrackPlayer.add({ id: 'local-track', url: localTrack, title: 'Pure (Demo)', artist: '<NAME>', artwork: 'https://picsum.photos/200', initialTime: 0, }) await TrackPlayer.play() } else { if (playbackState !== State.Playing) { await TrackPlayer.play() } else { await TrackPlayer.pause() } } } async function togglePlayWhenReady() { const current = await TrackPlayer.getPlayWhenReady() await TrackPlayer.setPlayWhenReady(!current) setPlayWhenReady(!current) } async function toggleRepeatMode() { let repeatMode = await TrackPlayer.getRepeatMode() switch (repeatMode) { case RepeatMode.None: repeatMode = RepeatMode.Queue break case RepeatMode.Queue: repeatMode = RepeatMode.Track break case RepeatMode.Track: repeatMode = RepeatMode.None break } await TrackPlayer.setRepeatMode(repeatMode) } async function seekTo(seconds: number) { await TrackPlayer.seekTo(seconds) await TrackPlayer.play() } return ( <View style={styles.container}> <Text style={styles.description}> We'll be inserting a playlist into the library loaded from `playlist.json`. We'll also be using the `ProgressComponent` which allows us to track playback time. </Text> <Player onNext={skipToNext} style={styles.player} onPrevious={skipToPrevious} onTogglePlayback={togglePlayback} onTogglePlayWhenReady={togglePlayWhenReady} onToggleRepeatMode={toggleRepeatMode} onSeekTo={seekTo} playWhenReady={playWhenReady} /> <Text style={styles.state}>{getStateName(playbackState)}</Text> </View> ) } PlaylistScreen.navigationOptions = { title: 'Playlist Example', } function getStateName(state) { switch (state) { case State.None: return 'None' case State.Playing: return 'Playing' case State.Paused: return 'Paused' case State.Stopped: return 'Stopped' case State.Buffering: return 'Buffering' case State.Ready: return 'Ready' case State.Connecting: return 'Connecting' default: return 'Unknown' } } async function skipToNext() { try { await TrackPlayer.skipToNext() } catch (_) {} } async function skipToPrevious() { try { // Rewinds if current progress >= 3 await TrackPlayer.skipToPrevious(3) } catch (_) {} } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#F5FCFF', }, description: { width: '80%', marginTop: 20, textAlign: 'center', }, player: { marginTop: 40, }, state: { marginTop: 20, }, })
<gh_stars>10-100 # -*- encoding: utf-8 -*- lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) require 'dalli/elasticache/version' Gem::Specification.new do |s| s.name = 'dalli-elasticache' s.version = Dalli::ElastiCache::VERSION s.licenses = ['MIT'] s.summary = "Configure Dalli clients with ElastiCache's AutoDiscovery" s.description = <<-EOS This gem provides an interface for fetching cluster information from an AWS ElastiCache AutoDiscovery server and configuring a Dalli client to connect to all nodes in the cache cluster. EOS s.authors = ["<NAME>", "<NAME>"] s.email = ["<EMAIL>", "<EMAIL>"] s.homepage = 'http://github.com/ktheory/dalli-elasticache' s.files = Dir.glob("{bin,lib}/**/*") + %w(README.md Rakefile) s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.test_files = Dir.glob("{test,spec}/**/*") s.required_ruby_version = '>= 1.9.2' # Maybe less? s.required_rubygems_version = '>= 1.3.5' s.add_development_dependency 'rake' s.add_development_dependency 'rspec' s.add_dependency 'dalli', ">= 1.0.0" # ?? end
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package org.ofbiz.minilang; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import org.ofbiz.base.location.FlexibleLocation; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.UtilXml; import org.ofbiz.base.util.cache.UtilCache; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.transaction.GenericTransactionException; import org.ofbiz.entity.transaction.TransactionUtil; import org.ofbiz.minilang.method.MethodContext; import org.ofbiz.minilang.method.MethodOperation; import org.ofbiz.minilang.method.MethodOperation.DeprecatedOperation; import org.ofbiz.minilang.method.callops.CallService; import org.ofbiz.minilang.method.callops.CallServiceAsynch; import org.ofbiz.minilang.method.callops.CallSimpleMethod; import org.ofbiz.minilang.method.callops.SetServiceFields; import org.ofbiz.minilang.method.conditional.MasterIf; import org.ofbiz.minilang.method.conditional.While; import org.ofbiz.minilang.method.entityops.GetRelated; import org.ofbiz.minilang.method.entityops.GetRelatedOne; import org.ofbiz.minilang.method.entityops.EntityAnd; import org.ofbiz.minilang.method.entityops.EntityCondition; import org.ofbiz.minilang.method.entityops.EntityCount; import org.ofbiz.minilang.method.entityops.EntityOne; import org.ofbiz.minilang.method.entityops.FindByAnd; import org.ofbiz.minilang.method.entityops.FindByPrimaryKey; import org.ofbiz.minilang.method.entityops.MakeValue; import org.ofbiz.minilang.method.envops.Iterate; import org.ofbiz.minilang.method.envops.IterateMap; import org.ofbiz.minilang.method.envops.Loop; import org.ofbiz.minilang.method.ifops.IfCompare; import org.ofbiz.minilang.method.ifops.IfCompareField; import org.ofbiz.minilang.method.ifops.IfEmpty; import org.ofbiz.minilang.method.ifops.IfHasPermission; import org.ofbiz.minilang.method.ifops.IfInstanceOf; import org.ofbiz.minilang.method.ifops.IfNotEmpty; import org.ofbiz.minilang.method.ifops.IfRegexp; import org.ofbiz.minilang.method.ifops.IfValidateMethod; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.ModelService; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.webslinger.invoker.Wrap; /** * SimpleMethod Mini Language Core Object */ public class SimpleMethod { private static final Map<String, MethodOperation.Factory<MethodOperation>> methodOperationFactories; // never read locally: private static final Method simpleMethodExecMethod; private static final Method methodOperationExecMethod; static { Map<String, MethodOperation.Factory<MethodOperation>> mapFactories = new HashMap<String, MethodOperation.Factory<MethodOperation>>(); Iterator<MethodOperation.Factory<MethodOperation>> it = UtilGenerics.cast(ServiceLoader.load(MethodOperation.Factory.class, SimpleMethod.class.getClassLoader()).iterator()); while (it.hasNext()) { MethodOperation.Factory<MethodOperation> factory = it.next(); mapFactories.put(factory.getName(), factory); } methodOperationFactories = Collections.unmodifiableMap(mapFactories); try { // never read locally: simpleMethodExecMethod = SimpleMethod.class.getDeclaredMethod("exec", MethodContext.class); methodOperationExecMethod = MethodOperation.class.getDeclaredMethod("exec", MethodContext.class); } catch (NoSuchMethodException e) { throw UtilMisc.initCause(new InternalError(e.getMessage()), e); } } public static final String module = SimpleMethod.class.getName(); public static final String err_resource = "MiniLangErrorUiLabels"; protected static UtilCache<String, Map<String, SimpleMethod>> simpleMethodsDirectCache = UtilCache.createUtilCache("minilang.SimpleMethodsDirect", 0, 0); protected static UtilCache<String, Map<String, SimpleMethod>> simpleMethodsResourceCache = UtilCache.createUtilCache("minilang.SimpleMethodsResource", 0, 0); protected static UtilCache<URL, Map<String, SimpleMethod>> simpleMethodsURLCache = UtilCache.createUtilCache("minilang.SimpleMethodsURL", 0, 0); // ----- Event Context Invokers ----- public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response) throws MiniLangException { return runSimpleMethod(xmlResource, methodName, new MethodContext(request, response, null)); } public static String runSimpleEvent(String xmlResource, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) throws MiniLangException { return runSimpleMethod(xmlResource, methodName, new MethodContext(request, response, loader)); } public static String runSimpleEvent(URL xmlURL, String methodName, HttpServletRequest request, HttpServletResponse response, ClassLoader loader) throws MiniLangException { return runSimpleMethod(xmlURL, methodName, new MethodContext(request, response, loader)); } // ----- Service Context Invokers ----- public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, Map<String, ? extends Object> context) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, null); runSimpleMethod(xmlResource, methodName, methodContext); return methodContext.getResults(); } public static Map<String, Object> runSimpleService(String xmlResource, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, loader); runSimpleMethod(xmlResource, methodName, methodContext); return methodContext.getResults(); } public static Map<String, Object> runSimpleService(URL xmlURL, String methodName, DispatchContext ctx, Map<String, ? extends Object> context, ClassLoader loader) throws MiniLangException { MethodContext methodContext = new MethodContext(ctx, context, loader); runSimpleMethod(xmlURL, methodName, methodContext); return methodContext.getResults(); } // ----- General Method Invokers ----- public static String runSimpleMethod(String xmlResource, String methodName, MethodContext methodContext) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = getSimpleMethods(xmlResource, methodContext.getLoader()); SimpleMethod simpleMethod = simpleMethods.get(methodName); if (simpleMethod == null) { throw new MiniLangException("Could not find SimpleMethod " + methodName + " in XML document in resource: " + xmlResource); } return simpleMethod.exec(methodContext); } public static String runSimpleMethod(URL xmlURL, String methodName, MethodContext methodContext) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = getSimpleMethods(xmlURL); SimpleMethod simpleMethod = simpleMethods.get(methodName); if (simpleMethod == null) { throw new MiniLangException("Could not find SimpleMethod " + methodName + " in XML document from URL: " + xmlURL.toString()); } return simpleMethod.exec(methodContext); } public static Map<String, SimpleMethod> getSimpleMethods(String xmlResource, ClassLoader loader) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = simpleMethodsResourceCache.get(xmlResource); if (simpleMethods == null) { synchronized (SimpleMethod.class) { simpleMethods = simpleMethodsResourceCache.get(xmlResource); if (simpleMethods == null) { //URL xmlURL = UtilURL.fromResource(xmlResource, loader); URL xmlURL = null; try { xmlURL = FlexibleLocation.resolveLocation(xmlResource, loader); } catch (MalformedURLException e) { throw new MiniLangException("Could not find SimpleMethod XML document in resource: " + xmlResource + "; error was: " + e.toString(), e); } if (xmlURL == null) { throw new MiniLangException("Could not find SimpleMethod XML document in resource: " + xmlResource); } simpleMethods = getAllSimpleMethods(xmlURL); // put it in the cache simpleMethodsResourceCache.put(xmlResource, simpleMethods); } } } return simpleMethods; } public static List<SimpleMethod> getSimpleMethodsList(String xmlResource, ClassLoader loader) throws MiniLangException { List<SimpleMethod> simpleMethods = FastList.newInstance(); // Let the standard Map returning method take care of caching and compilation Map<String, SimpleMethod> simpleMethodMap = SimpleMethod.getSimpleMethods(xmlResource, loader); // Load and traverse the document again to get a correctly ordered list of methods URL xmlURL = null; try { xmlURL = FlexibleLocation.resolveLocation(xmlResource, loader); } catch (MalformedURLException e) { throw new MiniLangException("Could not find SimpleMethod XML document in resource: " + xmlResource + "; error was: " + e.toString(), e); } // read in the file Document document = null; try { document = UtilXml.readXmlDocument(xmlURL, true, true); } catch (java.io.IOException e) { throw new MiniLangException("Could not read XML file", e); } catch (org.xml.sax.SAXException e) { throw new MiniLangException("Could not parse XML file", e); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new MiniLangException("XML parser not setup correctly", e); } if (document == null) { throw new MiniLangException("Could not find SimpleMethod XML document: " + xmlURL.toString()); } Element rootElement = document.getDocumentElement(); for (Element simpleMethodElement: UtilXml.childElementList(rootElement, "simple-method")) { simpleMethods.add(simpleMethodMap.get(simpleMethodElement.getAttribute("method-name"))); } return simpleMethods; } public static Map<String, SimpleMethod> getSimpleMethods(URL xmlURL) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = simpleMethodsURLCache.get(xmlURL); if (simpleMethods == null) { synchronized (SimpleMethod.class) { simpleMethods = simpleMethodsURLCache.get(xmlURL); if (simpleMethods == null) { simpleMethods = getAllSimpleMethods(xmlURL); // put it in the cache simpleMethodsURLCache.put(xmlURL, simpleMethods); } } } return simpleMethods; } protected static Map<String, SimpleMethod> getAllSimpleMethods(URL xmlURL) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = FastMap.newInstance(); // read in the file Document document = null; try { document = UtilXml.readXmlDocument(xmlURL, true, true); } catch (java.io.IOException e) { throw new MiniLangException("Could not read XML file", e); } catch (org.xml.sax.SAXException e) { throw new MiniLangException("Could not parse XML file", e); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new MiniLangException("XML parser not setup correctly", e); } if (document == null) { throw new MiniLangException("Could not find SimpleMethod XML document: " + xmlURL.toString()); } Element rootElement = document.getDocumentElement(); for (Element simpleMethodElement: UtilXml.childElementList(rootElement, "simple-method")) { SimpleMethod simpleMethod = compileSimpleMethod(simpleMethodElement, simpleMethods, xmlURL.toString()); simpleMethods.put(simpleMethod.getMethodName(), simpleMethod); } return simpleMethods; } protected static SimpleMethod compileSimpleMethod(Element simpleMethodElement, Map<String, SimpleMethod> simpleMethods, String location) { return new SimpleMethod(simpleMethodElement, simpleMethods, location); } public static Map<String, SimpleMethod> getDirectSimpleMethods(String name, String content, String fromLocation) throws MiniLangException { Map<String, SimpleMethod> simpleMethods = simpleMethodsDirectCache.get(name); if (simpleMethods == null) { synchronized (SimpleMethod.class) { simpleMethods = simpleMethodsDirectCache.get(name); if (simpleMethods == null) { simpleMethods = getAllDirectSimpleMethods(name, content, fromLocation); // put it in the cache simpleMethodsDirectCache.put(name, simpleMethods); } } } return simpleMethods; } protected static Map<String, SimpleMethod> getAllDirectSimpleMethods(String name, String content, String fromLocation) throws MiniLangException { if (UtilValidate.isEmpty(fromLocation)) { fromLocation = "<location not known>"; } Map<String, SimpleMethod> simpleMethods = FastMap.newInstance(); // read in the file Document document = null; try { if (content != null) { document = UtilXml.readXmlDocument(content, true, true); } } catch (java.io.IOException e) { throw new MiniLangException("Could not read XML content", e); } catch (org.xml.sax.SAXException e) { throw new MiniLangException("Could not parse direct XML content", e); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new MiniLangException("XML parser not setup correctly", e); } if (document == null) { throw new MiniLangException("Could not load SimpleMethod XML document: " + name); } Element rootElement = document.getDocumentElement(); for (Element simpleMethodElement: UtilXml.childElementList(rootElement, "simple-method")) { SimpleMethod simpleMethod = compileSimpleMethod(simpleMethodElement, simpleMethods, fromLocation); simpleMethods.put(simpleMethod.getMethodName(), simpleMethod); } return simpleMethods; } // Member fields begin here... protected List<MethodOperation> methodOperations = FastList.newInstance(); protected Map<String, SimpleMethod> parentSimpleMethodsMap; protected String fromLocation; protected String methodName; protected String shortDescription; protected String defaultErrorCode; protected String defaultSuccessCode; protected String parameterMapName; // event fields protected String eventRequestName; protected String eventSessionName; protected String eventResponseName; protected String eventResponseCodeName; protected String eventErrorMessageName; protected String eventErrorMessageListName; protected String eventEventMessageName; protected String eventEventMessageListName; // service fields protected String serviceResponseMessageName; protected String serviceErrorMessageName; protected String serviceErrorMessageListName; protected String serviceErrorMessageMapName; protected String serviceSuccessMessageName; protected String serviceSuccessMessageListName; protected boolean loginRequired = true; protected boolean useTransaction = true; protected String localeName; protected String delegatorName; protected String securityName; protected String dispatcherName; protected String userLoginName; public SimpleMethod(Element simpleMethodElement, Map<String, SimpleMethod> parentSimpleMethodsMap, String fromLocation) { this.parentSimpleMethodsMap = parentSimpleMethodsMap; this.fromLocation = fromLocation; this.methodName = simpleMethodElement.getAttribute("method-name"); this.shortDescription = simpleMethodElement.getAttribute("short-description"); defaultErrorCode = UtilXml.elementAttribute(simpleMethodElement, "default-error-code", "error"); defaultSuccessCode = UtilXml.elementAttribute(simpleMethodElement, "default-success-code", "success"); parameterMapName = UtilXml.elementAttribute(simpleMethodElement, "parameter-map-name", "parameters"); eventRequestName = UtilXml.elementAttribute(simpleMethodElement, "event-request-object-name", "request"); eventSessionName = UtilXml.elementAttribute(simpleMethodElement, "event-session-object-name", "session"); eventResponseName = UtilXml.elementAttribute(simpleMethodElement, "event-response-object-name", "response"); eventResponseCodeName = UtilXml.elementAttribute(simpleMethodElement, "event-response-code-name", "_response_code_"); eventErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-name", "_error_message_"); eventErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-error-message-list-name", "_error_message_list_"); eventEventMessageName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-name", "_event_message_"); eventEventMessageListName = UtilXml.elementAttribute(simpleMethodElement, "event-event-message-list-name", "_event_message_list_"); serviceResponseMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-response-message-name", "responseMessage"); serviceErrorMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-name", "errorMessage"); serviceErrorMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-list-name", "errorMessageList"); serviceErrorMessageMapName = UtilXml.elementAttribute(simpleMethodElement, "service-error-message-map-name", "errorMessageMap"); serviceSuccessMessageName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-name", "successMessage"); serviceSuccessMessageListName = UtilXml.elementAttribute(simpleMethodElement, "service-success-message-list-name", "successMessageList"); loginRequired = !"false".equals(simpleMethodElement.getAttribute("login-required")); useTransaction = !"false".equals(simpleMethodElement.getAttribute("use-transaction")); localeName = UtilXml.elementAttribute(simpleMethodElement, "locale-name", "locale"); delegatorName = UtilXml.elementAttribute(simpleMethodElement, "delegator-name", "delegator"); securityName = UtilXml.elementAttribute(simpleMethodElement, "security-name", "security"); dispatcherName = UtilXml.elementAttribute(simpleMethodElement, "dispatcher-name", "dispatcher"); userLoginName = UtilXml.elementAttribute(simpleMethodElement, "user-login-name", "userLogin"); readOperations(simpleMethodElement, this.methodOperations, this); } public String getFromLocation() { return this.fromLocation; } public String getMethodName() { return this.methodName; } public String getLocationAndName() { return this.fromLocation + "#" + this.methodName; } public SimpleMethod getSimpleMethodInSameFile(String simpleMethodName) { if (parentSimpleMethodsMap == null) return null; return parentSimpleMethodsMap.get(simpleMethodName); } public String getShortDescription() { return this.shortDescription + " [" + this.fromLocation + "#" + this.methodName + "]"; } public String getDefaultErrorCode() { return this.defaultErrorCode; } public String getDefaultSuccessCode() { return this.defaultSuccessCode; } public String getParameterMapName() { return this.parameterMapName; } // event fields public String getEventRequestName() { return this.eventRequestName; } public String getEventSessionName() { return this.eventSessionName; } public String getEventResponseCodeName() { return this.eventResponseCodeName; } public String getEventErrorMessageName() { return this.eventErrorMessageName; } public String getEventErrorMessageListName() { return this.eventErrorMessageListName; } public String getEventEventMessageName() { return this.eventEventMessageName; } public String getEventEventMessageListName() { return this.eventEventMessageListName; } // service fields public String getServiceResponseMessageName() { return this.serviceResponseMessageName; } public String getServiceErrorMessageName() { return this.serviceErrorMessageName; } public String getServiceErrorMessageListName() { return this.serviceErrorMessageListName; } public String getServiceErrorMessageMapName() { return this.serviceErrorMessageMapName; } public String getServiceSuccessMessageName() { return this.serviceSuccessMessageName; } public String getServiceSuccessMessageListName() { return this.serviceSuccessMessageListName; } public boolean getLoginRequired() { return this.loginRequired; } public boolean getUseTransaction() { return this.useTransaction; } public String getDelegatorEnvName() { return this.delegatorName; } public String getSecurityEnvName() { return this.securityName; } public String getDispatcherEnvName() { return this.dispatcherName; } public String getUserLoginEnvName() { return this.userLoginName; } public Set<String> getAllServiceNamesCalled() throws MiniLangException { Set<String> allServiceNames = FastSet.newInstance(); Set<String> simpleMethodsVisited = FastSet.newInstance(); findServiceNamesCalled(this.methodOperations, allServiceNames, simpleMethodsVisited); return allServiceNames; } protected static void findServiceNamesCalled(List<MethodOperation> methodOperations, Set<String> allServiceNames, Set<String> simpleMethodsVisited) throws MiniLangException { for (MethodOperation methodOperation: methodOperations) { if (methodOperation instanceof CallService) { String svcName = ((CallService) methodOperation).getServiceName(); if (UtilValidate.isNotEmpty(svcName)) allServiceNames.add(svcName); } else if (methodOperation instanceof CallServiceAsynch) { String svcName = ((CallServiceAsynch) methodOperation).getServiceName(); if (UtilValidate.isNotEmpty(svcName)) allServiceNames.add(svcName); } else if (methodOperation instanceof SetServiceFields) { String svcName = ((SetServiceFields) methodOperation).getServiceName(); if (UtilValidate.isNotEmpty(svcName)) allServiceNames.add(svcName); } else if (methodOperation instanceof CallSimpleMethod) { CallSimpleMethod csm = (CallSimpleMethod) methodOperation; try { SimpleMethod calledMethod = csm.getSimpleMethodToCall(methodOperations.getClass().getClassLoader()); if (calledMethod == null) { Debug.logWarning("Could not find simple-method [" + csm.getMethodName() + "] in [" + csm.getXmlResource() + "] from the SimpleMethod [" + csm.getSimpleMethod().getMethodName() + "] in [" + csm.getSimpleMethod().getFromLocation() + "]", module); } else { if (!simpleMethodsVisited.contains(calledMethod.getLocationAndName())) { simpleMethodsVisited.add(calledMethod.getLocationAndName()); findServiceNamesCalled(calledMethod.methodOperations, allServiceNames, simpleMethodsVisited); } } } catch (MiniLangException e) { Debug.logWarning("Error getting simple-method info in the [" + csm.getSimpleMethod().getMethodName() + "] in [" + csm.getSimpleMethod().getFromLocation() + "]: " + e.toString(), module); } } else if (methodOperation instanceof Iterate) { findServiceNamesCalled(((Iterate) methodOperation).getSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IterateMap) { findServiceNamesCalled(((IterateMap) methodOperation).getSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof Loop) { findServiceNamesCalled(((Loop) methodOperation).getSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof MasterIf) { findServiceNamesCalled(((MasterIf) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof While) { findServiceNamesCalled(((While) methodOperation).getThenSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfValidateMethod) { findServiceNamesCalled(((IfValidateMethod) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfInstanceOf) { findServiceNamesCalled(((IfInstanceOf) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfCompare) { findServiceNamesCalled(((IfCompare) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfCompareField) { findServiceNamesCalled(((IfCompareField) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfRegexp) { findServiceNamesCalled(((IfRegexp) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfEmpty) { findServiceNamesCalled(((IfEmpty) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfNotEmpty) { findServiceNamesCalled(((IfNotEmpty) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } else if (methodOperation instanceof IfHasPermission) { findServiceNamesCalled(((IfHasPermission) methodOperation).getAllSubOps(), allServiceNames, simpleMethodsVisited); } } } public Set<String> getAllEntityNamesUsed() throws MiniLangException { Set<String> allEntityNames = FastSet.newInstance(); Set<String> simpleMethodsVisited = FastSet.newInstance(); findEntityNamesUsed(this.methodOperations, allEntityNames, simpleMethodsVisited); return allEntityNames; } protected static void findEntityNamesUsed(List<MethodOperation> methodOperations, Set<String> allEntityNames, Set<String> simpleMethodsVisited) throws MiniLangException { for (MethodOperation methodOperation: methodOperations) { if (methodOperation instanceof FindByPrimaryKey) { String entName = ((FindByPrimaryKey) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof FindByAnd) { String entName = ((FindByAnd) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof EntityOne) { String entName = ((EntityOne) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof EntityAnd) { String entName = ((EntityAnd) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof EntityCondition) { String entName = ((EntityCondition) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof EntityCount) { String entName = ((EntityCount) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof MakeValue) { String entName = ((MakeValue) methodOperation).getEntityName(); if (UtilValidate.isNotEmpty(entName)) allEntityNames.add(entName); } else if (methodOperation instanceof GetRelated) { String relationName = ((GetRelated) methodOperation).getRelationName(); if (UtilValidate.isNotEmpty(relationName)) allEntityNames.add(relationName); } else if (methodOperation instanceof GetRelatedOne) { String relationName = ((GetRelatedOne) methodOperation).getRelationName(); if (UtilValidate.isNotEmpty(relationName)) allEntityNames.add(relationName); } else if (methodOperation instanceof CallSimpleMethod) { CallSimpleMethod csm = (CallSimpleMethod) methodOperation; try { SimpleMethod calledMethod = csm.getSimpleMethodToCall(null); if (calledMethod == null) { Debug.logWarning("Could not find simple-method [" + csm.getMethodName() + "] in [" + csm.getXmlResource() + "] from the SimpleMethod [" + csm.getSimpleMethod().getMethodName() + "] in [" + csm.getSimpleMethod().getFromLocation() + "]", module); } else { if (!simpleMethodsVisited.contains(calledMethod.getLocationAndName())) { simpleMethodsVisited.add(calledMethod.getLocationAndName()); findEntityNamesUsed(calledMethod.methodOperations, allEntityNames, simpleMethodsVisited); } } } catch (MiniLangException e) { Debug.logWarning("Error getting simple-method info in the [" + csm.getSimpleMethod().getMethodName() + "] in [" + csm.getSimpleMethod().getFromLocation() + "]: " + e.toString(), module); } } else if (methodOperation instanceof Iterate) { findEntityNamesUsed(((Iterate) methodOperation).getSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IterateMap) { findEntityNamesUsed(((IterateMap) methodOperation).getSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof Loop) { findEntityNamesUsed(((Loop) methodOperation).getSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof MasterIf) { findEntityNamesUsed(((MasterIf) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof While) { findEntityNamesUsed(((While) methodOperation).getThenSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfValidateMethod) { findEntityNamesUsed(((IfValidateMethod) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfInstanceOf) { findEntityNamesUsed(((IfInstanceOf) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfCompare) { findEntityNamesUsed(((IfCompare) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfCompareField) { findEntityNamesUsed(((IfCompareField) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfRegexp) { findEntityNamesUsed(((IfRegexp) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfEmpty) { findEntityNamesUsed(((IfEmpty) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfNotEmpty) { findEntityNamesUsed(((IfNotEmpty) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } else if (methodOperation instanceof IfHasPermission) { findEntityNamesUsed(((IfHasPermission) methodOperation).getAllSubOps(), allEntityNames, simpleMethodsVisited); } } } /** Execute the Simple Method operations */ public String exec(MethodContext methodContext) { // always put the null field object in as "null" methodContext.putEnv("null", GenericEntity.NULL_FIELD); methodContext.putEnv("nullField", GenericEntity.NULL_FIELD); methodContext.putEnv(delegatorName, methodContext.getDelegator()); methodContext.putEnv(securityName, methodContext.getSecurity()); methodContext.putEnv(dispatcherName, methodContext.getDispatcher()); methodContext.putEnv(localeName, methodContext.getLocale()); methodContext.putEnv(parameterMapName, methodContext.getParameters()); if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.putEnv(eventRequestName, methodContext.getRequest()); methodContext.putEnv(eventSessionName, methodContext.getRequest().getSession()); methodContext.putEnv(eventResponseName, methodContext.getResponse()); } methodContext.putEnv("methodName", this.getMethodName()); methodContext.putEnv("methodShortDescription", this.getShortDescription()); GenericValue userLogin = methodContext.getUserLogin(); Locale locale = methodContext.getLocale(); if (userLogin != null) { methodContext.putEnv(userLoginName, userLogin); } if (loginRequired) { if (userLogin == null) { Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("shortDescription", shortDescription); String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.must_logged_process", messageMap, locale) + "."; if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.getRequest().setAttribute("_ERROR_MESSAGE_", errMsg); return defaultErrorCode; } else if (methodContext.getMethodType() == MethodContext.SERVICE) { methodContext.putResult(ModelService.ERROR_MESSAGE, errMsg); methodContext.putResult(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); return null; } } } // if using transaction, try to start here boolean beganTransaction = false; if (useTransaction) { try { beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e) { String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.error_begin_transaction", locale) + ": " + e.getMessage(); Debug.logWarning(errMsg, module); Debug.logWarning(e, module); if (methodContext.getMethodType() == MethodContext.EVENT) { methodContext.getRequest().setAttribute("_ERROR_MESSAGE_", errMsg); return defaultErrorCode; } else if (methodContext.getMethodType() == MethodContext.SERVICE) { methodContext.putResult(ModelService.ERROR_MESSAGE, errMsg); methodContext.putResult(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR); return null; } } } // declare errorMsg here just in case transaction ops fail String errorMsg = ""; boolean finished = false; try { finished = runSubOps(methodOperations, methodContext); } catch (Throwable t) { // make SURE nothing gets thrown through String errMsg = UtilProperties.getMessage(SimpleMethod.err_resource, "simpleMethod.error_running", locale) + ": " + t.getMessage(); Debug.logError(errMsg, module); finished = false; errorMsg += errMsg + "<br/>"; } String returnValue = null; String response = null; StringBuilder summaryErrorStringBuffer = new StringBuilder(); if (methodContext.getMethodType() == MethodContext.EVENT) { boolean forceError = false; String tempErrorMsg = (String) methodContext.getEnv(eventErrorMessageName); if (errorMsg.length() > 0 || UtilValidate.isNotEmpty(tempErrorMsg)) { errorMsg += tempErrorMsg; methodContext.getRequest().setAttribute("_ERROR_MESSAGE_", errorMsg); forceError = true; summaryErrorStringBuffer.append(errorMsg); } List<Object> tempErrorMsgList = UtilGenerics.checkList(methodContext.getEnv(eventErrorMessageListName)); if (UtilValidate.isNotEmpty(tempErrorMsgList)) { methodContext.getRequest().setAttribute("_ERROR_MESSAGE_LIST_", tempErrorMsgList); forceError = true; summaryErrorStringBuffer.append("; "); summaryErrorStringBuffer.append(tempErrorMsgList.toString()); } String eventMsg = (String) methodContext.getEnv(eventEventMessageName); if (UtilValidate.isNotEmpty(eventMsg)) { methodContext.getRequest().setAttribute("_EVENT_MESSAGE_", eventMsg); } List<String> eventMsgList = UtilGenerics.checkList(methodContext.getEnv(eventEventMessageListName)); if (UtilValidate.isNotEmpty(eventMsgList)) { methodContext.getRequest().setAttribute("_EVENT_MESSAGE_LIST_", eventMsgList); } response = (String) methodContext.getEnv(eventResponseCodeName); if (UtilValidate.isEmpty(response)) { if (forceError) { //override response code, always use error code Debug.logInfo("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + "]", module); response = defaultErrorCode; } else { Debug.logInfo("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", module); response = defaultSuccessCode; } } else if ("null".equalsIgnoreCase(response)) { response = null; } returnValue = response; } else if (methodContext.getMethodType() == MethodContext.SERVICE) { boolean forceError = false; String tempErrorMsg = (String) methodContext.getEnv(serviceErrorMessageName); if (errorMsg.length() > 0 || UtilValidate.isNotEmpty(tempErrorMsg)) { errorMsg += tempErrorMsg; methodContext.putResult(ModelService.ERROR_MESSAGE, errorMsg); forceError = true; summaryErrorStringBuffer.append(errorMsg); } List<Object> errorMsgList = UtilGenerics.checkList(methodContext.getEnv(serviceErrorMessageListName)); if (UtilValidate.isNotEmpty(errorMsgList)) { methodContext.putResult(ModelService.ERROR_MESSAGE_LIST, errorMsgList); forceError = true; summaryErrorStringBuffer.append("; "); summaryErrorStringBuffer.append(errorMsgList.toString()); } Map<String, Object> errorMsgMap = UtilGenerics.checkMap(methodContext.getEnv(serviceErrorMessageMapName)); if (UtilValidate.isNotEmpty(errorMsgMap)) { methodContext.putResult(ModelService.ERROR_MESSAGE_MAP, errorMsgMap); forceError = true; summaryErrorStringBuffer.append("; "); summaryErrorStringBuffer.append(errorMsgMap.toString()); } String successMsg = (String) methodContext.getEnv(serviceSuccessMessageName); if (UtilValidate.isNotEmpty(successMsg)) { methodContext.putResult(ModelService.SUCCESS_MESSAGE, successMsg); } List<Object> successMsgList = UtilGenerics.checkList(methodContext.getEnv(serviceSuccessMessageListName)); if (UtilValidate.isNotEmpty(successMsgList)) { methodContext.putResult(ModelService.SUCCESS_MESSAGE_LIST, successMsgList); } response = (String) methodContext.getEnv(serviceResponseMessageName); if (UtilValidate.isEmpty(response)) { if (forceError) { //override response code, always use error code Debug.logVerbose("No response code string found, but error messages found so assuming error; returning code [" + defaultErrorCode + "]", module); response = defaultErrorCode; } else { Debug.logVerbose("No response code string or errors found, assuming success; returning code [" + defaultSuccessCode + "]", module); response = defaultSuccessCode; } } methodContext.putResult(ModelService.RESPONSE_MESSAGE, response); returnValue = null; } else { response = defaultSuccessCode; returnValue = defaultSuccessCode; } // decide whether or not to commit based on the response message, ie only rollback if error is returned and not finished boolean doCommit = true; if (!finished && defaultErrorCode.equals(response)) { doCommit = false; } if (doCommit) { // commit here passing beganTransaction to perform it properly try { TransactionUtil.commit(beganTransaction); } catch (GenericTransactionException e) { String errMsg = "Error trying to commit transaction, could not process method: " + e.getMessage(); Debug.logWarning(e, errMsg, module); errorMsg += errMsg + "<br/>"; } } else { // rollback here passing beganTransaction to either rollback, or set rollback only try { TransactionUtil.rollback(beganTransaction, "Error in simple-method [" + this.getShortDescription() + "]: " + summaryErrorStringBuffer, null); } catch (GenericTransactionException e) { String errMsg = "Error trying to rollback transaction, could not process method: " + e.getMessage(); Debug.logWarning(e, errMsg, module); errorMsg += errMsg + "<br/>"; } } return returnValue; } public static void readOperations(Element simpleMethodElement, List<MethodOperation> methodOperations, SimpleMethod simpleMethod) { List<? extends Element> operationElements = UtilXml.childElementList(simpleMethodElement); if (UtilValidate.isNotEmpty(operationElements)) { for (Element curOperElem: operationElements) { String nodeName = curOperElem.getNodeName(); MethodOperation methodOp = null; MethodOperation.Factory<MethodOperation> factory = methodOperationFactories.get(nodeName); if (factory != null) { methodOp = factory.createMethodOperation(curOperElem, simpleMethod); } else if ("else".equals(nodeName)) { // don't add anything, but don't complain either, this one is handled in the individual operations } else { Debug.logWarning("Operation element \"" + nodeName + "\" no recognized", module); } if (methodOp == null) continue; if (UtilProperties.propertyValueEquals("webslinger-invoker.properties", "wrap-calls", "true")) { Wrap<MethodOperation> wrap = new Wrap<MethodOperation>().fileName(simpleMethod.getLocationAndName()).wrappedClass(methodOp.getClass()); wrap.wrap(methodOperationExecMethod); Object startLine = curOperElem.getUserData("startLine"); if (startLine != null) { wrap.lineNumber(((Integer) startLine).intValue()); } methodOp = wrap.newInstance(new Class<?>[] {Element.class, SimpleMethod.class}, new Object[] {curOperElem, simpleMethod}); } methodOperations.add(methodOp); DeprecatedOperation depOp = methodOp.getClass().getAnnotation(DeprecatedOperation.class); if (depOp != null) Debug.logInfo("The " + nodeName + " operation has been deprecated in favor of the " + depOp.value() + " operation; found use of this in [" + simpleMethod.getShortDescription() + "]: " + methodOp.rawString(), module); } } } /** Execs the given operations returning true if all return true, or returning * false and stopping if any return false. */ public static boolean runSubOps(List<MethodOperation> methodOperations, MethodContext methodContext) { for (MethodOperation methodOperation: methodOperations) { try { if (!methodOperation.exec(methodContext)) { return false; } } catch (Throwable t) { String errMsg = "Error in simple-method operation [" + methodOperation.rawString() + "]: " + t.toString(); Debug.logError(t, errMsg, module); throw new RuntimeException(errMsg); } } return true; } }
<reponame>weikwer/spring-boot-market package com.weikwer.market.controller; import java.util.Map; public abstract class BaseController { /** * 通过返回true,否则返回false * @param strs * @param map * @return */ public boolean mapfilter(String[] strs, Map<String, String> map){ for(String s:strs){ if(!map.containsKey(s)||map.get(s)==null||map.get(s).equals("")) return false; } return true; } public Double DoubleWithNull(Object o){ try { if (o != null && !o.toString().equals("")) return Double.valueOf(o.toString()); }catch (Exception e){ e.printStackTrace(); return null; } return null; } public Integer IngegerWithNull(Object o){ try{ if(o!=null && !o.toString().equals("")) return Integer.valueOf(o.toString()); }catch (Exception e){ e.printStackTrace(); return null; } return null; } public Long LongWithNull(Object o){ try{ if(o!=null && !o.toString().equals("")) return Long.valueOf(o.toString()); }catch (Exception e){ e.printStackTrace(); return null; } return null; } }
#!/bin/sh ########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2018 RDK Management # # 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. ########################################################################## ########################################################################## # Copyright [2018] [Cisco Systems, 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. ######################################################################### source /etc/utopia/service.d/hostname_functions.sh source /etc/utopia/service.d/ulog_functions.sh source /etc/utopia/service.d/event_handler_functions.sh SERVICE_NAME="bridge" UDHCPC_PID_FILE=/var/run/udhcpc.pid UDHCPC_SCRIPT=/etc/utopia/service.d/service_bridge/dhcp_link.sh POSTD_START_FILE="/tmp/.postd_started" #Separate routing table used to ensure that responses from the web UI go directly to the LAN interface, not out erouter0 BRIDGE_MODE_TABLE=69 #------------------------------------------------------------- # Registration/Deregistration of dhcp client restart/release/renew handlers # These are only needed if the dhcp is used # Note that service_bridge is creating the pseudo service dhcp_client #------------------------------------------------------------- HANDLER="/etc/utopia/service.d/service_bridge/dhcp_link.sh" unregister_dhcp_client_handlers() { # ulog bridge status "$PID unregister_dhcp_client_handlers" asyncid1=`sysevent get ${SERVICE_NAME}_async_id_1`; if [ -n "$asyncid1" ] ; then sysevent rm_async $asyncid1 sysevent set ${SERVICE_NAME}_async_id_1 fi asyncid2=`sysevent get ${SERVICE_NAME}_async_id_2`; if [ -n "$asyncid2" ] ; then sysevent rm_async $asyncid2 sysevent set ${SERVICE_NAME}_async_id_2 fi asyncid3=`sysevent get ${SERVICE_NAME}_async_id_3`; if [ -n "$asyncid3" ] ; then sysevent rm_async $asyncid3 sysevent set ${SERVICE_NAME}_async_id_3 fi } register_dhcp_client_handlers() { # ulog bridge status "$PID register_dhcp_client_handlers" # Remove any prior notification requests unregister_dhcp_client_handlers # instantiate a request to be notified when the dhcp_client-restart changes # make it an event (TUPLE_FLAG_EVENT = $TUPLE_FLAG_EVENT) asyncid1=`sysevent async dhcp_client-restart "$HANDLER"`; sysevent setoptions dhcp_client-restart $TUPLE_FLAG_EVENT sysevent set ${SERVICE_NAME}_async_id_1 "$asyncid1" # instantiate a request to be notified when the dhcp_client-release / renew changes # make it an event (TUPLE_FLAG_EVENT = $TUPLE_FLAG_EVENT) asyncid2=`sysevent async dhcp_client-release "$HANDLER"`; sysevent setoptions dhcp_client-release $TUPLE_FLAG_EVENT sysevent set ${SERVICE_NAME}_async_id_2 "$asyncid2" asyncid3=`sysevent async dhcp_client-renew "$HANDLER"`; sysevent setoptions dhcp_client-renew $TUPLE_FLAG_EVENT sysevent set ${SERVICE_NAME}_async_id_3 "$asyncid3" } #-------------------------------------------------------------- # Enslave a physical or virtual interface to a bridge # # Takes parameters : # $1 : the name of the interface to enslave # $2 : the name of the interface to enslave it to #-------------------------------------------------------------- enslave_a_interface() { ip link set $1 up ip link set $1 allmulticast on brctl addif $2 $1 } #-------------------------------------------------------------- # Bring up the ethernet interfaces #-------------------------------------------------------------- bringup_ethernet_interfaces() { return 0 } #-------------------------------------------------------------- # Tear down the ethernet interfaces #-------------------------------------------------------------- teardown_ethernet_interfaces() { for loop in $SYSCFG_lan_ethernet_physical_ifnames do ip link set $loop down done } #-------------------------------------------------------------- # Bring up the wireless interfaces #-------------------------------------------------------------- bringup_wireless_interfaces() { INCR_AMOUNT=10 WIFI_IF_INDEX=1 if [ "" != "$SYSCFG_lan_wl_physical_ifnames" ] ; then for loop in $SYSCFG_lan_wl_physical_ifnames do MAC=`syscfg get "macwifi0${WIFI_IF_INDEX}bssid1"` ifconfig $loop hw ether $MAC ip link set $loop allmulticast on ulog lan status "setting $loop hw address to $MAC" WL_STATE=`syscfg get wl$(($WIFI_IF_INDEX-1))_state` ulog lan status "wlancfg $loop $WL_STATE" wlancfg $loop $WL_STATE wlancfg $loop $WL_STATE WIFI_IF_INDEX=`expr $WIFI_IF_INDEX + 1` done fi } #-------------------------------------------------------------- # Teardown the wireless interfaces #-------------------------------------------------------------- teardown_wireless_interfaces() { for loop in $SYSCFG_lan_wl_physical_ifnames do wlancfg $loop down ip link set $loop down done teardown_wireless_daemons } #-------------------------------------------------------------- # stop_firewall # If the firewall is up, then tear it down #-------------------------------------------------------------- stop_firewall() { STATUS=`sysevent get firewall-status` if [ "stopped" != "$STATUS" ] ; then sysevent set firewall-stop sleep 1 wait_till_end_state firewall fi } #-------------------------------------------------------------- # add_ebtable_rule # Add rule in ebtable nat PREROUTING chain #-------------------------------------------------------------- add_ebtable_rule() { echo "Inside add_ebtable_rule" # Add the rule to redirect diagnostic traffic to CM-LAN in bridge mode #prod_model=`awk -F'[-=]' '/^VERSION/ {print $2}' /etc/versions` cmdiag_if=`syscfg get cmdiag_ifname` cmdiag_if_mac=`ip link show $cmdiag_if | awk '/link/ {print $2}'` cmdiag_ip="192.168.100.1" wan_if=`syscfg get wan_physical_ifname` wan_if=`syscfg get wan_physical_ifname` #erouter0 subnet_wan=`ip route show | awk '/'$wan_if'/ {print $1}' | tail -1` echo "###############################################" echo "cmdiag_if=$cmdiag_if" echo "cmdiag_ip=$cmdiag_ip" echo "wan_if=$wan_if" echo "subnet_wan=$subnet_wan" echo "###############################################" echo "ip route del $subnet_wan dev $wan_if" ip route del $subnet_wan dev $wan_if echo "ip route add $subnet_wan dev $cmdiag_if" #proto kernel scope link src $cmdiag_ip" ip route add $subnet_wan dev $cmdiag_if #proto kernel scope link src $cmdiag_ip dst_ip="10.0.0.1" # RT-10-580 @ XB3 echo "ip addr add $dst_ip/24 dev $cmdiag_if" ip addr add $dst_ip/24 dev $cmdiag_if echo "ebtables -t nat -A PREROUTING -p ipv4 --ip-dst $dst_ip -j dnat --to-destination $cmdiag_if_mac" ebtables -t nat -A PREROUTING -p ipv4 --ip-dst $dst_ip -j dnat --to-destination $cmdiag_if_mac echo 2 > /proc/sys/net/ipv4/conf/wlan0/arp_announce echo "echo 2 > /proc/sys/net/ipv4/conf/wlan0/arp_announce" } #-------------------------------------------------------------- # del_ebtable_rule # Delete rule in ebtable nat PREROUTING chain #-------------------------------------------------------------- del_ebtable_rule() { prod_model=`awk -F'[-=]' '/^VERSION/ {print $2}' /etc/versions` cmdiag_if=`syscfg get cmdiag_ifname` cmdiag_if_mac=`ip link show $cmdiag_if | awk '/link/ {print $2}'` wan_if=`syscfg get wan_physical_ifname` wan_ip=`sysevent get ipv4_wan_ipaddr` subnet_wan=`ip route show | grep $cmdiag_if | grep -v 192.168.100. | grep -v 10.0.0 | awk '/'$cmdiag_if'/ {print $1}'` ip route del $subnet_wan dev $cmdiag_if ip route add $subnet_wan dev $wan_if proto kernel scope link src $wan_ip dst_ip="10.0.0.1" # RT-10-580 @ XB3 PRD ip addr del $dst_ip/24 dev $cmdiag_if ebtables -t nat -D PREROUTING -p ipv4 --ip-dst $dst_ip -j dnat --to-destination $cmdiag_if_mac #echo 0 > /proc/sys/net/ipv4/conf/wan0/arp_announce echo 0 > /proc/sys/net/ipv4/conf/wlan0/arp_announce echo "echo 0 > /proc/sys/net/ipv4/conf/wlan0/arp_announce" } #-------------------------------------------------------------- # do_start #-------------------------------------------------------------- do_start() { ulog bridge status "stopping firewall" stop_firewall ulog bridge status "firewall status is now `sysevent get firewall-status`" ulog bridge status "reprogramming ethernet switch to remove vlans" #disable_vlan_mode_on_ethernet_switch ulog bridge status "bringing up lan interface in bridge mode" bringup_ethernet_interfaces bringup_wireless_interfaces brctl addbr $SYSCFG_lan_ifname brctl setfd $SYSCFG_lan_ifname 0 #brctl stp $SYSCFG_lan_ifname on brctl stp $SYSCFG_lan_ifname off # enslave interfaces to the bridge enslave_a_interface $SYSCFG_wan_physical_ifname $SYSCFG_lan_ifname for loop in $LAN_IFNAMES do enslave_a_interface $loop $SYSCFG_lan_ifname done # bring up the bridge ip link set $SYSCFG_lan_ifname up ip link set $SYSCFG_lan_ifname allmulticast on ifconfig $SYSCFG_lan_ifname hw ether `get_mac $SYSCFG_wan_physical_ifname` # bridge_mode 1 is dhcp, bridge_mode 2 is static if [ "2" = "$SYSCFG_bridge_mode" ] && [ -n "$SYSCFG_bridge_ipaddr" ] && [ -n "$SYSCFG_bridge_netmask" ] && [ -n "$SYSCFG_bridge_default_gateway" ]; then RESOLV_CONF="/etc/resolv.conf" echo -n > $RESOLV_CONF if [ -n "$SYSCFG_bridge_domain" ] ; then echo "search $SYSCFG_bridge_domain" >> $RESOLV_CONF fi if [ -n "$SYSCFG_bridge_nameserver1" ] && [ "0.0.0.0" != "$SYSCFG_bridge_nameserver1" ] ; then echo "nameserver $SYSCFG_bridge_nameserver1" >> $RESOLV_CONF fi if [ -n "$SYSCFG_bridge_nameserver2" ] && [ "0.0.0.0" != "$SYSCFG_bridge_nameserver2" ] ; then echo "nameserver $SYSCFG_bridge_nameserver2" >> $RESOLV_CONF fi if [ -n "$SYSCFG_bridge_nameserver3" ] && [ "0.0.0.0" != "$SYSCFG_bridge_nameserver3" ] ; then echo "nameserver $SYSCFG_bridge_nameserver3" >> $RESOLV_CONF fi ip -4 addr add $SYSCFG_bridge_ipaddr/$SYSCFG_bridge_netmask broadcast + dev $SYSCFG_lan_ifname ip -4 route add default dev $SYSCFG_lan_ifname via $SYSCFG_bridge_default_gateway # set sysevent tuple showing current state sysevent set bridge_ipv4_ipaddr $SYSCFG_bridge_ipaddr sysevent set bridge_ipv4_subnet $SYSCFG_bridge_netmask sysevent set bridge_default_router $SYSCFG_bridge_default_gateway else udhcpc -S -b -i $SYSCFG_lan_ifname -h $SYSCFG_hostname -p $UDHCPC_PID_FILE --arping -s $UDHCPC_SCRIPT register_dhcp_client_handlers fi # vendor_block_dos_land_attack bringup_wireless_daemons prepare_hostname if [ "1" = "`sysevent get byoi_bridge_mode`" ]; then sysevent set dns-start fi ulog bridge status "lan interface up" } #-------------------------------------------------------------- # do_stop #-------------------------------------------------------------- do_stop() { sysevent set dns-stop unregister_dhcp_client_handlers ip link set $SYSCFG_lan_ifname down ip addr flush dev $SYSCFG_lan_ifname teardown_wireless_interfaces teardown_ethernet_interfaces # remove interfaces from the bridge for loop in $LAN_IFNAMES do ip link set $loop down brctl delif $SYSCFG_lan_ifname $loop done ip link set $SYSCFG_wan_physical_ifname down ip link set $SYSCFG_lan_ifname down brctl delbr $SYSCFG_lan_ifname } do_start_multi() { # TODO: add brport to defaults PRI_L2=`sysevent get primary_lan_l2net` sysevent set multinet-start $PRI_L2 /etc/utopia/service.d/ebtable_rules.sh # set brport enabled # set resync for primary l2net # set firewall restart } do_stop_multi() { # set brport disabled # set resync primary l2net # set firewall restart echo } #-------------------------------------------------------------- # service_init #-------------------------------------------------------------- service_init () { # Get all provisioning data # Figure out the names and addresses of the lan interface # # SYSCFG_lan_ethernet_physical_ifnames is the physical ethernet interfaces that # will be part of the lan # # SYSCFG_lan_wl_physical_ifnames is the names of each wireless interface as known # to the operating system SYSCFG_FAILED='false' FOO=`utctx_cmd get bridge_mode lan_ifname lan_ethernet_physical_ifnames lan_wl_physical_ifnames wan_physical_ifname bridge_ipaddr bridge_netmask bridge_default_gateway bridge_nameserver1 bridge_nameserver2 bridge_nameserver3 bridge_domain hostname` eval $FOO if [ $SYSCFG_FAILED = 'true' ] ; then ulog bridge status "$PID utctx failed to get some configuration data" ulog bridge status "$PID BRIDGE CANNOT BE CONTROLLED" exit fi if [ -z "$SYSCFG_hostname" ] ; then SYSCFG_hostname="Utopia" fi LAN_IFNAMES="$SYSCFG_lan_ethernet_physical_ifnames" # if we are using wireless interfafes then add them if [ "" != "$SYSCFG_lan_wl_physical_ifnames" ] ; then LAN_IFNAMES="$LAN_IFNAMES $SYSCFG_lan_wl_physical_ifnames" fi } #Create a virtual lan0 management interface and connect it to the bride #Also prevent this interface from sending any packets to the DOCSIS bridge virtual_interface() { echo "Inside virtual_interface" CMDIAG_IF=`syscfg get cmdiag_ifname` LAN_IP=`syscfg get lan_ipaddr` LAN_NETMASK=`syscfg get lan_netmask` if [ "$1" = "enable" ] ; then echo "ip link add $CMDIAG_IF type veth peer name l${CMDIAG_IF}" ip link add $CMDIAG_IF type veth peer name l${CMDIAG_IF} echo 1 > /proc/sys/net/ipv6/conf/llan0/disable_ipv6 echo "ifconfig $CMDIAG_IF hw ether `cat /sys/class/net/lan0/address`" ifconfig $CMDIAG_IF hw ether `cat /sys/class/net/${CMDIAG_IF}/address` virtual_interface_ebtables_rules enable echo "ifconfig l${CMDIAG_IF} promisc up" ifconfig l${CMDIAG_IF} promisc up echo "ifconfig $CMDIAG_IF $LAN_IP netmask $LAN_NETMASK up" ifconfig $CMDIAG_IF $LAN_IP netmask $LAN_NETMASK up if [ "$LAN_IP" != "$dst_ip" ]; then ifconfig $CMDIAG_IF $dst_ip netmask $LAN_NETMASK up fi else ifconfig $CMDIAG_IF down ifconfig l${CMDIAG_IF} down ip link del $CMDIAG_IF virtual_interface_ebtables_rules disable fi } virtual_interface_ebtables_rules () { CMDIAG_IF=`syscfg get cmdiag_ifname` CMDIAG_MAC=`cat /sys/class/net/${CMDIAG_IF}/address` EROUTER_MAC=`cat /sys/class/net/erouter0/address` BRIDGE_NAME=`syscfg get lan_ifname` LAN_IP=`syscfg get lan_ipaddr` if [ "$1" = "enable" ] ; then ##Filter table #-------------------------------------------------------------------------------------- #####Forward rules for virtual interface(Dont allow lan0 to send traffic to erouter0) #-------------------------------------------------------------------------------------- ebtables -N BRIDGE_FORWARD_FILTER ebtables -F BRIDGE_FORWARD_FILTER 2> /dev/null ebtables -I FORWARD -j BRIDGE_FORWARD_FILTER echo "ebtables -A BRIDGE_FORWARD_FILTER -s $CMDIAG_MAC -o erouter0 -j DROP" ebtables -A BRIDGE_FORWARD_FILTER -s $CMDIAG_MAC -o erouter0 -j DROP echo "ebtables -A BRIDGE_FORWARD_FILTER -j RETURN" ebtables -A BRIDGE_FORWARD_FILTER -j RETURN ##NAT TABLE #-------------------------------------------------------------------------------------- ####Redirect traffic destined to lan0 IP to lan0 MAC address from brlan0(Prerouting rules) #-------------------------------------------------------------------------------------- ebtables -t nat -N BRIDGE_REDIRECT ebtables -t nat -F BRIDGE_REDIRECT 2> /dev/null ebtables -t nat -I PREROUTING -j BRIDGE_REDIRECT echo "ebtables -t nat -A BRIDGE_REDIRECT --logical-in $BRIDGE_NAME -p ipv4 --ip-dst $LAN_IP -j dnat --to-destination $CMDIAG_MAC" ebtables -t nat -A BRIDGE_REDIRECT --logical-in $BRIDGE_NAME -p ipv4 --ip-dst $LAN_IP -j dnat --to-destination $CMDIAG_MAC #echo "ebtables -t nat -A BRIDGE_REDIRECT --logical-in $BRIDGE_NAME -p ipv4 --ip-dst $LAN_IP # -j forward --forward-dev l$CMDIAG_IF" #ebtables -t nat -A BRIDGE_REDIRECT --logical-in $BRIDGE_NAME -p ipv4 --ip-dst $LAN_IP -j forward --forward-dev l$CMDIAG_IF echo "ebtables -t nat -A BRIDGE_REDIRECT -j RETURN" ebtables -t nat -A BRIDGE_REDIRECT -j RETURN ###BROUTE TABLE #-------------------------------------------------------------------------------------- #DROP target in this BROUTING chain actually broutes the frame(frame has to be routed) #-------------------------------------------------------------------------------------- echo "ebtables -t broute -A BROUTING -i erouter0 -d $EROUTER_MAC -j redirect --redirect-target DROP" ebtables -t broute -A BROUTING -i erouter0 -d $EROUTER_MAC -j redirect --redirect-target DROP else echo "ebtables -D FORWARD -j BRIDGE_FORWARD_FILTER" ebtables -D FORWARD -j BRIDGE_FORWARD_FILTER echo "ebtables -X BRIDGE_FORWARD_FILTER" ebtables -X BRIDGE_FORWARD_FILTER echo "ebtables -t nat -D PREROUTING -j BRIDGE_REDIRECT" ebtables -t nat -D PREROUTING -j BRIDGE_REDIRECT echo "ebtables -t nat -X BRIDGE_REDIRECT" ebtables -t nat -X BRIDGE_REDIRECT fi } add_to_group() { bridge_name=`syscfg get lan_ifname` bridge_dir="/sys/class/net/$bridge_name" lan_ethernet_ifname=`syscfg get lan_ethernet_physical_ifnames` if [ -d "$bridge_dir" ] ;then bridge_status=`cat /sys/class/net/$bridge_name/operstate` if [ "$bridge_status" = "down" ] ; then echo "brctl addbr $bridge_name" brctl addbr $bridge_name ip link set $bridge_name up fi else echo "brctl addbr $bridge_name" brctl addbr $bridge_name ip link set $bridge_name up fi ifconfig $lan_ethernet_ifname up brctl addif $bridge_name $lan_ethernet_ifname cmdiag_if=`syscfg get cmdiag_ifname` wan_if=`syscfg get wan_physical_ifname` echo "brctl addif brlan0 l$cmdiag_if" brctl addif brlan0 l$cmdiag_if echo "brctl addif brlan0 $wan_if" brctl addif brlan0 $wan_if echo "brctl delif $bridge_name wlan0" brctl delif $bridge_name wlan0 } del_from_group() { bridge_name=`syscfg get lan_ifname` brctl addif $bridge_name wlan0 cmdiag_if=`syscfg get cmdiag_ifname` wan_if=`syscfg get wan_physical_ifname` echo "brctl delif brlan0 l$cmdiag_if $wan_if" brctl delif brlan0 l$cmdiag_if $wan_if } filter_local_traffic() { if [ "$1" = "enable" ] ; then echo "ebtables -N BRIDGE_OUTPUT_FILTER" ebtables -N BRIDGE_OUTPUT_FILTER ebtables -F BRIDGE_OUTPUT_FILTER 2> /dev/null ebtables -I OUTPUT -j BRIDGE_OUTPUT_FILTER echo "ebtables -A BRIDGE_OUTPUT_FILTER --logical-out $BRIDGE_NAME -j DROP" ebtables -A BRIDGE_OUTPUT_FILTER --logical-out $BRIDGE_NAME -j DROP echo "ebtables -A BRIDGE_OUTPUT_FILTER -o erouter0 -j DROP" ebtables -A BRIDGE_OUTPUT_FILTER -o erouter0 -j DROP #Return from filter chain echo "ebtables -A BRIDGE_OUTPUT_FILTER -j RETURN" ebtables -A BRIDGE_OUTPUT_FILTER -j RETURN else ebtables -D OUTPUT -j BRIDGE_OUTPUT_FILTER ebtables -X BRIDGE_OUTPUT_FILTER fi } routing_rules(){ CMDIAG_IF=`syscfg get cmdiag_ifname` LAN_IP=`syscfg get lan_ipaddr` if [ "$1" = "enable" ] ; then #Send responses from $BRIDGE_NAME IP to a separate bridge mode route table echo "ip rule add from $LAN_IP lookup $BRIDGE_MODE_TABLE" ip rule add from $LAN_IP lookup $BRIDGE_MODE_TABLE #if [ "$LAN_IP" != "$dst_ip" ]; then # echo "ip rule add from $dst_ip lookup $BRIDGE_MODE_TABLE" # ip rule add from $dst_ip lookup $BRIDGE_MODE_TABLE #fi echo "ip route add table $BRIDGE_MODE_TABLE default dev $CMDIAG_IF" ip route add table $BRIDGE_MODE_TABLE default dev $CMDIAG_IF else echo "ip rule del from $LAN_IP lookup $BRIDGE_MODE_TABLE" ip rule del from $LAN_IP lookup $BRIDGE_MODE_TABLE #if [ $LAN_IP != $dst_ip ]; then # ip rule del from $dst_ip lookup $BRIDGE_MODE_TABLE #fi echo "ip route flush table $BRIDGE_MODE_TABLE" ip route flush table $BRIDGE_MODE_TABLE fi } block_bridge(){ ebtables -A FORWARD -i erouter0 -j DROP } #Unblock bridged traffic through erouter0 unblock_bridge(){ ebtables -D FORWARD -i erouter0 -j DROP } #-------------------------------------------------------------- # service_start #-------------------------------------------------------------- service_start () { wait_till_end_state ${SERVICE_NAME} STATUS=`sysevent get ${SERVICE_NAME}-status` echo "sysevent get ${SERVICE_NAME}-status $STATUS" if [ "started" != "$STATUS" ] ; then sysevent set ${SERVICE_NAME}-errinfo sysevent set ${SERVICE_NAME}-status starting block_bridge virtual_interface enable #create lan0 interface and write ebtable rules routing_rules enable add_to_group filter_local_traffic enable unblock_bridge # Force a DHCP renew by issuing a physical link down/up, when WAN port mode switches between bridging and routing PSM_MODE=`sysevent get system_psm_mode` #if [ "$PSM_MODE" != "1" ]; then # It is not a good practice to force all physical links to refresh -- should have used arguments to specify which ports/links #gw_lan_refresh #fi prepare_hostname if [ -f /tmp/wifi_initialized ];then sysevent set ${SERVICE_NAME}-errinfo sysevent set ${SERVICE_NAME}-status started else sleep 60 sysevent set ${SERVICE_NAME}-errinfo sysevent set ${SERVICE_NAME}-status started fi fi } #-------------------------------------------------------------- # service_stop #-------------------------------------------------------------- service_stop () { wait_till_end_state ${SERVICE_NAME} #STATUS=`sysevent get ${SERVICE_NAME}-status` #if [ "stopped" != "$STATUS" ] ; then sysevent set ${SERVICE_NAME}-errinfo sysevent set ${SERVICE_NAME}-status stopping block_bridge del_from_group #Disconnect management interface virtual_interface disable filter_local_traffic disable routing_rules disable unblock_bridge #Flush connection tracking and packet processor sessions to avoid stale information flush_connection_info sysevent set ${SERVICE_NAME}-errinfo sysevent set ${SERVICE_NAME}-status stopped # fi } #------------------------------------------------------------------ # ENTRY #------------------------------------------------------------------ BRIDGE_NAME="$SYSCFG_lan_ifname" CMDIAG_IF=`syscfg get cmdiag_ifname` INSTANCE=`sysevent get primary_lan_l2net` LAN_NETMASK=`syscfg get lan_netmask` service_init echo "service_bridge.sh called with $1 $2" > /dev/console case "$1" in ${SERVICE_NAME}-start) firewall firewall-stop service_start if [ ! -f "$POSTD_START_FILE" ]; then touch $POSTD_START_FILE execute_dir /etc/utopia/post.d/ fi #gw_lan_refresh sysevent set firewall-restart ;; ${SERVICE_NAME}-stop) service_stop if [ ! -f "$POSTD_START_FILE" ]; then touch $POSTD_START_FILE execute_dir /etc/utopia/post.d/ fi #gw_lan_refresh sysevent set firewall-restart ;; ${SERVICE_NAME}-restart) sysevent set lan-restarting 1 service_stop service_start sysevent set lan-restarting 0 ;; *) echo "Usage: service-${SERVICE_NAME} [ ${SERVICE_NAME}-start | ${SERVICE_NAME}-stop | ${SERVICE_NAME}-restart]" > /dev/console exit 3 ;; esac
import { spawn } from 'child_process'; import { Injectable } from '@nestjs/common'; import { SimpleCommandExecutorComponentInterface } from '../../../executor/simple-command-executor-component.interface'; import { EnvVariablesSet } from '../../../sets/env-variables-set'; import { SimpleCommand } from '../../../executor/simple-command'; import { ExecuteServiceCmdCommand } from './command'; import { SpawnHelper } from '../../../helper/spawn-helper.component'; @Injectable() export class ExecuteServiceCmdCommandExecutorComponent implements SimpleCommandExecutorComponentInterface { constructor(private readonly spawnHelper: SpawnHelper) {} supports(command: SimpleCommand): boolean { return command instanceof ExecuteServiceCmdCommand; } async execute(command: SimpleCommand): Promise<any> { const { collectedEnvVariables, customEnvVariables, inheritedEnvVariables, containerId, executable, absoluteGuestInstancePath, commandLogger, } = command as ExecuteServiceCmdCommand; commandLogger.info(`Collecting environmental variables.`); const envVariables = new EnvVariablesSet(); for (const { name, value } of customEnvVariables.toList()) { envVariables.add(name, value); } commandLogger.info(`Custom environmental variables collected.`); const collectedEnvVariablesMap = collectedEnvVariables.toMap(); for (const { name, alias } of inheritedEnvVariables) { envVariables.add(alias || name, collectedEnvVariablesMap[name]); } commandLogger.info(`Inherited environmental variables collected.`); commandLogger.info(`Executing service command.`); commandLogger.info(`Container ID: ${containerId}`); commandLogger.info(`Command: ${executable[0]}`); commandLogger.info(`Arguments: ${JSON.stringify(executable.slice(1))}`); commandLogger.info( `Guest working directory: ${absoluteGuestInstancePath}`, ); commandLogger.infoWithEnvVariables( envVariables, 'Environmental variables', ); let cmd = ['docker', 'exec']; for (const { name, value } of envVariables.toList()) { cmd = cmd.concat(['-e', `${name}=${value}`]); } cmd.push(containerId); cmd = cmd.concat(executable); await this.spawnHelper.promisifySpawnedWithHeader( spawn(cmd[0], cmd.slice(1), { cwd: absoluteGuestInstancePath, }), commandLogger, 'execute service command', ); return {}; } }
<filename>src/main/java/com/github/thomasj/springcache/ext/memcached/MemcachedCache.java package com.github.thomasj.springcache.ext.memcached; import java.util.Date; import java.util.concurrent.*; import com.github.thomasj.springcache.ext.key.ExpiryKey; import com.github.thomasj.springcache.ext.util.NoSqlUtil; import org.springframework.cache.support.AbstractValueAdaptingCache; import org.springframework.cache.support.SimpleValueWrapper; import org.springframework.lang.Nullable; import com.danga.MemCached.MemCachedClient; import lombok.extern.slf4j.Slf4j; /** * @author <EMAIL> */ @Slf4j public class MemcachedCache extends AbstractValueAdaptingCache { private final static int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); private ThreadPoolExecutor pool = new ThreadPoolExecutor(AVAILABLE_PROCESSORS / 2, AVAILABLE_PROCESSORS, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10000), new ThreadPoolExecutor.AbortPolicy()); private ConcurrentHashMap<Object, FutureTask> readVisibility = new ConcurrentHashMap<>(); private String name; private MemCachedClient nativeCache; private Long expiryMills; public MemcachedCache(MemCachedClient nativeCache){ this("default", nativeCache, Long.MAX_VALUE, true); } public MemcachedCache(MemCachedClient nativeCache, Long expiryMills){ this("default", nativeCache, expiryMills, true); } public MemcachedCache(MemCachedClient nativeCache, Long expiryMills, boolean allowNullValues){ this("default", nativeCache, expiryMills, allowNullValues); } public MemcachedCache(String name, MemCachedClient nativeCache, Long expiryMills, boolean allowNullValues){ super(allowNullValues); this.name = name; this.nativeCache = nativeCache; this.expiryMills = expiryMills; } @Nullable @Override protected Object lookup (Object key) { if (log.isDebugEnabled()) { log.debug("lookup, 键: {}", key); } if (NoSqlUtil.objEmpty(key)) { return null; } if (key instanceof ExpiryKey) { ExpiryKey eKey = (ExpiryKey) key; if (NoSqlUtil.objEmpty(eKey.getKey())) { return null; } return this.nativeCache.get(eKey.getKey().toString()); } else { return this.nativeCache.get(key.toString()); } } @Override public String getName () { return this.name; } @Override public Object getNativeCache () { return this.nativeCache; } @Nullable @Override public <T>T get (Object key, Callable<T> valueLoader) { if (log.isDebugEnabled()) { log.debug("查询, 键: {}", key); } if (NoSqlUtil.objEmpty(key)) { return null; } if (key instanceof ExpiryKey) { ExpiryKey eKey = (ExpiryKey) key; if (NoSqlUtil.objEmpty(eKey.getKey())) { return null; } String k = eKey.getKey().toString(); T v = (T) this.nativeCache.get(k); if (v != null) { return v; } FutureTask future = new FutureTask( () -> { Object obj = valueLoader.call(); Date expiryDate = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(eKey.getExpiry(), eKey.getUnit())); nativeCache.set(k, obj, expiryDate); return obj; }); FutureTask readFuture = readVisibility.putIfAbsent(k, future); // first if (readFuture == null) { pool.submit(future); readFuture = future; } else { readFuture = readVisibility.get(k); } try { return (T) readFuture.get(); } catch (Exception e) { throw new ValueRetrievalException(eKey.getKey(), valueLoader, e.getCause()); } finally { readVisibility.remove(k); } } else { String k = key.toString(); T v = (T) this.nativeCache.get(k); if (v != null) { return v; } FutureTask future = new FutureTask( () -> { Object obj = valueLoader.call(); nativeCache.set(k, obj, new Date(System.currentTimeMillis() + expiryMills)); return obj; }); FutureTask readFuture = readVisibility.putIfAbsent(k, future); if (readFuture == null) { pool.submit(future); readFuture = future; } else { readFuture = readVisibility.get(k); } try { return (T) readFuture.get(); } catch (Exception e) { throw new ValueRetrievalException(key, valueLoader, e.getCause()); } finally { readVisibility.remove(k); } } } @Override public void put (Object key, @Nullable Object value) { if (log.isDebugEnabled()) { log.debug("添加缓存, 键: {}, 值: {}", key, value); } if (NoSqlUtil.objEmpty(key)) { return; } if (!this.isAllowNullValues() && value == null) { throw new NullPointerException(String.format("LRUKey: [%s], Value is null, isAllowNullValues [no]", key)); } if (key instanceof ExpiryKey) { ExpiryKey eKey = (ExpiryKey) key; if (NoSqlUtil.objEmpty(eKey.getKey())) { return; } this.nativeCache.set(eKey.getKey().toString(), value, new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(eKey.getExpiry(), eKey.getUnit()))); } else { if (expiryMills == Long.MAX_VALUE) { this.nativeCache.set(key.toString(), value); } else { this.nativeCache.set(key.toString(), value, new Date(System.currentTimeMillis() + expiryMills)); } } } @Nullable @Override public ValueWrapper putIfAbsent (Object key, @Nullable Object value) { if (log.isDebugEnabled()) { log.debug("添加缓存(不存在添加), 键: {}, 值: {}", key, value); } if (NoSqlUtil.objEmpty(key)) { return null; } if (!this.isAllowNullValues() && value == null) { throw new NullPointerException(String.format("LRUKey: [%s], Value is null, isAllowNullValues [no]", key)); } if (key instanceof ExpiryKey) { ExpiryKey eKey = (ExpiryKey) key; if (NoSqlUtil.objEmpty(eKey.getKey())) { return null; } String k = eKey.getKey().toString(); Object v = this.nativeCache.get(k); if (v == null) { this.nativeCache.set(k, value, new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(eKey.getExpiry(), eKey.getUnit()))); return null; } else { return new SimpleValueWrapper(v); } } else { String k = key.toString(); Object v = this.nativeCache.get(k); if (v == null) { if (expiryMills == Long.MAX_VALUE) { this.nativeCache.set(k, value); } else { this.nativeCache.set(k, value, new Date(System.currentTimeMillis() + expiryMills)); } return null; } else { return new SimpleValueWrapper(v); } } } @Override public void evict (Object key) { if (log.isDebugEnabled()) { log.debug("删除, 键: {}", key); } if (NoSqlUtil.objEmpty(key)) { return; } if (key instanceof ExpiryKey) { ExpiryKey eKey = (ExpiryKey) key; if (NoSqlUtil.objEmpty(eKey.getKey())) { return; } this.nativeCache.delete(eKey.getKey().toString()); } else { this.nativeCache.delete(key.toString()); } } @Override public void clear () { log.warn("清空缓存"); this.nativeCache.flushAll(); } }
/* eslint-disable-next-line no-var, no-use-before-define */ var SharkGame = SharkGame || {}; // CORE VARIABLES AND HELPER FUNCTIONS $.extend(SharkGame, { GAME_NAMES: [ "Five Seconds A Shark", "Next Shark Game", "Next Shark Game: Barkfest", "Sharky Clicker", "Weird Oceans", "You Have To Name The Shark Game", "Shark A Lark", "Bark Shark", "Fin Idle", "Ray of Dreams", "Shark Saver", "Shoal Sharker", "Shark Souls", "Saucy Sharks", "Sharkfall", "Heart of Sharkness", "Sharks and Recreation", "Alone in the Shark", "Sharkpocalypse", "Shark of Darkness", "Strange Oceans", "A New Frontier", "Lobster's Paradise", "Revenge of the Crabs", "Shark Box", "Dolphin Heroes", "Maws", "Sharky's Awkward Escapade: Part 6" ], GAME_NAME: null, ACTUAL_GAME_NAME: "Shark Game", VERSION: 0.1, ORIGINAL_VERSION: 0.71, VERSION_NAME: "New is Old", EPSILON: 1e-6, // floating point comparison is a joy // agreed, already had to deal with it on recycler revisions // did you know that reducing a float like 1.2512351261 to 1.25 by literally removing the decimal and multiplying by 100 gives you something like 125.0000001? INTERVAL: 1000 / 10, // 20 FPS // I'm pretty sure 1000 / 10 comes out to 10 FPS dt: 1 / 10, before: new Date(), timestampLastSave: false, timestampGameStart: false, timestampRunStart: false, timestampRunEnd: false, sidebarHidden: true, paneGenerated: false, gameOver: false, wonGame: false, credits: "<p>This game was originally created in 3 days for Seamergency 2014.<br/>" + "<span class='smallDesc'>(Technically it was 4 days, but sometimes plans go awry.)</span></p>" + "<p>It was made by <a href='http://cirri.al'>Cirr</a> who needs to update his website.<br/>" + "He has a rarely updated <a href='https://twitter.com/Cirrial'>Twitter</a> though.</p>" + "<p>Additional code and credit help provided by Dylan and <NAME>.<br/>" + "<span class='smallDesc'>Dylan is also graciously hosting the original game.</span></p>" + "<p><a href='https://github.com/spencers145/SharkGame'>Mod</a> created by base4/spencers145,<br/>" + "with sprite help from <a href='https://twitter.com/vhs_static'>@vhs_static</a> and friends." + '<br/><span style="color: rgba(0,0,0,0);">With some help by <a href="https://github.com/Toby222" style="color: rgba(0,0,0,0);">Toby</a></span>', ending: "<p>Congratulations! You did it.<br/>You saved the sharks!</p>" + "<p>The gate leads away from this strange ocean...</p>" + "<p>Back home to the oceans you came from!</p>" + "<h3>Or are they?</h3>", help: "<p>This game is a game about discovery, resources, and does not demand your full attention. " + "You are free to pay as much attention to the game as you want. " + "It will happily run in the background, and works even while closed.</p>" + "<p>To begin, you should catch fish. Once you have some fish, more actions will become available. " + 'If you have no idea what these actions do, click the "Toggle descriptions" button for more information.</p>' + "<p>If you are ever stuck, try actions you haven't yet tried. " + "Remember, though, that sometimes patience is the only way forward. Patience and ever escalating numbers.</p>" + "<p>If you are here because you think you have encountered a bug of some kind, report it on the <a href='https://discord.gg/nN7BQDJR2G' target='blank_'>discord</a>.</p>", donate: "<p>You can <a href='http://www.sharktrust.org/en/donate' target='_blank'>donate to help save sharks and mantas</a>!</p>" + "<p>Seems only fitting, given this game was made for a charity stream!</p>" + "<p><span class='smallDescAllowClicks'>(But if you'd rather, you can also " + "<a href='https://www.paypal.com/cgi-bin/" + "webscr?cmd=_donations&business=G3WPPAYAWTJCJ&lc=GB&" + "item_name=Shark%20Game%20Developer%20Support&" + "item_number=Shark%20Game%20Support&no_note=1&" + "no_shipping=1&currency_code=USD&" + "bn=PP%2dDonationsBF%3adonate%2epng%3aNonHosted' " + "target='_blank'>support the original developer</a>" + " if you'd like.)</span></p>", spriteIconPath: "img/sharksprites.png", spriteHomeEventPath: "img/sharkeventsprites.png", choose(choices) { return choices[Math.floor(Math.random() * choices.length)]; }, log10(val) { return Math.log(val) / Math.LN10; }, plural(number) { return number === 1 ? "" : "s"; }, colorLum(hex, lum) { // validate hex string hex = String(hex).replace(/[^0-9a-f]/gi, ""); if (hex.length < 6) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } lum = lum || 0; // convert to decimal and change luminosity let rgb = "#"; for (let i = 0; i < 3; i++) { let c = parseInt(hex.substr(i * 2, 2), 16); c = Math.round(Math.min(Math.max(0, c + c * lum), 255)).toString(16); rgb += ("00" + c).substr(c.length); } return rgb; }, getImageIconHTML(imagePath, width, height) { if (!imagePath) { imagePath = "http://placekitten.com/g/" + Math.floor(width) + "/" + Math.floor(height); } let imageHtml = ""; if (SharkGame.Settings.current.iconPositions !== "off") { imageHtml += "<img width=" + width + " height=" + height + " src='" + imagePath + "' class='button-icon-" + SharkGame.Settings.current.iconPositions + "'>"; } return imageHtml; }, changeSprite(spritePath, imageName, imageDiv, backupImageName) { let spriteData = SharkGame.Sprites[imageName]; if (!imageDiv) { imageDiv = $("<div>"); } // if the original sprite data is undefined, try loading the backup if (!spriteData) { spriteData = SharkGame.Sprites[backupImageName]; } if (spriteData) { imageDiv.css("background-image", "url(" + spritePath + ")"); imageDiv.css("background-position", "-" + spriteData.frame.x + "px -" + spriteData.frame.y + "px"); imageDiv.width(spriteData.frame.w); imageDiv.height(spriteData.frame.h); } else { imageDiv.css("background-image", 'url("//placehold.it/50x50")'); imageDiv.width(50); imageDiv.height(50); } return imageDiv; }, }); SharkGame.TitleBar = { saveLink: { name: "save", main: true, onClick() { try { try { SharkGame.Save.saveGame(); } catch (err) { SharkGame.Log.addError(err); console.log(err); } SharkGame.Log.addMessage("Saved game."); } catch (err) { SharkGame.Log.addError(err.message); } }, }, optionsLink: { name: "options", main: true, onClick() { SharkGame.Main.showOptions(); }, }, changelogLink: { name: "changelog", main: false, onClick() { SharkGame.Main.showChangelog(); }, }, helpLink: { name: "help", main: true, onClick() { SharkGame.Main.showHelp(); }, }, skipLink: { name: "skip", main: true, onClick() { if (SharkGame.Main.isFirstTime()) { // save people stranded on home world if (confirm("Do you want to reset your game?")) { // just reset SharkGame.Main.init(); } } else { if (confirm("Is this world causing you too much trouble? Want to go back to the gateway?")) { SharkGame.wonGame = false; SharkGame.Main.endGame(); } } }, }, creditsLink: { name: "credits", main: false, onClick() { SharkGame.Main.showPane("Credits", SharkGame.credits); }, }, donateLink: { name: "donate", main: false, onClick() { SharkGame.Main.showPane("Donate", SharkGame.donate); }, }, discordLink: { name: "discord", main: false, link: "https://discord.gg/nN7BQDJR2G", }, }; SharkGame.Tabs = { current: "home", }; SharkGame.Main = { tickHandler: -1, autosaveHandler: -1, beautify(number, suppressDecimals, toPlaces) { let formatted; let negative = false; if (number < 0) { negative = true; number *= -1; } if (number === Number.POSITIVE_INFINITY) { formatted = "infinite"; } else if (number < 1 && number >= 0) { if (suppressDecimals) { formatted = "0"; } else if (number >= 0.01) { formatted = number.toFixed(2) + ""; } else if (number >= 0.001) { formatted = number.toFixed(3) + ""; } else if (number >= 0.0001) { formatted = number.toFixed(4) + ""; } else if (number >= 0.00001) { // number > 0.00001 && negative -> number > 0.00001 && number < 0 -> false formatted = number.toFixed(5) + ""; } else { formatted = "0"; } if (negative) { formatted = "-" + formatted; } } else { const suffixes = ["", "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc"]; const digits = Math.floor(SharkGame.log10(number)); let precision = 2 - (digits % 3); // in case the highest supported suffix is not specified precision = Math.max(0, precision); const suffixIndex = Math.floor(digits / 3); let suffix; if (suffixIndex >= suffixes.length) { formatted = "lots"; } else { suffix = suffixes[suffixIndex]; // fix number to be compliant with suffix if (suffixIndex > 0) { number /= Math.pow(1000, suffixIndex); } let formattedNumber; if (suffixIndex === 0) { if (toPlaces && toPlaces - digits > 0 && number !== Math.floor(number)) { formattedNumber = number.toFixed(toPlaces - digits); } else { formattedNumber = Math.floor(number); } } else if (suffixIndex > 0) { formattedNumber = number.toFixed(precision) + suffix; } else { formattedNumber = number.toFixed(precision); } formatted = (negative ? "-" : "") + formattedNumber; } } return formatted; }, formatTime(milliseconds) { const numSeconds = Math.floor(milliseconds / 1000); const numMinutes = Math.floor(numSeconds / 60); const numHours = Math.floor(numMinutes / 60); const numDays = Math.floor(numHours / 24); const numWeeks = Math.floor(numDays / 7); const numMonths = Math.floor(numWeeks / 4); const numYears = Math.floor(numMonths / 12); const formatSeconds = (numSeconds % 60).toString(10).padStart(2, "0"); const formatMinutes = numMinutes > 0 ? (numMinutes % 60).toString(10).padStart(2, "0") + ":" : ""; const formatHours = numHours > 0 ? (numHours % 24).toString() + ":" : ""; const formatDays = numDays > 0 ? (numDays % 7).toString() + "D, " : ""; const formatWeeks = numWeeks > 0 ? (numWeeks % 4).toString() + "W, " : ""; const formatMonths = numMonths > 0 ? (numMonths % 12).toString() + "M, " : ""; const formatYears = numYears > 0 ? numYears.toString() + "Y, " : ""; return formatYears + formatMonths + formatWeeks + formatDays + formatHours + formatMinutes + formatSeconds; }, // credit where it's due, i didn't write this (regexes fill me with fear), pulled from // http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript/196991#196991 toTitleCase(str) { return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); }, // also functions as a reset init() { const now = _.now(); SharkGame.before = now; if (SharkGame.GAME_NAME === null) { SharkGame.GAME_NAME = SharkGame.choose(SharkGame.GAME_NAMES); document.title = SharkGame.ACTUAL_GAME_NAME + ": " + SharkGame.GAME_NAME; } $("#sidebar").hide(); const overlay = $("#overlay"); overlay.hide(); $("#gameName").html("- " + SharkGame.GAME_NAME + " -"); $("#versionNumber").html("New Frontiers v " + SharkGame.VERSION + " - " + SharkGame.VERSION_NAME + "<br/> " + "Mod of v " + SharkGame.ORIGINAL_VERSION); SharkGame.sidebarHidden = true; SharkGame.gameOver = false; // remove any errant classes $("#pane").removeClass("gateway"); overlay.removeClass("gateway"); // initialise timestamps to something sensible SharkGame.timestampLastSave = SharkGame.timestampLastSave || now; SharkGame.timestampGameStart = SharkGame.timestampGameStart || now; SharkGame.timestampRunStart = SharkGame.timestampRunStart || now; // preserve settings or set defaults $.each(SharkGame.Settings, (k, v) => { if (k === "current") { return; } const currentSetting = SharkGame.Settings.current[k]; if (typeof currentSetting === "undefined") { SharkGame.Settings.current[k] = v.defaultSetting; } }); // initialise and reset resources SharkGame.Resources.init(); // initialise world // MAKE SURE GATE IS INITIALISED AFTER WORLD!! SharkGame.World.init(); SharkGame.World.apply(); SharkGame.Gateway.init(); SharkGame.Gateway.applyArtifacts(); // if there's any effects to carry over from a previous run // reset log SharkGame.Log.clearMessages(); // initialise tabs SharkGame.Home.init(); SharkGame.Lab.init(); SharkGame.Stats.init(); SharkGame.Recycler.init(); SharkGame.Gate.init(); SharkGame.Reflection.init(); SharkGame.Main.setUpTitleBar(); SharkGame.Tabs.current = "home"; // load save game data if present if (SharkGame.Save.savedGameExists()) { try { SharkGame.Save.loadGame(); SharkGame.Log.addMessage("Loaded game."); } catch (err) { SharkGame.Log.addError(err.message); } } // rename a game option if this is a first time run if (SharkGame.Main.isFirstTime()) { SharkGame.TitleBar.skipLink.name = "reset"; SharkGame.Main.setUpTitleBar(); } // discover actions that were present in last save SharkGame.Home.discoverActions(); // set up tab after load SharkGame.Main.setUpTab(); if (SharkGame.Main.tickHandler === -1) { SharkGame.Main.tickHandler = setInterval(SharkGame.Main.tick, SharkGame.INTERVAL); } if (SharkGame.Main.autosaveHandler === -1) { SharkGame.Main.autosaveHandler = setInterval( SharkGame.Main.autosave, SharkGame.Settings.current.autosaveFrequency * 60000 ); } }, tick() { if (SharkGame.gameOver) { // tick gateway stuff SharkGame.Gateway.update(); } else { // tick main game stuff const now = _.now(); const elapsedTime = now - SharkGame.before; const r = SharkGame.Resources; const m = SharkGame.Main; // check if the sidebar needs to come back if (SharkGame.sidebarHidden) { m.showSidebarIfNeeded(); } if (elapsedTime > SharkGame.INTERVAL) { // Compensate for lost time. m.processSimTime(SharkGame.dt * (elapsedTime / SharkGame.INTERVAL)); } else { m.processSimTime(SharkGame.dt); } r.updateResourcesTable(); const tabCode = SharkGame.Tabs[SharkGame.Tabs.current].code; tabCode.update(); m.checkTabUnlocks(); SharkGame.before = now; } }, checkTabUnlocks() { $.each(SharkGame.Tabs, (k, v) => { if (k === "current" || v.discovered) { return; } let reqsMet = true; // check resources if (v.discoverReq.resource) { reqsMet = reqsMet && SharkGame.Resources.checkResources(v.discoverReq.resource, true); } // discover which upgrade table is in use const ups = SharkGame.Upgrades.getUpgradeTable(); // check upgrades if (v.discoverReq.upgrade) { $.each(v.discoverReq.upgrade, (_, value) => { if (ups[value]) { reqsMet = reqsMet && ups[value].purchased; } else { reqsMet = false; // can't have a nonexistent upgrade } }); } if (reqsMet) { // unlock tab! SharkGame.Main.discoverTab(k); SharkGame.Log.addDiscovery("Discovered " + v.name + "!"); } }); }, processSimTime(numberOfSeconds) { const r = SharkGame.Resources; // income calculation r.processIncomes(numberOfSeconds); }, autosave() { try { SharkGame.Save.saveGame(); SharkGame.Log.addMessage("Autosaved."); } catch (err) { SharkGame.Log.addError(err.message); console.log(err.trace); } }, setUpTitleBar() { const titleMenu = $("#titlemenu"); const subTitleMenu = $("#subtitlemenu"); titleMenu.empty(); subTitleMenu.empty(); $.each(SharkGame.TitleBar, (k, v) => { let option; if (v.link) { option = "<li><a id='" + k + "' href='" + v.link + "' target='_blank'>" + v.name + "</a></li>"; } else { option = "<li><a id='" + k + "' href='javascript:;'>" + v.name + "</a></li>"; } if (v.main) { titleMenu.append(option); } else { subTitleMenu.append(option); } $("#" + k).on("click", v.onClick); }); }, setUpTab() { const tabs = SharkGame.Tabs; // empty out content div const content = $("#content"); content.empty(); content.append( '<div id="contentMenu"><ul id="tabList"></ul><ul id="tabButtons"></ul></div><div id="tabBorder" class="clear-fix"></div>' ); SharkGame.Main.createTabNavigation(); SharkGame.Main.createBuyButtons(); // set up tab specific stuff const tab = tabs[tabs.current]; const tabCode = tab.code; tabCode.switchTo(); }, createTabMenu() { SharkGame.Main.createTabNavigation(); SharkGame.Main.createBuyButtons(); }, createTabNavigation() { const tabs = SharkGame.Tabs; const tabList = $("#tabList"); tabList.empty(); // add navigation // check if we have more than one discovered tab, else bypass this let numTabsDiscovered = 0; $.each(tabs, (k, v) => { if (v.discovered) { numTabsDiscovered++; } }); if (numTabsDiscovered > 1) { // add a header for each discovered tab // make it a link if it's not the current tab $.each(tabs, (k, v) => { const onThisTab = SharkGame.Tabs.current === k; if (v.discovered) { const tabListItem = $("<li>"); if (onThisTab) { tabListItem.html(v.name); } else { tabListItem.append( $("<a>") .attr("id", "tab-" + k) .attr("href", "javascript:;") .html(v.name) .on("click", function callback() { const tab = $(this).attr("id").split("-")[1]; SharkGame.Main.changeTab(tab); }) ); } tabList.append(tabListItem); } }); } }, createBuyButtons(customLabel) { // add buy buttons const buttonList = $("#tabButtons"); buttonList.empty(); $.each(SharkGame.Settings.buyAmount.options, (_, v) => { const amount = v; const disableButton = v === SharkGame.Settings.current.buyAmount; buttonList.prepend( $("<li>").append( $("<button>") .addClass("min") .attr("id", "buy-" + v) .prop("disabled", disableButton) ) ); let label = customLabel ? customLabel + " " : "buy "; if (amount < 0) { if (amount < -2) { label += "1/3 max"; } else if (amount < -1) { label += "1/2 max"; } else if (amount < 0) { label += "max"; } } else { label += SharkGame.Main.beautify(amount); } $("#buy-" + v) .html(label) .on("click", function callback() { const thisButton = $(this); SharkGame.Settings.current.buyAmount = parseInt(thisButton.attr("id").slice(4)); $("button[id^='buy-']").prop("disabled", false); thisButton.prop("disabled", true); }); }); }, changeTab(tab) { SharkGame.Tabs.current = tab; SharkGame.Main.setUpTab(); }, discoverTab(tab) { SharkGame.Tabs[tab].discovered = true; // force a total redraw of the navigation SharkGame.Main.createTabMenu(); }, showSidebarIfNeeded() { // if we have any non-zero resources, show sidebar // if we have any log entries, show sidebar if (SharkGame.Resources.haveAnyResources() || SharkGame.Log.haveAnyMessages()) { // show sidebar if (SharkGame.Settings.current.showAnimations) { $("#sidebar").show("500"); } else { $("#sidebar").show(); } // flag sidebar as shown SharkGame.sidebarHidden = false; SharkGame.Log.adjustLogMaxHeight(); } }, showOptions() { const optionsContent = SharkGame.Main.setUpOptions(); SharkGame.Main.showPane("Options", optionsContent); }, setUpOptions() { const optionsTable = $("<table>").attr("id", "optionTable"); // add settings specified in settings.js $.each(SharkGame.Settings, (key, value) => { if (key === "current" || !value.show) { return; } const row = $("<tr>"); // show setting name row.append( $("<td>") .addClass("optionLabel") .html(value.name + ":" + "<br/><span class='smallDesc'>(" + value.desc + ")</span>") ); const currentSetting = SharkGame.Settings.current[key]; // show setting adjustment buttons $.each(value.options, (k, v) => { const isCurrentSetting = k === value.options.indexOf(currentSetting); row.append( $("<td>").append( $("<button>") .attr("id", "optionButton-" + key + "-" + k) .addClass("option-button") .prop("disabled", isCurrentSetting) .html(typeof v === "boolean" ? (v ? "on" : "off") : v) .on("click", SharkGame.Main.onOptionClick) ) ); }); optionsTable.append(row); }); // SAVE IMPORT/EXPORT // add save import/export let row = $("<tr>"); row.append( $("<td>").html( "Import/Export Save:<br/><span class='smallDesc'>(You should probably save first!) Import or export save as text. Keep it safe!</span>" ) ); row.append( $("<td>").append( $("<button>") .html("import") .addClass("option-button") .on("click", function callback() { const importText = $("#importExportField").val(); if (importText === "") { SharkGame.hidePane(); SharkGame.Log.addError("You need to paste something in first!"); } else if (confirm("Are you absolutely sure? This will override your current save.")) { SharkGame.Save.importData(importText); } }) ) ); row.append( $("<td>").append( $("<button>") .html("export") .addClass("option-button") .on("click", function callback() { $("#importExportField").val(SharkGame.Save.exportData()); }) ) ); // add the actual text box row.append( $("<td>").attr("colSpan", 4).append($("<input>").attr("type", "text").attr("id", "importExportField")) ); optionsTable.append(row); // SAVE WIPE // add save wipe row = $("<tr>"); row.append( $("<td>").html( "Wipe Save<br/><span class='smallDesc'>(Completely wipe your save and reset the game. COMPLETELY. FOREVER.)</span>" ) ); row.append( $("<td>").append( $("<button>") .html("wipe") .addClass("option-button") .on("click", () => { if (confirm("Are you absolutely sure you want to wipe your save?\nIt'll be gone forever!")) { SharkGame.Save.deleteSave(); SharkGame.Gateway.deleteArtifacts(); // they're out of the save data, but not the working game memory! SharkGame.Resources.reconstructResourcesTable(); SharkGame.World.worldType = "start"; // nothing else will reset this SharkGame.World.planetLevel = 1; SharkGame.Main.init(); // reset } }) ) ); optionsTable.append(row); return optionsTable; }, onOptionClick() { const buttonLabel = $(this).attr("id"); const settingInfo = buttonLabel.split("-"); const settingName = settingInfo[1]; const optionIndex = parseInt(settingInfo[2]); // change setting to specified setting! SharkGame.Settings.current[settingName] = SharkGame.Settings[settingName].options[optionIndex]; // update relevant table cell! // $('#option-' + settingName) // .html("(" + ((typeof newSetting === "boolean") ? (newSetting ? "on" : "off") : newSetting) + ")"); // enable all buttons $('button[id^="optionButton-' + settingName + '"]').prop("disabled", false); // disable this button $(this).attr("disabled", "true"); // if there is a callback, call it, else call the no op (SharkGame.Settings[settingName].onChange || $.noop)(); }, showChangelog() { const changelogContent = $("<div>").attr("id", "changelogDiv"); $.each(SharkGame.Changelog, (version, changes) => { const segment = $("<div>").addClass("paneContentDiv"); segment.append($("<h3>").html(version + ": ")); const changeList = $("<ul>"); $.each(changes, (_, v) => { changeList.append($("<li>").html(v)); }); segment.append(changeList); changelogContent.append(segment); }); SharkGame.Main.showPane("Changelog", changelogContent); }, showHelp() { const helpDiv = $("<div>"); helpDiv.append($("<div>").append(SharkGame.help).addClass("paneContentDiv")); SharkGame.Main.showPane("Help", helpDiv); }, endGame(loadingFromSave) { // stop autosaving clearInterval(SharkGame.Main.autosaveHandler); SharkGame.Main.autosaveHandler = -1; // flag game as over SharkGame.gameOver = true; // grab end game timestamp SharkGame.timestampRunEnd = _.now(); // kick over to passage SharkGame.Gateway.enterGate(loadingFromSave); }, purgeGame() { // empty out all the containers! $("#status").empty(); SharkGame.Log.clearMessages(); $("#content").empty(); }, loopGame() { if (SharkGame.gameOver) { SharkGame.gameOver = false; SharkGame.wonGame = false; SharkGame.Main.hidePane(); // copy over all special category resources // artifacts are preserved automatically within gateway file const backup = {}; _.each(SharkGame.ResourceCategories.special.resources, (resourceName) => { backup[resourceName] = { amount: SharkGame.Resources.getResource(resourceName), totalAmount: SharkGame.Resources.getTotalResource(resourceName), }; }); SharkGame.Save.deleteSave(); // otherwise it will be loaded during main init and fuck up everything!! SharkGame.Main.init(); SharkGame.Log.addMessage(SharkGame.World.getWorldEntryMessage()); // restore special resources $.each(backup, (resourceName, resourceData) => { SharkGame.Resources.setResource(resourceName, resourceData.amount); SharkGame.Resources.setTotalResource(resourceName, resourceData.totalAmount); }); SharkGame.timestampRunStart = _.now(); try { SharkGame.Save.saveGame(); SharkGame.Log.addMessage("Game saved."); } catch (err) { SharkGame.Log.addError(err.message); console.log(err.trace); } } }, buildPane() { const pane = $("<div>").attr("id", "pane"); $("body").append(pane); // set up structure of pane const titleDiv = $("<div>").attr("id", "paneHeader"); titleDiv.append($("<div>").attr("id", "paneHeaderTitleDiv")); titleDiv.append( $("<div>") .attr("id", "paneHeaderCloseButtonDiv") .append( $("<button>") .attr("id", "paneHeaderCloseButton") .addClass("min") .html("&nbsp x &nbsp") .on("click", SharkGame.Main.hidePane) ) ); pane.append(titleDiv); pane.append($("<div>").attr("id", "paneHeaderEnd").addClass("clear-fix")); pane.append($("<div>").attr("id", "paneContent")); pane.hide(); SharkGame.paneGenerated = true; return pane; }, showPane(title, contents, hideCloseButton, fadeInTime, customOpacity) { let pane; // GENERATE PANE IF THIS IS THE FIRST TIME if (!SharkGame.paneGenerated) { pane = SharkGame.Main.buildPane(); } else { pane = $("#pane"); } // begin fading in/displaying overlay if it isn't already visible const overlay = $("#overlay"); // is it already up? fadeInTime = fadeInTime || 600; if (overlay.is(":hidden")) { // nope, show overlay const overlayOpacity = customOpacity || 0.5; if (SharkGame.Settings.current.showAnimations) { overlay.show().css("opacity", 0).animate({ opacity: overlayOpacity }, fadeInTime); } else { overlay.show().css("opacity", overlayOpacity); } // adjust overlay height overlay.height($(document).height()); } // adjust header const titleDiv = $("#paneHeaderTitleDiv"); const closeButtonDiv = $("#paneHeaderCloseButtonDiv"); if (!title || title === "") { titleDiv.hide(); } else { titleDiv.show(); if (!hideCloseButton) { // put back to left titleDiv.css({ float: "left", "text-align": "left", clear: "none" }); titleDiv.html("<h3>" + title + "</h3>"); } else { // center titleDiv.css({ float: "none", "text-align": "center", clear: "both" }); titleDiv.html("<h2>" + title + "</h2>"); } } if (hideCloseButton) { closeButtonDiv.hide(); } else { closeButtonDiv.show(); } // adjust content const paneContent = $("#paneContent"); paneContent.empty(); paneContent.append(contents); if (SharkGame.Settings.current.showAnimations && customOpacity) { pane.show().css("opacity", 0).animate({ opacity: 1.0 }, fadeInTime); } else { pane.show(); } }, hidePane() { $("#overlay").hide(); $("#pane").hide(); }, isFirstTime() { return SharkGame.World.worldType === "start" && !(SharkGame.Resources.getTotalResource("essence") > 0); }, // DEBUG FUNCTIONS discoverAll() { $.each(SharkGame.Tabs, (k, v) => { if (k !== "current") { SharkGame.Main.discoverTab(k); } }); }, }; SharkGame.Button = { makeHoverscriptButton(id, name, div, handler, hhandler, huhandler) { return $("<button>") .html(name) .attr("id", id) .appendTo(div) .on("click", handler) .on("mouseenter", hhandler) .on("mouseleave", huhandler); }, makeButton(id, name, div, handler) { return $("<button>").html(name).attr("id", id).appendTo(div).on("click", handler); }, replaceButton(id, name, handler) { return $("#" + id) .html(name) .off("click") .on("click", handler); }, }; SharkGame.FunFacts = [ "Shark Game's initial bare minimum code came from an abandoned idle game about bees. Almost no trace of bees remains!", "The existence of resources that create resources that create resources in this game were inspired by Derivative Clicker!", "Kitten Game was an inspiration for this game! This surprises probably no one. The very first message the game gives you is a nod of sorts.", "There have been social behaviours observed in lemon sharks, and evidence that suggests they prefer company to being alone.", "Sea apples are a type of sea cucumber.", "Magic crystals are probably not real.", "There is nothing suspicious about the machines.", "There are many species of sharks that investigate things with their mouths. This can end badly for the subject of investigation.", "Some shark species display 'tonic immobility' when rubbed on the nose. They stop moving, appear deeply relaxed, and can stay this way for up to 15 minutes before swimming away.", "In some shark species eggs hatch within their mothers, and in some of these species the hatched babies eat unfertilised or even unhatched eggs.", "Rays can be thought of as flattened sharks.", "Rays are pancakes of the sea. (note: probably not true)", "Chimaera are related to sharks and rays and have a venomous spine in front of their dorsal fin.", "More people are killed by lightning every year than by sharks.", "There are real eusocial shrimps that live as a community in sponges on reefs, complete with queens.", "White sharks have been observed to have a variety of body language signals to indicate submission and dominance towards each other without violence.", "Sharks with lasers were overdone, okay?", "There is a surprising deficit of cookie in this game.", "Remoras were banished from the oceans in the long bygone eras. The sharks hope they never come back.", "A kiss from a shark can make you immortal. But only if they want you to be immortal.", "A shark is worth one in the bush, and a bunch in the sea water. Don't put sharks in bushes.", ]; SharkGame.Changelog = { "<a href='https://github.com/spencers145/SharkGame'>New Frontiers</a> 0.1 - New is Old (2021/01/??)": [ "22 NEW SPRITES! More are coming but we couldn't finish all the sprites in time!", "TRUE OFFLINE PROGRESS! Days are compressed to mere seconds with RK4 calculation.", "Attempted to rebalance worlds, especially frigid and abandoned, by making hazardous materials more threatening and meaningful.", "Halved the effectiveness of the 3 basic shark machines (except sand digger, which is 2/3 as productive), but added a new upgrade to counterbalance it.", "Added recycler efficiency system. The more you recycle at once, the more you lose in the process. Added an upgrade which makes the mechanic less harsh.", "Added new UI elements to the Recycler to make it less of a guessing game and more of a cost-benefit analysis.", "Increased the effectiveness of many machines.", "Greatly improved number formatting.", "World shaper has been disabled because it will probably break plans for future game balance.", "Distant foresight now has a max level of 5, and reveals 20% of world properties per level, up to 100% at level 5.", "Fixed exploits, bugs, and buggy exploits and exploitable bugs. No more crystals -> clams & sponges -> science & clams -> crystals loop.", "No more science from sponges.", "Removed jellyfish from a bunch of worlds where the resource was a dead end.", ], "0.71 (2014/12/20)": [ "Fixed and introduced and fixed a whole bunch of horrible game breaking bugs. If your save was lost, I'm sorry.", "Made the recycler stop lying about what could be made.", "Made the recycler not pay out so much for animals.", "Options are no longer reset after completing a run for real this time.", "Bunch of tweaked gate costs.", "One new machine, and one new job.", "Ten new post-chasm-exploration technologies to invest copious amounts of science into.", ], "0.7 - Stranger Oceans (2014/12/19)": [ "WHOLE BUNCH OF NEW STUFF ADDED.", "Resource system slightly restructured for something in the future.", "New worlds with some slight changes to availabilities, gate demands, and some other stuff.", "Categories added to Home Sea tab for the benefit of trying to make sense of all the buttons.", "Newly added actions show up in highlights for your convenience.", "The way progress continues beyond the gate is now... a little tweaked.", "Options are no longer reset after completing a run.", "Artifacts exist.", "Images are a work in progress. Apologies for the placeholder graphics in these trying times.", "Partial production when there's insufficient resources for things that take costs. Enjoy watching your incomes slow to a trickle!", ], "0.62 (2014/12/12)": [ "Fixed infinity resource requirement for gate.", "Attempted to fix resource table breaking in some browsers for some sidebar widths.", ], "0.61 (2014/12/12)": [ "Added categories for buttons in the home sea, because there are going to be so many buttons.", "Miscellaneous shuffling of files.", "Some groundwork laid for v0.7, which will be the actual official release.", ], "0.6 - Return of Shark (2014/12/8)": [ "Major graphical update!", "Now features graphics sort of!", "Some UI rearrangements:" + "<ul><li>Researched techs now show in lab instead of grotto.</li>" + "<li>General stats now on right of grotto instead of left.</li>" + "<li>Large empty space in grotto right column reserved for future use!</li></ul>", "Pointless version subtitle!", "<span class='medDesc'>Added a donate link. Hey, sharks gotta eat.</span>", ], "0.59 (2014/09/30)": [ "Bunch of small fixes and tweaks!", "End of run time now shown at the end of a run.", "A couple of fixes for issues only found in IE11.", "Fixed a bug that could let people buy hundreds of things for cheap by overwhelming the game's capacity for input. Hopefully fixed, anyway.", "Gaudy social media share menu shoehorned in below the game title. Enjoy!", ], "0.531 (2014/08/20)": [ "Banned sea apples from the recycler because the feedback loop is actually far more crazy powerful than I was expecting. Whoops!", ], "0.53 (2014/08/18)": [ "Changed Recycler so that residue into new machines is linear, but into new resources is constant.", ], "0.52 (2014/08/18)": [ "Emergency bug-fixes.", "Cost to assemble residue into new things is now LINEAR (gets more expensive as you have more things) instead of CONSTANT.", ], "0.51 (2014/08/18)": [ "Edited the wording of import/export saving.", "Made machine recycling less HORRIBLY BROKEN in terms of how much a machine is worth.", ], "0.5 (2014/08/18)": [ "Added the Grotto - a way to better understand what you've accomplished so far.", "Added the Recycler. Enjoy discovering its function!", "Added sand machines for more machine sand goodness.", "Fixed oscillation/flickering of resources when at zero with anything providing a negative income.", "Added 'support' for people stumbling across the page with scripts turned off.", "Upped the gate kelp requirement by 10x, due to request.", "Added time tracking. Enjoy seeing how much of your life you've invested in this game.", "Added grouping for displaying resources on the left.", "Added some help and action descriptions.", "Added some text to the home tab to let people have an idea of where they should be heading in the very early game.", "Thanks to assistance from others, the saves are now much, much smaller than before.", "Made crab broods less ridiculously explosive.", "Adjusted some resource colours.", "Added a favicon, probably.", "<span class='medDesc'>Added an overdue copyright notice I guess.</span>", ], "0.48 (2014/08-ish)": [ "Saves are now compressed both in local storage and in exported strings.", "Big costs significantly reduced.", "Buy 10, Buy 1/3 max and Buy 1/2 max buttons added.", "Research impact now displayed on research buttons.", "Resource effectiveness multipliers now displayed in table." + "<ul><li>These are not multipliers for how much of that resource you are getting.</li></ul>", "Some dumb behind the scenes things to make the code look nicer.", "Added this changelog!", "Removed upgrades list on the left. It'll come back in a future version.", "Added ray and crab generating resources, and unlocking techs.", ], "0.47 (2014/08-ish)": ["Bulk of game content added.", "Last update for Seamergency 2014!"], "0.4 (2014/08-ish)": ["Added Laboratory tab.", "Added the end of the game tab."], "0.3 (2014/08-ish)": ["Added description to options.", "Added save import/export.", "Added the ending panel."], "0.23 (2014/08-ish)": ["Added autosave.", "Income system overhauled.", "Added options panel."], "0.22 (2014/08-ish)": [ "Offline mode added. Resources will increase even with the game off!", "(Resource income not guaranteed to be 100% accurate.)", ], "0.21 (2014/08-ish)": ["Save and load added."], "<0.21 (2014/08-ish)": ["A whole bunch of stuff.", "Resource table, log, initial buttons, the works."], }; $(() => { $("#game").show(); SharkGame.Main.init(); // ctrl+s saves $(window).on("keydown", (event) => { if (event.ctrlKey || event.metaKey) { switch (String.fromCharCode(event.key).toLowerCase()) { case "s": event.preventDefault(); SharkGame.Save.saveGame(); break; case "o": event.preventDefault(); SharkGame.Main.showOptions(); break; } } }); });
import javax.swing.*; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class CalculatorApp extends JFrame { private JTextField input; private JTextField output; public CalculatorApp() { // GUI initialization code } public void calculate() { String inputExpression = input.getText(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); try { Object result = engine.eval(inputExpression); output.setText(String.valueOf(result)); } catch (ScriptException e) { output.setText("Error: Invalid expression"); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { CalculatorApp app = new CalculatorApp(); app.setVisible(true); }); } }
import React, {useEffect, useRef} from 'react' import { animated, useSpring } from 'react-spring' import {useSelector} from 'react-redux' const AppearContainer = ({children, getSpring, className, tspan, ...rest}) => { const container = useRef() const pageLoaded = useSelector(state => state.pageLoaded) const pageLoadedMinimal = useSelector(state => state.pageLoadedMinimal) const props = useSpring({ from:{ visibility: 'hidden', }, to:{ visibility: (pageLoaded && pageLoadedMinimal) ? 'hidden' : 'visible', }, delay:0, config:{ duration:25 }, ref: container }) useEffect(() => { if(getSpring){ getSpring(container) } }, []) if(!tspan){ return ( <animated.div className={className} {...rest} style={props}> {children} </animated.div> ) }else{ return ( <animated.tspan className={className} {...rest} style={props}> {children} </animated.tspan> ) } } export default AppearContainer
import styled from 'styled-components'; import Image from '@crystallize/react-image'; import { H2 as H, responsive } from 'ui'; export const Outer = styled.article` max-width: 600px; margin: 0 auto; `; export const HeroImage = styled.div` margin-bottom: 100px; `; export const Img = styled(Image)` > img { width: 200px; } `; export const List = styled.div` display: grid; grid-gap: 5px; grid-template-columns: repeat(12, 1fr); ${responsive.md} { grid-template-columns: repeat(9, 1fr); } ${responsive.sm} { grid-template-columns: repeat(6, 1fr); } ${responsive.xs} { grid-template-columns: repeat(3, 1fr); } `; export const H2 = styled(H)` display: block; font-size: 1rem; text-transform: uppercase; color: var(--color-text-main); ${responsive.xs} { text-align: center; } `; export const Related = styled.div` border-top: 2px solid #efefef; max-width: 1600px; padding: 100px 100px 0 100px; margin: 100px auto; display: block; ${responsive.smAndLess} { padding: 50px; } `;
<gh_stars>0 import os import string # clean_string import json # config from difflib import SequenceMatcher # similar # slugify import re import unicodedata import text_unidecode as unidecode _unicode = str _unicode_type = str unichr = chr QUOTE_PATTERN = re.compile(r'[\']+') ALLOWED_CHARS_PATTERN = re.compile(r'[^-a-z0-9]+') ALLOWED_CHARS_PATTERN_WITH_UPPERCASE = re.compile(r'[^-a-zA-Z0-9]+') DUPLICATE_DASH_PATTERN = re.compile(r'-{2,}') NUMBERS_PATTERN = re.compile(r'(?<=\d),(?=\d)') DEFAULT_SEPARATOR = '-' # ~ Lib with simple functions to help keep main prog clean ~ # """ Compares two strings @return True if strings are similar """ def similar(a, b): return SequenceMatcher(None, a, b).ratio() > 0.5 """ Removes the "'feat." type from the title @return corrected title """ def remove_feat(title): lst1 = ["(Ft", "(ft", "(FEAT", "(Feat", "(feat", "(with", "(With", "FEAT"] for element in lst1 : if element in title : title = title[0:title.rfind(element)] return title.strip() return title.strip() """ Removes "the" from the title @return corrected title """ def remove_the(string) : if string[:3] == "the" or string[:3] == "The": return string[3:].strip() else : return string def slugify(text, separator=DEFAULT_SEPARATOR, lowercase=True): """ Make a slug from the given text. @return corrected text """ # ensure text is unicode if not isinstance(text, _unicode_type): text = _unicode(text, 'utf-8', 'ignore') # replace quotes with dashes - pre-process text = QUOTE_PATTERN.sub(DEFAULT_SEPARATOR, text) # decode unicode text = unidecode.unidecode(text) # ensure text is still in unicode if not isinstance(text, _unicode_type): text = _unicode(text, 'utf-8', 'ignore') # translate text = unicodedata.normalize('NFKD', text) # make the text lowercase (optional) if lowercase: text = text.lower() # remove generated quotes -- post-process text = QUOTE_PATTERN.sub('', text) # cleanup numbers text = NUMBERS_PATTERN.sub('', text) # replace all other unwanted characters if lowercase: pattern = ALLOWED_CHARS_PATTERN else: pattern = ALLOWED_CHARS_PATTERN_WITH_UPPERCASE text = re.sub(pattern, DEFAULT_SEPARATOR, text) # remove redundant text = DUPLICATE_DASH_PATTERN.sub(DEFAULT_SEPARATOR, text).strip(DEFAULT_SEPARATOR) if separator != DEFAULT_SEPARATOR: text = text.replace(DEFAULT_SEPARATOR, separator) return text """ Removes / modifies none ascii characters and punctuation @return the clean string""" def clean_string(data) : for c in string.punctuation: data = data.replace(c, "") return data.replace(" ", "-") """ Updates/ create config file according to given params""" def update_config(config, interface): jsonString = json.dumps(config) try : with open("config.json", mode="w") as j_object: j_object.write(jsonString) return True except FileNotFoundError: if interface.ask("No config file found \ncreate one ?") : pass return True except Exception as e : interface.warn("unknown error during writing to config file : \n" + str(e)) return False def read_config(interface) : config = {} try: with open("config.json", mode="r") as j_object: config = json.load(j_object) except FileNotFoundError: interface.warn("No config file found \nusing standard setup") except json.JSONDecodeError as e: interface.warn("At line " + str(e.lineno)+ " of the config file, bad syntax (" + str(e.msg) + ")\nusing standard setup") except Exception as e : interface.warn("unknown error : " + str(e) + "\nusing standard setup") params = {} params['feat_acronym'] = str (config.get("feat_acronym", "feat.")) params['default_genre'] = str(config.get("default_genre","Other")) params['folder_name'] = str (config.get("folder_name","music")) params['get_label'] = bool (config.get("get_label",True)) params['get_bpm'] = bool (config.get("get_bpm",True)) params['get_lyrics'] = bool (config.get("get_lyrics",True)) params['store_image_in_file'] = bool (config.get("store_image_in_file",True)) return params def create_config() : try : f = open('config.json','w+') f.close() return True except : return False def rm_file(file_name): try : os.remove(file_name) return True except : return False def find_ffmpeg(): def is_exe(prg): return os.path.isfile(prg) and os.access(prg, os.X_OK) # just for windows if os.name == 'nt' : ffmpeg_name = 'ffmpeg.exe' ffprobe_name = 'ffprobe.exe' else : ffmpeg_name = 'ffmpeg' ffprobe_name = 'ffprobe' #if exec in folder : if os.path.exists("ffmpeg/"+ffmpeg_name) and os.path.exists("ffmpeg/"+ffprobe_name) : return "./"+ffmpeg_name #else tries to see if exec exists if os.path.split("ffmpeg")[0]: if is_exe(ffmpeg_name) : return ffmpeg_name else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, ffmpeg_name) if is_exe(exe_file) : return exe_file return False
// Copyright 2008 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.internal.structure; import org.apache.tapestry5.runtime.Event; /** * Base class for most implementations of {@link org.apache.tapestry5.internal.structure.ComponentCallback}, used when * there is an underlying {@link org.apache.tapestry5.runtime.Event}. * * @see LifecycleNotificationComponentCallback */ public abstract class AbstractComponentCallback implements ComponentCallback { private final Event event; public AbstractComponentCallback(Event event) { this.event = event; } public boolean isEventAborted() { return event.isAborted(); } }
#! /bin/bash chown shib.shib /opt/shib -R su - shib -c "cd /opt/shib && npm start"
<filename>mobile/src/pages/Main.js import React, { useState, useEffect } from 'react' import { StyleSheet, Image } from 'react-native' import MapView, { Marker } from 'react-native-maps' import { requestPermissionsAsync, getCurrentPositionAsync } from 'expo-location' function Main() { const [currentRegion, setCurrentRegion] = useState(null) useEffect(() => { async function loadInitialPosition() { const { granted } = await requestPermissionsAsync() if (granted) { const { coords } = await getCurrentPositionAsync({ enableHighAccuracy: true, }) const { latitude, longitude } = coords setCurrentRegion({ latitude, longitude, latitudeDelta: 0.04, longitudeDelta: 0.04 }) } } loadInitialPosition() }, []) if (!currentRegion) { return null } return ( <MapView initialRegion={ currentRegion } style={ styles.map }> <Marker coordinate={{ latitude: -29.6756312, longitude: -53.8074866 }}> <Image style={styles.avatar} src={{ uri: 'https://avatars2.githubusercontent.com/u/20098577?s=460&v=4' }} /> </Marker> </MapView> ) } const styles = StyleSheet.create({ map: { flex: 1 }, avatar: { width: 54, height: 54, borderRadius: 4, borderWidth: 4, borderColor: '#FFF' } }) export default Main
#!/usr/bin/env bash FOLDER_PATH=$PWD echo "START \"set path variables\"" \ && echo "" \ && php -v \ && echo "" \ && echo "prepare php.ini and set include path" \ && sudo cp -f /etc/php.ini.default /etc/php.ini \ && sudo chmod u+w /etc/php.ini \ && echo "include_path = \".:/php/includes:${FOLDER_PATH}\"" | sudo tee -a /etc/php.ini \ && echo "" \ && echo "" \ && echo "check if everything is successfully installed" \ && php -r "require('lib/pan_php_framework.php');print \"PAN-OS-PHP LIBRARY - OK INSTALL SUCCESSFUL\n\";" \ && echo "" \ && echo "" \ && echo "set user bash profile" \ && echo "source \"${FOLDER_PATH}/utils/alias.sh\"" >> ~/.profile \ && echo "source \"${FOLDER_PATH}/utils/alias.sh\"" >> ~/.bash_profile \ && echo "source \"${FOLDER_PATH}/utils/alias.sh\"" >> ~/.zshrc \ && echo "" \ && echo "" \ && echo "END script"
#include "main.h" static boolean_t is_empty_command(job_data_t* job_data, int index) { int i; i = 0; while(job_data->children_data[index].command[i] != '\0') { if(isspace(job_data->children_data[index].command[i]) == 0) return FALSE; } return TRUE; } boolean_t read_next_command(job_data_t* job_data, int index) { char* trim; do { if(fgets(job_data->children_data[index].command, MAX_COMMAND_SIZE, job_data->file) == NULL) return FALSE; trim = strchr(job_data->children_data[index].command, '\n'); if(trim != NULL) *trim = '\0'; trim = strchr(job_data->children_data[index].command, '#'); if(trim != NULL) *trim = '\0'; } while(is_empty_command(job_data, index) == TRUE); return TRUE; }
<reponame>SenaiCIC/jhean package aula08; public class EscopoInicializazao { public static void main(String[] args) { int global= 6; String nome; if(global>5){ nome="xuxu"; }else{ nome="adailton"; } System.out.println(global); System.out.println(nome); } }
#!/usr/bin/env bash source "../../config.sh" curl -X "POST" "https://rest.nexmo.com/sms/json" \ -d "from=$FROM_NUMBER" \ -d "text=A text message sent using the Nexmo SMS API" \ -d "to=$TO_NUMBER" \ -d "api_key=$NEXMO_API_KEY" \ -d "sig=$NEXMO_SIGNATURE_SECRET"
#!/bin/bash # ========== Experiment Seq. Idx. 2692 / 52.0.4.0 / N. 0 - _S=52.0.4.0 D1_N=39 a=-1 b=1 c=1 d=1 e=-1 f=-1 D3_N=7 g=1 h=1 i=1 D4_N=2 j=2 D5_N=0 ========== set -u # Prints header echo -e '\n\n========== Experiment Seq. Idx. 2692 / 52.0.4.0 / N. 0 - _S=52.0.4.0 D1_N=39 a=-1 b=1 c=1 d=1 e=-1 f=-1 D3_N=7 g=1 h=1 i=1 D4_N=2 j=2 D5_N=0 ==========\n\n' # Prepares all environment variables JBHI_DIR="$HOME/jbhi-special-issue" RESULTS_DIR="$JBHI_DIR/results" if [[ "Yes" == "Yes" ]]; then SVM_SUFFIX="svm" PREDICTIONS_FORMAT="isbi" else SVM_SUFFIX="nosvm" PREDICTIONS_FORMAT="titans" fi RESULTS_PREFIX="$RESULTS_DIR/deep.39.layer.7.test.2.index.2692.$SVM_SUFFIX" RESULTS_PATH="$RESULTS_PREFIX.results.txt" # ...variables expected by jbhi-checks.include.sh and jbhi-footer.include.sh SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue" LIST_OF_INPUTS="$RESULTS_PREFIX.finish.txt" # ...this experiment is a little different --- only one master procedure should run, so there's only a master lock file METRICS_TEMP_PATH="$RESULTS_DIR/this_results.anova.txt" METRICS_PATH="$RESULTS_DIR/all_results.anova.txt" START_PATH="$METRICS_PATH.start.txt" FINISH_PATH="-" LOCK_PATH="$METRICS_PATH.running.lock" LAST_OUTPUT="$METRICS_PATH" mkdir -p "$RESULTS_DIR" # # Assumes that the following environment variables where initialized # SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue" # LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODELS_DIR/finish.txt:" # START_PATH="$OUTPUT_DIR/start.txt" # FINISH_PATH="$OUTPUT_DIR/finish.txt" # LOCK_PATH="$OUTPUT_DIR/running.lock" # LAST_OUTPUT="$MODEL_DIR/[[[:D1_MAX_NUMBER_OF_STEPS:]]].meta" EXPERIMENT_STATUS=1 STARTED_BEFORE=No # Checks if code is stable, otherwise alerts scheduler pushd "$SOURCES_GIT_DIR" >/dev/null GIT_STATUS=$(git status --porcelain) GIT_COMMIT=$(git log | head -n 1) popd >/dev/null if [ "$GIT_STATUS" != "" ]; then echo 'FATAL: there are uncommitted changes in your git sources file' >&2 echo ' for reproducibility, experiments only run on committed changes' >&2 echo >&2 echo ' Git status returned:'>&2 echo "$GIT_STATUS" >&2 exit 162 fi # The experiment is already finished - exits with special code so scheduler won't retry if [[ "$FINISH_PATH" != "-" ]]; then if [[ -e "$FINISH_PATH" ]]; then echo 'INFO: this experiment has already finished' >&2 exit 163 fi fi # The experiment is not ready to run due to dependencies - alerts scheduler if [[ "$LIST_OF_INPUTS" != "" ]]; then IFS=':' tokens_of_input=( $LIST_OF_INPUTS ) input_missing=No for input_to_check in ${tokens_of_input[*]}; do if [[ ! -e "$input_to_check" ]]; then echo "ERROR: input $input_to_check missing for this experiment" >&2 input_missing=Yes fi done if [[ "$input_missing" != No ]]; then exit 164 fi fi # Sets trap to return error code if script is interrupted before successful finish LOCK_SUCCESS=No FINISH_STATUS=161 function finish_trap { if [[ "$LOCK_SUCCESS" == "Yes" ]]; then rmdir "$LOCK_PATH" &> /dev/null fi if [[ "$FINISH_STATUS" == "165" ]]; then echo 'WARNING: experiment discontinued because other process holds its lock' >&2 else if [[ "$FINISH_STATUS" == "160" ]]; then echo 'INFO: experiment finished successfully' >&2 else [[ "$FINISH_PATH" != "-" ]] && rm -f "$FINISH_PATH" echo 'ERROR: an error occurred while executing the experiment' >&2 fi fi exit "$FINISH_STATUS" } trap finish_trap EXIT # While running, locks experiment so other parallel threads won't attempt to run it too if mkdir "$LOCK_PATH" --mode=u=rwx,g=rx,o=rx &>/dev/null; then LOCK_SUCCESS=Yes else echo 'WARNING: this experiment is already being executed elsewhere' >&2 FINISH_STATUS="165" exit fi # If the experiment was started before, do any cleanup necessary if [[ "$START_PATH" != "-" ]]; then if [[ -e "$START_PATH" ]]; then echo 'WARNING: this experiment is being restarted' >&2 STARTED_BEFORE=Yes fi #...marks start date -u >> "$START_PATH" echo GIT "$GIT_COMMIT" >> "$START_PATH" fi if [[ "$STARTED_BEFORE" == "Yes" ]]; then # If the experiment was started before, do any cleanup necessary echo -n else echo "D1_N;D3_N;D4_N;a;b;c;d;e;f;g;h;i;j;m_ap;m_auc;m_tn;m_fp;m_fn;m_tp;m_tpr;m_fpr;k_ap;k_auc;k_tn;k_fp;k_fn;k_tp;k_tpr;k_fpr;isbi_auc" > "$METRICS_PATH" fi python \ "$SOURCES_GIT_DIR/etc/compute_metrics.py" \ --metadata_file "$SOURCES_GIT_DIR/data/all-metadata.csv" \ --predictions_format "$PREDICTIONS_FORMAT" \ --metrics_file "$METRICS_TEMP_PATH" \ --predictions_file "$RESULTS_PATH" EXPERIMENT_STATUS="$?" echo -n "39;7;2;" >> "$METRICS_PATH" echo -n "-1;1;1;1;-1;-1;1;1;1;2;" >> "$METRICS_PATH" tail "$METRICS_TEMP_PATH" -n 1 >> "$METRICS_PATH" # #...starts training if [[ "$EXPERIMENT_STATUS" == "0" ]]; then if [[ "$LAST_OUTPUT" == "" || -e "$LAST_OUTPUT" ]]; then if [[ "$FINISH_PATH" != "-" ]]; then date -u >> "$FINISH_PATH" echo GIT "$GIT_COMMIT" >> "$FINISH_PATH" fi FINISH_STATUS="160" fi fi
#!/bin/sh libtoolize -c -f || exit 1 aclocal --force --verbose || exit 1 autoheader -fv || exit 1 automake -acfv || exit 1 autoreconf -ifv || exit 1 # ./configure
#!/bin/bash # Generate test certificates: # # ca.{crt,key} Self signed CA certificate. # redis.{crt,key} A certificate with no key usage/policy restrictions. dir=`dirname $0` # Generate CA openssl genrsa -out ${dir}/ca.key 4096 openssl req \ -x509 -new -nodes -sha256 \ -key ${dir}/ca.key \ -days 3650 \ -subj '/O=redis_exporter/CN=Certificate Authority' \ -out ${dir}/ca.crt # Generate cert openssl genrsa -out ${dir}/redis.key 2048 openssl req \ -new -sha256 \ -subj "/O=redis_exporter/CN=localhost" \ -key ${dir}/redis.key | \ openssl x509 \ -req -sha256 \ -CA ${dir}/ca.crt \ -CAkey ${dir}/ca.key \ -CAserial ${dir}/ca.txt \ -CAcreateserial \ -days 3650 \ -out ${dir}/redis.crt
<reponame>openfirmware/ccadi_geoserver<gh_stars>0 # zfs.rb # Install ZFS tools alongside GeoServer installation. # Sets up kABI installation (no DKMS required), but does not create # any ZFS pools. # # For more information on the Policyfile feature, visit # https://docs.chef.io/policyfile/ # A name that describes what the system you're building with Chef does. name 'ccadi_geoserver' # Where to find external cookbooks: default_source :supermarket # run_list: chef-client will run these recipes in the order specified. run_list 'ccadi_geoserver::zfs', 'ccadi_geoserver::default' # Specify a custom source for a single cookbook: cookbook 'ccadi_geoserver', path: '..'
from dagster import graph, op, resource @resource def external_service(): ... @op(required_resource_keys={"external_service"}) def do_something(): ... @graph def do_it_all(): do_something() do_it_all_job = do_it_all.to_job(resource_defs={"external_service": external_service})
int[] arr = new int[10]; for (int i=0; i<10; i++){ arr[i] = i+1; }
<filename>server/app/state/config_dep_map.go<gh_stars>1-10 package state const ConfigDepMapKey = "ConfigDepMap"
<reponame>KimJeongYeon/jack2_android<gh_stars>10-100 /* Copyright (C) 2010 <NAME> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <memory> #include "JackFFADOMidiInputPort.h" #include "JackMidiUtil.h" #include "JackError.h" using Jack::JackFFADOMidiInputPort; JackFFADOMidiInputPort::JackFFADOMidiInputPort(size_t max_bytes) { event = 0; receive_queue = new JackFFADOMidiReceiveQueue(); std::auto_ptr<JackFFADOMidiReceiveQueue> receive_queue_ptr(receive_queue); write_queue = new JackMidiBufferWriteQueue(); std::auto_ptr<JackMidiBufferWriteQueue> write_queue_ptr(write_queue); raw_queue = new JackMidiRawInputWriteQueue(write_queue, max_bytes, max_bytes); write_queue_ptr.release(); receive_queue_ptr.release(); } JackFFADOMidiInputPort::~JackFFADOMidiInputPort() { delete raw_queue; delete receive_queue; delete write_queue; } void JackFFADOMidiInputPort::Process(JackMidiBuffer *port_buffer, uint32_t *input_buffer, jack_nframes_t frames) { receive_queue->ResetInputBuffer(input_buffer, frames); write_queue->ResetMidiBuffer(port_buffer, frames); jack_nframes_t boundary_frame = GetLastFrame() + frames; if (! event) { event = receive_queue->DequeueEvent(); } for (; event; event = receive_queue->DequeueEvent()) { switch (raw_queue->EnqueueEvent(event)) { case JackMidiWriteQueue::BUFFER_FULL: // Processing events early might free up some space in the raw // input queue. raw_queue->Process(boundary_frame); switch (raw_queue->EnqueueEvent(event)) { case JackMidiWriteQueue::BUFFER_TOO_SMALL: // This shouldn't really happen. It indicates a bug if it // does. jack_error("JackFFADOMidiInputPort::Process - **BUG** " "JackMidiRawInputWriteQueue::EnqueueEvent returned " "`BUFFER_FULL`, and then returned " "`BUFFER_TOO_SMALL` after a `Process()` call."); // Fallthrough on purpose case JackMidiWriteQueue::OK: continue; default: return; } case JackMidiWriteQueue::BUFFER_TOO_SMALL: jack_error("JackFFADOMidiInputPort::Process - The write queue " "couldn't enqueue a %d-byte event. Dropping event.", event->size); // Fallthrough on purpose case JackMidiWriteQueue::OK: continue; default: // This is here to stop compliers from warning us about not // handling enumeration values. ; } break; } raw_queue->Process(boundary_frame); }
package plugin.album; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import plugin.album.data.MediaItem; public class MediaMgr { private static final MediaMgr sInstance = new MediaMgr(); private MediaMgr() {} public static MediaMgr getInstance() { return sInstance; } private AlbumPlugin mAlbumPlugin; public void initAlbumPlugin(AlbumPlugin albumPlugin) { mAlbumPlugin = albumPlugin; } private List<MediaItem> mMediaItems = new ArrayList<>(); private int mSelectIndex = 0; public boolean setMultimediaItems(List<String> urlList, int selectIndex) { if (urlList == null || urlList.isEmpty()) return false; mSelectIndex = selectIndex; mMediaItems.clear(); for (int i = 0; i < urlList.size(); ++i) { MediaItem tempItem = createItem(urlList.get(i)); if (tempItem != null) { mMediaItems.add(tempItem); } } if (!mMediaItems.isEmpty()) { return true; } return false; } public List<MediaItem> getMultimediaItems() { return mMediaItems; } public int getSelectIndex() { return mSelectIndex; } public void insertData(List<String> urlList) { if (urlList == null || urlList.isEmpty()) return; List<MediaItem> newList = new ArrayList<>(); for (int i = 0; i < urlList.size(); ++i) { MediaItem tempItem = createItem(urlList.get(i)); if (tempItem != null) { newList.add(tempItem); } } mSelectIndex = mSelectIndex + newList.size(); mMediaItems.addAll(0, newList); EventBus.getDefault().post(new ListDataUpdateAction()); } public void loadHistoryData(int currentSelect) { mSelectIndex = currentSelect; if (mAlbumPlugin != null) mAlbumPlugin.loadHistoryFile(); } public MediaItem createItem(String url) { String filePath = url; int pos = filePath.indexOf("?"); if (pos > 0) { filePath = filePath.substring(0, pos); } int type; if (isPicture(filePath)) { type = MediaItem.TYPE_IMAGE; } else if (isVideo(filePath)) { type = MediaItem.TYPE_VIDEO; url = filePath; } else if (isGif(filePath)) { type = MediaItem.TYPE_GIF; url = filePath; } else { return null; } return new MediaItem(type, url); } public boolean isPicture(String path) { if (path == null || path.isEmpty()) return false; return Pattern.compile(".(png|jpe?g|svg|webp|heic|bmp)").matcher(path.toLowerCase()).find(); } public boolean isGif(String path) { if (path == null || path.isEmpty()) return false; return Pattern.compile(".(gif)").matcher(path.toLowerCase()).find(); } public boolean isVideo(String path) { if (path == null || path.isEmpty()) return false; return Pattern.compile(".(mp4|video|mov|qlv)").matcher(path.toLowerCase()).find(); } public static class ListDataUpdateAction {} }
import { combineReducers } from "redux"; import game from "./game"; const reducers = combineReducers({ game }); export default reducers;
from django.contrib import admin from django.http.response import HttpResponseRedirect from hoodalert.models import HealthDep, Neighbourhood, PoliceDep # Register your models here. admin.site.register(HealthDep) admin.site.register(PoliceDep) admin.site.register(Neighbourhood)
var this_js_script = $("script[src*=apppagos]"); var my_var_1 = this_js_script.attr("data-my_var_1"); if (typeof my_var_1 === "undefined") { var my_var_1 = "some_default_value"; } Vue.config.devtools = true; Vue.component("v-select", VueSelect.VueSelect); //Vue.use(VeeValidate); Vue.use(VeeValidate, { classes: true, // Sí queremos que ponga clases automáticamente // Indicar qué clase poner al input en caso de que sea // válido o inválido. Usamos Bootstrap 4 classNames: { valid: "is-valid", invalid: "is-invalid" }, // Podría ser blur, change, etcétera. Si está vacío // entonces se tiene que validar manualmente events: "change|blur|keyup" }); VeeValidate.Validator.localize("es"); var vcon = new Vue({ el: "#app", data: { url: my_var_1, addModal: false, editModal: false, cargando: false, error: false, perfil: false, loading: false, divmensaje: false, divmesajeDetallePago: false, btnpagar: false, mensajeDetallePago: "", mensaje: "", inputalumno: true, total: 0, totalapagar: 0, totalpagado: 0, alumnos: [], formapagos: [], pagosalumno: [], array_pago_detalle: [], array_forma_pago: [], array_descuento_fijo: [], array_descuento_porcentaje: [], establecer_porcentaje_descuento: "Establecer", establecer_fijo_descuento: "Establecer", newFormaPago: { descuento: "", numautorizacion: "", idformapago: "" }, newDescuento: { descuento: "" }, newDescuentoPorcentaje: { descuento: "" }, visiblemsgerror: false, msgerror: "", detalleAlumno: [], chooseAlumno: {}, formValidate: [], successMSG: "", events: "change|blur|keyup" }, created() { this.showAllAlumnos(); this.showAllFormaPago(); this.iniciales(); this.habilitarBoton(); }, methods: { iniciales() { if (vcon.newDescuento.descuento != "") { vcon.establecer_fijo_descuento = vcon.newDescuento.descuento; } if (vcon.newDescuentoPorcentaje.descuento != "") { vcon.establecer_porcentaje_descuento = vcon.newDescuentoPorcentaje.descuento + "%"; } }, habilitarBoton() { if (vcon.total > 0 && vcon.totalapagar == 0) { vcon.btnpagar = true; } else { vcon.btnpagar = false; } }, abrirModalDescuentoFijo() { if (vcon.total > 0) { $("#addDescuentoFijo").modal("show"); } else { //vcon.divmensaje = true; // vcon.mensaje = "Total deber ser mayor a 0"; Swal({type: "info", title: "Información", text: "El total a pagar deber ser mayor a $0.00"}); //swal({position: "center", type: "success", title: "Exito!", showConfirmButton: false, timer: 2000}); //swal({icon: "error", title: "Informació", text: "Es total a pagar deber ser mayor a $0.00"}); } }, abrirModalDescuentoPorcentaje() { if (vcon.total > 0) { $("#addDescuentoPorcentaje").modal("show"); } else { //vcon.divmensaje = true; // vcon.mensaje = "Total deber ser mayor a 0"; Swal({type: "info", title: "Información", text: "El total a pagar deber ser mayor a $0.00"}); //swal({position: "center", type: "success", title: "Exito!", showConfirmButton: false, timer: 2000}); //swal({icon: "error", title: "Informació", text: "Es total a pagar deber ser mayor a $0.00"}); } }, showAllAlumnos() { axios.get(this.url + "Pago/showAllAlumnos/").then(response => (this.alumnos = response.data.alumnos)); }, showAllFormaPago() { axios.get(this.url + "Pago/showAllFormaPago/").then(response => (this.formapagos = response.data.formapagos)); }, selectAlumno(alumno) { vcon.chooseAlumno = alumno; }, updateTotalEliminarArray(index) { var item = vcon.array_pago_detalle.slice(index, 1); console.log(item); //vcon.total = vcon.total - parseFloat(item[0].descuento); }, deleteItemFormaPago(index) { item = vcon.array_forma_pago[index]; vcon.totalpagado = parseFloat(vcon.totalpagado).toFixed(2) - parseFloat(item.descuento).toFixed(2); vcon.totalapagar = parseFloat(vcon.totalapagar) + parseFloat(item.descuento); vcon.array_forma_pago.splice(index, 1); vcon.habilitarBoton(); }, deleteItem(index) { //var item = vcon.array_pago_detalle.slice(index, 1); //vcon.total = vcon.total - parseFloat(item[0].descuento); //console.log(index); //console.log(vcon.array_pago_detalle); //console.log(vcon.array_pago_detalle[index]); item = vcon.array_pago_detalle[index]; //console.log(parseFloat(item.descuento.toFixed(2))); vcon.total = parseFloat(vcon.total.toFixed(2)) - parseFloat(item.total.toFixed(2)); vcon.totalapagar = parseFloat(vcon.totalapagar.toFixed(2)) - parseFloat(item.total.toFixed(2)); vcon.array_pago_detalle.splice(index, 1); if (vcon.establecer_porcentaje_descuento != "Establecer") { var descuento_porcentaje = 0; var subtotal = 0; vcon.array_descuento_porcentaje = []; for (var a = 0, l = vcon.array_pago_detalle.length; a < l; a++) { descuento_porcentaje += vcon.array_pago_detalle[a].total; subtotal += vcon.array_pago_detalle[a].descuento; } var forma_pago = { opcion: 1, concepto: vcon.establecer_porcentaje_descuento, descuento: parseFloat(subtotal - descuento_porcentaje).toFixed(2) }; vcon.array_descuento_porcentaje.push(forma_pago); } if (vcon.array_pago_detalle.length == 0) { vcon.clearAll(); } //var eliminado = vcon.array_pago_detalle.splice(index, 1); }, quitarAlumno() { vcon.inputalumno = true; vcon.array_pago_detalle = []; vcon.perfil = false; vcon.pagosalumno = []; vcon.total = 0; vcon.totalapagar = 0; vcon.clearAll(); vcon.iniciales(); }, changedLabel(event) { //console.log(event.idalumno); vcon.array_pago_detalle = []; axios.get(this.url + "Pago/pagosAlumno/", { params: { idalumno: event.idalumno } }).then(response => (this.pagosalumno = response.data)); axios.get(this.url + "Pago/detalleAlumno/", { params: { idalumno: event.idalumno } }).then(response => (this.detalleAlumno = response.data.alumno)); vcon.perfil = true; vcon.inputalumno = false; }, agregarDescuentoFijo() { this.$validator.validateAll("form2").then(isValid => { if (isValid) { var descuento = vcon.validarNumeroEntero(vcon.newDescuento.descuento); console.log(descuento); if (descuento < vcon.totalapagar) { vcon.array_descuento_fijo = []; var forma_pago = { opcion: 0, concepto: "Descuento Fijo", descuento: descuento }; vcon.totalapagar = vcon.totalapagar - parseFloat(descuento); vcon.total = vcon.total - parseFloat(descuento); vcon.array_descuento_fijo.push(forma_pago); vcon.cerrarDescuentoFijo(); vcon.iniciales(); } else { Swal({type: "info", title: "Información", text: "El descuento debe ser menor o igual al total a pagar."}); } } }); }, agregarDescuentoPorcentaje() { this.$validator.validateAll("form3").then(isValid => { if (isValid) { vcon.array_descuento_porcentaje = []; var descuento = vcon.validarNumeroEntero(vcon.newDescuentoPorcentaje.descuento); var subtotal = 0; var total_descuento_fijo = 0; for (var e = 0, l = vcon.array_descuento_fijo.length; e < l; e++) { total_descuento_fijo += vcon.array_descuento_fijo[e].descuento; } var total = 0; for (var i = 0, l = vcon.array_pago_detalle.length; i < l; i++) { //ES LA PRIMERA VEZ CON DESCUENTO GLOBAL vcon.array_pago_detalle[i].descuentoporcentajeglobal = descuento; vcon.array_pago_detalle[i].descuentoporcentajeindividual = 0; var nuevodescuento = descuento; var descuento_real = vcon.array_pago_detalle[i].descuento - this.descuentoPorcentaje(vcon.array_pago_detalle[i].descuento, nuevodescuento); vcon.array_pago_detalle[i].total = parseFloat(descuento_real); total += parseFloat(descuento_real); subtotal += parseFloat(vcon.array_pago_detalle[i].descuento); } vcon.total = parseFloat(total).toFixed(2) - total_descuento_fijo; var forma_pago = { opcion: 1, concepto: nuevodescuento + "%", descuento: subtotal - parseFloat(total).toFixed(2) }; vcon.array_descuento_porcentaje.push(forma_pago); var total_pagado = 0; for (var a = 0, l = vcon.array_forma_pago.length; a < l; a++) { total_pagado += vcon.array_forma_pago[a].descuento; } if (total_pagado > 0) { vcon.totalapagar = parseFloat(total_pagado) - (parseFloat(total).toFixed(2) - total_descuento_fijo); } else { vcon.totalapagar = parseFloat(total).toFixed(2) - total_descuento_fijo; } vcon.cerrarDescuentoPorcentaje(); vcon.iniciales(); } }); }, agregarDetalleFormaPago() { this.divmesajeDetallePago = false; this.mensajeDetallePago = ""; this.$validator.validateAll("form1").then(isValid => { if (isValid) { this.divmesajeDetallePago = false; this.mensajeDetallePago = ""; var descuento = vcon.validarNumeroEntero(vcon.newFormaPago.descuento); var idformapago = vcon.newFormaPago.idformapago.idtipopago; var formapago = vcon.newFormaPago.idformapago.nombretipopago; var numautorizacion = vcon.newFormaPago.numautorizacion; if (vcon.totalapagar <= 0) { if (parseFloat(vcon.newFormaPago.descuento) <= vcon.totalapagar) { var forma_pago = { idformapago: idformapago, formapago: formapago, descuento: descuento, numautorizacion: numautorizacion }; vcon.array_forma_pago.push(forma_pago); vcon.totalpagado = vcon.totalpagado + parseFloat(vcon.newFormaPago.descuento); vcon.totalapagar = vcon.totalapagar - parseFloat(vcon.newFormaPago.descuento); } else { Swal({type: "info", title: "Información", text: "La cantidad deber ser menor o igual al total a pagar."}); //vcon.visiblemsgerror = true; //vcon.msgerror = "El total a pagar debe ser igual."; } } else { Swal({type: "info", title: "Información", text: "El total a pagar deber ser mayor a $0.00"}); } vcon.iniciales(); vcon.habilitarBoton(); } }); }, changedAdd(event) { if (event.idconcepto == 3) { //Es colegiatura const resultado = vcon.array_pago_detalle.find(row => row.idmes === event.idmes); if (resultado === undefined) { // No exite la mensualidad registrada var forma_pago = { id: this.aleatorio(1, 200), idconcepto: event.idconcepto, concepto: event.concepto, descuento: parseFloat(event.descuento), descuentoporcentajeindividual: 0, descuentoporcentajeglobal: 0, total: parseFloat(event.descuento), idmes: event.idmes, nombremes: event.nombremes }; //creamos la variable personas, con la variable nombre y apellidos vcon.total = vcon.total + parseFloat(event.descuento); vcon.totalapagar = vcon.totalapagar + parseFloat(event.descuento); vcon.array_pago_detalle.push(forma_pago); //añadimos el la variable persona al array } } else { const resultado = vcon.array_pago_detalle.find(row => row.idconcepto === event.idconcepto); if (resultado === undefined) { // No exite el concepto registrado var forma_pago = { id: this.aleatorio(1, 200), idconcepto: event.idconcepto, concepto: event.concepto, descuento: parseFloat(event.descuento), descuentoporcentajeindividual: 0, descuentoporcentajeglobal: 0, total: parseFloat(event.descuento), idmes: event.idmes, nombremes: event.nombremes }; //creamos la variable personas, con la variable nombre y apellidos vcon.total = vcon.total + parseFloat(event.descuento); vcon.totalapagar = vcon.totalapagar + parseFloat(event.descuento); vcon.array_pago_detalle.push(forma_pago); //añadimos el la variable persona al array } } vcon.iniciales(); }, quitarDescuentoFijo() { vcon.total = vcon.total + parseFloat(vcon.newDescuento.descuento); vcon.totalapagar = vcon.totalapagar + parseFloat(vcon.newDescuento.descuento); // $("#addDescuentoFijo").modal("hide"); vcon.formValidate = false; vcon.array_descuento_fijo = []; var total = 0; var totalapagar = 0; //var descuentoporcentaje = 0; var nuevodescuento = 0; vcon.array_pago_detalle.forEach(element => { //total = total + element.descuento; //totalapagar = totalapagar + element.descuento; if (element.descuentoporcentajeindividual > 0) { nuevodescuento += element.total; } else if (element.descuentoporcentajeglobal > 0) { nuevodescuento += element.total; } else { total = total + element.descuento; totalapagar = totalapagar + element.descuento; } }); vcon.total = total + nuevodescuento; vcon.totalapagar = totalapagar + nuevodescuento; console.log(nuevodescuento); }, cerrarDescuentoFijo() { $("#addDescuentoFijo").modal("hide"); vcon.formValidate = false; }, cerrarDescuentoPorcentaje() { $("#addDescuentoPorcentaje").modal("hide"); vcon.formValidate = false; }, descuentoPorcentaje(cantidad, porcentahe) { return Math.floor(cantidad * porcentahe) / 100; }, validarDecimal(numero) { resultado = false; var decimal = /^[-+]?[0-9]+\.[0-9]+$/; console.log(numero); if (numero.match(decimal)) { resultado = true; } else { resultado = false; } }, validarNumeroEntero(numero) { resultado = 0; if (numero % 1 == 0) { var numerotemporal = parseFloat(numero + ".00"); return (resultado = numerotemporal); //return true; } else { return (resultado = numero); } }, clearAll() { vcon.newDescuento = { descuento: "" }; vcon.newDescuentoPorcentaje = { descuento: "" }; vcon.array_descuento_fijo = []; vcon.array_descuento_porcentaje = []; vcon.array_forma_pago = []; vcon.establecer_porcentaje_descuento = "Establecer"; vcon.establecer_fijo_descuento = "Establecer"; vcon.totalapagar = 0; vcon.total = 0; }, aleatorio(min, max) { var num = Math.floor(Math.random() * (max - min + 1)) + min; return num; } } });
<reponame>bryanvillamil/proyect-Gatbsy import styled from 'styled-components'; import breakpoint from 'styled-components-breakpoint'; export const ContentGetaQuote = styled.div` background: red; padding: 1em; `; export const Container = styled.div` width: 100%; margin: 0 auto; ${breakpoint('tablet')` width: 650px; `} ${breakpoint('desktop')` width: 991px; `} `; export const QuoteTop = styled.div` background: blue; padding: 1em .5em 0; display: flex; justify-content: center; align-items: center; p { text-align: center; } `; export const QuoteBottom = styled.div` background: green; display: flex; justify-content: center; align-items: center; padding: 1em; `;
#!/bin/bash -xe # Validations MANDATORY_ENVS="IMAGE_VERSION BUILD_NUMBER DOCKER_REGISTRY OPERATOR_IMAGE GIT_BRANCH" for envi in $MANDATORY_ENVS; do [ -z "${!envi}" ] && { echo "Error - Env $envi is mandatory for the script."; exit 1; } || : done # Prepare specific tag for the image tags=`build/ci/get_image_tags_from_branch.sh ${GIT_BRANCH} ${IMAGE_VERSION} ${BUILD_NUMBER} ${GIT_COMMIT}` specific_tag=`echo $tags | awk '{print$1}'` # Set latest tag only if its from develop branch or master and prepare tags [ "$GIT_BRANCH" = "develop" -o "$GIT_BRANCH" = "origin/develop" -o "$GIT_BRANCH" = "master" ] && tag_latest="true" || tag_latest="false" # Operator # -------------- operator_registry="${DOCKER_REGISTRY}/${OPERATOR_IMAGE}" operator_tag_specific="${operator_registry}:${specific_tag}" operator_tag_latest=${operator_registry}:latest [ "$tag_latest" = "true" ] && taglatestflag="-t ${operator_tag_latest}" echo "Build and push the Operator image" docker build -t ${operator_tag_specific} $taglatestflag -f build/Dockerfile.operator --build-arg VERSION="${IMAGE_VERSION}" --build-arg BUILD_NUMBER="${BUILD_NUMBER}" . docker push ${operator_tag_specific} [ "$tag_latest" = "true" ] && docker push ${operator_tag_latest} || : set +x echo "" echo "Image ready:" echo " ${operator_tag_specific}" [ "$tag_latest" = "true" ] && { echo " ${operator_tag_specific}"; } || : # if param $1 given the script echo the specific tag [ -n "$1" ] && printf "${operator_tag_specific}" > $1 || :
curl -X POST -H "DD-API-KEY: [[apiKey]]" -H "DD-APPLICATION-KEY: [[apiKey]]" "https://api.datadoghq.com/v1/monitor/mute_all"
def get_validation_rules(config_settings: dict, setting_name: str) -> list: if setting_name in config_settings: return [config_settings[setting_name]] else: return []
#!/bin/sh # # Wrapper script to nosetests # # Usage: run_nose_tests.sh [nose options] test_modules... # # Wrapper script to run tests using nose. # # To run tests: # [cd to minipylib package directory] # ./bin/run_nose_tests.sh minipylib # # To print diagnostic info when running tests: # ./bin/run_nose_tests.sh -D minipylib # # # * created: 2014-08-28 Kevin Chan <kefin@makedostudio.com> # * updated: 2014-09-01 kchan ######################################################################## myname="${0##*/}" OLD_PWD=$PWD cd $(dirname "$0") mydir="${PWD%/}" cd "$OLD_PWD" ######################################################################## ######################################################################## # helper functions verbose=0 usage() { cat <<EOF # Usage: $myname [nose options] test_modules... # options: # -h | --help # print usage and exit # -D # print debug message during tests # # * any other options not listed above will pass to nose. @ # Wrapper script to run tests using nose. # # To run tests: # [cd to minipylib package directory] # ./bin/run_nose_tests.sh minipylib # # To print diagnostic info when running tests: # ./bin/run_nose_tests.sh -D minipylib EOF exit 1 } error() { [ "$1" ] && printf >&2 "### %s\n" "$*" exit 1 } ######################################################################## # execute command NOSETESTS=$(which nosetests) if [ -z "$NOSETESTS" ]; then error "nosetests not found!" fi NOSE_OPTS="--nocapture --nologcapture --with-ignore-docstrings" nose_opts="$NOSE_OPTS" debug_msgs=0 modules= while [ $# -gt 0 ] do case "$1" in -D) debug_msgs=1 ;; -\?|-h|-help|--help) usage ;; -*) nose_opts="$nose_opts $1" ;; *) modules="$modules $1" ;; esac shift done if [ $# -eq 1 ]; then { [ "$1" = "-h" ] || [ "$1" = "--help" ]; } && usage fi # run nosetests cleanup() { unset TEST_DEBUG } trap "cleanup" EXIT if [ "$debug_msgs" -gt 0 ]; then export TEST_DEBUG=1 fi "$NOSETESTS" \ $nose_opts \ $modules cleanup exit
def solveTSP(cities): # Get the number of cities num_cities = len(cities) # Set the initial conditions including # the default distance matrix, visited set, # and an empty tour # distance matrix distance_matrix = [[0 for x in range(num_cities)] for y in range(num_cities)] for i in range(num_cities): for j in range(num_cities): distance_matrix[i][j] = calculateDistance( cities[i], cities[j]) # create visited set visited = [False for i in range(num_cities)] # create an empty tour tour = [] # set the first city as source source = 0 # Find the minimum weight hamiltonian cycle min_cost = find_hamiltonian_cycle(distance_matrix, visited, source, tour) # Print the minimum tour cost and tour path print("Minimum cost:", min_cost) printTour(tour)
from rest_framework import generics, permissions from django.contrib.auth.models import Group from .models import Status, Criticality from .serializers import StatusSerializer, CriticalitySerializer, GroupSerializer class StatusView(generics.ListAPIView): """.""" permission_classes = [permissions.IsAuthenticated] queryset = Status.objects.all() serializer_class = StatusSerializer class GroupView(generics.ListAPIView): """.""" permission_classes = [permissions.IsAuthenticated] queryset = Group.objects.all() serializer_class = GroupSerializer class CriticalityView(generics.ListAPIView): """.""" permission_classes = [permissions.IsAuthenticated] queryset = Criticality.objects.all() serializer_class = CriticalitySerializer
#!/usr/local/bin/bash set -e set -x # pull latest changes ssh roa@95.217.177.163 'cd mataroa && git pull' # sync requirements ssh roa@95.217.177.163 'cd mataroa && source venv/bin/activate && pip install -r requirements.txt' # collect static ssh roa@95.217.177.163 'cd mataroa && source venv/bin/activate && python manage.py collectstatic --noinput' # migrate database ssh roa@95.217.177.163 'cd mataroa && source venv/bin/activate && source .envrc && python manage.py migrate' # reload ssh roa@95.217.177.163 'cd mataroa && source venv/bin/activate && uwsgi --reload mataroa.pid'
var app = { findMinMax: function(numbers) { maximum = numbers[0]; minimum = numbers[0]; for (i = 0; i <= numbers.length - 1; i++) { if (maximum < numbers[i]) { maximum = numbers[i]; } // return large; } for (i = 0; i <= numbers.length - 1; i++) { if (minimum > numbers[i]) { minimum = numbers[i]; } // return smallest; } if (minimum == maximum) { return [minimum]; } return [minimum, maximum]; } } module.exports = app
#!/bin/sh #Make appropriate directories mkdir /usr/share/python-daemon mkdir /var/log/python-daemon mkdir /var/run/python-daemon #move the init script cp fsmetrics /etc/init.d/ #copy all other files to home directory cp * /usr/share/python-daemon/
from pytube import YouTube from tkinter import * def main_program(url): x = YouTube(url) print(x) for i in x.streams.first().download(): print(i) class Main(): def __init__(self): self.win = Tk() #config self.config_title = 'youtube downloader' self.config_width = 450 self.confing_heigt = 350 self.config_resizable = [False, False] self.config_background = '#F36A05' #load functions self.Load_Configs() self.Load_objects() #mainloop mainloop() def Load_Configs(self): self.win.title(self.config_title) self.win.geometry(str(self.config_width) + 'x' + str(self.confing_heigt)) self.win.resizable(self.config_resizable[0], self.config_resizable[1]) self.win.config(bg = self.config_background) def download_click(self): a = self.link_input.get() main_program(a) def Load_objects(self): #space bitween head and text label Label( self.win, text = ' ', background = self.config_background, font = ('Arial', 30) ).pack() Label( self.win, text = "Give me your youtube link: ", foreground = 'black', background = self.config_background, font = ('Arial', 20, 'bold') , ).pack() link_input = Entry( self.win, background = '#FFFFFF', foreground = 'black', width = 64, ) self.link_input = link_input link_input.pack() #space bitween download button and text label Label( self.win, text = ' ', background = self.config_background, font = ('Arial', 30) ).pack() download_button = Button( self.win, text = 'download', background = '#0DF55E', foreground = 'black', border = 5, ) download_button.config(command = self.download_click) download_button.pack() #space Label( self.win, text = ' ', background = self.config_background, font = ('Arial', 80) ).pack() copy = Label( self.win, text = 'Copyright (c) 2021 <NAME>', background = self.config_background, foreground = 'black', font = ('Arial', 10), ) copy.pack() app = Main()
#!/usr/bin/env bash set -e # Ethos Repl database if [ -z "$ETHOS_REPL_DB_PASSWORD" ]; then echo "ERROR: Missing environment variables. Set value for 'ETHOS_REPL_DB_PASSWORD'." exit 1 fi psql -v ON_ERROR_STOP=1 --username postgres --set USERNAME=ethos --set PASSWORD=${ETHOS_REPL_DB_PASSWORD} <<-EOSQL CREATE USER :USERNAME WITH PASSWORD ':PASSWORD'; CREATE DATABASE ethos WITH OWNER = :USERNAME ENCODING = 'UTF-8' CONNECTION LIMIT = -1; EOSQL
import { Disposable } from '../Disposable'; import { Listener } from './Listener'; import { Key, ListenableType, listen, listenOnce, getListener, unlistenByKey } from './index'; import { EventTarget as LEventTarget } from './EventTarget'; import { ListenableKey } from './ListenableKey'; export class EventHandler extends Disposable { private _scope: Object; private _keys: {[key: string]: ListenableKey} = {}; constructor(scope?: any) { super(); this._scope = scope; } protected disposeInternal() { super.disposeInternal(); this.removeAll(); } listen(src: ListenableType, type: string, fn?: Function, options: boolean|AddEventListenerOptions = false, scope?: Object): EventHandler { const listenerObj = listen(src, type, fn || this.handleEvent, options, scope || this._scope || this); if (!listenerObj) { return this; } const key = listenerObj.key; this._keys[key] = listenerObj; return this; } listenOnce(src: ListenableType, type: string, fn?: Function, options: boolean|AddEventListenerOptions = false, scope?: Object): EventHandler { const listenerObj = listenOnce(src, type, fn || this.handleEvent, options, scope || this._scope || this); if (!listenerObj) { return this; } const key = listenerObj.key; this._keys[key] = listenerObj; return this; } unlisten(src: ListenableType, type: string, fn?: Function, options: boolean|AddEventListenerOptions = false, scope?: Object) { const capture = typeof options === 'object' ? !!options.capture : !!options; const listener = getListener(src, type, fn || this.handleEvent, capture, scope || this._scope || this); if (listener) { unlistenByKey(listener); delete this._keys[listener.key]; } return this; } removeAll() { for (let key in this._keys) { let listenerObj = this._keys[key]; if (this._keys.hasOwnProperty(key)) { unlistenByKey(listenerObj); } } this._keys = {}; } getListenerCount(): number { let count = 0; for (let key in this._keys) { if (Object.prototype.hasOwnProperty.call(this._keys, key)) { count++; } } return count; } handleEvent() { throw new Error('EventHandler.handleEvent not implemented'); } }
#Turning Xcompmgr composite effects ON if pgrep xcompmgr &>/dev/null; then pkill xcompmgr & fi if pgrep compton &>/dev/null; then pkill compton & fi notify-send -t 2500 "Turning COMPTON effects ON" compton &
#!/bin/bash # If # (not within Vagrant Guest OS) and (not within Travis) # then # exit 1 if [ `whoami` != "vagrant" ] && [ `whoami` != "travis" ]; then echo The command should be executed within the guest OS! exit 1 fi php app/console cache:clear --env=prod php app/console cache:warmup --env=prod mysql -u root < 00-extra/db/create-empty-database.sql php app/console doctrine:schema:update --force php app/console fos:user:create admin admin@example.net password --super-admin
package ca.tetchel.shexter.sms.util; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.telephony.SmsMessage; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import ca.tetchel.shexter.R; import ca.tetchel.shexter.RingCommandActivity; import ca.tetchel.shexter.ShexterNotificationManager; import ca.tetchel.shexter.eventlogger.EventLogger; import ca.tetchel.shexter.main.MainActivity; import ca.tetchel.shexter.sms.ShexterService; import ca.tetchel.shexter.sms.subservices.SmsSendThread; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_CONTACTS; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_READ; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_RING; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_SEND; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_SEND_INITIALIZER; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_SETPREF; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_SETPREF_LIST; import static ca.tetchel.shexter.sms.util.ServiceConstants.COMMAND_UNREAD; import static ca.tetchel.shexter.sms.util.ServiceConstants.SETPREF_REQUIRED; public class CommandProcessor { private static final String TAG = MainActivity.MASTER_TAG + CommandProcessor.class.getSimpleName(); /** * @return The response to be returned to the client. */ public static String process(Context context, String command, String originalRequest, Contact contact, BufferedReader requestReader) throws IOException { if (COMMAND_SEND_INITIALIZER.equals((command))) { // This command returns the name and number of the contact who will receive the message. if (contact == null) { return "No matching contact was found"; } else { return contact.name() + ", " + contact.preferred(); } } else if (COMMAND_SEND.equals(command)) { return sendCommand(context, contact, requestReader); } else if (COMMAND_READ.equals(command)) { return readCommand(context, contact, requestReader); } else if (COMMAND_UNREAD.equals(command)) { // Unread for a particular contact would need to be passed here return unreadCommand(context, requestReader); } else if (COMMAND_SETPREF_LIST.equals(command)) { Log.d(TAG, "SetPrefList"); // respond to client with list of numbers to select from. StringBuilder listBuilder = new StringBuilder(); listBuilder.append(SETPREF_REQUIRED).append('\n'); listBuilder.append(contact.name()) .append(" has ") .append(contact.count()) .append(" numbers: "); for (int i = 0; i < contact.count(); i++) { listBuilder.append('\n') .append(i + 1) .append(": ") .append(contact.numbers().get(i)); } if (contact.hasPreferred()) { listBuilder.append("\nCurrent: ") .append(contact.preferred()); } EventLogger.log(context, context.getString(R.string.event_command_succeeded), context.getString(R.string.event_setpref_list, contact.name())); return listBuilder.toString(); } else if (COMMAND_SETPREF.equals(command)) { Log.d(TAG, "SetPrefCommand"); // receive the index to set the new preferred number to. int replyIndex = Integer.parseInt(requestReader.readLine()); Log.d(TAG, "Setting pref to " + replyIndex); contact.setPreferred(replyIndex); // Get the original command's data - will do a recursive call to perform it. BufferedReader originalRequestReader = new BufferedReader(new StringReader(originalRequest)); String originalCommand = originalRequestReader.readLine(); // Remove the contact from the original - we already know it originalRequestReader.readLine(); if(COMMAND_SETPREF.equals(originalCommand)) { Log.d(TAG, "Regular setpref success."); String resp = context.getString(R.string.event_setpref, contact.name(), contact.preferred()); EventLogger.log(context, context.getString(R.string.event_command_succeeded), resp); return resp; } else { Log.d(TAG, "SetPref success; now running original command."); // still need to perform the original command return process(context, originalCommand, "", contact, originalRequestReader); } } else if (COMMAND_CONTACTS.equals(command)) { Log.d(TAG, "Contacts command."); try { String allContacts = SmsUtilities.getAllContacts(ShexterService.instance() .getApplicationContext()); if (allContacts != null && !allContacts.isEmpty()) { EventLogger.log(context, context.getString(R.string.event_contacts, allContacts.length())); Log.d(TAG, "Retrieved contacts successfully."); return allContacts; } else { EventLogger.log(context, context.getString(R.string.event_contacts, 0)); Log.d(TAG, "Retrieved NO contacts!"); return "An error occurred getting contacts, or you have no contacts!"; } } catch (SecurityException e) { Log.w(TAG, "No contacts permission for Contacts command!"); EventLogger.logError(context, context.getString(R.string.event_command_failed), e); return "No Contacts permission! Open the app and give Contacts permission."; } } else if (COMMAND_RING.equals(command)) { Log.d(TAG, "Ring command"); return ringCommand(context); } else { EventLogger.logError(context, context.getString(R.string.event_unknown_command, command)); //should never happen return "'" + command + "' is a not a recognized command. " + "Please report this issue on GitHub."; } } private static String sendCommand(Context context, Contact contact, BufferedReader requestReader) throws IOException { Log.d(TAG, "SendCommand"); StringBuilder msgBodyBuilder = new StringBuilder(); //read the message body into msgBodyBuilder int current; char previous = ' '; while ((current = requestReader.read()) != -1) { char chr = (char) current; if (chr == '\n' && previous == '\n') { // Double newline means end-of-send. // It would be preferable for the request to contain a length header. break; } msgBodyBuilder.append(chr); previous = chr; } String messageInput = msgBodyBuilder.toString(); try { Integer numberSent = (new SmsSendThread().execute(contact.preferred(), messageInput)) .get(); /* String preferred = ""; if(!contact.name().equals(contact.preferred())) { // Don't display the preferred twice in the -n case. preferred = ", " + contact.preferred(); }*/ Log.d(TAG, "Send command (probably) succeeded."); String response = context.getString(R.string.event_sent_messages, //numberSent, numberSent != 1 ? "s" : "", contact.name(), preferred); numberSent, numberSent != 1 ? "s" : "", contact.name()); EventLogger.log(context, context.getString(R.string.event_command_succeeded), response); return response; } catch (SecurityException e) { Log.w(TAG, "No SMS Permission for send!", e); EventLogger.logError(context, context.getString(R.string.event_command_failed), e); return "No Send SMS permission! Open the app and give SMS permission."; } catch (Exception e) { Log.e(TAG, "Exception from sendThread", e); EventLogger.logError(context, context.getString(R.string.event_command_failed), e); return "Unexpected exception in the SMS send thread; " + "please report this issue on GitHub."; } } private static String readCommand(Context context, Contact contact, BufferedReader requestReader) throws IOException { Log.d(TAG, "Enter ReadCommand"); int numberToRetrieve = Integer.parseInt(requestReader.readLine()); int outputWidth = Integer.parseInt(requestReader.readLine()); try { String convo = SmsUtilities.getConversation(ShexterService.instance() .getContentResolver(), contact, numberToRetrieve, outputWidth); if (convo != null) { ShexterService.instance().getSmsReceiver() .removeMessagesFromNumber(contact.preferred()); Log.d(TAG, "Responded with convo."); EventLogger.log(context, context.getString(R.string.event_command_succeeded), context.getString(R.string.event_read_messages, contact.name())); return convo; } else { String response = "No messages found with " + contact.name(); if (!contact.name().equals(contact.preferred())) { // Don't display the preferred twice in the -n case. response += ", " + contact.preferred() + "."; } Log.d(TAG, "Responded with no convo."); return response + '.'; } } catch (SecurityException e) { Log.w(TAG, "No Read SMS permission!", e); EventLogger.logError(context, context.getString(R.string.event_command_failed), e); return "No Read SMS permission! Open the app and give SMS permission."; } } private static String unreadCommand(Context context, BufferedReader requestReader) throws IOException { Log.d(TAG, "UnreadCommand"); int outputWidth = Integer.parseInt(requestReader.readLine()); try { List<SmsMessage> unreadMessages = ShexterService.instance().getSmsReceiver() .getAllSms(); List<String> formattedMessages = new ArrayList<>(unreadMessages.size()); List<Long> dates = new ArrayList<>(unreadMessages.size()); for(SmsMessage sms : unreadMessages) { String sender = sms.getOriginatingAddress(); Uri lookupUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(sender)); Cursor c = ShexterService.instance().getContentResolver() .query(lookupUri, new String[]{ ContactsContract.Data.DISPLAY_NAME }, null, null, null); if(c != null) { try { if(c.moveToFirst()) { String displayName = c.getString(0); if(!displayName.isEmpty()) { sender = displayName + ": "; } } } catch (Exception e) { Log.e(TAG, "Exception occurred getting contact name for sms.", e); EventLogger.logError(context, e); } finally { c.close(); } } long timestamp = sms.getTimestampMillis(); formattedMessages.add(SmsUtilities.formatSms(sender, "", sms.getMessageBody(), timestamp, outputWidth)); dates.add(timestamp); } String unread = SmsUtilities.messagesIntoOutput(formattedMessages, dates); EventLogger.log(context, context.getString(R.string.event_command_succeeded), context.getString(R.string.event_unread)); if (!unread.isEmpty()) { unread = "Unread Messages:\n" + unread; Log.d(TAG, "Replying with unread messages."); return unread; } else { Log.d(TAG, "Replying with NO unread messages."); return "No unread messages."; } } catch (SecurityException e) { Log.w(TAG, "No SMS permission for reading."); EventLogger.logError(context, context.getString(R.string.event_command_failed), e); return "No Read SMS permission! Open the app and give SMS permission."; } } private static String ringCommand(Context context) { NotificationManager nm = ShexterNotificationManager.tryGetNotifManager(context); if(nm == null || (MainActivity.isDndPermissionRequired() && !nm.isNotificationPolicyAccessGranted())) { EventLogger.logError(context, context.getString(R.string.event_command_failed), context.getString(R.string.event_no_ring_perm)); return context.getString(R.string.phone_ringing_failure_response); } else { Intent ringIntent = new Intent(context, RingCommandActivity.class); context.startActivity(ringIntent); EventLogger.log(context, context.getString(R.string.event_command_succeeded), context.getString(R.string.event_ring)); return context.getString(R.string.phone_ringing_response); } } }
def mergeSortedList(list1, list2): i = j = 0 merged_list = [] while i < len(list1) and j < len(list2): if list1[i] < list2[j]: merged_list.append(list1[i]) i += 1 else: merged_list.append(list2[j]) j += 1 merged_list += list1[i:] merged_list += list2[j:] return merged_list
import Quick import Nimble class AuthManagerSpec: QuickSpec { override func spec() { describe("Auth Manager") { context("when logging out") { it("should call the completion handler with success") { let manager = Manager.auth waitUntil { done in manager.logout { success in expect(success).to(beTrue()) done() } } } } } } }
#!/bin/sh SCRIPT_ABS_PATH=$(cd "$(dirname "$0")" && pwd) . ${SCRIPT_ABS_PATH}/common-env.sh echo . ${KAFKA_BIN_PATH}/kafka-topics.sh --delete --zookeeper localhost:2181 --topic contextmodel ${KAFKA_BIN_PATH}/kafka-topics.sh --delete --zookeeper localhost:2181 --topic orchestrationservice ${KAFKA_BIN_PATH}/kafka-topics.sh --delete --zookeeper localhost:2181 --topic virtualobject ${KAFKA_BIN_PATH}/kafka-topics.sh --delete --zookeeper localhost:2181 --topic devicecontrol ${KAFKA_BIN_PATH}/kafka-topics.sh --delete --zookeeper localhost:2181 --topic devicecontrol-seq
#!/usr/bin/dash -e # Copyright (c) 2019-2020, Firas Khalil Khana # Distributed under the terms of the ISC License . /home/glaucus/scripts/toolchain/variables . $TSCR/prepare . $TSCR/cross/run . $TSCR/native/run . $TSCR/backup
<reponame>melkishengue/cpachecker /* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 <NAME> * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.predicate; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.cpachecker.core.interfaces.ConfigurableProgramAnalysis; import org.sosy_lab.cpachecker.core.interfaces.Refiner; import org.sosy_lab.cpachecker.cpa.arg.AbstractARGBasedRefiner; import org.sosy_lab.cpachecker.util.CPAs; public abstract class ImpactRefiner implements Refiner { public static Refiner create(ConfigurableProgramAnalysis pCpa) throws InvalidConfigurationException { PredicateCPA predicateCpa = CPAs.retrieveCPAOrFail(pCpa, PredicateCPA.class, ImpactRefiner.class); RefinementStrategy strategy = new ImpactRefinementStrategy( predicateCpa.getConfiguration(), predicateCpa.getSolver(), predicateCpa.getPredicateManager()); return AbstractARGBasedRefiner.forARGBasedRefiner( new PredicateCPARefinerFactory(pCpa).create(strategy), pCpa); } }
<reponame>yjfnypeu/Router-RePlugin<gh_stars>10-100 package com.lzh.router.replugin.core; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import com.lzh.nonview.router.Router; import com.lzh.nonview.router.extras.RouteBundleExtras; /** * 插件间跳转的中间桥接页面。当Router启动一个未被加载的插件的路由时。在加载插件成功后。将会跳转到此页面并恢复之前启动的路由。 * * <p>外部不应该直接跳转至此页面。此页面跳转处应只存在于{@link RePluginRouteCallback}中</p> */ public class RouterBridgeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent.hasExtra(Keys.KEY_URI)) { // 当含有URI值时。直接恢复路由 Uri uri = intent.getParcelableExtra(Keys.KEY_URI); RouteBundleExtras extras = intent.getParcelableExtra(Keys.KEY_EXTRAS); Router.resume(uri, extras).open(this); } else { // 启动插件成功后,将其转回启动的插件(或宿主)中去进行路由恢复 Intent resume = new Intent(); String action = intent.getStringExtra(Keys.KEY_ACTION); resume.setAction(action); resume.putExtras(intent); sendBroadcast(resume); } finish(); } }
import click import os @click.command() @click.argument('filename') def create_file(filename): with open(filename, 'w') as file: file.write('Hello, World!') def test_create_file(runner_): with runner_.isolated_filesystem(): result = runner_.invoke(create_file, ['test.txt']) assert result.exit_code == 0 assert os.path.exists('test.txt') with open('test.txt', 'r') as file: content = file.read() assert content == 'Hello, World!'
import os.path as osp from .recognition_dataset import RecognitionDataset from .registry import DATASETS @DATASETS.register_module() class RawframeDataset(RecognitionDataset): """RawframeDataset dataset for action recognition. The dataset loads raw frames and apply specified transforms to return a dict containing the frame tensors and other information. The ann_file is a text file with multiple lines, and each line indicates the directory to frames of a video, the label of a video, start/end frames of the clip, start/end frames of the video and video frame rate, which are split with a whitespace. Example of a full annotation file: .. code-block:: txt some/directory-1 1 0 120 0 120 30.0 some/directory-2 1 0 120 0 120 30.0 some/directory-3 2 0 120 0 120 30.0 some/directory-4 2 0 120 0 120 30.0 some/directory-5 3 0 120 0 120 30.0 some/directory-6 3 0 120 0 120 30.0 Example of a simple annotation file: .. code-block:: txt some/directory-1 163 1 some/directory-2 122 1 some/directory-3 258 2 some/directory-4 234 2 some/directory-5 295 3 some/directory-6 121 3 Example of a multi-class annotation file: .. code-block:: txt some/directory-1 163 1 3 5 some/directory-2 122 1 2 some/directory-3 258 2 some/directory-4 234 2 4 6 8 some/directory-5 295 3 some/directory-6 121 3 Example of a with_offset annotation file (clips from long videos), each line indicates the directory to frames of a video, the index of the start frame, total frames of the video clip and the label of a video clip, which are split with a whitespace. .. code-block:: txt some/directory-1 12 163 3 some/directory-2 213 122 4 some/directory-3 100 258 5 some/directory-4 98 234 2 some/directory-5 0 295 3 some/directory-6 50 121 3 Args: ann_file (str): Path to the annotation file. pipeline (list[dict | callable]): A sequence of data transforms. test_mode (bool): Store True when building test or validation dataset. Default: False. filename_tmpl (str): Template for each filename. Default: 'img_{:05}.jpg'. multi_class (bool): Determines whether it is a multi-class recognition dataset. Default: False. num_classes (int): Number of classes in the dataset. Default: None. modality (str): Modality of data. Support 'RGB', 'Flow'. Default: 'RGB'. """ def __init__(self, start_index=1, filename_tmpl='img_{:05}.jpg', **kwargs): self.filename_tmpl = filename_tmpl super().__init__(start_index=start_index, **kwargs) def _parse_data_source(self, data_source, data_prefix): record = dict( filename_tmpl=self.filename_tmpl, ) frame_dir = data_source record['rel_frame_dir'] = frame_dir if data_prefix is not None: frame_dir = osp.join(data_prefix, frame_dir) record['frame_dir'] = frame_dir return record
package ordt.output.systemverilog.common; public class SystemVerilogInstance { private SystemVerilogModule mod; private String name; private RemapRuleList rules = null; public SystemVerilogInstance(SystemVerilogModule mod, String name) { this.mod=mod; this.name=name; //System.out.println("SystemVerilogModule new: mod=" + mod.getName() + ", name=" + name); } public SystemVerilogInstance(SystemVerilogModule mod, String name, RemapRuleList rules) { this.mod=mod; this.name=name; this.rules=rules; //System.out.println("SystemVerilogModule new: mod=" + mod.getName() + ", name=" + name); } public SystemVerilogModule getMod() { return mod; } public String getName() { return name; } public void setRemapRules(RemapRuleList rules) { this.rules=rules; } /** add a rule to the list - first in list is highest match priority */ public boolean hasRemapRules() { return rules != null; } /** return the first resulting name of a match */ public String getRemappedSignal(String oldName, Integer sigFrom, Integer sigTo) { return hasRemapRules()? rules.getRemappedName(oldName, sigFrom, sigTo) : oldName; } }
<reponame>msnraju/al-productivity-tools import _ = require("lodash"); import DATATYPE_KEYWORDS from "../maps/data-type-keywords"; import ITokenReader from "../../tokenizers/models/token-reader.model"; import IVariable from "../models/variable.model"; import VARIABLE_KEYWORDS from "../maps/variable-keywords"; import DATATYPE_WEIGHT from "../maps/data-type-weights"; import IToken from "../../tokenizers/models/token.model"; import TokenReader from "../../tokenizers/token-reader"; import Variable from "../components/variable"; export default class VariableReader { static read( tokenReader: ITokenReader, returnType: boolean, resetIndex: number ): IVariable | undefined { const variable: IVariable = new Variable(); variable.name = tokenReader.peekTokenValue(); if (returnType && variable.name === ":") { variable.name = ""; } else { tokenReader.next(); } tokenReader.readWhiteSpaces(); const colon = tokenReader.tokenValue(); if (colon !== ":") { tokenReader.pos = resetIndex; return; } tokenReader.readWhiteSpaces(); variable.dataType = this.getDataType(tokenReader); variable.weight = this.getWeight(tokenReader, variable.dataType); const subType = this.getSubType(tokenReader); variable.value = `${variable.name}: ${variable.dataType}${subType}`; return variable; } private static getSubType(tokenReader: ITokenReader) { const tokens: IToken[] = []; let value = tokenReader.peekTokenValue().toLowerCase(); while ( value !== ";" && value !== ")" && value !== "var" && value !== "begin" ) { tokens.push(tokenReader.token()); value = tokenReader.peekTokenValue().toLowerCase(); } if (value === ";") { tokens.push(tokenReader.token()); tokenReader.readWhiteSpaces(); } return TokenReader.tokensToString(tokens, VARIABLE_KEYWORDS); } private static getDataType(tokenReader: ITokenReader): string { let dataType = tokenReader.tokenValue().toLowerCase(); if (DATATYPE_KEYWORDS[dataType]) { dataType = DATATYPE_KEYWORDS[dataType]; } return dataType; } private static getWeight( tokenReader: ITokenReader, dataType: string ): number { if (dataType.toLowerCase() !== "array") { return DATATYPE_WEIGHT[dataType.toLowerCase()] || 100; } let pos = tokenReader.pos; pos = _.findIndex( tokenReader.tokens, (item) => item.value.toLowerCase() === "of", pos ); if (tokenReader.tokens[pos].value.toLowerCase() === "of") { pos++; tokenReader.readWhiteSpaces(); } const dataType2 = tokenReader.tokens[pos].value.toLowerCase(); if (DATATYPE_KEYWORDS[dataType2]) { tokenReader.tokens[pos].value = DATATYPE_KEYWORDS[dataType2]; } return DATATYPE_WEIGHT[dataType2] || 100; } }
package com.acmvit.acm_app.util.reactive; import android.util.Log; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import java.util.concurrent.atomic.AtomicBoolean; public class SingleLiveEvent<T> extends MutableLiveData<T> { private static final String TAG = "SingleLiveEvent"; private final AtomicBoolean isPending = new AtomicBoolean(false); @MainThread @Override public void setValue(T value) { isPending.compareAndSet(false, true); super.setValue(value); } @Override public void observe( @NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer ) { if (hasActiveObservers()) { Log.w( TAG, "Multiple observers registered but only one will be notified of changes." ); } // Observe the internal MutableLiveData super.observe( owner, t -> { if (isPending.compareAndSet(true, false)) { observer.onChanged(t); } } ); } }
def ai_strategy_tree(state): if is_goal(state): return "Goal" successors = get_successors(state) best_solution = INF for successor in successors: score = max(ai_strategy_tree(successor)) best_solution = min(best_solution, score) return best_solution
<gh_stars>10-100 package io.opensphere.mantle.data.dynmeta.impl; import io.opensphere.core.Toolbox; import io.opensphere.mantle.data.DataTypeInfo; /** * The Class DynamicColumnObjectController. */ public class DynamicMetadataObjectController extends AbstractDynamicMetadataController<Object> { /** * Instantiates a new dynamic column object controller. * * @param tb the tb * @param columnIndex the column index * @param columnName the column name * @param dti the dti */ public DynamicMetadataObjectController(Toolbox tb, int columnIndex, String columnName, DataTypeInfo dti) { super(tb, columnIndex, columnName, dti); } @Override public Class<?> getColumnClass() { return Object.class; } @Override public boolean supportsAppend() { return false; } }
<gh_stars>1-10 require "test/test_helper" class Admin::PostsControllerTest < ActionController::TestCase context "Index" do setup do get :index end should "render index and validates_presence_of_custom_partials" do assert_match "posts#_index.html.erb", @response.body end should "render_index_and_verify_page_title" do assert_select "title", "Posts" end should "render index_and_show_add_entry_link" do assert_select "#sidebar ul" do assert_select "li", "Add new" end end should "render_index_and_show_trash_item_image" do assert_response :success assert_select '.trash', 'Trash' end end context "New" do setup do get :new end should "render new and partials_on_new" do assert_match "posts#_new.html.erb", @response.body end should "render new and verify page title" do assert_select "title", "New Post" end end context "Edit" do setup do get :edit, { :id => Factory(:post).id } end should "render_edit_and_verify_presence_of_custom_partials" do assert_match "posts#_edit.html.erb", @response.body end should "render_edit_and_verify_page_title" do assert_select "title", "Edit Post" end end context "Show" do setup do get :show, { :id => Factory(:post).id } end should "render_show_and_verify_presence_of_custom_partials" do assert_match "posts#_show.html.erb", @response.body end should "render_show_and_verify_page_title" do assert_select "title", "Show Post" end end should "get_index_and_render_edit_or_show_links" do %w(edit show).each do |action| Typus::Resource.expects(:default_action_on_item).at_least_once.returns(action) get :index Post.all.each do |post| assert_match "/posts/#{action}/#{post.id}", @response.body end end end context "Designer" do setup do @typus_user = Factory(:typus_user, :email => "<EMAIL>", :role => "designer") @request.session[:typus_user_id] = @typus_user.id end should "render_index_and_not_show_add_entry_link" do get :index assert_response :success assert_no_match /Add Post/, @response.body end should "render_index_and_not_show_trash_image" do get :index assert_response :success assert_select ".trash", false end end context "Editor" do setup do @typus_user = Factory(:typus_user, :email => "<EMAIL>", :role => "editor") @request.session[:typus_user_id] = @typus_user.id end should "get_index_and_render_edit_or_show_links_on_owned_records" do get :index Post.all.each do |post| action = post.owned_by?(@typus_user) ? "edit" : "show" assert_match "/posts/#{action}/#{post.id}", @response.body end end should "get_index_and_render_edit_or_show_on_only_user_items" do %w(edit show).each do |action| Typus::Resource.stubs(:only_user_items).returns(true) Typus::Resource.stubs(:default_action_on_item).returns(action) get :index Post.all.each do |post| if post.owned_by?(@typus_user) assert_match "/posts/#{action}/#{post.id}", @response.body else assert_no_match /\/posts\/#{action}\/#{post.id}/, @response.body end end end end end end