text
stringlengths
1
1.05M
import tkinter as tk import sys def create_gui_application(): main_win = tk.Tk() # Create the main window main_win.columnconfigure(0, weight=1) # Configure the first column to expand main_win.rowconfigure(0, weight=1) # Configure the first row to expand main_frm = tk.Frame(main_win) # Create a frame inside the main window main_frm.columnconfigure(1, weight=1) # Configure the second column of the frame to expand main_frm.grid(row=0, column=0, sticky="nsew") # Place the frame inside the main window main_win.mainloop() # Enter the main event loop sys.exit() # Gracefully exit the application
SELECT Department_Name, AVG(Hours_Worked) FROM Employees GROUP BY Department_Name;
#!/bin/sh # This file is used both to rebuild the header file and to set the # environment variables on the config call BuildVersion="$Id: writeBuildNum.sh,v 1.28732 2010/05/29 13:12:08 fsg Exp $" BuildType=T MajorVer=5 MinorVer=0 RevNo=0 BuildNum=359 NowAt=`pwd` cd `dirname $0` Root=`pwd` cd $NowAt Root=`dirname $Root` Root=`dirname $Root` if [ "$SPECIAL_BUILD_SUFFIX" = "" ]; then # Normal builds SuffixKind="Initial" SuffixVer="" BuildSuffix="Firebird $MajorVer.$MinorVer" [ "$SuffixKind" = "" ] || BuildSuffix="$BuildSuffix $SuffixKind" [ "$SuffixVer" = "" ] || BuildSuffix="$BuildSuffix $SuffixVer" FIREBIRD_PACKAGE_VERSION="$SuffixKind$SuffixVer" [ "$FIREBIRD_PACKAGE_VERSION" = "" ] && FIREBIRD_PACKAGE_VERSION=0 PRODUCT_VER_STRING="$MajorVer.$MinorVer.$RevNo.$BuildNum" else # Special builds (daily snapshots, etc) BuildSuffix="Firebird $MajorVer.$MinorVer $SPECIAL_BUILD_SUFFIX" FIREBIRD_PACKAGE_VERSION=$SPECIAL_BUILD_SUFFIX PRODUCT_VER_STRING="$MajorVer.$MinorVer.$RevNo.$BuildNum-$SPECIAL_BUILD_SUFFIX" fi FIREBIRD_PACKAGE_VERSION=`echo $FIREBIRD_PACKAGE_VERSION | tr -d '[ ]'` FIREBIRD_VERSION="$MajorVer.$MinorVer.$RevNo" FILE_VER_STRING="WI-$BuildType$MajorVer.$MinorVer.$RevNo.$BuildNum" FILE_VER_NUMBER="$MajorVer, $MinorVer, $RevNo, $BuildNum" if [ $# -eq 3 ] then headerFile=$2 tempfile=$3; else tempfile=gen/test.header.txt headerFile=src/jrd/build_no.h; fi #______________________________________________________________________________ # Routine to build a new jrd/build_no.h file. If required. rebuildHeaderFile() { cat > $tempfile <<eof /* FILE GENERATED BY src/misc/writeBuildNum.sh *** DO NOT EDIT *** TO CHANGE ANY INFORMATION IN HERE PLEASE EDIT src/misc/writeBuildNum.sh FORMAL BUILD NUMBER:$BuildNum */ #define PRODUCT_VER_STRING "$PRODUCT_VER_STRING" #define FILE_VER_STRING "$FILE_VER_STRING" #define LICENSE_VER_STRING "$FILE_VER_STRING" #define FILE_VER_NUMBER $FILE_VER_NUMBER #define FB_MAJOR_VER "$MajorVer" #define FB_MINOR_VER "$MinorVer" #define FB_REV_NO "$RevNo" #define FB_BUILD_NO "$BuildNum" #define FB_BUILD_TYPE "$BuildType" #define FB_BUILD_SUFFIX "$BuildSuffix" eof cmp -s $headerFile $tempfile Result=$? if [ $Result -lt 0 ] then echo "error comparing $tempfile and $headerFile" elif [ $Result -gt 0 ] then echo "updating header file $headerFile" cp $tempfile $headerFile else echo "files are identical" fi } #______________________________________________________________________________ # Routine to build a new gen/make.version file. createMakeVersion() { TmpDir="${TMPDIR:-/tmp}" OdsH="${Root}/src/jrd/ods.h" Mini="${TmpDir}/miniods.h" TestCpp="${TmpDir}/test.cpp" AOut="${TmpDir}/a.out" grep ODS_VERSION $OdsH | grep -v ENCODE_ODS >$Mini cat >$TestCpp <<eof #include <stdlib.h> typedef unsigned short USHORT; #include "$Mini" int main() { return ODS_VERSION; } eof [ -z "$CXX" ] && CXX=g++ $CXX $TestCpp -o $AOut if [ -x $AOut ] then $AOut OdsVersion=$? else OdsVersion=0 fi rm -f $Mini $TestCpp $AOut cat >$1 <<eof # FILE GENERATED BY src/misc/writeBuildNum.sh # *** DO NOT EDIT *** # TO CHANGE ANY INFORMATION IN HERE PLEASE # EDIT src/misc/writeBuildNum.sh # FORMAL BUILD NUMBER:$BuildNum MajorVer = $MajorVer MinorVer = $MinorVer RevNo = $RevNo BuildNum = $BuildNum BuildType = $BuildType BuildSuffix = $BuildSuffix PackageVersion = $FIREBIRD_PACKAGE_VERSION FirebirdVersion = $FIREBIRD_VERSION OdsVersion = $OdsVersion eof } if [ "$1" = "rebuildHeader" ] then rebuildHeaderFile elif [ "$1" = "createMakeVersion" ] then if [ -z "$2" ] then createMakeVersion gen/Make.Version else createMakeVersion "$2" fi elif [ "$1" = "--version" ] then echo "" echo "Build Version : " $BuildType$PRODUCT_VER_STRING $BuildSuffix echo "" #echo "($BuildVersion)" echo "(`echo $BuildVersion | cut -c3-60` )" fi
<form> <label>Name:</label> <input type="text" name="name" /> <br/> <label>Age:</label> <input type="number" name="age" /> <br/> <label>Gender:</label> <select name="gender"> <option value="male">Male</option> <option value="female">Female</option> </select> <br/> <label>Occupation:</label> <input type="text" name="occupation" /> <br/> <label>Nationality:</label> <input type="text" name="nationality" /> <br/> <input type="submit" value="Submit" /> </form>
#include <xc.h> #include "Hardware.h" // ---------------------------------------------------------------------------- // OscillatorModule_InternalClockFrequency // ---------------------------------------------------------------------------- enum OscillatorModule_InternalClockFrequency_Constants { HF_16MHz = 0b1111, HF_8MHz = 0b1110, HF_4MHz = 0b1101, HF_2MHz = 0b1100, HF_1MHz = 0b1011, HF_500kHz = 0b1010, HF_250kHz = 0b1001, HF_125kHz = 0b1000, MF_500kHz = 0b0111, MF_250kHz = 0b0110, MF_125kHz = 0b0101, MF_62500Hz = 0b0100, HF_31250Hz = 0b0011, MF_31250Hz = 0b0010, LF_31kHz = 0b0001, }; const struct OscillatorModule_InternalClockFrequency OscillatorModule_InternalClockFrequency = { HF_16MHz, HF_8MHz, HF_4MHz, HF_2MHz, HF_1MHz, HF_500kHz, HF_250kHz, HF_125kHz, MF_500kHz, MF_250kHz, MF_125kHz, MF_62500Hz, HF_31250Hz, MF_31250Hz, LF_31kHz, }; // ---------------------------------------------------------------------------- // OscillatorModule_PhaseLockedLoop // ---------------------------------------------------------------------------- enum OscillatorModule_PhaseLockedLoop_Constants { ENABLE = 1, DISABLE = 0, }; const struct OscillatorModule_PhaseLockedLoop OscillatorModule_PhaseLockedLoop = { ENABLE, DISABLE, }; // ---------------------------------------------------------------------------- // OscillatorModule_SystemClockSource // ---------------------------------------------------------------------------- enum OscillatorModule_SystemClockSource_Constants { INTERNAL = 0b10, SECONDARY = 0b01, DETERMINED_BY_CONFIG = 0b00, }; const struct OscillatorModule_SystemClockSource OscillatorModule_SystemClockSource = { INTERNAL, SECONDARY, DETERMINED_BY_CONFIG, }; void OscillatorModule_configure( char internalClockFrequency, char phaseLockedLoop, char systemClockSource) { OSCCONbits.IRCF = internalClockFrequency; OSCCONbits.SPLLEN = phaseLockedLoop; OSCCONbits.SCS = systemClockSource; }
<gh_stars>10-100 class CreateSkills < ActiveRecord::Migration def change create_table :skills do |t| t.timestamps null: false t.string :name end add_index :skills, :name, unique: true create_join_table :auctions, :skills end end
#!/usr/bin/env bash # A helper script for quickly tearing down the containers and rebuilding them. DOCKER_MACHINE_NAME=docker-vsphere-js LOCAL_DATA_SOURCE=/Users/jsanford/data/NBNDP DOCKER_DATA_TARGET=/home/docker docker pull mysql:5.6 docker pull unblibraries/fedora-solr-gsearch:3.8.x docker pull unblibraries/drupal:apache docker-compose stop docker-compose rm cd drupal docker build . cd .. docker-compose build # docker-machine scp -r ${LOCAL_DATA_SOURCE} ${DOCKER_MACHINE_NAME}:${DOCKER_DATA_TARGET} docker-compose up -d
<filename>src/main/java/com/movella/service/MovelService.java<gh_stars>0 package com.movella.service; import java.util.Base64; import java.util.UUID; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.movella.dao.MovelDAO; import com.movella.exceptions.InvalidDataException; import com.movella.model.Usuario; import com.movella.responses.BadRequest; import com.movella.responses.Forbidden; import com.movella.responses.Success; import com.movella.utils.Localization; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import spark.*; public class MovelService { public static Route create = (Request req, Response res) -> { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); if (sessionUsuario.getAcesso().equals("normal")) return new Forbidden(res); final JsonObject body = JsonParser.parseString(req.body()).getAsJsonObject(); final JsonElement _nome = body.get("nome"); final JsonElement _categoria = body.get("categoria"); final JsonElement _descricao = body.get("descricao"); final JsonElement _valorMes = body.get("valorMes"); final JsonElement _altura = body.get("altura"); final JsonElement _largura = body.get("largura"); final JsonElement _espessura = body.get("espessura"); if (_nome == null) return new BadRequest(res, Localization.invalidName); if (_categoria == null) return new BadRequest(res, Localization.invalidCategory); if (_descricao == null) return new BadRequest(res, Localization.invalidDescription); if (_valorMes == null) return new BadRequest(res, Localization.invalidMonthlyValue); if (_altura == null) return new BadRequest(res, Localization.invalidHeight); if (_largura == null) return new BadRequest(res, Localization.invalidWidth); if (_espessura == null) return new BadRequest(res, Localization.invalidThickness); final String nome = _nome.getAsString(); final int categoriaId = _categoria.getAsInt(); final String descricao = _descricao.getAsString(); final double valorMes = Double .parseDouble(_valorMes.getAsString().replace(",", "!").replace(".", "").replace("!", ".")); final double altura = _altura.getAsDouble(); final double largura = _largura.getAsDouble(); final double espessura = _espessura.getAsDouble(); try { MovelDAO.insert(categoriaId, sessionUsuario.getId(), descricao, "movel-default.png", nome, valorMes, true, altura, largura, espessura); return new Success(res, Localization.furnitureCreateSuccess); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; public static Route adminAll = (Request req, Response res) -> { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); if (!sessionUsuario.getAcesso().equals("admin")) return new Forbidden(res); try { final JsonArray out = new JsonArray(); MovelDAO.all().forEach((v) -> { out.add(v.toJson()); }); return new Success(res, out); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; public static Route all = (Request req, Response res) -> { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); if (sessionUsuario.getAcesso().equals("normal")) return new Forbidden(res); final int id = sessionUsuario.getId(); try { final JsonArray out = new JsonArray(); MovelDAO.all(id).forEach((v) -> { out.add(v.toJson()); }); return new Success(res, out); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; public static Route pagination = (Request req, Response res) -> { final JsonObject body = JsonParser.parseString(req.body()).getAsJsonObject(); final JsonElement _limit = body.get("limit"); final JsonElement _offset = body.get("offset"); final JsonElement _categoria = body.get("categoria"); final JsonElement _filtro = body.get("filtro"); final JsonElement _disponivel = body.get("disponivel"); final JsonElement _order = body.get("order"); if (_limit == null) return new BadRequest(res, Localization.invalidLimit); if (_offset == null) return new BadRequest(res, Localization.invalidOffset); if (_categoria == null) return new BadRequest(res, Localization.invalidCategory); if (_filtro == null) return new BadRequest(res, Localization.invalidFilter); if (_disponivel == null) return new BadRequest(res, Localization.invalidDisponivel); if (_order == null) return new BadRequest(res, Localization.invalidOrder); final int limit = _limit.getAsInt(); final int offset = _offset.getAsInt(); final String categoria = _categoria.getAsString(); final String filtro = _filtro.getAsString(); final Boolean disponivel = _filtro.getAsBoolean(); final String order = _order.getAsString(); try { String usuarioNome = ""; try { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); usuarioNome = sessionUsuario.getNome(); } catch (Exception e) { } final JsonObject out = new JsonObject(); final JsonArray array = new JsonArray(); final int qntPages = MovelDAO.getPages(limit, offset, categoria, filtro, disponivel, order); out.add("moveis", array); out.addProperty("qntPages", qntPages); MovelDAO.pagination(limit, offset, categoria, filtro, disponivel, order, usuarioNome).forEach((v) -> { array.add(v.toJson()); }); return new Success(res, out); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; public static Route upload = (Request req, Response res) -> { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); final String _id = req.params("id"); final String body = req.body(); if (_id == null) return new BadRequest(res, Localization.invalidId); int id; try { id = Integer.parseInt(_id); } catch (Exception e) { return new BadRequest(res, Localization.invalidId); } try { final String name = UUID.randomUUID().toString(); try { final byte[] bytes = Base64.getDecoder().decode(body.replaceAll(".+,(.+)", "$1")); final Region region = Region.US_EAST_2; final S3Client s3 = S3Client.builder() .region(region) .build(); final PutObjectRequest putOb = PutObjectRequest.builder() .bucket(System.getenv("S3_BUCKET_NAME")) .key(name) .acl("public-read") .build(); s3.putObject(putOb, RequestBody.fromBytes(bytes)); } catch (Exception e) { System.out.println(e.getStackTrace()); } final int maxId = MovelDAO.maxUploadId(); MovelDAO.upload(id == 0 ? maxId : id, sessionUsuario.getId(), name); return new Success(res, Localization.furniturePictureUploadSuccess); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; public static Route delete = (Request req, Response res) -> { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); if (sessionUsuario.getAcesso().equals("normal")) return new Forbidden(res); final JsonObject body = JsonParser.parseString(req.body()).getAsJsonObject(); final JsonElement _id = body.get("id"); if (_id == null) return new BadRequest(res, Localization.invalidId); final int usuarioId = sessionUsuario.getId(); final int id = _id.getAsInt(); try { MovelDAO.delete(id, usuarioId); return new Success(res, Localization.furnitureDeleteSuccess); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; public static Route adminDelete = (Request req, Response res) -> { final Session session = req.session(); final Usuario sessionUsuario = (Usuario) session.attribute("user"); if (!sessionUsuario.getAcesso().equals("admin")) return new Forbidden(res); final JsonObject body = JsonParser.parseString(req.body()).getAsJsonObject(); final JsonElement _id = body.get("id"); if (_id == null) return new BadRequest(res, Localization.invalidId); final int id = _id.getAsInt(); try { MovelDAO.delete(id); return new Success(res, Localization.furnitureDeleteSuccess); } catch (InvalidDataException e) { return new BadRequest(res, e.message); } catch (RuntimeException e) { return new BadRequest(res); } }; }
<filename>src/Etterna/Models/Misc/Game.cpp #include "Etterna/Globals/global.h" #include "Game.h" TapNoteScore Game::MapTapNoteScore(TapNoteScore tns) const { switch (tns) { case TNS_W1: return m_mapW1To; case TNS_W2: return m_mapW2To; case TNS_W3: return m_mapW3To; case TNS_W4: return m_mapW4To; case TNS_W5: return m_mapW5To; default: return tns; } } static const Game::PerButtonInfo g_CommonButtonInfo[] = { { GameButtonType_Menu }, // GAME_BUTTON_MENULEFT { GameButtonType_Menu }, // GAME_BUTTON_MENURIGHT { GameButtonType_Menu }, // GAME_BUTTON_MENUUP { GameButtonType_Menu }, // GAME_BUTTON_MENUDOWN { GameButtonType_Menu }, // GAME_BUTTON_START { GameButtonType_Menu }, // GAME_BUTTON_SELECT { GameButtonType_Menu }, // GAME_BUTTON_BACK { GameButtonType_Menu }, // GAME_BUTTON_COIN { GameButtonType_Menu }, // GAME_BUTTON_OPERATOR { GameButtonType_Menu }, // GAME_BUTTON_EFFECT_UP { GameButtonType_Menu }, // GAME_BUTTON_EFFECT_DOWN { GameButtonType_Menu }, // GAME_BUTTON_RESTART }; const Game::PerButtonInfo* Game::GetPerButtonInfo(GameButton gb) const { COMPILE_ASSERT(GAME_BUTTON_NEXT == ARRAYLEN(g_CommonButtonInfo)); if (gb < GAME_BUTTON_NEXT) return &g_CommonButtonInfo[gb]; return &m_PerButtonInfo[gb - GAME_BUTTON_NEXT]; } TapNoteScore Game::GetMapJudgmentTo(TapNoteScore tns) const { switch (tns) { case TNS_W1: return m_mapW1To; case TNS_W2: return m_mapW2To; case TNS_W3: return m_mapW3To; case TNS_W4: return m_mapW4To; case TNS_W5: return m_mapW5To; default: return TapNoteScore_Invalid; } } // lua start #include "Etterna/Models/Lua/LuaBinding.h" /** @brief Allow Lua to have access to the Game. */ class LunaGame : public Luna<Game> { public: static int GetName(T* p, lua_State* L) { lua_pushstring(L, p->m_szName); return 1; } static int CountNotesSeparately(T* p, lua_State* L) { lua_pushstring(L, "deprecated use GAMESTATE function instead"); return 1; } DEFINE_METHOD(GetMapJudgmentTo, GetMapJudgmentTo(Enum::Check<TapNoteScore>(L, 1))) DEFINE_METHOD(GetSeparateStyles, m_PlayersHaveSeparateStyles); LunaGame() { ADD_METHOD(GetName); ADD_METHOD(CountNotesSeparately); ADD_METHOD(GetMapJudgmentTo); ADD_METHOD(GetSeparateStyles); } }; LUA_REGISTER_CLASS(Game) // lua end
<gh_stars>0 package list4.e1; import org.junit.*; import static org.junit.Assert.*; import java.util.*; import br.edu.fatecfranca.list4.e1.*; public class PassengerTest { private Passenger passenger; private Reserve reserve; @Before public void setUp() { passenger = new Passenger(); reserve = new Reserve(2, new Flight()); } @Test public void testCreationName() { assertEquals("Daniel", passenger.getName()); } @Test public void testSetReserve() { passenger.setReserve(reserve); assertEquals(2, passenger.getReserve().getId()); } @Test public void testGetReserve() { passenger.setReserve(reserve); assertEquals(reserve, passenger.getReserve()); } @Test public void testShow() { assertEquals("Passenger Name: Daniel Reserve Id: 1", passenger.show()); } }
<reponame>imsnif/bit-envs export { getBabelDynamicPackageDependencies, babelFindConfiguration, getPresetPackageName, getPluginPackageName } from './babel-dependencies'
import { Schema, Document } from "mongoose"; import { Timestamps } from "../timestamp"; export interface ICronJob extends Document, Timestamps { name: string; lastStartDate: Date; lastErrorDate: Date; lastError: string; lastSuccessDate: Date; lastSuccessStartDate: Date; running: boolean; } const CronJobSchema = new Schema<ICronJob>( { name: { type: String, unique: true, index: true, required: true }, lastStartDate: { type: Date, default: null }, lastErrorDate: { type: Date, default: null }, lastError: { type: String, default: null }, lastSuccessDate: { type: Date, default: null }, lastSuccessStartDate: { type: Date, default: null }, running: { type: Boolean, default: false }, }, { timestamps: true } ); export default CronJobSchema;
const app = new Vue({ el:'#app', data: { hexColor: '', hexColor2: '', hexColo3: '', hexColor4: '', }, mounted() { let colors = document.querySelectorAll('.col'); for(let index = 0; index < colors.length; index++) { this.hexColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16); this.hexColor2 = '#'+(Math.random()*0xFFFFFF<<0).toString(16); this.hexColor3= '#'+(Math.random()*0xFFFFFF<<0).toString(16); this.hexColor4 = '#'+(Math.random()*0xFFFFFF<<0).toString(16); colors[index].style.backgroundColor = this.hexColor; } }, methods: { randomHex() { let colors = document.querySelectorAll('.col'); for(let index = 0; index < colors.length; index++) { this.hexColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16); this.hexColor2 = '#'+(Math.random()*0xFFFFFF<<0).toString(16); this.hexColor3= '#'+(Math.random()*0xFFFFFF<<0).toString(16); this.hexColor4 = '#'+(Math.random()*0xFFFFFF<<0).toString(16); colors[0].style.backgroundColor = this.hexColor; colors[1].style.backgroundColor = this.hexColor2; colors[2].style.backgroundColor = this.hexColor3; colors[3].style.backgroundColor = this.hexColor4; } }, } })
#!/usr/bin/env bash # # Copyright 2021 Fabiano Fidêncio # # SPDX-License-Identifier: Apache-2.0 # KATA_DEPLOY_DIR="`dirname $0`/../" KATA_DEPLOY_ARTIFACT="$1" echo "Copying $KATA_DEPLOY_ARTIFACT to $KATA_DEPLOY_DIR" cp $KATA_DEPLOY_ARTIFACT $KATA_DEPLOY_DIR pushd $KATA_DEPLOY_DIR IMAGE_TAG="quay.io/kata-containers/kata-deploy-cc:v0" echo "Building the image" docker build --tag $IMAGE_TAG . echo "Pushing the image to quay.io" docker push $IMAGE_TAG popd
#!/bin/bash set -e if [[ ! -d ~/src ]]; then mkdir ~/src fi if [[ ! -d ~/src/iSniff-GPS ]]; then cd ~/src git clone https://github.com/hubert3/iSniff-GPS.git fi if ! dpkg --status virtualenv > /dev/null 2>&1 ; then apt-get update apt-get install -y virtualenv fi if [[ ! -d ~/src/iSniff-GPS/.env ]]; then cd ~/src/iSniff-GPS virtualenv --no-site-packages .env # shellcheck disable=SC1091 . .env/bin/activate && pip install -U -r requirements.txt # shellcheck disable=SC1091 . .env/bin/activate && pip install scapy # shellcheck disable=SC1091 . .env/bin/activate && ./manage.py syncdb fi
<reponame>GMcD/telar-web package config type ( Configuration struct { BaseRoute string QueryPrettyURL bool Debug bool // Debug enables verbose logging of claims / cookies } ) // CollectiveConfig holds the configuration values from collectives_config.yml file var CollectiveConfig Configuration
<reponame>jdemeuse1204/OR-M-Data-Entities<filename>OR-M Data Entities/OR-M Data Entities.Tests.Database/dbo/Tables/Agent.sql CREATE TABLE [dbo].[Agent] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Name] VARCHAR(50) NULL, CONSTRAINT [PK_Agent] PRIMARY KEY CLUSTERED ([Id] ASC) )
<gh_stars>0 #ifndef _TONE32_h #define _TONE32_h #define TONE_CHANNEL 15 #include "Arduino.h" #include "pitches.h" void tone32(uint8_t pin, unsigned int frequency, unsigned long duration = 0, uint8_t channel = TONE_CHANNEL); void noTone32(uint8_t pin, uint8_t channel = TONE_CHANNEL); #endif
<gh_stars>0 #pragma once #include "util/math_tables.hh" #include <cmath> #include <cstdint> #include <cstdlib> namespace MathTools { #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288f #endif template<typename Tval, typename Tin, typename Tout> static constexpr Tout map_value(const Tval x, const Tin in_min, const Tin in_max, const Tout out_min, const Tout out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } template<typename T> static constexpr T constrain(const T val, const T min, const T max) { return val < min ? min : val > max ? max : val; } template<typename T> static constexpr T max(const T val1, const T val2) { if (val1 > val2) { return val1; } else { return val2; } } template<typename T> static constexpr T min(const T val1, const T val2) { if (val1 < val2) { return val1; } else { return val2; } } inline float interpolate(float in1, float in2, float phase) { return (in2 * phase) + in1 * (1.0f - phase); } template<class T> T randomNumber(T minNum, T maxNum) { return map_value<int, long, T>(std::rand(), 0, RAND_MAX, minNum, maxNum); } template<unsigned int N> struct Log2 { enum { val = Log2<N / 2>::val + 1 }; }; template<> struct Log2<1> { enum { val = 0 }; }; constexpr bool is_power_of_2(unsigned int v) { return v && ((v & (v - 1)) == 0); } // Todo: log2_ceiling() constexpr unsigned int log2_floor(const unsigned int x) { int i = 32; while (i--) { if (x & (1UL << i)) return i; } return 0; } constexpr unsigned int ipow(unsigned int a, unsigned int b) { return b == 0 ? 1 : a * ipow(a, b - 1); } // Todo: this needs a better name template<typename T> constexpr unsigned int bipolar_type_range(T val) { return ipow(2, (sizeof(val) * 8) - 1) - 1; } template<uint32_t Max, typename T = uint32_t> T wrap(T val) { while (val >= Max) val -= Max; return val; } constexpr float f_abs(float x) { return (x >= 0.f) ? x : -x; } template<typename T> constexpr T diff(T a, T b) { return (a > b) ? (a - b) : (b - a); } // [0..1] --> [-1..1] // 0.00 => 0 // 0.25 => -1 // 0.50 => 0 // 0.75 => 1 // 1.00 => 0 constexpr float faster_sine(float x) { x = (x * 2.f) - 1.f; return 4.f * (x - x * f_abs(x)); } constexpr uint16_t swap_bytes16(uint16_t halfword) { return ((halfword & 0xFF) << 8) | (halfword >> 8); } constexpr uint32_t swap_bytes32(uint32_t word) { return ((word & 0x000000FF) << 24) | ((word & 0x0000FF00) << 8) | ((word & 0x00FF0000) >> 8) | (word >> 24); } constexpr uint32_t swap_bytes_and_combine(uint16_t halfword1, uint16_t halfword2) { return ((halfword1 & 0xFF) << 24) | ((halfword1 & 0xFF00) << 8) | ((halfword2 & 0x00FF) << 8) | (halfword2 >> 8); } constexpr float setPitchMultiple(float val) { float pitchMultiple = 1; if (val >= 0) pitchMultiple = exp5Table.interp(constrain(val, 0.0f, 1.0f)); else { float invertPitch = val * -1.0f; pitchMultiple = 1.0f / exp5Table.interp(constrain(invertPitch, 0.0f, 1.0f)); } return pitchMultiple; } static inline float audioFreqToNorm(float input) // normalized filter frequency conversion { float output = 0; input = constrain(input, 20.0f, 20000.0f); float temp1 = logTable.interp(map_value(input, 20.0f, 20000.0f, 0.0f, 1.0f)); output = (temp1 - 2.99573f) / (6.90776f); return output; } // Returns 2^x static inline float pow2(float x) { x = x / 5.0f; float res = 1.f; for (;;) { if (x < 1.f) { // Note: exp5Table.interp(x) = 2^(x*5), where 0 <= x <= 1 res *= exp5Table.interp(x); break; } else { res *= 32.f; x -= 1.f; } } return res; } static inline float sin(float x) { return sinTable.interp_wrap(x / (2.f * M_PI)); } // static inline float sin01(float x) { return sinTable.interp_wrap(x); } static inline float cos(float x) { return sinTable.interp_wrap((x / (2.f * M_PI)) + 0.25f); } static inline float cos_close(float x) { return sinTable.closest_wrap((x / (2.f * M_PI)) + 0.25f); } static inline float tan(float x) { return tanTable.interp_wrap(x / M_PI); } static inline float tan_close(float x) { return tanTable.closest_wrap(x / M_PI); } // Apply a hysteresis threshold on a gate signal. Assumes 0.0f = off, 1.0f = on // Converts a real-world analog signal (0.f to 1.0f) to a clean gate (0 or 1, but not in between) // and debounces chatter when crossing the threshold -- without introducing delay like debouncers typically do. // Slightly slower than hysteresis_feedback(), but with more intuitive parameters. // The input must exceed the turn_on threshold to make the output 1 // and must go below turn_off threshold to make the output 0 // Returns updated output, which should be passed as old_val the next time the function is called static inline float hysteresis_gate(float turn_off_thresh, float turn_on_thresh, float last_output, float new_input) { float feedback_amt = (turn_on_thresh - turn_off_thresh) * 0.5f; float feedback = feedback_amt * last_output; float test_signal = new_input + feedback; float threshold = (turn_on_thresh + turn_off_thresh) * 0.5f; return test_signal > threshold ? 1.f : 0.f; } // Apply a hysteresis threshold on a gate signal. Assumes 0.0f = off, 1.0f = on // Converts a real-world analog signal (0.f to 1.0f) to a clean gate (0 or 1, but not in between) // and debounces chatter when crossing the threshold -- without introducing delay like debouncers typically do. // Slightly faster version of hysteresis_gate(), where the two params are half the sum/difference of the on/off thresholds // @param: feedback_coef: feedback amount (typically a small value, 0.1 for example) // @param: thresh: threshold for turning on or off, after applying feedback. Typically 0.5f; // @param: last_output: the last output value (0.f or 1.f) // @param: new_input: the input value (0.f to 1.0f) // The input must exceed the turn_on threshold to make the output 1 // and must go below turn_off threshold to make the output 0 // Returns updated output, which should be passed as old_val the next time the function is called static inline float hysteresis_feedback(float feedback_coef, float thresh, float last_output, float new_input) { return (new_input + last_output * feedback_coef) > thresh ? 1.f : 0.f; } }; // namespace MathTools
<gh_stars>1-10 import * as t from './constants'; type Action = { type: string, payload?: any, error?: boolean, meta?: any, } export function updateRequest(contentType: string, text: string, id?: number): Action { return {type: t.UPDATE_REQUEST, payload: text, meta: {contentType, id}}; } export function updateName(scenarioName: string): Action { return {type: t.UPDATE_NAME, payload: scenarioName}; } export function updateJson(jsonStr: string, contentType: string): Action { try { const jsonObj = JSON.parse(jsonStr); return {type: t.UPDATE_JSON, payload: jsonObj, meta: contentType, rawPayload: jsonStr}; } catch (_) { return {type: t.UPDATE_JSON_FAILED, meta: contentType, rawPayload: jsonStr}; } } export function updateInitializationScript(json: string): Action { return {type: t.UPDATE_DATABASE_INITALIZATION_QUERY, payload: json}; } export function updateSelect(query: string): Action { return {type: t.UPDATE_DATABASE_ASSERTION_QUERY, payload: query}; } export function updateExpected(expectedCsv: string): Action { return {type: t.UPDATE_EXPECTED_DATABASE, payload: expectedCsv}; } export function initializeDatabase(): Action { return {type: t.INITIALIZE_DATABASE}; } export function assertDatabaseValues(): Action { return {type: t.ASSERT_DATABASE_VALUES}; } export function postJson(): Action { return {type: t.POST_JSON}; } export function newScenario(): Action { return {type: t.NEW_SCENARIO}; } export function saveScenario(): Action { return {type: t.SAVE_SCENARIO}; } export function runScenario(): Action { return {type: t.RUN_SCENARIO}; } export function loadScenarios(): Action { return {type: t.LOAD_SCENARIOS}; } export function selectScenario(name: string): Action { return {type: t.SELECT_SCENARIO, payload: name}; } export function selectAndRunScenario(name: string): Action { return {type: t.SELECT_AND_RUN_SCENARIO, payload: name}; }
<reponame>wongoo/alipay-sdk-java-all package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.eco.edu.kt.settleinfo.query response. * * @author auto create * @since 1.0, 2021-05-20 10:50:21 */ public class AlipayEcoEduKtSettleinfoQueryResponse extends AlipayResponse { private static final long serialVersionUID = 6398442954682356811L; /** * 账户类型 */ @ApiField("account_type") private String accountType; /** * 账户名 */ @ApiField("bank_account_name") private String bankAccountName; /** * 账户(脱敏) */ @ApiField("bank_account_no") private String bankAccountNo; /** * 银行名称 */ @ApiField("bank_name") private String bankName; /** * 退票时间,格式为yyyy-MM-dd HH:mm:ss。 */ @ApiField("dishonoured_time") private String dishonouredTime; /** * 结算失败(退票)的原因码(结算失败或退票消息为必选字段)。 ACCOUNT_NOT_MATCH:银行校验账号和户名不一致; ACCOUNT_DISABLED:银行账户不可用; DEFAULT_MSG:处理延时,请等待,系统稍后将自动重试; */ @ApiField("fail_code") private String failCode; /** * 结算失败(退票)的原因描述(结算失败或退票为必选)。 ACCOUNT_NOT_MATCH:银行校验账号和户名不一致; ACCOUNT_DISABLED:银行账户不可用; DEFAULT_MSG:处理延时,请等待,系统稍后将自动重试; */ @ApiField("fail_desc") private String failDesc; /** * 净结算金额,取值范围[0.01,100000000],精确到小数点后2位。 */ @ApiField("settle_amount") private String settleAmount; /** * 净结算金额的币种 */ @ApiField("settle_currency") private String settleCurrency; /** * 支付宝结算单据号 */ @ApiField("settle_id") private String settleId; /** * 本次结算对应的结算周期的起始时间(包含此时间点),格式为yyyy-MM-dd HH:mm:ss。 例如,若按天结算,日切点为0点时,某一笔的结算周期时间为: settle_period_begin_time = 2018-01-01 00:00:00 settle_period_end_time = 2018-01-02 00:00:00 */ @ApiField("settle_period_begin_time") private String settlePeriodBeginTime; /** * 本次结算对应的结算周期的起始时间(不包含此时间点),格式为yyyy-MM-dd HH:mm:ss。 例如,若按天结算,日切点为0点时,某一笔的结算周期时间为: settle_period_begin_time = 2018-01-01 00:00:00 settle_period_end_time = 2018-01-02 00:00:00 */ @ApiField("settle_period_end_time") private String settlePeriodEndTime; /** * 结算成功时间,格式为yyyy-MM-dd HH:mm:ss。 */ @ApiField("settle_time") private String settleTime; /** * 结算状态 0 成功 1 失败 2 退票 */ @ApiField("status") private String status; public void setAccountType(String accountType) { this.accountType = accountType; } public String getAccountType( ) { return this.accountType; } public void setBankAccountName(String bankAccountName) { this.bankAccountName = bankAccountName; } public String getBankAccountName( ) { return this.bankAccountName; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getBankAccountNo( ) { return this.bankAccountNo; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankName( ) { return this.bankName; } public void setDishonouredTime(String dishonouredTime) { this.dishonouredTime = dishonouredTime; } public String getDishonouredTime( ) { return this.dishonouredTime; } public void setFailCode(String failCode) { this.failCode = failCode; } public String getFailCode( ) { return this.failCode; } public void setFailDesc(String failDesc) { this.failDesc = failDesc; } public String getFailDesc( ) { return this.failDesc; } public void setSettleAmount(String settleAmount) { this.settleAmount = settleAmount; } public String getSettleAmount( ) { return this.settleAmount; } public void setSettleCurrency(String settleCurrency) { this.settleCurrency = settleCurrency; } public String getSettleCurrency( ) { return this.settleCurrency; } public void setSettleId(String settleId) { this.settleId = settleId; } public String getSettleId( ) { return this.settleId; } public void setSettlePeriodBeginTime(String settlePeriodBeginTime) { this.settlePeriodBeginTime = settlePeriodBeginTime; } public String getSettlePeriodBeginTime( ) { return this.settlePeriodBeginTime; } public void setSettlePeriodEndTime(String settlePeriodEndTime) { this.settlePeriodEndTime = settlePeriodEndTime; } public String getSettlePeriodEndTime( ) { return this.settlePeriodEndTime; } public void setSettleTime(String settleTime) { this.settleTime = settleTime; } public String getSettleTime( ) { return this.settleTime; } public void setStatus(String status) { this.status = status; } public String getStatus( ) { return this.status; } }
#!/usr/bin/env bash pytest -n 3 --durations=20 --timeout=300 --dist load --timeout-method=thread -v $1
#! /bin/sh TAG=${1:-'0.1.4'} cd .. mvn clean compile assembly:single@yahcli-jar cd - run/refresh-jar.sh docker build -t yahcli:$TAG .
<filename>testsuite/prometheus/src/test/java/io/smallrye/opentelemetry/sdk/prometheus/TestDoubleCounter.java package io.smallrye.opentelemetry.sdk.prometheus; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.Labels; import io.opentelemetry.api.metrics.DoubleCounter; class TestDoubleCounter extends AbstractTestBase { @Test void testPrometheusOutputWithoutLabels() { DoubleCounter doubleCounter = OpenTelemetry.getGlobalMeter("nonsense-value") .doubleCounterBuilder("doubleCounter") .setDescription("This is my first counter") .build(); doubleCounter.add(2, Labels.empty()); DoubleCounter anotherCounter = OpenTelemetry.getGlobalMeter("nonsense-value") .doubleCounterBuilder("anotherDoubleCounter") .setDescription("This is another counter") .build(); anotherCounter.add(6.3, Labels.empty()); // Verify Prometheus String output = prometheusMeterRegistry.scrape(); assertThat(output) .contains("# HELP doubleCounter_1_total This is my first counter") .contains("# TYPE doubleCounter_1_total counter") .contains("doubleCounter_1_total 2.0") .contains("# HELP anotherDoubleCounter_1_total This is another counter") .contains("# TYPE anotherDoubleCounter_1_total counter") .contains("anotherDoubleCounter_1_total 6.3"); } @Test void testPrometheusOutputWithLabels() { DoubleCounter doubleCounter = OpenTelemetry.getGlobalMeter("nonsense-value") .doubleCounterBuilder("doubleCounterLabels") .setDescription("This is my first counter with Labels") .build(); doubleCounter.add(4, Labels.of("myKey", "aValue")); DoubleCounter anotherCounter = OpenTelemetry.getGlobalMeter("nonsense-value") .doubleCounterBuilder("anotherDoubleCounterLabels") .setDescription("This is another counter with Labels") .build(); anotherCounter.add(6.3, Labels.of("someKey", "someValue")); doubleCounter.add(3.2, Labels.of("myKey", "aValue")); anotherCounter.add(0.4, Labels.of("someKey", "someValue")); // Verify Prometheus String output = prometheusMeterRegistry.scrape(); assertThat(output) .contains("# HELP doubleCounterLabels_1_total This is my first counter with Labels") .contains("# TYPE doubleCounterLabels_1_total counter") .contains("doubleCounterLabels_1_total{myKey=\"aValue\",} 7.2") .contains("# HELP anotherDoubleCounterLabels_1_total This is another counter with Labels") .contains("# TYPE anotherDoubleCounterLabels_1_total counter") .contains("anotherDoubleCounterLabels_1_total{someKey=\"someValue\",} 6.7"); } }
<filename>config/GlobalTimer.ts import {TimerData} from "../redux/store/State"; export const GLOBAL_TIMER: Required<TimerData> = { levelTime: 120, canvasBaseTime: 5, canvasPerColorTime: 2 };
//=========================================== // Lumina-DE source code // Copyright (c) 2015, <NAME> // Available under the 3-clause BSD license // See the LICENSE file for full details //=========================================== #include "ColorDialog.h" #include "ui_ColorDialog.h" #include <QColorDialog> #include <QStringList> #include <LuminaXDG.h> ColorDialog::ColorDialog(QSettings *set, QWidget *parent) : QDialog(parent), ui(new Ui::ColorDialog()){ ui->setupUi(this); settings = set; connect(ui->push_cancel, SIGNAL(clicked()), this, SLOT(close()) ); connect(ui->push_apply, SIGNAL(clicked()), this, SLOT(saveColors()) ); connect(ui->push_getcolor, SIGNAL(clicked()), this, SLOT(changeColor()) ); } void ColorDialog::LoadColors(){ ui->treeWidget->clear(); QStringList colors = settings->allKeys().filter("colors/"); for(int i=0; i<colors.length(); i++){ QTreeWidgetItem *it = new QTreeWidgetItem(); it->setText(0, colors[i].section("/",-1)); it->setText(1, settings->value(colors[i]).toString() ); it->setBackground(2, QBrush(QColor( it->text(1) ) ) ); ui->treeWidget->addTopLevelItem(it); } } void ColorDialog::updateIcons(){ this->setWindowIcon( LXDG::findIcon("format-fill-color") ); ui->push_cancel->setIcon( LXDG::findIcon("dialog-cancel") ); ui->push_apply->setIcon( LXDG::findIcon("dialog-ok") ); ui->push_getcolor->setIcon( LXDG::findIcon("format-fill-color") ); } void ColorDialog::saveColors(){ for(int i=0; i<ui->treeWidget->topLevelItemCount(); i++){ QTreeWidgetItem *it = ui->treeWidget->topLevelItem(i); settings->setValue("colors/"+it->text(0), it->text(1)); } emit colorsChanged(); this->close(); } void ColorDialog::changeColor(){ QTreeWidgetItem *it = ui->treeWidget->currentItem(); if(it==0){ return; } QColor color = QColorDialog::getColor(QColor( it->text(1)), this, tr("Select Color")); if(!color.isValid()){ return; } it->setText(1, color.name()); it->setBackground(2, QBrush(color)); }
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { expect } from 'chai'; import { Web3Provider } from './web3-provider.js'; describe('Initialize Web3', () => { it('Is constructable from HTTP', async () => { const web3Provider = Web3Provider.fromUri('https://rinkeby.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4'); const isListening = await web3Provider.eth.net.isListening(); expect(isListening).to.equal(true); }); });
import { Component } from 'react'; import PropTypes from 'prop-types'; const COUNTDOWN_UNIT = 1000; class CountDown extends Component { constructor(props) { super(props); this.state = { delay: props.delay, }; this.startCountDown = this.startCountDown.bind(this); } componentDidMount() { this.startCountDown(); } countdownInterval = null; startCountDown() { this.countdownInterval = setInterval(() => { if (this.state.delay > 0) { this.setState({ delay: this.state.delay - COUNTDOWN_UNIT, }); } else { clearInterval(this.countdownInterval); } }, COUNTDOWN_UNIT); } render() { return parseInt(this.state.delay / COUNTDOWN_UNIT, 10); } } CountDown.propTypes = { delay: PropTypes.number, // (ms) }; CountDown.defaultProps = { delay: 0, }; export default CountDown;
#!/bin/bash rm -rf output_dev sculpin generate --watch --server
<gh_stars>100-1000 var group__CMSIS__CBAR = [ [ "CBAR Bits", "group__CMSIS__CBAR__BITS.html", null ], [ "__get_CBAR", "group__CMSIS__CBAR.html#gab0f00668bb0f6cbe3cc8b90535d66d8e", null ] ];
import re def parseFormElements(html): form_elements = re.findall(r'<label>(.*?)<\/label>.*?<input type="(.*?)" name="(.*?)"(?: checked)?>', html, re.DOTALL) parsed_elements = [] for element in form_elements: label, input_type, name = element checked = True if 'checked' in element[0] else False parsed_elements.append({ "label": label.strip(), "type": input_type, "name": name, "checked": checked }) return parsed_elements
# mac osx setup export TCHEM_DEMO_ROOT=${PWD} export JFLAG=4 export CXX=clang++-mp-9.0 export CC=clang-mp-9.0 # # set paths # export TCHEM_ROOT_PATH=${TCHEM_DEMO_ROOT}/tchem export TCHEM_INSTALL_PATH=${TCHEM_DEMO_ROOT}/demo export GTEST_ROOT_PATH=${TCHEM_DEMO_ROOT}/gtest export KOKKOS_ROOT_PATH=${TCHEM_DEMO_ROOT}/kokkos export MATHUTILS_ROOT_PATH=${TCHEM_DEMO_ROOT}/mathutils # this is for Macport export LIBRARY_PATH=${LIBRARY_PTH}:/opt/local/lib # # clone repository # git clone https://github.com/google/googletest.git ${GTEST_ROOT_PATH}/master git clone https://github.com/kokkos/kokkos.git ${KOKKOS_ROOT_PATH}/master git clone kyukim@getz.ca.sandia.gov:/home/gitroot/math_utils ${MATHUTILS_ROOT_PATH}/master git clone kyukim@getz.ca.sandia.gov:/home/gitroot/TChem++ ${TCHEM_ROOT_PATH}/master cd ${TCHEM_ROOT_PATH}/master; #git checkout v2.0.0; git checkout --track origin/kyungjoo-develop git pull cd ${TCHEM_DEMO_ROOT} # compile gtest cd ${GTEST_ROOT_PATH}; mkdir build; cd build; cmake \ -D CMAKE_CXX_COMPILER=${CXX} \ -D CMAKE_INSTALL_PREFIX=${TCHEM_DEMO_ROOT}/install \ ${GTEST_ROOT_PATH}/master make -j${JFLAG} install rm -rf ${GTEST_ROOT_PATH}/build # compile kokkos cd ${KOKKOS_ROOT_PATH}; mkdir build; cd build; cmake \ -D CMAKE_INSTALL_PREFIX=${TCHEM_DEMO_ROOT}/install \ -D CMAKE_CXX_COMPILER=${CXX} \ -D CMAKE_CXX_FLAGS="-g" \ -D Kokkos_ENABLE_SERIAL=ON \ -D Kokkos_ENABLE_OPENMP=ON \ -D Kokkos_ENABLE_DEPRECATED_CODE=OFF \ -D Kokkos_ARCH_HSW=ON \ -D Kokkos_ENABLE_TESTS=OFF \ ${KOKKOS_ROOT_PATH}/master make -j${JFLAG} install rm -rf ${KOKKOS_ROOT_PATH}/build # compile MathUtils cd ${MATHUTILS_ROOT_PATH}; mkdir build; cd build; rm -rf *; cmake \ -D CMAKE_INSTALL_PREFIX=${TCHEM_DEMO_ROOT}/install \ -D CMAKE_CXX_COMPILER=${CXX} \ -D CMAKE_CXX_FLAGS="-g" \ -D CMAKE_EXE_LINKER_FLAGS="" \ -D CMAKE_BUILD_TYPE=RELEASE \ -D MATHUTILS_ENABLE_DEBUG=OFF \ -D MATHUTILS_ENABLE_VERBOSE=ON \ -D MATHUTILS_ENABLE_KOKKOS=ON \ -D MATHUTILS_ENABLE_TEST=OFF \ -D MATHUTILS_ENABLE_EXAMPLE=OFF \ -D KOKKOS_INSTALL_PATH=${TCHEM_DEMO_ROOT}/install \ -D GTEST_INSTALL_PATH=${TCHEM_DEMO_ROOT}/install \ -D OPENBLAS_INSTALL_PATH=/opt/local \ ${MATHUTILS_ROOT_PATH}/master/src make -j${JFLAG} install rm -rf ${MATHUTILS_ROOT_PATH}/build # compile tchem cd ${TCHEM_ROOT_PATH}; mkdir build; cd build; cmake \ -D CMAKE_INSTALL_PREFIX=${TCHEM_INSTALL_PATH} \ -D CMAKE_CXX_COMPILER=${CXX} \ -D CMAKE_CXX_FLAGS="-g" \ -D CMAKE_EXE_LINKER_FLAGS="" \ -D CMAKE_BUILD_TYPE=RELEASE \ -D TCHEM_ENABLE_VERBOSE=OFF \ -D TCHEM_ENABLE_TEST=ON \ -D TCHEM_ENABLE_EXAMPLE=ON \ -D TCHEM_ENABLE_PROBLEMS_NUMERICAL_JACOBIAN=OFF \ -D KOKKOS_INSTALL_PATH=${TCHEM_DEMO_ROOT}/install \ -D GTEST_INSTALL_PATH=${TCHEM_DEMO_ROOT}/install \ -D MATHUTILS_INSTALL_PATH=${TCHEM_DEMO_ROOT}/install \ ${TCHEM_ROOT_PATH}/master/src make -j${jflag} install # back to root directory cd ${TCHEM_DEMO_ROOT} echo 'TChem demo compiling is done'
<gh_stars>1-10 import AlphaVantageAPI from "../../src/mocks/alphaVantageAPI"; import { matchesSnapshot } from "../utils"; jest.setTimeout(30000); let alpha; beforeAll(() => { alpha = new AlphaVantageAPI(); }); it(`daily data works`, () => { return alpha.forex.daily('btc', 'usd') .then(matchesSnapshot); }); it(`exchangeRates data works`, () => { return alpha.forex.exchangeRates('btc', 'usd') .then(matchesSnapshot); }); describe(`exchangeTimeSeries data works`, () => { it('5min', () => alpha.forex.exchangeTimeSeries({ from_symbol:'btc', to_symbol: 'usd', interval: '5min' }) .then(matchesSnapshot) ); }); it(`intraday data works`, () => { return alpha.forex.intraday('btc', 'usd') .then(matchesSnapshot); }); it(`monthly data works`, () => { return alpha.forex.monthly('btc', 'usd') .then(matchesSnapshot); }); it(`weekly data works`, () => { return alpha.forex.weekly('btc', 'usd') .then(matchesSnapshot); });
<gh_stars>0 /* * Copyright 2017 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 org2.beryx.textio.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; import spark.Response; import spark.Session; import java.nio.charset.StandardCharsets; import java.util.function.BiFunction; import java.util.function.Function; import static spark.Spark.*; /** * A SparkJava-based web server that allows clients to access the {@link DataApi}. */ public class SparkDataServer extends AbstractDataServer<Request> { private static final Logger logger = LoggerFactory.getLogger(SparkDataServer.class); static { exception(Exception.class, (exception, request, response) -> logger.error("Spark failure", exception)); } private final BiFunction<SessionHolder, String, DataApi> dataApiCreator; private final Function<SessionHolder, DataApi> dataApiGetter; private final DataApiProvider<Request> dataApiProvider = new DataApiProvider<Request>() { @Override public DataApi create(Request request, String initData) { return dataApiCreator.apply(getSessionHolder(request), initData); } @Override public DataApi get(Request request) { return dataApiGetter.apply(getSessionHolder(request)); } }; public static class SessionHolder { public final String sessionId; public final Session session; public SessionHolder(String sessionId, Session session) { this.sessionId = sessionId; this.session = session; } } private static SessionHolder getSessionHolder(Request r) { return new SessionHolder(getId(r), r.session()); } @Override public DataApiProvider<Request> getDataApiProvider() { return dataApiProvider; } public SparkDataServer(BiFunction<SessionHolder, String, DataApi> dataApiCreator, Function<SessionHolder, DataApi> dataApiGetter) { this.dataApiCreator = dataApiCreator; this.dataApiGetter = dataApiGetter; } @Override public SparkDataServer withPort(int portNumber) { port(portNumber); return this; } @Override public int getPort() { return port(); } protected static String getId(Request request) { Session session = request.session(); String id = session.id(); String uuid = request.headers("uuid"); if(uuid != null) { id += "-" + uuid; } logger.trace("id: {}", id); return id; } protected String configureResponseData(Response response, ResponseData r) { response.status(r.status); response.type(r.contentType); response.body(r.text); return r.text; } @Override public void init() { post("/" + getPathForPostInit(), (request, response) -> { logger.trace("Received INIT"); String initData = new String(request.bodyAsBytes(), StandardCharsets.UTF_8); return configureResponseData(response, handleInit(request, initData)); }); get("/" + getPathForGetData(), "application/json", (request, response) -> { logger.trace("Received GET"); return configureResponseData(response, handleGetData(request)); }); post("/" + getPathForPostInput(), (request, response) -> { logger.trace("Received POST"); boolean userInterrupt = Boolean.parseBoolean(request.headers("textio-user-interrupt")); String handlerId = request.headers("textio-handler-id"); String input = new String(request.body().getBytes(), StandardCharsets.UTF_8); return configureResponseData(response, handlePostInput(request, input, userInterrupt, handlerId)); }); } }
<gh_stars>0 package io.github.poulad.hnp.web.model; import javax.annotation.Nonnull; public record ImageDto( @Nonnull String url ) { }
package is.tagomor.woothee.appliance; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.regex.MatchResult; import is.tagomor.woothee.AgentCategory; import is.tagomor.woothee.DataSet; public class Nintendo extends AgentCategory { public static boolean challenge(final String ua, final Map<String,String> result) { Map<String,String> data = null; // for Opera of DSi/Wii, see os.Appliance if (ua.indexOf("Nintendo 3DS;") > -1) { data = DataSet.get("Nintendo3DS"); } else if (ua.indexOf("Nintendo DSi;") > -1) { data = DataSet.get("NintendoDSi"); } else if (ua.indexOf("Nintendo Wii;") > -1) { data = DataSet.get("NintendoWii"); } else if (ua.indexOf("(Nintendo WiiU)") > -1) { data = DataSet.get("NintendoWiiU"); } if (data == null) return false; updateMap(result, data); return true; } }
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class MatrixPredictions { public static void main(String[] args) { if (args.length != 3) { System.err.println("Usage: java MatrixPredictions <userModelFile> <itemModelFile> <outputFile>"); System.exit(1); } String userModelFile = args[0]; String itemModelFile = args[1]; String outputFile = args[2]; // Read user and item models from the specified files // Perform matrix predictions using collaborative filtering algorithm // Write the results to the output file try (FileWriter writer = new FileWriter(new File(outputFile))) { // Write the matrix predictions results to the output file writer.write("Matrix predictions results"); } catch (IOException e) { System.err.println("Error writing to the output file: " + e.getMessage()); } } }
/* * Copyright 2014-2018 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.dbflute.cbean.sqlclause.query; import org.dbflute.cbean.sqlclause.join.InnerJoinNoWaySpeaker; /** * @author jflute * @since 0.9.9.0A (2011/07/27 Wednesday) */ public class QueryUsedAliasInfo { protected final String _usedAliasName; // not null protected final InnerJoinNoWaySpeaker _innerJoinNoWaySpeaker; // null allowed /** * @param usedAliasName The alias name of joined table (or local) where it is used in query. (NotNull) * @param innerJoinNoWaySpeaker The no-way speaker for auto-detect of inner-join. (NullAllowed: null means inner-allowed) */ public QueryUsedAliasInfo(String usedAliasName, InnerJoinNoWaySpeaker innerJoinNoWaySpeaker) { _usedAliasName = usedAliasName; _innerJoinNoWaySpeaker = innerJoinNoWaySpeaker; } public String getUsedAliasName() { return _usedAliasName; } public InnerJoinNoWaySpeaker getInnerJoinAutoDetectNoWaySpeaker() { return _innerJoinNoWaySpeaker; } }
#!/bin/sh set -e nproc=$(nproc || echo 4) make clean make -j$nproc cd site git init git add . git commit -m 'Deploy' git remote add github git@github.com:lambda-fairy/maud.git git push -f github master:gh-pages
<gh_stars>0 type Listener<EventType> = (ev: EventType) => void; function createObserver<EventType>(): { subscribe: (listener: Listener<EventType>) => () => void; publish: (event: EventType) => void; } { let listeners: Array<Listener<EventType>> = []; return { subscribe: (listener: Listener<EventType>): (() => void) => { listeners.push(listener); return () => { listeners = listeners.filter((l) => l !== listener); }; }, publish: (event: EventType): void => { listeners.forEach((l) => l(event)); }, }; } interface BeforeSetEvent<T> { value: T; newValue: T; } interface AfterSetEvent<T> { value: T; } interface BaseRecord { id: string; } interface Pokemon extends BaseRecord { name: string; } interface Database<T extends BaseRecord> { get(id: string): T | undefined; set(newValue: T): void; onBeforeAdd(listener: Listener<BeforeSetEvent<T>>): () => void; onAfterAdd(listener: Listener<AfterSetEvent<T>>): () => void; } module SingletonHider { class InMemoryDatabase<T extends BaseRecord> implements Database<T> { private db: Record<string, T> = {}; private beforeAddListeners = createObserver<BeforeSetEvent<T>>(); private afterAddListeners = createObserver<AfterSetEvent<T>>(); public set(newValue: T): void { this.beforeAddListeners.publish({ newValue, value: this.db[newValue.id], }); this.db[newValue.id] = newValue; this.afterAddListeners.publish({ value: newValue, }); } public onBeforeAdd(listener: Listener<BeforeSetEvent<T>>): () => void { return this.beforeAddListeners.subscribe(listener); } public onAfterAdd(listener: Listener<AfterSetEvent<T>>): () => void { return this.afterAddListeners.subscribe(listener); } public get(id: string): T | undefined { return this.db[id]; } } export class SingletonDBConstructor<T extends BaseRecord> { private instance: InMemoryDatabase<T> = new InMemoryDatabase<T>(); public getDb(): InMemoryDatabase<T> { return this.instance; } } } const singletonProvider = new SingletonHider.SingletonDBConstructor<Pokemon>(); const singletonDb = singletonProvider.getDb(); singletonDb.set({ id: '1', name: 'pika', }); const unsubscribe = singletonDb.onBeforeAdd(({ value }) => { console.log("before add", value); }) unsubscribe(); singletonDb.onAfterAdd(({ value }) => { console.log("after add", value); }) singletonDb.set({ id: '2', name: 'Ketchup', });
/* Copyright 2019 The Jetstack cert-manager contributors. 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 cainjector import ( "io/ioutil" admissionreg "k8s.io/api/admissionregistration/v1beta1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" apireg "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/source" certmanager "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1" ) // injectorSet describes a particular setup of the injector controller type injectorSetup struct { resourceName string injector CertInjector listType runtime.Object } var ( MutatingWebhookSetup = injectorSetup{ resourceName: "mutatingwebhookconfiguration", injector: mutatingWebhookInjector{}, listType: &admissionreg.MutatingWebhookConfigurationList{}, } ValidatingWebhookSetup = injectorSetup{ resourceName: "validatingwebhookconfiguration", injector: validatingWebhookInjector{}, listType: &admissionreg.ValidatingWebhookConfigurationList{}, } APIServiceSetup = injectorSetup{ resourceName: "apiservice", injector: apiServiceInjector{}, listType: &apireg.APIServiceList{}, } injectorSetups = []injectorSetup{MutatingWebhookSetup, ValidatingWebhookSetup, APIServiceSetup} ControllerNames []string ) // Register registers an injection controller with the given manager, and adds relevant indicies. func Register(mgr ctrl.Manager, setup injectorSetup) error { typ := setup.injector.NewTarget().AsObject() if err := mgr.GetFieldIndexer().IndexField(typ, injectFromPath, injectableIndexer); err != nil { return err } cfg := mgr.GetConfig() caBundle, err := dataFromSliceOrFile(cfg.CAData, cfg.CAFile) if err != nil { return err } return ctrl.NewControllerManagedBy(mgr). For(typ). Watches(&source.Kind{Type: &certmanager.Certificate{}}, &handler.EnqueueRequestsFromMapFunc{ToRequests: &certMapper{ Client: mgr.GetClient(), log: ctrl.Log.WithName("cert-mapper"), toInjectable: certToInjectableFunc(setup.listType, setup.resourceName), }}). Watches(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestsFromMapFunc{ ToRequests: &secretMapper{ Client: mgr.GetClient(), log: ctrl.Log.WithName("secret-mapper"), toInjectable: certToInjectableFunc(setup.listType, setup.resourceName), }}). Complete(&genericInjectReconciler{ Client: mgr.GetClient(), apiserverCABundle: caBundle, log: ctrl.Log.WithName("inject-controller"), resourceName: setup.resourceName, injector: setup.injector, }) } // dataFromSliceOrFile returns data from the slice (if non-empty), or from the file, // or an error if an error occurred reading the file func dataFromSliceOrFile(data []byte, file string) ([]byte, error) { if len(data) > 0 { return data, nil } if len(file) > 0 { fileData, err := ioutil.ReadFile(file) if err != nil { return []byte{}, err } return fileData, nil } return nil, nil } // RegisterALL registers all known injection controllers with the given manager, and adds relevant indicides. func RegisterAll(mgr ctrl.Manager) error { for _, setup := range injectorSetups { if err := Register(mgr, setup); err != nil { return err } } return nil }
def find_max(arr): max_number = -float('inf') for i in range(len(arr)): if arr[i] > max_number: max_number = arr[i] return max_number arr = [4, 9, 8, 20, 5] max_number = find_max(arr) print("The maximum number is:", max_number)
<reponame>liderman/go-hotellook-api<gh_stars>1-10 package hotellook import "fmt" type HotelsResponse struct { GenTimestamp float64 `json:"gen_timestamp" bson:"gen_timestamp"` Hotels []Hotel `json:"hotels" bson:"hotels"` Pois []Poi `json:"pois" bson:"pois"` } type Hotel struct { Address map[string]string `json:"address" bson:"address"` CheckIn string `json:"checkIn" bson:"checkIn"` CheckOut string `json:"checkOut" bson:"checkOut"` CityId int `json:"cityId" bson:"cityId"` CntFloors int `json:"cntFloors" bson:"cntFloors"` CntRooms int `json:"cntRooms" bson:"cntRooms"` CntSuites int `json:"cntSuites" bson:"cntSuites"` Distance float64 `json:"distance" bson:"distance"` Facilities []int `json:"facilities" bson:"facilities"` Id int `json:"id" bson:"id"` Link string `json:"link" bson:"link"` Location Coordinates `json:"location" bson:"location"` Name map[string]string `json:"name" bson:"name"` PhotoCount int `json:"photoCount" bson:"photoCount"` Photos []Photo `json:"photos" bson:"photos"` PhotosByRoomType map[string]int `json:"photosByRoomType" bson:"photosByRoomType"` PoiDistance map[string]int `json:"poi_distance" bson:"poi_distance"` Popularity int `json:"popularity" bson:"popularity"` Pricefrom int `json:"pricefrom" bson:"pricefrom"` PropertyType int `json:"propertyType" bson:"propertyType"` Rating int `json:"rating" bson:"rating"` ShortFacilities []string `json:"shortFacilities" bson:"shortFacilities"` Stars int `json:"stars" bson:"stars"` YearOpened int `json:"yearOpened" bson:"yearOpened"` YearRenovated int `json:"yearRenovated" bson:"yearRenovated"` } type Poi struct { Category string `json:"category" bson:"category"` Confirmed bool `json:"confirmed" bson:"confirmed"` Geom Geom `json:"geom" bson:"geom"` Id int `json:"id" bson:"id"` Location Coordinates `json:"location" bson:"location"` Name string `json:"name" bson:"name"` Rating float64 `json:"rating" bson:"rating"` } type Geom struct { Coordinates []interface{} `json:"coordinates" bson:"coordinates"` Type string `json:"type" bson:"type"` } type Photo struct { Url string `json:"url" bson:"url"` Width int `json:"width" bson:"width"` Height int `json:"height" bson:"height"` } type Coordinates struct { Lon float64 `json:"lon" bson:"lon"` Lan float64 `json:"lat" bson:"lat"` } // Hotels returns a list of hotels by locationId. // // Documentation: // https://support.travelpayouts.com/hc/en-us/articles/115000343268-Hotels-data-API#44 // // Example URI: // http://engine.hotellook.com/api/v2/static/hotels.json?locationId=895&token=YOUR_TOKEN func (a *HotellookApi) Hotels(locationId int) (hotels HotelsResponse, err error) { err = a.getJson( "static/hotels.json", map[string]string{ "locationId": fmt.Sprintf("%d", locationId), }, &hotels, ) return }
class NeighbourReport { public 1 = 0 public 2 = 0 public 3 = 0 } const countRowNeighbors = (row: number[], col: number, notThis: boolean = false) => { return [ (row[col - 1] ?? 0), (notThis ? 0 : (row[col] ?? 0)), (row[col + 1] ?? 0), ] } export const countNeighbors = (state: number[][], row: number, col: number): NeighbourReport => { const prevRow = state[row - 1] ?? [] const thisRow = state[row] const nextRow = state[row + 1] ?? [] return countRowNeighbors(prevRow, col).concat( countRowNeighbors(thisRow, col, true)).concat( countRowNeighbors(nextRow, col)).reduce( (prev, curr) => ({ ...prev, [curr]: (prev[curr] ?? 0) + 1, }), new NeighbourReport(), ) } const handleDead = (neighbors: NeighbourReport): number => { return neighbors[1] === 3 ? 1 : neighbors[2] === 3 ? 2 : neighbors[3] === 3 ? 3 : 0 } const handleAlive = (me: number, neighbors: NeighbourReport): number => { switch (neighbors[me]) { case 0: case 1: return 0 case 2: case 3: return me default: return 0 } } export const simulate = (state: number[][]): number[][] => { return state.map((row, rowI) => row.map((me, i) => { const neighbors = countNeighbors(state, rowI, i) return me === 0 ? handleDead(neighbors) : handleAlive(me, neighbors) }), ) }
#!/bin/bash perl parse.pl
<reponame>szab100/secmgr<filename>src/main/java/com/google/common/labs/matcher/AnalyzedUrl.java<gh_stars>1-10 // Copyright 2008 Google 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. package com.google.common.labs.matcher; import static com.google.common.labs.matcher.ParsedUrlPattern.URL_METAPATTERN; import static com.google.common.labs.matcher.ParsedUrlPattern.getGroup; import com.google.common.base.Preconditions; import com.google.common.labs.matcher.ParsedUrlPattern.MetaRegexGroup; import java.util.regex.Matcher; /** * Analyzer for URL strings, for use with the {@link ParsedUrlPattern}. You can * access the host and path portions through {@link AnalyzedUrl#getHostPart()} * and {@link AnalyzedUrl#getPathPart()}. It is recommended that this parser be * used rather than the standard {@code getHost()} and {@code getPath()} * functions of {@link java.net.URL}, because this class and * {@code ParsedUrlPattern} share parsing infrastructure and at present, there * is at least one significant difference: {@code AnalyzedUrl.getPathPart()} * includes the leading slash but {@code java.net.URL.getPath()} does not. TODO: * fix this. */ class AnalyzedUrl { private final String completeUrl; private final String host; private final String path; /** * Parses a URL string into components. These components may be empty if the * input is fragmentary. * * @param url the URL string to parse */ public AnalyzedUrl(String url) { Preconditions.checkNotNull(url); String pathPart = null; String hostPart = null; // extract the components from the subject string Matcher m = URL_METAPATTERN.matcher(url); if (m.find()) { hostPart = buildHostPart(m); pathPart = buildPathPart(m); } completeUrl = url; path = pathPart; host = hostPart; } /** * Returns the host (protocol-authority) part: from the beginning up through * the first single-slash. * * @return the host (protocol-authority) portion of the URL, as a String */ public String getHostPart() { return host; } /** * Returns the path part from the first single-slash through the end (includes * anchor and query if present). * * @return the path portion of the URL, as a String */ public String getPathPart() { return path; } /** * Returns the complete URL. * * @return the entire URL, as a String */ public String getCompleteUrl() { return completeUrl; } private String buildHostPart(Matcher m) { StringBuilder sb = new StringBuilder(); sb.append(getGroup(m, MetaRegexGroup.PROTOCOL_AUTHORITY)); sb.append(getGroup(m, MetaRegexGroup.SLASH_AFTER_AUTHORITY)); return sb.toString(); } private String buildPathPart(Matcher m) { StringBuilder sb = new StringBuilder(); sb.append("/"); sb.append(getGroup(m, MetaRegexGroup.FILE)); return sb.toString(); } }
/** * Get a unique client identifier. * * @todo Change this to be a username or something more unique. */ 'use strict'; const os = require('os'); module.exports = os.hostname();
<filename>sortandsearch/search_matrix.py class Solution(object): def search_matrix(self, matrix, target): """ :param matrix: List[List[int]] :param target: int :return: List[int] Time: O(m + n) Space: O(1) """ if not matrix: return False row = 0 col = len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] == target: return [row, col] elif target < matrix[row][col]: col -= 1 else: row += 1 return [-1, -1] if __name__ == '__main__': ip = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] print(Solution().search_matrix(ip, 30)) print(Solution().search_matrix(ip, 20))
<reponame>orthopus/01-myocoach<filename>src/software/webapp/front/components/common/MobileDrawer.tsx<gh_stars>1-10 import * as React from 'react'; import IconButton from "@mui/material/IconButton"; import MuiDrawer, {DrawerProps} from "@mui/material/Drawer"; import List from "@mui/material/List"; import {NavLink, NavLinkProps} from "react-router-dom"; import Collapse from "@mui/material/Collapse"; import Divider from "@mui/material/Divider"; import {LinkProps} from "@mui/material/Link"; import ListItem from "@mui/material/ListItem"; import ListItemIcon from "@mui/material/ListItemIcon"; import ListItemText from "@mui/material/ListItemText"; import Tooltip from "@mui/material/Tooltip"; import {CSSObject, Theme} from "@mui/material"; import useTheme from "@mui/material/styles/useTheme"; import ExpandLess from "@mui/icons-material/ExpandLess"; import ExpandMore from "@mui/icons-material/ExpandMore"; import MenuIcon from "@mui/icons-material/Menu"; import MenuOpenIcon from "@mui/icons-material/MenuOpen"; import ShowChart from "@mui/icons-material/ShowChart"; import FitnessCenter from "@mui/icons-material/FitnessCenter"; import Info from "@mui/icons-material/Info"; import SportsEsports from "@mui/icons-material/SportsEsports"; import WifiIcon from "@mui/icons-material/Wifi"; import WifiOffIcon from "@mui/icons-material/WifiOff"; import PowerIcon from "@mui/icons-material/Power"; import PowerOffIcon from "@mui/icons-material/PowerOff"; import Settings from "@mui/icons-material/Settings"; import Fullscreen from "@mui/icons-material/Fullscreen"; import FullscreenExit from "@mui/icons-material/FullscreenExit"; import Brightness4Icon from "@mui/icons-material/Brightness4"; import Brightness7Icon from "@mui/icons-material/Brightness7"; import styled from "@mui/material/styles/styled"; /* MyoCoach frontend mobile navigation drawer component ==================================================== Authors: Julien & <NAME> - RE-FACTORY SARL Company: ORTHOPUS SAS License: Creative Commons Zero v1.0 Universal Website: <EMAIL> Last edited: October 2021 */ interface ListItemLinkProps extends LinkProps { name: string; open?: boolean; onClick?: () => void; } function ListItemLink(props: Omit<ListItemLinkProps, 'ref'>) { const { name, open, onClick } = props; return ( <Tooltip title={name}> <ListItem button onClick={onClick}> <ListItemIcon><SportsEsports/></ListItemIcon> <ListItemText primary={name} /> { open != null ? open ? <ExpandLess /> : <ExpandMore /> : null } </ListItem> </Tooltip> ); } const drawerWidth = 280; const openedMixin = (theme: Theme): CSSObject => ({ width: drawerWidth, transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), overflowX: 'hidden', }); const closedMixin = (theme: Theme): CSSObject => ({ transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), overflowX: 'hidden', width: `calc(${theme.spacing(7)} + 1px)`, [theme.breakpoints.up('sm')]: { width: `calc(${theme.spacing(9)} + 1px)`, }, }); const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })<DrawerProps>( ({theme, open}) => ({ width: drawerWidth, flexShrink: 0, whiteSpace: 'nowrap', backgroundColor: theme.palette.primary.main, boxSizing: 'border-box', ...(open && { ...openedMixin(theme), '& .MuiDrawer-paper': openedMixin(theme), }), ...(!open && { ...closedMixin(theme), '& .MuiDrawer-paper': closedMixin(theme), }), }) ); const ToolbarWrapper = styled('div')(({ theme }) => ({ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', padding: theme.spacing(0, 1), })); const StyledNavLink = styled(NavLink)<NavLinkProps>(() => ({ color: "inherit", textDecoration: "inherit", })); const MobileDrawer: React.FC<{ gameList: Array<GameDescription>, serverConnected: boolean, sensorsConnected: boolean, onToggleFullscreenEvent: () => void, onToggleDarkModeEvent: () => void }> = ({ gameList, serverConnected, sensorsConnected, onToggleFullscreenEvent, onToggleDarkModeEvent }) => { const theme = useTheme(); const [openDrawerGameMenu, setOpenDrawerGameMenu] = React.useState(false); const [open, setOpen] = React.useState(false); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { setOpen(false); setOpenDrawerGameMenu(false); }; function handleToogleDrawerGameMenuClick() { if(openDrawerGameMenu) { setOpenDrawerGameMenu(false); } else { setOpen(true); setOpenDrawerGameMenu(true); } } return (<React.Fragment> <Drawer variant={"permanent"} open={open}> <ToolbarWrapper> { open ? <IconButton onClick={handleDrawerClose}> <MenuOpenIcon/> </IconButton> : <IconButton onClick={handleDrawerOpen}> <MenuIcon/> </IconButton> } </ToolbarWrapper> <Divider /> <List> <Tooltip title={"Signal"}> <StyledNavLink to={'/'}> <ListItem button onClick={handleDrawerClose}> <ListItemIcon><ShowChart/></ListItemIcon> <ListItemText primary={"Signal"}/> </ListItem> </StyledNavLink> </Tooltip> <Tooltip title={"Training"}> <StyledNavLink to={'/training'}> <ListItem button onClick={handleDrawerClose}> <ListItemIcon><FitnessCenter/></ListItemIcon> <ListItemText primary={"Training"}/> </ListItem> </StyledNavLink> </Tooltip> <ListItemLink name={"Games"} open={openDrawerGameMenu} onClick={handleToogleDrawerGameMenuClick} /> <Collapse component="li" in={openDrawerGameMenu} timeout="auto" unmountOnExit> <List disablePadding> { gameList.map((description: GameDescription) => <StyledNavLink key={description.url} to={description.url}> <ListItem button onClick={handleDrawerClose}> <ListItemText sx={{paddingLeft: theme.spacing(4)}} primary={description.name}/> </ListItem> </StyledNavLink> ) } </List> </Collapse> <Tooltip title={"About"}> <StyledNavLink to={'/about'}> <ListItem button onClick={handleDrawerClose}> <ListItemIcon><Info/></ListItemIcon> <ListItemText primary={"About"}/> </ListItem> </StyledNavLink> </Tooltip> </List> <Divider /> <List> { theme.palette.mode == "dark" ? ( <Tooltip title={"Light Mode"}> <ListItem onClick={onToggleDarkModeEvent}> <ListItemIcon> <Brightness7Icon/> </ListItemIcon> <ListItemText primary={"Light Mode"}/> </ListItem> </Tooltip>) : (<Tooltip title={"Dark Mode"}> <ListItem onClick={onToggleDarkModeEvent}> <ListItemIcon> <Brightness4Icon/> </ListItemIcon> <ListItemText primary={"Dark Mode"}/> </ListItem> </Tooltip>) } { document.fullscreenEnabled ? !document.fullscreenElement ? ( <Tooltip title={"Enter Fullscreen"}> <ListItem onClick={onToggleFullscreenEvent}> <ListItemIcon> <Fullscreen/> </ListItemIcon> <ListItemText primary={"Enter Fullscreen"}/> </ListItem> </Tooltip>) : (<Tooltip title={"Exit Fullscreen"}> <ListItem onClick={onToggleFullscreenEvent}> <ListItemIcon> <FullscreenExit/> </ListItemIcon> <ListItemText primary={"Exit Fullscreen"}/> </ListItem> </Tooltip>) : null } { serverConnected ? (<Tooltip title={"Server connected"}> <ListItem> <ListItemIcon> <WifiIcon style={{color: theme.palette.success.main}}/> </ListItemIcon> <ListItemText style={{color: theme.palette.success.main}} primary={"Server connected"}/> </ListItem> </Tooltip>) : ( <Tooltip title={"Server not connected"}> <ListItem> <ListItemIcon> <WifiOffIcon style={{color: theme.palette.warning.main}}/> </ListItemIcon> <ListItemText style={{color: theme.palette.warning.main}} primary={"Server not connected"}/> </ListItem> </Tooltip>) } { sensorsConnected ? (<Tooltip title={"Sensors connected"}> <ListItem> <ListItemIcon> <PowerIcon style={{color: theme.palette.success.main}}/> </ListItemIcon> <ListItemText style={{color: theme.palette.success.main}} primary={"Sensors connected"}/> </ListItem> </Tooltip>) : (<Tooltip title={"Sensors not connected"}> <ListItem> <ListItemIcon> <PowerOffIcon style={{color: theme.palette.warning.main}}/> </ListItemIcon> <ListItemText style={{color: theme.palette.warning.main}} primary={"Sensors not connected"}/> </ListItem> </Tooltip>) } <Tooltip title={"Settings"}> <StyledNavLink to={'/settings'}> <ListItem button onClick={handleDrawerClose}> <ListItemIcon><Settings/></ListItemIcon> <ListItemText primary={"Settings"}/> </ListItem> </StyledNavLink> </Tooltip> </List> </Drawer> </React.Fragment>); } export default MobileDrawer;
#!/bin/bash IP_HOST_MACHINE=$(/sbin/ip route|awk '/default/ { print $3 }') RANDOM_KEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 50 | head -n 1) if [[ "$MYSQL_HOST" == "host.machine" ]]; then export MYSQL_HOST="$IP_HOST_MACHINE" fi if [[ "$SECRET_KEY" == "random" ]]; then export SECRET_KEY="$RANDOM_KEY" fi .venv/bin/gunicorn --workers=4 --bind 0.0.0.0:"$PORT" app:app
array = [1, 10, 50, 3, 8] # Get the maximum element max_element = max(array) print(max_element) # Output: 50
@font-face { font-family: '<%= fontName %>'; src: url('<%= fontPath + fontName %>.eot'); src: url('<%= fontPath + fontName %>.eot?#iefix') format('eot'), url('<%= fontPath + fontName %>.woff') format('woff'), url('<%= fontPath + fontName %>.ttf') format('truetype'), url('<%= fontPath + fontName %>.svg#<%= fontName %>') format('svg'); } %icon { font-family: '<%= fontName %>'; font-smoothing: antialiased; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-style: normal; font-variant: normal; font-weight: normal; text-decoration: none; text-transform: none; text-rendering: auto; } @function icon-char($filename) { $char: ''; <% _.each(glyphs, function(glyph) { %> @if $filename == <%= glyph.fileName %> { $char: '\<%= glyph.codePoint %>'; }<% }); %> @return $char; } @mixin icon($filename, $insert: before) { &:#{$insert} { @extend %icon; content: icon-char($filename); } } <% _.each(glyphs, function(glyph) { %>%icon-<%= glyph.fileName %> { @include icon(<%= glyph.fileName %>); } <% }); %>
<gh_stars>0 package com.wangxy.exoskeleton.service.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.wangxy.exoskeleton.api.BaiduTranslateUtil; import com.wangxy.exoskeleton.entity.DictItem; import com.wangxy.exoskeleton.entity.Pagelable; import com.wangxy.exoskeleton.entity.TranslateResult; import com.wangxy.exoskeleton.service.IDealI18NService; import com.wangxy.exoskeleton.service.IDictItemService; import com.wangxy.exoskeleton.service.IPageLableService; @Service public class DealI18NServiceImpl implements IDealI18NService { @Autowired IPageLableService pageLableService; @Autowired IDictItemService dictItemService; /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#autoDealI18N(java.lang.String) */ @Override @Transactional public void autoDealI18N(String path) throws IOException { String pageId = null; String directoryPath = null; File file = new File(path); File[] tempList = new File[1]; if (file.isDirectory()) { tempList = file.listFiles(); //要只取一层目录下的文件 directoryPath = path; String[] split = directoryPath.split("\\\\"); pageId = split[split.length-1]; }else { tempList[0]= file; directoryPath = file.getParent(); String[] pathPart = path.split("\\."); //注意要替换转义字符\得用\\\\ String[] folderAndFile = pathPart[0].split("\\\\"); //文件名 pageId = folderAndFile[folderAndFile.length - 1]; } Set<String> dictSet = new HashSet<String>(); Map<String, String> chineseWords = new HashMap<String, String>(); for (File file1 : tempList) { String absolutePath = file1.getAbsolutePath(); //html中中文字 chineseWords.putAll(jsoupGetCnWordFromHtml(absolutePath)); //数据字典 dictSet.addAll(getDict(absolutePath)); } String dictSqlPath = directoryPath+"/" + pageId+"_dictSql.sql"; generateDictSqlFile(dictSet,dictSqlPath); String pageSqlPath = directoryPath+"/" + pageId+"_pageSql.sql"; // html处理。产生sql脚本 Map<String, TranslateResult> htmlCodeMap = htmlCodeDeal(pageSqlPath, pageId,chineseWords); // 根据数据库,用中文查询对应的标签语法,并替换到文件中 //存放js中文对应的翻译结果 Map<String, TranslateResult> jsCodeMap = new HashMap<String, TranslateResult>(); for (File file1 : tempList) { String absolutePath = file1.getAbsolutePath(); List<String> list = FileUtils.readLines(new File(absolutePath)); // js代码处理。 // 固定替换,固定替换后产生其他中文翻译结果的key List<String> resultList = fixReplaceDeal4JsGenMap(list,jsCodeMap); //直接覆盖原文件 File resultFile = new File(absolutePath); FileUtils.writeLines(resultFile, resultList); } //js中文产生翻译结果。产生json对象,产生文件 generateJsMsgJson(jsCodeMap,directoryPath,pageId); for (File file1 : tempList) { String absolutePath = file1.getAbsolutePath(); List<String> list = FileUtils.readLines(new File(absolutePath)); // 固定替换 List<String> resultListAfterHtml = fixReplaceDeal4Html(list,htmlCodeMap); // js代码处理。 // 翻译替换 //List<String> resultList = replaceDeal4Js(resultListAfterHtml,jsCodeMap); // 固定替换后进行翻译替换 // resultList = translateDeal(resultList); //直接覆盖原文件 File resultFile = new File(absolutePath); FileUtils.writeLines(resultFile, resultListAfterHtml); } System.out.println("========================================"); System.out.println("<%@taglib uri='/WEB-INF/jui.tld' prefix='jui'%>"); System.out.println("<%@include file=\"/topjui/jsp/main/jsinc.jsp\"%>"); System.out.println("<script Language=\"JavaScript\" src=\"js/"+pageId+".<%=LangValue%>.js\"></script>"); System.out.println("<% \n String LangValue=\"\"; \n LangValue=(String)session.getAttribute(\"lang\"); \n %>"); System.out.println(pageId+"Msg.tempInfo"); System.out.println("========================================"); } private void generateJsMsgJson(Map<String, TranslateResult> jsCodeMap,String directoryPath, String pageId) throws IOException { // generateI18nJsFile(jsCodeMap,i18nJsDirectoryPath); Map<String, TranslateResult> tempJsCodeMap = new HashMap<String, TranslateResult>(); Map<String, Object> cnJsMap = new HashMap<String, Object>(); Map<String, Object> enJsMap = new HashMap<String, Object>(); int jsonKeyId = 1; for (Map.Entry<String, TranslateResult> entry : jsCodeMap.entrySet()) { // System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); TranslateResult res = new TranslateResult(); // 现有的没有才去翻译.拿中文匹配 res.setPageId(pageId); res.setSource(entry.getKey()); String lineToTranslate = res.getSource().substring(1,res.getSource().length()-1); String transResult = BaiduTranslateUtil.translate4PrdUpt(lineToTranslate, "auto", "en"); transResult = transResult.replace("< br >", "<br>"); res.setTranslateResult(transResult); res.setJsonKey(res.getPageId()+"MsgInfo"+jsonKeyId);//pageidMsgInfo+自增数字是为了避免重复,后面产生文件后还要自己修改 // pageLableService.addPagelable(convertTranslateResultToPagelable(res)); tempJsCodeMap.put(res.getSource(), res); cnJsMap.put(res.getJsonKey(), lineToTranslate); enJsMap.put(res.getJsonKey(), res.getTranslateResult()); jsonKeyId++; } if (cnJsMap.size()>0) { JSONObject enjson = new JSONObject(enJsMap); JSONObject cnjson = new JSONObject(cnJsMap); String i18nJsDirectoryPath = directoryPath+"/js/"; String cnJsPath = i18nJsDirectoryPath + pageId+".zh_CN.js"; String enJsPath = i18nJsDirectoryPath + pageId+".en.js"; File cnJs = new File(cnJsPath); FileUtils.write(cnJs, pageId+"Msg="+cnjson.toJSONString(cnjson,true)); File enJs = new File(enJsPath); FileUtils.write(enJs, pageId+"Msg="+enjson.toJSONString(enjson,true)); } } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#generateDictSqlFile(java.util.Set, java.lang.String) */ @Override public void generateDictSqlFile(Set<String> dict, String path) throws IOException { if (dict == null||dict.size()==0) { return ; } List<String> dictSql = new ArrayList<String>(); List<String> cnDictSql = null; List<String> enDictSql = null; for (String dictEntryCode : dict) { List<DictItem> enDictItems = dictItemService.getDictItems(dictEntryCode, "en"); if (enDictItems==null||enDictItems.size()==0) {//不存在en List<DictItem> cnDictItems = dictItemService.getCnDictItems(dictEntryCode); cnDictSql = new ArrayList<String>(); enDictSql = new ArrayList<String>(); for (DictItem dictItem : cnDictItems) { cnDictSql.add(generateInsDictSql(dictItem, "zh_CN")); //翻译dict中中文 String transResult = BaiduTranslateUtil.translate4PrdUpt(dictItem.getDictItemName(), "zh", "en"); dictItem.setDictItemName(firstUpperFormat(transResult," ")); enDictSql.add(generateInsDictSql(dictItem, "en")); } String cnLang = "zh_CN"; String delItemExample = "delete from tsys_dict_item where dict_entry_code='"+dictEntryCode+"' and lang='"+cnLang+"';"; dictSql.add(delItemExample); dictSql.addAll(cnDictSql); dictSql.add("\n"); dictSql.add("\n"); String enLang = "en"; String delEnItemExample = "delete from tsys_dict_item where dict_entry_code='"+dictEntryCode+"' and lang='"+enLang+"';"; dictSql.add(delEnItemExample); dictSql.addAll(enDictSql); dictSql.add("\n"); dictSql.add("\n"); } } File resultFile = new File(path); FileUtils.writeLines(resultFile, "UTF-8", dictSql); } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#generateInsDictSql(com.wangxy.exoskeleton.entity.DictItem, java.lang.String) */ @Override public String generateInsDictSql(DictItem dictItem, String lang) { String example = "insert into tsys_dict_item (DICT_ITEM_CODE, DICT_ENTRY_CODE, DICT_ITEM_NAME, DICT_ITEM_ORDER, LIFECYCLE, PLATFORM, REL_CODE, LANG)\n" + "values ("+"'" + dictItem.getDictItemCode() + "'," +"'" + dictItem.getDictEntryCode()+ "'," +"'" + dictItem.getDictItemName()+ "'," + dictItem.getDictItemOrder()+ "," +"null" +"," +"null" +"," +"null" +"," +"'" + lang +"'" +");"; return example; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#getDict(java.lang.String) */ @Override public Set<String> getDict(String path) throws IOException { File input = new File(path); Document doc = Jsoup.parse(input, "UTF-8"); Set<String> dict = new HashSet<String>(); //jui:Init标签属性 Elements allDict = doc.getElementsByTag("jui:Init"); for (Element dictTag : allDict) { String params = dictTag.attr("params"); String[] dictNames = params.split(","); for (String dictName : dictNames) { dict.add(dictName); } } //input标签data-options里的url属性的&key= Elements allInput = doc.getElementsByTag("input"); for (Element dictTag : allInput) { String options = dictTag.attr("data-options"); if (options.contains("url") && options.contains("key=")) { options = options.replaceAll(" ", ""); options = options.replaceAll("&codes=(.*?)',", "',");//勉强模式匹配codes的值,把codes的配置替换为空 options = toStrictJson(options); JSONObject jsonObject; try { jsonObject = JSONObject.parseObject(options); } catch (Exception e) { e.printStackTrace(); System.out.println("错误options="+options); throw e; } String url = jsonObject.getString("url"); //获取url参数 String paramIn = url.substring(url.indexOf("?") + 1, url.length()); paramIn = paramIn.replaceAll("=", "\":\""); paramIn = paramIn.replaceAll("&", "\",\""); paramIn = "{\"" + paramIn + "\"}"; JSONObject urlParam = JSONObject.parseObject(paramIn); dict.add(urlParam.getString("key")); } } return dict; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#htmlCodeDeal(java.lang.String, java.lang.String, java.util.Map) */ @Override @Transactional public Map<String, TranslateResult> htmlCodeDeal(String path, String pageId,Map<String, String> chineseWords) throws IOException { //翻译结果Map,包括直接界面英文,page表现有,百度翻译 Map<String, TranslateResult> translateMap = new HashMap<String, TranslateResult>(); //包括百度翻译部分,直接界面英文 List<TranslateResult> wordNeedGenSql = new ArrayList<TranslateResult>(); // 翻译后,产生tsys_pagelable对象,用这个对象来产生i18N脚本,把对象插入数据库 //获取最大id int id = pageLableService.getMaxId(); //int id = 901000; id = id/100*100; id += 100; for (Map.Entry<String, String> entry : chineseWords.entrySet()) { // System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); TranslateResult res = new TranslateResult(); // 现有的没有才去翻译.拿中文匹配 Pagelable matchPagelable = pageLableService.matchPagelable(entry.getKey()); if (matchPagelable != null) { Pagelable pagelableInEn = pageLableService.getPagelable(matchPagelable.getPageId(), matchPagelable.getLableId(), "en"); res.setPageId(pagelableInEn.getPageId()); res.setLabelId(pagelableInEn.getLableId()); res.setSource(entry.getKey()); res.setTranslateResult(pagelableInEn.getLableInfo()); } else { res.setPageId(pageId); res.setLabelId(String.valueOf(id)); res.setSource(entry.getKey()); // 属性有英文的直接用 if (!StringUtils.isEmpty(entry.getValue())) { String translatedWord = entry.getValue(); res.setTranslateResult(firstUpperFormat(translatedWord, "_")); } else { String transResult = BaiduTranslateUtil.translate4PrdUpt(res.getSource(), "auto", "en"); res.setTranslateResult(firstUpperFormat(transResult, " ")); } // pageLableService.addPagelable(convertTranslateResultToPagelable(res)); wordNeedGenSql.add(res); id++; } translateMap.put(res.getSource(), res); } // 产生翻译表,产生脚本,插入数据库 List<String> pageLableSql = new ArrayList<String>(); if (wordNeedGenSql.size()>0){ //pageLableSql String delExample = "delete from tsys_pagelable where page_id='"+wordNeedGenSql.get(0).getPageId()+"';"; pageLableSql.add(delExample); } Pagelable enLable = new Pagelable(); Pagelable cnLable = new Pagelable(); System.out.println("开始产生html翻译脚本并插入"); for (TranslateResult translateResult : wordNeedGenSql) { String enExample = "insert into tsys_pagelable (PAGE_ID, LABLE_ID, LANG, LABLE_INFO)\n" + "values ('"+translateResult.getPageId()+"', '"+translateResult.getLabelId()+"', 'en', '"+translateResult.getTranslateResult()+"');"; String cnExample = "insert into tsys_pagelable (PAGE_ID, LABLE_ID, LANG, LABLE_INFO)\n" + "values ('"+translateResult.getPageId()+"', '"+translateResult.getLabelId()+"', 'zh_CN', '"+translateResult.getSource()+"');"; pageLableSql.add(enExample); pageLableSql.add(cnExample); enLable.setPageId(translateResult.getPageId()); enLable.setLableId(translateResult.getLabelId()); enLable.setLang("en"); enLable.setLableInfo(translateResult.getTranslateResult()); cnLable.setPageId(translateResult.getPageId()); cnLable.setLableId(translateResult.getLabelId()); cnLable.setLang("zh_CN"); cnLable.setLableInfo(translateResult.getSource()); pageLableService.addPagelable(enLable); pageLableService.addPagelable(cnLable); } File resultFile = new File(path); FileUtils.writeLines(resultFile,"UTF-8",pageLableSql); return translateMap; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#convertTranslateResultToPagelable(com.wangxy.exoskeleton.entity.TranslateResult) */ @Override public Pagelable convertTranslateResultToPagelable(TranslateResult res) { Pagelable pagelable = new Pagelable(); pagelable.setPageId(res.getPageId()); pagelable.setLableId(res.getLabelId()); pagelable.setLang("en"); pagelable.setLableInfo(res.getTranslateResult()); return pagelable; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#fixReplaceDeal4Html(java.util.List, java.util.Map) */ @Override public List<String> fixReplaceDeal4Html(List<String> oriList,Map<String, TranslateResult> htmlCodeMap) throws IOException { List<String> reultLines = new ArrayList<>(); boolean isJsCode = false; for (String ss : oriList) { String resultLine =ss; if (ss.contains("<script>")) { isJsCode = true; } if (!isJsCode) { //遍历key,如果包括key,就去替换 for (Map.Entry<String, TranslateResult> entry : htmlCodeMap.entrySet()) { if (ss.contains("'"+entry.getKey()+"'")||ss.contains("\""+entry.getKey()+"\"")||ss.contains(">"+entry.getKey()+"<")) { TranslateResult translateResult = entry.getValue(); resultLine = resultLine.replace(entry.getKey(), gen18NTag(translateResult)); } } } reultLines.add(resultLine); } // System.out.println(sb.toString()); return reultLines; } public List<String> replaceDeal4Js(List<String> oriList,JSONObject jsCodeMap,String jsonObjName) throws IOException { List<String> reultLines = new ArrayList<>(); boolean isJsCode = false; for (String ss : oriList) { String resultLine =ss; if (ss.contains("<script>")) { isJsCode = true; } if (isJsCode) { //遍历key,如果包括key,就去替换 for (Map.Entry<String, Object> entry : jsCodeMap.entrySet()) { //如果替换了一次就退出单层循环.如果确定一行只有一句中文。一行可能有多句中文所以不能只替换一次就退出 String cnValue = String.valueOf(entry.getValue()); String jsonKey = jsonObjName+"."+entry.getKey(); if (ss.contains(cnValue)) { String tempRegex = "[\"|']"+cnValue+"[\"|']"; List<String> matchString = getMatchString(ss, tempRegex); for (String matchWord : matchString) { resultLine = resultLine.replace(matchWord, jsonKey); } } } } reultLines.add(resultLine); } // System.out.println(sb.toString()); return reultLines; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#gen18NTag(com.wangxy.exoskeleton.entity.TranslateResult) */ @Override public String gen18NTag(TranslateResult translateResult) { return "<jui:I18N page=\""+translateResult.getPageId()+"\" id=\""+translateResult.getLabelId()+"\" ></jui:I18N>"; } public String genJsMsg(TranslateResult translateResult) { // return translateResult.getPageId()+"Msg."+translateResult.getJsonKey(); return translateResult.getJsonKey(); } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#fixReplaceDeal(java.util.List) */ @Override public List<String> fixReplaceDeal4JsGenMap(List<String> oriList,Map<String, TranslateResult> jsCodeMap) throws IOException { List<String> reultLines = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean isJsCode = false; for (String ss : oriList) { // sb.append(ss + "\n"); if (ss.contains("<script>")) { isJsCode = true; } String resultLine =ss; if (isJsCode) { resultLine = fixReplaceDeal(ss); // 如果还有''或者""包含中文,就是要翻译的(包含中文且包含'")(不包含//这样处理快一些),放进map if (!resultLine.contains("//")&&(resultLine.contains("'")||resultLine.contains("\""))) { Set<String> translateLine = getTranslateLine(resultLine); for (String string : translateLine) { jsCodeMap.put(string, null); } } } reultLines.add(resultLine); } // System.out.println(sb.toString()); return reultLines; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#translateDeal(java.util.List) */ @Override public List<String> translateDeal(List<String> oriList) throws IOException { Set<String> lineToTranslate = new HashSet<String>(); //这里只翻译js脚本中 boolean isJsCode = false; for (String ss : oriList) { if (ss.contains("<script>")) { isJsCode = true; } if (isJsCode) { lineToTranslate.addAll(getTranslateLine(ss)); } } // System.out.println(sb.toString()); //翻译产生map集合 //中文字符串-----对应翻译结果对象(id,翻译结果1) List<TranslateResult> translateResults = generateTranslateResult(lineToTranslate); //循环替换 List<String> reultLines = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (String ss : oriList) { String resultLine = new String(""); for (TranslateResult translateResult : translateResults) { resultLine = ss.replaceAll(translateResult.getSource(),translateResult.getPageId()+"."+translateResult.getLabelId()); } reultLines.add(resultLine); } return reultLines; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#generateTranslateResult(java.util.Set) */ @Override public List<TranslateResult> generateTranslateResult(Set<String> lineToTranslate) { List<TranslateResult> translateResults = new ArrayList<TranslateResult>(); int i =0; for (String line : lineToTranslate) { i++; TranslateResult tr = new TranslateResult(); tr.setPageId("temp"); tr.setLabelId("info"+i); tr.setSource(line); String transResult = BaiduTranslateUtil.translate4PrdUpt(line, "zh", "en"); tr.setTranslateResult(firstUpperFormat(transResult," ")); translateResults.add(tr); } return translateResults; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#getTranslateLine(java.lang.String) */ @Override public Set<String> getTranslateLine(String line) { Set<String> translateLine = new HashSet<String>(); String regex = "[\"|'][^,]*?[\"|']"; List<String> matchString = getMatchString(line, regex); for (String matchWord : matchString) { if (isContainChinese(matchWord)){ translateLine.add(matchWord); } } return translateLine; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#getMatchString(java.lang.String, java.lang.String) */ @Override public List<String> getMatchString(String sourceString,String regex) { List<String> matchString = new ArrayList<>(); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(sourceString); while (matcher.find()) { //此处find()每次被调用后,会偏移到下一个匹配 matchString.add(matcher.group());//获取当前匹配的值 } return matchString; } /** * 判断字符串是否包含中文 * @param str * @return */ public static boolean isContainChinese(String str) { Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); Matcher m = p.matcher(str); if (m.find()) { return true; } return false; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#autoReplaceDeal(java.lang.String) */ @Override public String fixReplaceDeal(String inLine) { inLine = inLine.replaceAll("['|\"]提示['|\"]", "dialogMsg.info"); inLine = inLine.replaceAll("['|\"]警告['|\"]", "dialogMsg.warn"); inLine = inLine.replaceAll("['|\"]确认['|\"]", "dialogMsg.confirm"); inLine = inLine.replaceAll("['|\"]请选择要删除的数据!['|\"]", "dialogMsg.delWarnInfo"); inLine = inLine.replaceAll("['|\"]您确认想要删除(.*)['|\"]", "dialogMsg.delConfirmInfo"); //inLine = inLine.replaceAll("[^" + "'*\\+\\+\\+'" + "]", "dialogMsg.processingInfo"); inLine = inLine.replaceAll("['|\"]请选择一条要修改(.*)['|\"]", "dialogMsg.edtWarnInfo"); inLine = inLine.replaceAll(",['|\"](.*)\\+{3,}['|\"]",",dialogMsg.processingInfo"); //inLine = inLine.replaceAll("'正在提交\\+\\+\\+'", "dialogMsg.processingInfo"); return inLine; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#needAutoReplace(java.lang.String) */ @Override public boolean needAutoReplace(String inLine) { // return true; } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#jsoupGetCnWordFromHtml(java.lang.String) */ @Override public Map<String,String> jsoupGetCnWordFromHtml(String path) throws IOException { File input = new File(path); Document doc = Jsoup.parse(input, "UTF-8"); // doc.getElementById("stock_detail") Map<String,String> chinese = new HashMap<String,String>(); //th标签属性 Elements allTh = doc.getElementsByTag("th"); for (Element th : allTh) { String options = th.attr("data-options"); options = toStrictJson(options); JSONObject jsonObject = JSONObject.parseObject(options); if (jsonObject.getString("field").trim().length() > 0) { String key = jsonObject.getString("title"); if (!StringUtils.isEmpty(key)) { chinese.put(key, jsonObject.getString("field")); } } } //input标签属性 Elements allInput = doc.getElementsByTag("input"); for (Element inputTag : allInput) { String options = inputTag.attr("data-options"); System.out.println("原始options="+options); // options = options.replaceAll("\\n", ""); options = options.replace(",groupSeparator:','", "");//特殊情况 options = options.replaceAll(" ", ""); options = options.replaceAll("&codes=(.*?)',", "',");//勉强模式匹配codes的值,把codes的配置替换为空 options = options.replaceAll(",prompt:'(.*?)',", "',");//勉强模式匹配prompt的值,把prompt替换为空 // options = options.replaceAll("\r\n|\r|\n", ""); options = options.replaceAll("\r", ""); options = options.replaceAll("\n", ""); System.out.println("去换行后="+options); options = options.replaceAll("\\{(.*)\\}", "temp");//替换buttonParams options = toStrictJson(options); options = options.replaceAll("\\[(.*)\\]", "temp");//替换validType JSONObject jsonObject = null; try { jsonObject = JSONObject.parseObject(options); } catch (Exception e) { e.printStackTrace(); System.out.println("错误options="+options); throw e; } String key = jsonObject.getString("label"); if (!StringUtils.isEmpty(key)) { chinese.put(key, jsonObject.getString("name")); } } //a标签包裹值,属性值text Elements allATag = doc.getElementsByTag("a"); for (Element aTag : allATag) { // chinese.put(aTag.text(), aTag.attr("id")); if (!StringUtils.isEmpty(aTag.text())) { chinese.put(aTag.text(), ""); } String options = aTag.attr("data-options"); if (options.contains("text")) { System.out.println("原始options="+options); options = toStrictJson(options); JSONObject jsonObject = null; try { jsonObject = JSONObject.parseObject(options); } catch (Exception e) { e.printStackTrace(); System.out.println("错误options="+options); throw e; } String key = jsonObject.getString("text"); if (!StringUtils.isEmpty(key)) { chinese.put(key, ""); } } } //legend标签包裹值 Elements allLegendTag = doc.getElementsByTag("legend"); for (Element legend : allLegendTag) { String key = legend.text(); if (!StringUtils.isEmpty(key)) { chinese.put(key, ""); } } //label标签包裹值 Elements allLabelTag = doc.getElementsByTag("label"); for (Element label : allLabelTag) { String key = label.text(); if (!StringUtils.isEmpty(key)) { chinese.put(key, ""); } } //div标签属性title Elements allDiv = doc.getElementsByTag("div"); for (Element div : allDiv) { String title = div.attr("title"); if (!StringUtils.isEmpty(title)) { chinese.put(title, ""); } } return chinese; /* List<String> reultLines = new ArrayList<>(); List<String> list = FileUtils.readLines(new File(path)); StringBuilder sb = new StringBuilder(); for (String ss : list) { sb.append(ss + "\n"); // 根据指定情况替换 } System.out.println(sb.toString()); String resultPath = path.split("\\.")[0] + "_res_" + ".jsp"; File resultFile = new File(resultPath); FileUtils.writeLines(resultFile, list); */ } /* (non-Javadoc) * @see com.wangxy.exoskeleton.controller.IDealI18NService#toStrictJson(java.lang.String) */ @Override public String toStrictJson(String options) { String regex = "\\[.*\\]"; options = options.replaceAll(regex,"validType"); options = options.replaceAll("'",""); options = options.replaceAll("\"",""); options = options.replaceAll(":","\":\""); options = options.replaceAll(",","\",\""); options = "{\"" + options +"\"}"; return options; } /** * 首字母大写 * 产生英文格式调整,首字母大写 * @param targetLangWord * @return */ public static String firstUpperFormat(String targetLangWord,String splitword) { String[] words = targetLangWord.split(splitword); String newWord = ""; //按空格分隔成数组 for (int i = 0; i <words.length ; i++) { // .substring(0,1) 截取数组的首字母 +split[i].substring(1); 再加上后面 String word = words[i].substring(0, 1).toUpperCase()+words[i].substring(1); newWord+=" "; newWord+=word; } return newWord.replaceFirst(" ", "");//用于去掉第一个空格 } @Override public void jsCodeReplace(String path) throws IOException { String pageId = null; String directoryPath = null; File file = new File(path); File[] tempList = new File[1]; if (file.isDirectory()) { tempList = file.listFiles(); //要只取一层目录下的文件 directoryPath = path; String[] split = directoryPath.split("\\\\"); pageId = split[split.length-1]; }else { tempList[0]= file; directoryPath = file.getParent(); String[] pathPart = path.split("\\."); //注意要替换转义字符\得用\\\\ String[] folderAndFile = pathPart[0].split("\\\\"); //文件名 pageId = folderAndFile[folderAndFile.length - 1]; } //读取文件,json String cnJsPath = directoryPath+"/js/"+pageId+".zh_CN.js"; File cnJs = new File(cnJsPath); String cnJsContent = FileUtils.readFileToString(cnJs, "UTF-8"); JSONObject cnjsJsonObj = JSON.parseObject(cnJsContent.substring(cnJsContent.indexOf("{"))); String jsonObjName = pageId+"Msg"; for (File file1 : tempList) { String absolutePath = file1.getAbsolutePath(); List<String> list = FileUtils.readLines(new File(absolutePath)); // 固定替换 // js代码处理。 // 翻译替换 List<String> resultList = replaceDeal4Js(list,cnjsJsonObj,jsonObjName); // 固定替换后进行翻译替换 // resultList = translateDeal(resultList); //直接覆盖原文件 File resultFile = new File(absolutePath); FileUtils.writeLines(resultFile, resultList); } } }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <map> #include <memory> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/arena.h> #include <google/protobuf/map.h> #include <google/protobuf/arena_test_util.h> #include <google/protobuf/map_unittest.pb.h> #include <google/protobuf/map_test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/map_field_inl.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/wire_format_lite_inl.h> #include <gtest/gtest.h> namespace google { namespace protobuf { namespace internal { using unittest::TestAllTypes; class MapFieldBaseStub : public MapFieldBase { public: typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; MapFieldBaseStub() {} explicit MapFieldBaseStub(Arena* arena) : MapFieldBase(arena) {} void SyncRepeatedFieldWithMap() const { MapFieldBase::SyncRepeatedFieldWithMap(); } void SyncMapWithRepeatedField() const { MapFieldBase::SyncMapWithRepeatedField(); } // Get underlined repeated field without synchronizing map. RepeatedPtrField<Message>* InternalRepeatedField() { return repeated_field_; } bool IsMapClean() { return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_MAP; } bool IsRepeatedClean() { return state_.load(std::memory_order_relaxed) != STATE_MODIFIED_REPEATED; } void SetMapDirty() { state_.store(STATE_MODIFIED_MAP, std::memory_order_relaxed); } void SetRepeatedDirty() { state_.store(STATE_MODIFIED_REPEATED, std::memory_order_relaxed); } bool ContainsMapKey(const MapKey& map_key) const { return false; } bool InsertOrLookupMapValue(const MapKey& map_key, MapValueRef* val) { return false; } bool DeleteMapValue(const MapKey& map_key) { return false; } bool EqualIterator(const MapIterator& a, const MapIterator& b) const { return false; } int size() const { return 0; } void MapBegin(MapIterator* map_iter) const {} void MapEnd(MapIterator* map_iter) const {} void InitializeIterator(MapIterator* map_iter) const {} void DeleteIterator(MapIterator* map_iter) const {} void CopyIterator(MapIterator* this_iterator, const MapIterator& other_iterator) const {} void IncreaseIterator(MapIterator* map_iter) const {} void SetDefaultMessageEntry(const Message* message) const {} const Message* GetDefaultMessageEntry() const { return NULL; } }; class MapFieldBasePrimitiveTest : public ::testing::Test { protected: typedef unittest::TestMap_MapInt32Int32Entry_DoNotUse EntryType; typedef MapField<EntryType, int32, int32, WireFormatLite::TYPE_INT32, WireFormatLite::TYPE_INT32, false> MapFieldType; MapFieldBasePrimitiveTest() { // Get descriptors map_descriptor_ = unittest::TestMap::descriptor() ->FindFieldByName("map_int32_int32") ->message_type(); key_descriptor_ = map_descriptor_->FindFieldByName("key"); value_descriptor_ = map_descriptor_->FindFieldByName("value"); // Build map field map_field_.reset(new MapFieldType); map_field_base_ = map_field_.get(); map_ = map_field_->MutableMap(); initial_value_map_[0] = 100; initial_value_map_[1] = 101; map_->insert(initial_value_map_.begin(), initial_value_map_.end()); EXPECT_EQ(2, map_->size()); } std::unique_ptr<MapFieldType> map_field_; MapFieldBase* map_field_base_; Map<int32, int32>* map_; const Descriptor* map_descriptor_; const FieldDescriptor* key_descriptor_; const FieldDescriptor* value_descriptor_; std::map<int32, int32> initial_value_map_; // copy of initial values inserted }; TEST_F(MapFieldBasePrimitiveTest, SpaceUsedExcludingSelf) { EXPECT_LT(0, map_field_base_->SpaceUsedExcludingSelf()); } TEST_F(MapFieldBasePrimitiveTest, GetRepeatedField) { const RepeatedPtrField<Message>& repeated = reinterpret_cast<const RepeatedPtrField<Message>&>( map_field_base_->GetRepeatedField()); EXPECT_EQ(2, repeated.size()); for (int i = 0; i < repeated.size(); i++) { const Message& message = repeated.Get(i); int key = message.GetReflection()->GetInt32(message, key_descriptor_); int value = message.GetReflection()->GetInt32(message, value_descriptor_); EXPECT_EQ(value, initial_value_map_[key]); } } TEST_F(MapFieldBasePrimitiveTest, MutableRepeatedField) { RepeatedPtrField<Message>* repeated = reinterpret_cast<RepeatedPtrField<Message>*>( map_field_base_->MutableRepeatedField()); EXPECT_EQ(2, repeated->size()); for (int i = 0; i < repeated->size(); i++) { const Message& message = repeated->Get(i); int key = message.GetReflection()->GetInt32(message, key_descriptor_); int value = message.GetReflection()->GetInt32(message, value_descriptor_); EXPECT_EQ(value, initial_value_map_[key]); } } TEST_F(MapFieldBasePrimitiveTest, Arena) { // Allocate a large initial block to avoid mallocs during hooked test. std::vector<char> arena_block(128 * 1024); ArenaOptions options; options.initial_block = &arena_block[0]; options.initial_block_size = arena_block.size(); Arena arena(options); { // TODO(liujisi): Re-write the test to ensure the memory for the map and // repeated fields are allocated from arenas. // NoHeapChecker no_heap; MapFieldType* map_field = Arena::CreateMessage<MapFieldType>(&arena); // Set content in map (*map_field->MutableMap())[100] = 101; // Trigger conversion to repeated field. map_field->GetRepeatedField(); } { // TODO(liujisi): Re-write the test to ensure the memory for the map and // repeated fields are allocated from arenas. // NoHeapChecker no_heap; MapFieldBaseStub* map_field = Arena::CreateMessage<MapFieldBaseStub>(&arena); // Trigger conversion to repeated field. EXPECT_TRUE(map_field->MutableRepeatedField() != NULL); } } namespace { enum State { CLEAN, MAP_DIRTY, REPEATED_DIRTY }; } // anonymous namespace class MapFieldStateTest : public testing::TestWithParam<State> { public: protected: typedef unittest::TestMap_MapInt32Int32Entry_DoNotUse EntryType; typedef MapField<EntryType, int32, int32, WireFormatLite::TYPE_INT32, WireFormatLite::TYPE_INT32, false> MapFieldType; MapFieldStateTest() : state_(GetParam()) { // Build map field map_field_.reset(new MapFieldType()); map_field_base_ = map_field_.get(); Expect(map_field_.get(), MAP_DIRTY, 0, 0, true); switch (state_) { case CLEAN: AddOneStillClean(map_field_.get()); break; case MAP_DIRTY: MakeMapDirty(map_field_.get()); break; case REPEATED_DIRTY: MakeRepeatedDirty(map_field_.get()); break; default: break; } } void AddOneStillClean(MapFieldType* map_field) { MapFieldBase* map_field_base = map_field; Map<int32, int32>* map = map_field->MutableMap(); (*map)[0] = 0; map_field_base->GetRepeatedField(); Expect(map_field, CLEAN, 1, 1, false); } void MakeMapDirty(MapFieldType* map_field) { Map<int32, int32>* map = map_field->MutableMap(); (*map)[0] = 0; Expect(map_field, MAP_DIRTY, 1, 0, true); } void MakeRepeatedDirty(MapFieldType* map_field) { MakeMapDirty(map_field); MapFieldBase* map_field_base = map_field; map_field_base->MutableRepeatedField(); // We use MutableMap on impl_ because we don't want to disturb the syncing Map<int32, int32>* map = map_field->impl_.MutableMap(); map->clear(); Expect(map_field, REPEATED_DIRTY, 0, 1, false); } void Expect(MapFieldType* map_field, State state, int map_size, int repeated_size, bool is_repeated_null) { MapFieldBase* map_field_base = map_field; MapFieldBaseStub* stub = reinterpret_cast<MapFieldBaseStub*>(map_field_base); // We use MutableMap on impl_ because we don't want to disturb the syncing Map<int32, int32>* map = map_field->impl_.MutableMap(); RepeatedPtrField<Message>* repeated_field = stub->InternalRepeatedField(); switch (state) { case MAP_DIRTY: EXPECT_FALSE(stub->IsMapClean()); EXPECT_TRUE(stub->IsRepeatedClean()); break; case REPEATED_DIRTY: EXPECT_TRUE(stub->IsMapClean()); EXPECT_FALSE(stub->IsRepeatedClean()); break; case CLEAN: EXPECT_TRUE(stub->IsMapClean()); EXPECT_TRUE(stub->IsRepeatedClean()); break; default: FAIL(); } EXPECT_EQ(map_size, map->size()); if (is_repeated_null) { EXPECT_TRUE(repeated_field == NULL); } else { EXPECT_EQ(repeated_size, repeated_field->size()); } } std::unique_ptr<MapFieldType> map_field_; MapFieldBase* map_field_base_; State state_; }; INSTANTIATE_TEST_CASE_P(MapFieldStateTestInstance, MapFieldStateTest, ::testing::Values(CLEAN, MAP_DIRTY, REPEATED_DIRTY)); TEST_P(MapFieldStateTest, GetMap) { map_field_->GetMap(); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), CLEAN, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } } TEST_P(MapFieldStateTest, MutableMap) { map_field_->MutableMap(); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } } TEST_P(MapFieldStateTest, MergeFromClean) { MapFieldType other; AddOneStillClean(&other); map_field_->MergeFrom(other); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } Expect(&other, CLEAN, 1, 1, false); } TEST_P(MapFieldStateTest, MergeFromMapDirty) { MapFieldType other; MakeMapDirty(&other); map_field_->MergeFrom(other); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } Expect(&other, MAP_DIRTY, 1, 0, true); } TEST_P(MapFieldStateTest, MergeFromRepeatedDirty) { MapFieldType other; MakeRepeatedDirty(&other); map_field_->MergeFrom(other); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); } Expect(&other, CLEAN, 1, 1, false); } TEST_P(MapFieldStateTest, SwapClean) { MapFieldType other; AddOneStillClean(&other); map_field_->Swap(&other); Expect(map_field_.get(), CLEAN, 1, 1, false); switch (state_) { case CLEAN: Expect(&other, CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(&other, MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(&other, REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, SwapMapDirty) { MapFieldType other; MakeMapDirty(&other); map_field_->Swap(&other); Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); switch (state_) { case CLEAN: Expect(&other, CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(&other, MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(&other, REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, SwapRepeatedDirty) { MapFieldType other; MakeRepeatedDirty(&other); map_field_->Swap(&other); Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); switch (state_) { case CLEAN: Expect(&other, CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(&other, MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(&other, REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, Clear) { map_field_->Clear(); if (state_ != MAP_DIRTY) { Expect(map_field_.get(), MAP_DIRTY, 0, 1, false); } else { Expect(map_field_.get(), MAP_DIRTY, 0, 0, true); } } TEST_P(MapFieldStateTest, SpaceUsedExcludingSelf) { map_field_base_->SpaceUsedExcludingSelf(); switch (state_) { case CLEAN: Expect(map_field_.get(), CLEAN, 1, 1, false); break; case MAP_DIRTY: Expect(map_field_.get(), MAP_DIRTY, 1, 0, true); break; case REPEATED_DIRTY: Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); break; default: break; } } TEST_P(MapFieldStateTest, GetMapField) { map_field_base_->GetRepeatedField(); if (state_ != REPEATED_DIRTY) { Expect(map_field_.get(), CLEAN, 1, 1, false); } else { Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); } } TEST_P(MapFieldStateTest, MutableMapField) { map_field_base_->MutableRepeatedField(); if (state_ != REPEATED_DIRTY) { Expect(map_field_.get(), REPEATED_DIRTY, 1, 1, false); } else { Expect(map_field_.get(), REPEATED_DIRTY, 0, 1, false); } } } // namespace internal } // namespace protobuf } // namespace google
<filename>demo/mysetdefault.py allGuests = { 'Alice': {'apples': 15, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1} } def totalBrought(): item_num = {} for item in allGuests.values(): for k,v in item.items(): item_num.setdefault(k,0) item_num[k] = item_num[k] + v print(item_num) totalBrought() # if 'color' not in spam: # spam['color'] = 'black' # # spam.setdefault('color', 'black')
Knjiga je djelo uma, radi svoj posao na način na koji um smatranajbolje. To je opasno. Je rad nekih samo individualnog uma vjerovatnosluže ciljevima kolektivno prihvatili kompromise, koji su poznati uškola kao "standardi"? Bilo vidu da bi hrabro stavio sebe dalje uraditi sve sama je sigurno loš primjer za studente, i vjerojatno, akoNe veoma antisocijalnim, barem malo off-centar, samo-popustljiv,elitistička. ... To je samo dobar pedagogije, dakle, da se drži podalje od takvihstvari, i korištenje umjesto toga, ako film-trake i rap-sesija mora bitidopuniti, 'tekstovi,' odabran, ili pripremljen, ili prilagoditi, realprofesionalci. Ti tekstovi se nazivaju 'materijal za čitanje. " Oni suakademski ekvivalent 'slušanje materijala' koja ispunjava čekanja sobe,i "jede materijal 'koji možete kupiti u hiljadama zgodno jeloresurs centara duž puteva. -- The Underground Grammarian % Definicija nastave: casting lažne bisere pred svinje pravi. -- Bill Cain, "Stand Up Tragedy" % Mozak budale vari filozofiju u glupost, nauku u praznovjerje, iumjetnost u cjepidlačenje. Stoga visoko obrazovanje. -- G. B. Shaw % Dobro pitanje nikad nije odgovorio. To nije vijak da se zategnutina svoje mjesto, ali seme da se sadi i da nose više sjemena premaNadam se ozelenjavanja pejzaža ideje. -- John Ciardi % Život gramatičar je uvijek u napetim. -- John Ciardi % Veliki broj ljudi misle da razmišljaju kada su samopreuređivanje njihove predrasude. -- William James % Majka Miš je to njen veliki legla za šetnju po kuhinjipod jedan dan kada je lokalna mačka, po podvig stealth neobično čak i zasvoje vrste, uspio da primi ih u korner. Djeca su šćućurili,užasnuta ovim strašnim zvijer, žalostivo plače, "Pomoć, majko!Spasi nas! Spasi nas! Mi smo uplašeni, majko! "Majka Mouse, sa beznadežno hrabrost roditelja štiti svojedjeca, okrenuo sa zubima ogoljeno do mačka, visokim ogroman iznad njih,i odjednom je počeo da laje na način koji bi učinio bilo Dobermanponosan. U zaprepastilo mačka pobjegli u strahu za svoj život.Kao što joj je zahvalan potomstvo nagrnuli oko nje viče: "O, majko,vi nas je spasio! "i" To! Uplašio si mačka dalje! "okrenula da ihnamjerno i izjavio: "Vidiš kako je korisno je znati drugijezik? " -- William James % Parabola moderne istraživanja:Bob je izgubio ključeve u sobi koja je tamna, osim za jedanvedro lit ugla."Zašto tražiš pod svjetlo, izgubio si ih u mraku!""Vidim samo ovdje." -- William James % Olovka sa ni u jednom trenutku ne treba gumica. -- William James % Plan za unapređenje engleskog Spellingpripisuje Mark TwainNa primjer, u prvoj godini 1 da beskorisno "C" će biti ispuštenada se replased bilo "k" ili "S", a isto tako "x" više bi nebiti dio abecede. Jedini kase u kojoj je "C" će biti zadržanbi bio "ch" formacije, koja će se baviti kasnije. godine 2Možda reforme "W" pravopisa, tako da je "što" i "One" će uzetiisti konsonant, Wile Godina 3 može i ukinuti "y" replasing sa"Ja" i Iear 4 moći Fiks je "g / j" Anomali wonse i za sve.Jenerally, onda, poboljšanje bi kontinue iear bai iearsa Iear 5 radi Awai sa beskorisnim dvostruko konsonants, i Iears 6-12ili tako modifaiing vowlz i rimeining voist i unvoist konsonants.Bai Iear 15 ili sou, to wud fainali bi posibl tu Meik ius ov treridandant letez "C", "y" i "x" - Bai sada jast je Memorija u maindzov Ould doderez - Tu riplais "ch", "sh", i "th" rispektivli.Fainali, Xen, aafte sam 20 iers ov orxogrefkl riform, WI WudHEV je lojikl, kohirnt speling u ius xrewawt XE Ingliy-Govorno werld. -- William James % Profesor je onaj koji govori u snu nekog drugog. -- William James % Čitač navodi da kada je pacijent umro, prisutni doktorsnimljen sljedeće na grafikonu pacijenta: "Pacijent nije ispunilanjegova wellness potencijal. "Još jedan doktor javlja da je u posljednje izdanje * American JournalFamily Practice * buve su se zvali "hematophagous insekata vektora."prenosi Čitač da ih vojska naziva "vertikalno raspoređeni protivosoblje uređajima. "Verovatno ih zvati bombe.Na bazi McClellan Air Force u Sacramento, California, civilmehaničari su postavljeni na "ne-dužnost, status ne plate." To jest, oni su otkaz.Nakon što je putovanje života, naš čitalac poslao svog dvanaest rolnifilma u Kodak za razvoj (ili "obrada", kao Kodak voli da ga zovu)samo da dobiju sledeće obaveštenje: "Moramo prijavi da je tokom rukovanjaVaše dvanaest 35mm Kodachrome slajd naredbe, filmovi su bili uključeni uneobično laboratorija iskustvo. "Upotreba pasivnih je posebno lijepdodir, zar ne mislite? Niko ništa filmova učinio; oni samo imali lošiskustvo. Naravno, naš čitač može uvijek vratiti na Tibet i uzmeslika sve iznova, koristeći dvanaest zamjene role Kodak tako velikodušnoposlao ga je. -- Quarterly Review of Doublespeak (NCTE) % Student koji mijenja tok istorije je vjerovatno polaganje ispita. -- Quarterly Review of Doublespeak (NCTE) % Sinonim je riječ koristite kad ne možete prvo čarolija je li riječmislili. -- Burt Bacharach % Tautologija je stvar koja je tautološka. -- Burt Bacharach % Univerzitet je ono što je koledž postaje kada fakulteta gubi intereskod učenika. -- John Ciardi % "A Univerzitet bez učenika kao mast bez zgazio." -- Ed Nather, professor of astronomy at UT Austin % O svemu su neki ljudi postigli u životu je da pošalje sina na Harvard. -- Ed Nather, professor of astronomy at UT Austin % Sažetak:Ova studija ispitala incidencija mašne zategnutosti u grupiod 94 bijelo-okovratnik rade muškarci i efekat čvrsto poslovno-okovratnik košuljei vezati na vizuelne performanse od 22 muških ispitanika. Od bijelo-okovratnikmuškarci meri, 67% je utvrđeno da se nosi mašne to je jače negovrat obim. Vizuelna diskriminacije 22 ispitanika jeocijenjen pomoću testa kritična treperenja frekvencije (CFF). Rezultati CFFtest pokazuje da čvrsto mašne značajno smanjio vizualniučinak subjekata i da vizualni učinak nije poboljšalaOdmah kada je uklonjen čvrsto mašne.Vrat u odnosu na vizuelne performanse. "Ljudskog faktora 29,# 1 (Februar 1987), str. 67-71. -- Langan, L. M. and Watkins, S. M. "Pressure of Menswear on the % Akademska politika je najviše začarani i gorak oblik politike,jer je ulog tako nisko. -- Wallace Sayre % Akademici brige, to je ko. -- Wallace Sayre % =============== Brucoša NAPOMENA ===============Da bi se smanjila zakazivanje zabune, molimo vas da shvatite da ako uzimate jedanNaravno, što se nudi u samo jednom trenutku na određeni dan, a drugi koji jeponudio u svako doba na taj dan, drugi razred će biti uređen kao napriuštiti maksimalno neugodnosti studentu. Na primjer, ako se desiraditi na kampusu, od vas će imati 1-2 sati između klasa. Ako putujete,tu će biti najmanje 6 sati između dvije klase. -- Wallace Sayre % Investicija u znanje uvijek isplati najboljem interesu. -- Benjamin Franklin % Bilo dva filozofa može reći jedni drugima sve što znaju u dva sata. -- Oliver Wendell Holmes, Jr. % Kao što je general de Gaulle povremeno priznaje Ameriku da bude kćerEvrope, tako da sam zadovoljan da dođe na Yale, kćer Harvard. -- J. F. Kennedy % Dokle god je odgovor je u pravu, koga briga ako je pitanje nije u redu? -- J. F. Kennedy % Ukratko rečeno, nalazi se da kada je predstavio sa nizompodataka ili niz događaja u kojima su instrukcije da otkrijuosnovni poredak, subjekti pokazuju snažne tendencije da vide kakoi kauzalnost u slučajnim nizovima, da vide obrazac ili korelacijašto se čini a priori intuitivno ispravan čak i kada je stvarna korelacijau podacima je nelogično, da skoči na zaključke o pravilnomhipoteza, da traže i da koriste samo pozitivne ili potvrdne dokaze, datumačenje dokaza liberalno kao potvrde, da ne stvaraju iliprocijeniti alternativne hipoteze, i nakon što je na taj način uspio da se razotkrijesamo da potvrde slučajevima, da se tako pogrešno uvjeren važenjanjihovih presuda (Jahoda, 1969; Einhorn i Hogarth, 1978). Uanalizu događaja iz prošlosti, te tendencije su pogoršani neuspjeh ucijeniti zamke post hoc analize. -- A. Benjamin % Britanski obrazovanje je vjerojatno najbolji na svijetu, ako može opstatito. Ako ne možete da se ništa nije ostalo za vas, ali i diplomatskog kora. -- Peter Ustinov % ... Ali ako se smijati sa poruzi, nikada nećemo shvatiti. ljudskiintelektualni kapacitet nije promijenjen hiljadama godina tako dalekomožemo reći. Ako inteligentni ljudi uložili intenzivne energije u pitanjimakoji sada čini glupo da nas, onda je neuspjeh leži u našem razumijevanjunjihovog svijeta, a ne u svoje iskrivljene percepcije. Čak i standardprimjer drevne gluposti - rasprava o anđelima na vaši mozgovi -ima smisla kada shvatite da teolozi nisu razgovaralida li pet ili osamnaest bi se uklopio, ali da li je pin mogao udomitikonačan ili beskonačan broj. -- S. J. Gould, "Wide Hats and Narrow Minds" % Campus trotoara nikada postojati kao najpraviju linija između dvije točke. -- M. M. Johnston % Upoređujući informacija i znanja je kao da pitate da li je debljinasvinje je više ili manje zelene od određenog pravilo udarač. " -- David Guaspari % Dragi Freshman,Vi ne znate ko sam i iskreno ne bi trebalo da zanima, alinepoznato da ti imamo nešto zajedničko. Mi smo oboje priličnosklon greškama. Ja sam izabran za studentskog predsjednika Vlade pogreška, i došli u školu ovdje greškom. -- David Guaspari % Draga gospođice Manners:Moj dom ekonomija učitelj kaže da se nikada ne mora staviti nečijelaktovima na stolu. Međutim, ja sam pročitao da je jedan lakat, izmeđukurseva, sve je u redu. Koji je ispravan?Gentle Reader:Za potrebe odgovaranja preglede u vašem domu ekonomijeklase, vaš učitelj je ispravan. Lov na ovaj principobrazovanje može biti čak i veći značaj sada nego učenjeispravan trenutni ponašanje za stolom, od vitalnog značaja kao Miss Manners smatra da je. -- David Guaspari % Odjel predsednici nikad ne umiru, oni samo gube fakultetima. -- David Guaspari % Da li ste znali Univerziteta Iowa zatvoren nakon nekog ukrao knjigu? -- David Guaspari % Ne blokira ustava intelekt sa bita znanja sumnjive namjene. -- David Guaspari % Znate li razliku između obrazovanja i iskustva? obrazovanjeje ono što dobivate kada ste pročitali sitnim slovima; Iskustvo je ono što dobivatekad ne znaš. -- Pete Seeger % Da li mislite da nepismeni ljudi dobiti puni efekat abeceda juha? -- Pete Seeger % Obrazovanje i religija su dvije stvari nisu regulisana ponude ipotražnja. U manje od bilo ljudi, manje žele. -- Charlotte Observer, 1897 % Obrazovanje je divljenja stvar, ali to je dobro zapamtiti, s vremena navremena da ništa što je vrijedno znati da se uči. -- Oscar Wilde, "The Critic as Artist" % Obrazovanje se uči ono što nije ni znala da nisi znao. -- Daniel J. Boorstin % Obrazovanje je proces casting lažnih bisera pred pravi svinje. -- Irwin Edman % Obrazovanje je ono što preživljava kada ono što je naučio je zaboravljena. -- B. F. Skinner % Obrazovni televizije treba apsolutno zabranjeno. To može samo dovestina nerazumne razočarenje kada vaše dijete otkriva da je pismaabecede ne skoči se iz knjiga i plešu oko saroyal-plava pilića. -- Fran Lebowitz, "Social Studies" % Elokvencija je logika na vatru. -- Fran Lebowitz, "Social Studies" % Enciklopedija za prodaju po oca. Sin zna sve. -- Fran Lebowitz, "Social Studies" % Inženjering: "Kako će ovaj posao?"Nauka: "Zašto će ovaj posao?"Uprava: "Kada će ovaj posao?"Liberal Arts: "Želite li pomfrit sa tim?" -- Fran Lebowitz, "Social Studies" % Čak i ako ne nauče da govore korektnom engleskom jeziku, koga ćeš govoritito? -- Clarence Darrow % Gdje god idem sam pitao da li mislim da univerzitet guši pisaca. mojamišljenje je da oni nisu dovoljno ih ugušiti. Postoji mnogo bestselerkoje su se mogle spriječiti dobar učitelj. -- Flannery O'Connor % Ispiti su impresivan čak i najbolje pripremljeni, začak i najveća budala može tražiti više i najmudriji čovjek može da odgovori. -- C. C. Colton % Iskustvo je najgori nastavnik. Uvijek daje prvi test iinstrukcije kasnije. -- C. C. Colton % F u cn rd THS u CNT SPL WRTH a dm! -- C. C. Colton % F u cn rd THS, ITN tyg h myxbl cd. -- C. C. Colton % F u cn rd THS, u CN GT GD jb n cmptr prgrmmng. -- C. C. Colton % F u cn rd THS, u r prbbly je LSY spllr. -- C. C. Colton % Fortune vodič za Freshman Notetaking:KADA JE PROFESOR KAŽE: pišete:Vjerojatno najveći kvalitet poezije John Milton - rođen 1608John Milton, koji je rođen u 1608, jespoj ljepote i snage. malo imajubriljirao ga u upotrebi engleskog jezika,ili što se toga tiče, u lucidnost stiha forme,'Paradise Lost' se kaže da je najvećasingle pjesma ikad napisana. "Trenutno istoričari su došli do Većina problema koje sadaSumnjam kompletan advantageousness lice Sjedinjene Države sunekih Roosevelt je politika ... direktno povezati nazamršenu i pohlepa predsjednikaRoosevelt.... Moguće je da mi jednostavno do Professor Mitchell jene razumijem ruski gledišta ... komunista. -- C. C. Colton % Četrnaest godina u profesor Dodge me je naučila da se može raspravljatigenijalno u ime bilo koje teorije, primijeniti na bilo koji komad literature.Ovo je rijetko štetan, jer obično niko čita takve eseja. -- Robert Parker, quoted in "Murder Ink", ed. D. Wynn % Odlazak u crkvu ne čini osoba vjerske, niti ide u školunapraviti osoba obrazovani, ništa više nego da se ide u garažu čini osobu automobil. -- Robert Parker, quoted in "Murder Ink", ed. D. Wynn % Dobar dan izbjeći policiju. Puzi u školu. -- Robert Parker, quoted in "Murder Ink", ed. D. Wynn % Dobra nastava je jedna četvrtina pripreme i tri četvrtine dobro pozorište. -- Gail Godwin % Diplomiram život: To nije samo posao. To je zaloge. -- Gail Godwin % Diplomirani studenti i većina profesora nisu pametniji od dodiplomaca.Oni su samo stariji. -- Gail Godwin % On je sam uči ima budala za gospodara. -- Benjamin Franklin % "On je bio skroman, dobroćudan dečko. To je bio Oxford da ga je nepodnošljivo." -- Benjamin Franklin % Onaj koji piše bez pogrešno napisane riječi spriječio prvi sumnjena granicama svojih stipendiju ili, u društvenom svijetu, njegove opšteobrazovanja i kulture. -- Julia Norton McCorkle % [On] odveo me u svoju biblioteku i pokazao mi njegove knjige, od kojih je on imaokompletan set. -- Ring Lardner % Visoko obrazovanje pomaže kapaciteta zaradu. Pitajte bilo kog profesor na koledžu. -- Ring Lardner % Povijest knjige koje sadrže laži su izuzetno dosadni. -- Ring Lardner % Povijest nije ništa drugo nego zbirka basni i beskorisne sitnice,pretrpan sa masu nepotrebnih brojke i vlastita imena. -- Leo Tolstoy % Kako objašnjavate škole na višu inteligenciju? -- Elliot, "E.T." % Ja sam bookaholic. Ako ste pristojna osoba, nećete me prodatidrugu knjigu. -- Elliot, "E.T." % "Nisam siguran šta je to, ali je` F 'bi to udostojiti samo. " -- English Professor % Vraćam se ovo inače dobro kucanje papir da ti jer je nekoje štampana gluposti sve preko toga i stavite svoje ime na vrhu. -- Professor Lowd, English, Ohio University % Cijenim činjenicu da je ovaj nacrt je učinjeno na brzinu, ali neki odrečenica koju šalje u svijet da radite svoj posao za Vasdangubljenja u konobama ili spava pored autoputa.University of Tennessee Knoxville -- Dr. Dwight Van de Vate, Professor of Philosophy, % Došao sam od dvanaest godina koledža i nisam ni znao kako da šije.Sve što sam mogao je račun - Nisam mogao ni računa za sebe. -- Firesign Theatre % Došao sam u MIT da se obrazovanje za sebe i diplomu za moju majku. -- Firesign Theatre % Napravio sam ovo pismo duže nego što je uobičajeno, jer mi nedostaje vremena da sečine ga kraće. -- Blaise Pascal % "Moram vas uvjeriti, ili barem snijeg tebe ..." -- Prof. Romas Aleliunas, CS 435 % Čuo sam definiciju intelektualca, da sam mislio da je vrlo zanimljivo:čovjek koji traje više riječi nego je potrebno reći više nego što zna. -- Dwight D. Eisenhower % Poštujem vjeru, ali sumnja je ono što ti daje obrazovanje. -- Wilson Mizner % Mislim da je vaša mišljenja su razumne, osim one o mom mentalnomnestabilnost. -- Psychology Professor, Farifield University % "Vraćam ovu poruku za vas, umjesto vašeg rada, jer je (tvoj papir)trenutno zauzima dno mog kaveza za ptice. " -- English Professor, Providence College % Ako bilo koji čovjek želi da se ponizio i trula, pusti ga da postane predsjednikHarvard. -- Edward Holyoke % Ako je naučio samo malo manje, kako beskrajno bolje bi mogao imatinaučio mnogo više! -- Edward Holyoke % Ako neznanje je blaženstvo, zašto nema više sretan ljudi? -- Edward Holyoke % Ako ništa drugo, mozak je obrazovna igračka. -- Tom Robbins % Da mi je netko rekao da bi papa jedan dan, ja bih studirao teže. -- Pope John Paul I % Ako su fakulteti bili bolji, ako su zaista imali, ti bi trebalo da sepolicija na vrata da održi red u inrushing mnoštvu. Pogledajte ukoledž kako osujetiti prirodne ljubavi učenja ostavljajući prirodnimmetoda nastave šta svaka želi da uči, i insistira da ćenaučiti ono što nemaju ukusa ili kapaciteta za. Koledž, koja bibiti mjesto divan rada, čini odvratan i nezdravo, amladići su u iskušenju da neozbiljna zabave da se okupe svoje jaded duhove.Bih studija izborni. Stipendija će biti kreiranuprinudno, nego budi čist interes u znanju. mudarinstruktor to postiže otvaranjem njegovim učenicima upravoznamenitosti studija ima za sebe. Obilježavanje je sistem za škole,ne za koledž; za dječake, a ne za muškarce; i to je nezahvalnost posaostavi na profesora. -- Ralph Waldo Emerson % Ako je istina ljepote, kako to da niko nije svoju kosu radi u biblioteci? -- Lily Tomlin % Ako bismo govorili drugi jezik, mi bismo sagledati nešto drugačiji svijet. -- Wittgenstein % Ako dok ste u školi, postoji manjak kvalifikovanih kadrovau određenoj oblasti, onda kada ste diplomirali s potrebnimkvalifikacije, tržište rada to polje je otrov. -- Marguerite Emmons % Ako ste previše zauzet za čitanje, onda ste previše zauzet. -- Marguerite Emmons % Ako ne možete pročitati ovo, krivi učitelj. -- Marguerite Emmons % Ako odolim čitate ono što se ne slažu sa, kako ćete ikada stećidublje uvide u ono što vjerujete? U stvari najviše vrijedan čitanjasu upravo one koje dovode u pitanje naše osude. -- Marguerite Emmons % Ako mislite da je obrazovanje skupo, pokušajte neznanje. -- Derek Bok, president of Harvard % Ako ste uzeli sve studente koji osjetio spava u razredu i položio ih na kraju ukraju, oni bi mnogo ugodnije. -- "Graffiti in the Big Ten" % "Ako znate šta radite, niste ništa učenje." -- A. L. % Neznanje nikad ne izlazi iz mode. bio je to bilo u modi, to jebes danas, i to će postaviti tempo sutra. -- Franklin K. Dane % Neznanje je kada ne znaš ništa i neko nađe ga. -- Franklin K. Dane % Neznanje mora svakako biti blaženstva ili ne bi bilo toliko ljuditako odlučno ga sprovodi. -- Franklin K. Dane % Nepismeni? Napišite danas, za besplatnu pomoć! -- Franklin K. Dane % U šumi lisica naleti na malo zeca, i kaže: "Bok,Junior, šta si ti do? ""Pišem disertaciju o tome kako zečevi jedu lisice", rekao jezec."Hajde, prijatelj zec, znate da je to nemoguće! Nikoće objaviti takve gluposti! ""Pa, za mnom i ja ću ti pokazati."Obojica su ući u stan zeca i nakon nekog vremenazec pojavljuje sa zadovoljan izraz na njegovom licu. Dolazi dužvuk. "Zdravo, mali druže, šta radimo ovih dana?""Pišem 2'nd poglavlje moje teze, o tome kako zečevi proždiruvukovi. ""Jesi li ti lud? Gdje ti je akademsko poštenje?""Pođi sa mnom i ja ću ti pokazati."Kao i do sada, zec izlazi sa zadovoljan izraz na njegovom licui diplomu u šapi. Konačno, tave kamera u pećinu zecai, kao i svi bi trebalo da pretpostavi do sada, vidimo srednja izgleda, ogromnalav, sjedi, branje zube i podrigivanje, pored neke Furry, krvaveostaci vuka i lisica.Moralni: To nije sadržaj vašeg teze da suvažno - to je tvoj dr savjetnik koji je zaista bitno. -- Franklin K. Dane % U Kaliforniji, Bill Honig, nadzornik Javne uputstva, rekao je onSmatra se da je javnost treba imati glas u definiranju što je odličannastavnik treba da zna. "Ne bih napustiti definicija matematike," Dr. Honigrekao je, "do matematičara." -- The New York Times, October 22, 1985 % Umjesto davanja novca za osnivanje fakulteta za promociju učenja, zašto neoni prolaze ustavni amandman neko od učenja o zabraniništa? Ako to radi kao dobar kao zabrani piše da, zašto, u petgodine ćemo imati najpametnijih rasa ljudi na Zemlji. -- The Best of Will Rogers % Iowa State - srednju školu, nakon srednje škole! -- Crow T. Robot % Rečeno je [od Anatole France], "to ne zabavlja sebeda je jedan uči, "i, u odgovoru:" To je * ____ * Samo po zabavlja sebe damože naučiti. " -- Edward Kasner and James R. Newman % To je dugo bio član našeg folklora koji previše znanja ili vještina,ili posebno savršen stručnost, je loša stvar. To dehumanizuje kopostići to, i otežava njihovu trgovinu sa samo običan narod, u komedobri stari razum nije uništena samo knjiga za učenje ili fancypojmove. Ova popularna zabluda cvjeta sada više nego ikad, jer smo svizaraženo je u školama, gdje pedagoga ga uzdigaofolklor člana od vjerovanja. To povećava svoje samopouzdanje i olakšavanjihove muke pružajući teoretsko opravdanje za odlučivanje dazahvalnost, ili čak i jednostavna svijest, je da se cijenjena od znanja,i odnose (sebi i drugima), više nego vještina, u kojem minimumnadležnost će biti sasvim dovoljno. -- The Underground Grammarian % To je duboko pogrešna istina, ponavljaju sve copy-knjige ieminentni ljudi kada su držali govore, da treba da se kultivišunaviku razmišljanja o onome što radimo. Precizan suprotno jeslučaj. Civilizacija napredak proširenjem broja važnih operacijakoje možemo izvesti bez razmišljanja o njima. Operacije misli sukao naknada konjica u borbi - oni su strogo ograničeni u broju, onizahtijevaju odmorne konje, i mora biti samo u odlučujućim trenucima. -- Alfred North Whitehead % To je grad vreme ispita ...RAČUNARSKA NAUKAUnutar vašem stolu ćete naći popis operativnih DEC / VMSsistem u IBM 1710 mašinski kod. Pokazati što promjene su neophodne za konverzijuovaj kod u UNIX Berkeley 7 operativni sistem. Dokazati da su ovi popravci subug besplatno i ispravno. Trebao bi dobiti najmanje 150% efikasnosti unovi sistem. (Trebalo bi da ne više od 10 minuta na ovo pitanje.)MATEMATIKAAko je X jednako PI puta R ^ 2, izgraditi formula pokazuje koliko dugobilo bi potrebno vatru mrava da izbušiti rupu kroz kopra krastavac, akoOdnos dužine obim mrava na Pickle su 98.17: 1.OPĆE ZNANJEOpišite Universe. Daj tri primjera. -- Alfred North Whitehead % To je grad vreme ispita ...MEDICINEVi ste dobili sa žiletom, komad gaze, iboca viskija. Skinite dodatak. Ne zašijte dok vaš rad imapregledan. (Imate 15 minuta.)POVIJESTOpišite istoriji papstva od svojih početaka do danasdan, napadi posebno, ali ne isključivo, na njegov društveni, politički,ekonomske, vjerske i philisophical uticaj na Europi, Aziji, Americi, iAfrici. Budi kratak, koncizan, i specifične.BIOLOGIJAStvoriti život. Procijeniti razlike u kasnijim ljudske kultureako je to oblik života je stvorena prije 500 miliona godina ili ranije, saposebnu pažnju na svoje verovatno uticaj na parlamentarni sistem engleski. -- Alfred North Whitehead % To je ne, nije nije, i to je to, a ne svoje, ako mislite na toje. Ako ne, to je svoje. Onda previše, to je njena. To nije ona je. toNije nam je bilo. To je naša, i isto tako tvoj i njihov. -- Oxford University Press, Edpress News % Joe Cool uvijek provodi prve dvije sedmice na faksu jedrenje njegov frizbi. -- Snoopy % Učeni ljudi su cisterne znanja, a ne vrela. -- Snoopy % Učenje u nekim školama je kao da pije iz vatrogasnog creva. -- Snoopy % Učenje bez razmišljanja je rad izgubio;misao bez učenja je opasno. -- Confucius % Možda nije nije tako tačno, ali primetio sam da puno ljudi koji nekoristeći se ne ne jedem dobro '. -- Will Rogers % Većina seminara imati sretan kraj. Svi su drago kad su više. -- Will Rogers % Moj otac, dobar čovjek, mi je rekao, "Nikad ne gubi neznanje; ne možešzamijeniti ga. " -- Erich Maria Remarque % Nikada toliko shvatiti tako malo o tako puno. -- James Burke % Nikada ne dozvolite da školovanje ometa svoje obrazovanje. -- James Burke % No disciplina ikada potrebne prisiliti prisustvo na predavanja koja sustvarno vredi prisutnih. -- Adam Smith, "The Wealth of Nations" % Bez obzira ko ste, neki naučnik može vam pokazati veliku ideju ste imalije imao neko pre vas. -- Adam Smith, "The Wealth of Nations" % Nije ni čudo da si umoran! Toliko ste shvatili danas. -- Adam Smith, "The Wealth of Nations" % Obično naša pravila su kruti; mi imaju tendenciju da diskreciju, ako ni zbog čega drugognego samo-zaštitu. Mi nikada ne preporučujemo neki od naših diplomiranih studenata, iako smoveselo pružaju informacije i onima koji nisu svoje kurseve. -- Jack Vance, "Freitzke's Turn" % Ne samo da ovo nerazumljivo, ali tinta je ružna i papirje od pogrešne vrste drveća.Radujem se saradnji sa vama na ovom iduće godine. -- Professor, Harvard, on a senior thesis. % `O 'NIVOU Counter CultureTimewarp dozvoljeno: 3 sata. Ne Scrawl situationalist grafiti umargine ili stub svoj zbirne ispravke u inkwells. Orange može nositi. kreditće se dati kandidatima koji samoaktualizovanje.(1) Usporedba i kontrast Pink Floyd sa Black Sabbath i reći zaštoniti ima street kredibilitet.(2) "Čak i Buda bi bilo teško gurnuti do Nirvana čučanjena Juggernaut ruti. "Razmotrimo dijalektike unutarnje istinei unutrašnjeg grada.(3) Razmotriti stupanj komplikacija uključenih u paranoju o usisavanjuu crnu rupu.(4) "The Egomaniac oslobodilački front bili gomila revizionističkeripoff trgovca. "Komentar na ovu uvredu.(5) Račun za nedostatak referenci na smeđe riže u Dylanova tekstovi.(6) "Castenada je pomalo Božo." Koliko je to fer sumiranjedo zapadne dualizma?(7) Hermann Hesse je Riba. Razgovarajte. -- Professor, Harvard, on a senior thesis. % "U redu, sada pogledajmo četiri dimenzije na tabli." -- Dr. Joy % OK, ti si doktor Samo ne diraj ništa. -- Dr. Joy % Ne može se napraviti omlet bez razbijanja jaja - ali je neverovatnokoliko jaja može slomiti bez pravljenja pristojan omlet. -- Professor Charles P. Issawi % Perifraza je stavljanje stvari u povratno o način. "Troškovi mogu bitigore od figura, a ispod 10m #. "je perifraza za troškove može bitiskoro 10m #. "U Parizu postoji vlada potpuni izostanak stvarno pouzdanvijest "je perifraza za Nema pouzdanih vijesti u Parizu." Rijetko se događai 'Little Summer' Linger do novembra, ali s vremena na vreme svoj boravak jeprodužen do prilično kasno u ovogodišnjem pretposlednji mjesec "sadržiperifraza za novembar, a drugi za zadržava. "Odgovor je unegativan "je perifraza za broj" je izvršena dobitnik "jeperifraza za predstavljen je s. Stil perifraza je teško mogućena bilo kojoj značajnoj mjeri, bez mnogo koristi apstraktne imenice, kao što su "osnovi,slučaju, karakter, priključak, nedostatak, opis, trajanje, okvir, nedostatak,priroda, referenca, u vezi, poštovanje ". Postojanje apstraktnih imenica jedokaz da je došlo do apstraktne misli; apstraktna misao je znakcivilizovanog čoveka; i tako je došlo do toga da perifraza i civilizacija sumnogi smatrati nerazdvojni. Ovi dobri ljudi osjećaju da je gotovonepristojno golotinja, povratak na varvarstvo, u rekavši Nema vijest je dobra vijestumjesto "Odsustvo inteligencije je pokazatelj zadovoljavajućirazvoj. " -- Fowler's English Usage % "IMAJTE porrf raed." -- Prof. Michael O'Longhlin, S.U.N.Y. Purchase % Praksa je najbolji od svih instruktora. -- Publilius % Princeton ukus je slatka kao jagoda tart. Harvard je suptilnaukus, kao što su viski, kafa, ili duhan. To čak može biti loša navika, zasve što znam. -- Prof. J. H. Finley '25 % Profesor Gorden Newell bacio još jedan Shutout u prošle sedmice Chem Eng. 130srednjoročni. Ponovo student nije dobio jednu točku na njegovom ispitu.Newell je sada bacio 5 shutouts ovom kvartalu. Newell je zaradio ispit prosjekaje sada pala na fenomenalnih 30%. -- Prof. J. H. Finley '25 % Čitanje misli s nekom drugom glavu umjesto vlastite. -- Prof. J. H. Finley '25 % Reading je na umu ono što vježbe je da se tijelo. -- Prof. J. H. Finley '25 % Reporter: "Kako vam se dopao školu kad si odrastao, Yogi?"Yogi Berra: "Zatvoreno". -- Prof. J. H. Finley '25 % Pravila za dobro gramatike # 4.(1) Ne koristite ni dvostruke negacije.(2) da svaki zamjenica slažu sa njihovim prethodnike.(3) Pridružite klauzule dobro, kao zajedno treba.(4) O njima kazna fragmenata.(5) Kada je visio, pazi participa.(6) Glagoli ima da se dogovore sa svojim podanicima.(7) Samo između vas i ja, slučaj je važan.(8) Ne pišite rade na kazne kada su teško pročitati.(9) Ne koristite zareze, koje nisu neophodne.(10) Pokušajte da nikad ne podijeliti infinitivima.(11) Važno je da vaše apostrof je ispravno koristiti.(12) korekturu vaše pisanje da vidim da li bilo riječi van.(13) Tako je speling je od suštinskog značaja.(14) A prijedlog je nešto što nikada ne završi rečenicu s.(15) Dok je uzvišena vokabular je za svaku pohvalu, jedan mora biti vječnopazite da izračunate cilj komunikacije nepostati ensconsed u tami. Drugim riječima, suzdržava zbunjivanja. -- Prof. J. H. Finley '25 % Pamet vodi u mojoj porodici. Kada sam išao u školu bio sam tako pametan mojaUčiteljica je bila u mom razredu za pet godina. -- George Burns % Neki naučnici su kao magarci, oni samo nose puno knjiga. -- Folk saying % "Brzina je subsittute fo tačnosti." -- Folk saying % Pravopis je izgubljenu umjetnost. -- Folk saying % Odjednom, profesor Liebowitz shvata da je došao na seminarbez njegovog patka ... -- Folk saying % Nastavnici imaju klasu. -- Folk saying % "A" je za sadržaj, u "minus" je za ne to kucanje. Nemoj nikad uraditiovo moje oči ponovo. -- Professor Ronald Brady, Philosophy, Ramapo State College % Alarm sat koji je glasniji od samog Boga pripada cimer sanajranije klase. -- Professor Ronald Brady, Philosophy, Ramapo State College % Prosječna dr teza nije ništa drugo do prenošenje kostiju izjedan groblje na drugu. -- J. Frank Dobie, "A Texan in England" % U zanimanje procjene kvarova boljih ljudi može se uključitiu udoban život, pružajući vam napravite to sa Ph.D. -- Nelson Algren, "Writers at Work" % "Najbolja stvar za što sad", odgovorio je Merlin, počinju da puffi udarac, "je da naučite nešto. To je jedina stvar koja nikada ne uspije.Možete ostariti i drhtala u anatomije, možda lažeš budan unoć slušajući poremećaj vaše vene, možda nedostaje samo ljubav,možete vidjeti na svijet oko vas razoren zlo ludaka, ili svoječast gazi u kanalizaciji Baser umova. Postoji samo jedna stvar zaonda - da uče. Saznajte zašto je svijet maše i šta maše to. To jejedina stvar koja um nikada ne može iscrpiti, nikad otuđiti, nikada neće bitimučili, nikada strah ili nepovjerenje, i nikada ne sanjaju žalim. učenjeje jedina stvar za vas. Vidi šta puno stvari postoje da uče. " -- T. H. White, "The Once and Future King" % Mozak je divan organ; počinje rad u trenutku kada ustanešujutro, i ne prestaje dok ne dođete u školu. -- T. H. White, "The Once and Future King" % Diplomskom koledž je predstavljen sa kožuh da pokrije svojuintelektualne golotinja. -- Robert M. Hutchins % Kraj svijeta će doći na 03:00, u petak, uzSimpozij slijediti. -- Robert M. Hutchins % Budućnost je trka između obrazovanja i katastrofe. -- H. G. Wells % Važno je da se ne zaustavi ispitivanja. -- H. G. Wells % Čovjek koji nikada nije bio bičevan nikada nije naučio. -- Menander % Jedina stvar koja iskustvo nas uči da nas iskustvo uči ništa. -- Andre Maurois (Emile Herzog) % Jedina stvar koju smo naučili iz istorije je da ne uče.Da muškarci ne mnogo naučiti iz istorije je najvažniji od svihlekcije koje povijest mora naučiti.Učimo iz istorije da ne uče iz istorije.POVIJEST: Papa Hegel je rekao da sve što naučiti iz istorije je da učimoništa iz istorije. Znam ljude koji ne mogu ni naučiti iz onoga što se dogodiloovo jutro. Hegel mora da je u daljinu. -- Chad C. Mulligan, "The Hipcrime Vocab" % Jedina stvar koju smo naučili iz istorije je da učimo ništa iz istorije.Znam da momci ne mogu naučiti od juče ... Hegel mora biti u daljinu. -- John Brunner, "Stand on Zanzibar" % Problem sa diplomiranih studenata, općenito, je da oni imajuda spava svakih nekoliko dana. -- John Brunner, "Stand on Zanzibar" % Odnos pismenosti u nepismenosti je konstanta, ali danas jenepismenih može čitati. -- Alberto Moravia % Pravi cilj knjige je da primi um u radi vlastite razmišljanja. -- Christopher Morley % "Student u pitanju obavlja minimalno za svoje vršnjaka ije u nastajanju gubitnik. " -- Christopher Morley % Zbir inteligencije na svijetu je konstantna. Stanovništvo je,naravno, raste. -- Christopher Morley % U sunlights se razlikuju, ali postoji samo jedan mrak. -- Ursula K. LeGuin, "The Dispossessed" % Test prvorazredni inteligencija je sposobnost da drži dva suprotstavljenaideje u umu, u isto vrijeme i dalje zadržati sposobnost da funkcioniše. -- F. Scott Fitzgerald % Tri najbolje stvari idu u školu su lipanj, srpanj, i kolovoz. -- F. Scott Fitzgerald % The Tree of Learning nosi najplemenitije voće, ali plemenito voće ukus loše. -- F. Scott Fitzgerald % SAD je tako ogroman, i tako brojni su svoje škole, fakulteti i vjerskeseminarima, mnogi posvećena posebna vjerska uvjerenja u rasponu odneortodoksne na Dotty, koje teško možemo zapitati na svom donosi višeobilan žetva zapetljano od ostatka svijeta zajedno. -- Sir Peter Medawar % Svijet se bliži kraju! Pokajte se i vratiti te knjige iz biblioteke! -- Sir Peter Medawar % Svijet je pun ljudi koji nikada nisu, od djetinjstva, upoznaootvorena vrata s otvorenog uma. -- E. B. White % Nema odgovora, samo cross-reference. -- Weiner % To je vrsta engleskog jezika s kojima neću staviti. -- Winston Churchill % Oni koji obrazuju djecu i više će biti poštovan od roditelja, zate je dao samo život, oni umetnost dobro žive. -- Aristotle % Time je veliki učitelj, ali nažalost ubija sve svoje učenike. -- Hector Berlioz % Optuživati ​​druge za vlastite nesreće je znak nedostatka obrazovanja.Optužiti sebe pokazuje da je počeo jedan obrazovanja. Optuživati ​​nisebi ni drugima pokazuje da je jedan obrazovanja je potpuna. -- Epictetus % Da craunch a marmoset. -- Pedro Carolino, "English as She is Spoke" % Da nauči je da uče dva puta. -- Joseph Joubert % Da nauči je da naučite. -- Joseph Joubert % Pokušajte ne da imaju dobar provod ... Ovo bi trebalo da bude edukativnog karaktera. -- Charles Schulz % Pokušavam da se obrazovanje ovdje je kao da pokušavate dobiti piće iz vatrogasnog šmrka. -- Charles Schulz % Univerziteti su mjesta znanja. U brucoš svaki donijeti malou s njima, kao i seniori uzeti ništa dalje, tako da znanje se akumulira. -- Charles Schulz % politika Univerziteta su začarani upravo zato što je ulog tako mali. -- C. P. Snow % Walt: Tata, šta je postepeno u školi?Garp: Postepeno škole?Walt: Da. Mama sada kaže da više zabave njen posao je da ona predajepostepeno škole.Garp: Oh. Pa, postepeno škola je negdje idete i postepenosaznati da ne želim više da ide u školu. -- The World According To Garp % "Zahtijevamo strogo definisane oblasti sumnje i nesigurnosti!" -- Vroomfondel % Mi znamo gotovo ništa o gotovo svemu. Nije potrebnoznati porijeklo svemira; potrebno je da žele da znaju.Civilizacija ne zavisi o bilo kojem određenom znanja, ali na raspolaganjeda žude znanja. -- George Will % Mi smo fantastično neverovatno mi je za sve ove izuzetno nerazumnostvari koje smo radili. Mogu samo da se izjasni da je moja jednostavna, jedva živa prijateljai ja su ugrožene, lišeni i studenti. -- Waldo D. R. Dobbs % "Ponestaje nam pridjeva opisati našu situaciju. Miimali krizu, onda smo otišli u haos, i sad šta mi ovo zovemo? ", rekao jeNikaragve ekonomista Francisco Mayorga, koji ima doktorat iz Yale.The New Yorker je komentar:Na Harvardu oni bi to nazvao imenica. -- The Washington Post, February, 1988 % Šta obrazovanje često rade? To čini ravan rez jarak odfree vijuganje potoka. -- Henry David Thoreau % Ono što sam uradio tokom mog zimskog semestraNa prvi dan mog zimskog semestra, ustao sam.Onda sam otišao u biblioteku pronaći temu teza.Onda sam visio ispred Dover.Na drugi dan mog zimskog semestra, ustao sam.Onda sam otišao u biblioteku pronaći temu teza.Onda sam visio ispred Dover.Na treći dan mog zimskog semestra, ustao sam.Onda sam otišao u biblioteku pronaći temu teza.Našao sam temu tezu:Kako zadržati ljude iz visi ispred Dover. -- Sister Mary Elephant, "Student Statement for Black Friday" % Zašto misliš da Graduate School bi trebalo da bude zadovoljavajuća? -- Erica Jong, "Fear of Flying" % Ono što prolazi za optimizam je najčešće efekt intelektualne greške. -- Raymond Aron, "The Opium of the Intellectuals" % Ono što ne razumiju da ne posjeduju. -- Goethe % Ono što je na strani jedan, a preventivni napad? -- Professor Freund, Communication, Ramapo State College % Kad sam bio u školi, varao sam na metafizici ispit: Pogledao sam uduša dječak sjedi pored mene. -- Woody Allen % Kad god neko kaže, "teoretski", oni stvarno znače, "Ne baš." -- Dave Parnas % Gdje mogu naći vremena za ne čitanje toliko knjiga? -- Karl Kraus % "Koga ste vi?" rekao je, jer je bio u večernju školu. -- George Ade % Ne bi rečenicu "Želim da stavite crticu između riječi Fishi A i A i Chips u mom Fish-I-Chips znak "su jasniji akonavodnicima je stavljen pred Riba, kao i između Riba i i, ii i A, i A i i, i i i A, i A i i, i i iChips, kao i nakon Chips? -- George Ade % Ne možete očekivati ​​dječak biti zlobni dok je on bio u dobru školu. -- H. H. Munro % Ne morate da mislim previše kada razgovarate sa nastavnicima. -- J. D. Salinger % Možda ste čuli da je dekan je na fakultetu kao hidrant je pas. -- Alfred Kahn % "Trebalo bi, bez oklijevanja, udaraš svojim pisaće mašine u lemeš,svoj rad u đubrivo, i unesite poljoprivrede " -- Business Professor, University of Georgia % Vaše obrazovanje počinje u kojoj ono što se zove svoje obrazovanje je gotovo. -- Business Professor, University of Georgia %
<h3><strong><em>This is a heading</em></strong></h3> <p><strong><em>This is some text.</em></strong></p>
import React, {Component} from 'react' // import '../index.css'; // import '../App.css'; import Password from './Password' import Header from './Header' // import App from '../App' class Banner extends Component { render() { return ( <h1> PassBlock <Header/> </h1> ) } } export default Banner
<filename>src/org/sosy_lab/cpachecker/cpa/dca/DCATransferRelation.java<gh_stars>0 /* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2019 <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. */ package org.sosy_lab.cpachecker.cpa.dca; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.core.defaults.SingleEdgeTransferRelation; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.cpa.automaton.AutomatonState; import org.sosy_lab.cpachecker.cpa.automaton.AutomatonTransferRelation; import org.sosy_lab.cpachecker.exceptions.CPATransferException; public class DCATransferRelation extends SingleEdgeTransferRelation { private AutomatonTransferRelation automatonTR; public DCATransferRelation(AutomatonTransferRelation pAutomatonTransferRelation) { automatonTR = pAutomatonTransferRelation; } @Override public Collection<? extends AbstractState> getAbstractSuccessorsForEdge( AbstractState pState, Precision pPrecision, CFAEdge pCfaEdge) throws CPATransferException, InterruptedException { checkArgument(pState instanceof DCAState); DCAState state = (DCAState) pState; List<Set<AutomatonState>> listOfStates = new ArrayList<>(); for (AutomatonState compositeState : state.getCompositeStates()) { ImmutableSet<AutomatonState> successorsStates = ImmutableSet.copyOf( automatonTR.getAbstractSuccessorsForEdge(compositeState, pPrecision, pCfaEdge)); if (successorsStates.isEmpty()) { return ImmutableSet.of(); } listOfStates.add(successorsStates); } Set<List<AutomatonState>> cartesianProduct = Sets.cartesianProduct(listOfStates); ImmutableSet<AutomatonState> buechiSuccessorsStates = ImmutableSet.copyOf( automatonTR.getAbstractSuccessorsForEdge(state.getBuechiState(), pPrecision, pCfaEdge)); ImmutableSet.Builder<DCAState> builder = ImmutableSet.<DCAState>builder(); for (List<AutomatonState> productStates : cartesianProduct) { for (AutomatonState buechiSuccessorState : buechiSuccessorsStates) { builder.add(new DCAState(buechiSuccessorState, productStates)); } } return builder.build(); } @Override public Collection<? extends AbstractState> strengthen( AbstractState pState, Iterable<AbstractState> pOtherStates, @Nullable CFAEdge pCfaEdge, Precision pPrecision) throws CPATransferException, InterruptedException { checkArgument(pState instanceof DCAState); List<Set<AutomatonState>> listOfStates = new ArrayList<>(); DCAState state = (DCAState) pState; for (AutomatonState s : state.getCompositeStates()) { Set<AutomatonState> strengthenResult = ImmutableSet.copyOf(automatonTR.strengthen(s, pOtherStates, pCfaEdge, pPrecision)); if (strengthenResult.isEmpty()) { return ImmutableSet.of(); } listOfStates.add(strengthenResult); } Set<List<AutomatonState>> cartesianProduct = Sets.cartesianProduct(listOfStates); Set<AutomatonState> buechiStrengthenResults = ImmutableSet.copyOf( automatonTR.strengthen(state.getBuechiState(), pOtherStates, pCfaEdge, pPrecision)); ImmutableSet.Builder<DCAState> builder = ImmutableSet.<DCAState>builder(); for (List<AutomatonState> productStates : cartesianProduct) { for (AutomatonState buechiStrenghtenState : buechiStrengthenResults) { builder.add(new DCAState(buechiStrenghtenState, productStates)); } } return builder.build(); } }
package net.andreaskluth.elefantenstark.work; import static java.util.Objects.requireNonNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** Provides a facility to store context data for a {@link WorkItem}. */ public class WorkItemDataMap { private static final WorkItemDataMap EMPTY = new WorkItemDataMap(Collections.emptyMap()); private final Map<String, String> map; /** * Creates a new {@link WorkItem} based on a {@link Map} which is stored alongside the {@link * WorkItem}. * * @param map the context data. */ public WorkItemDataMap(Map<String, String> map) { Map<String, String> unsafe = requireNonNull(map); this.map = new HashMap<>(unsafe); } /** * Creates a copy of the passed in {@link WorkItemDataMap}. * * @param source to create a clone form. */ protected WorkItemDataMap(WorkItemDataMap source) { requireNonNull(source); this.map = new HashMap<>(source.map); } /** * @return an empty immutable {@link WorkItemDataMap} */ public static WorkItemDataMap empty() { return EMPTY; } /** * @return the inner map */ public Map<String, String> map() { return new HashMap<>(map); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WorkItemDataMap that = (WorkItemDataMap) o; return Objects.equals(map, that.map); } @Override public int hashCode() { return Objects.hash(map); } }
module ToolbarHelper def new_link_to(url, name = I18n.t(:create, scope: 'freya.toolbar'), options = {}) link_to url, class: 'btn btn--iconable' do content_tag :div, class: 'flexbox flexbox--vcentered' do concat content_tag :i, 'add', class: 'material-icons icon icon--left flexbox__fixed' concat name end end end def destroy_link(url, name, options = {}) link_to url, class: 'btn btn--danger btn--iconable', method: :delete, data: { confirm: I18n.t(:delete_confirm, scope: 'freya.toolbar') } do content_tag :div, class: 'flexbox flexbox--vcentered' do concat content_tag :i, 'delete', class: 'material-icons icon icon--left flexbox__fixed' concat name end end end end
<reponame>divolgin/replicated-2 package test import ( "bufio" "bytes" "os" "strconv" . "github.com/onsi/ginkgo" "github.com/replicatedhq/replicated/cli/cmd" apps "github.com/replicatedhq/replicated/gen/go/v1" releases "github.com/replicatedhq/replicated/gen/go/v1" "github.com/replicatedhq/replicated/pkg/platformclient" "github.com/stretchr/testify/assert" ) var _ = Describe("release update", func() { api := platformclient.NewHTTPClient(os.Getenv("REPLICATED_API_ORIGIN"), os.Getenv("REPLICATED_API_TOKEN")) t := GinkgoT() app := &apps.App{Name: mustToken(8)} var release *releases.AppReleaseInfo BeforeEach(func() { var err error app, err = api.CreateApp(&platformclient.AppOptions{Name: app.Name}) assert.Nil(t, err) release, err = api.CreateRelease(app.Id, "") assert.Nil(t, err) }) AfterEach(func() { deleteApp(app.Id) }) Context("with an existing release sequence and valid --yaml", func() { It("should update the release's config", func() { var stdout bytes.Buffer var stderr bytes.Buffer sequence := strconv.Itoa(int(release.Sequence)) cmd.RootCmd.SetArgs([]string{"release", "update", sequence, "--yaml", yaml, "--app", app.Slug}) cmd.RootCmd.SetOutput(&stderr) err := cmd.Execute(nil, &stdout, &stderr) assert.Nil(t, err) assert.Empty(t, stderr.String(), "Expected no stderr output") assert.NotEmpty(t, stdout.String(), "Expected stdout output") r := bufio.NewScanner(&stdout) assert.True(t, r.Scan()) }) }) })
[[ $- == *i* ]] && source "/usr/local/opt/fzf/shell/completion.zsh" 2> /dev/null
#!/bin/sh set -e # first arg is `-f` or `--some-option` if [ "${1#-}" != "$1" ]; then set -- php-fpm "$@" fi if [ "$1" = 'php-fpm' ] || [ "$1" = 'php' ] || [ "$1" = 'bin/console' ]; then PHP_INI_RECOMMENDED="$PHP_INI_DIR/php.ini-production" if [ "$APP_ENV" != 'prod' ]; then PHP_INI_RECOMMENDED="$PHP_INI_DIR/php.ini-development" fi ln -sf "$PHP_INI_RECOMMENDED" "$PHP_INI_DIR/php.ini" mkdir -p var/cache var/log setfacl -R -m u:www-data:rwX -m u:"$(whoami)":rwX var setfacl -dR -m u:www-data:rwX -m u:"$(whoami)":rwX var if [ "$APP_ENV" != 'prod' ]; then composer install --prefer-dist --no-progress --no-interaction echo "Making sure public / private keys for JWT exist..." php bin/console lexik:jwt:generate-keypair --skip-if-exists --no-interaction setfacl -R -m u:www-data:rX -m u:"$(whoami)":rwX config/jwt setfacl -dR -m u:www-data:rX -m u:"$(whoami)":rwX config/jwt fi if grep -q DATABASE_URL= .env; then echo "Waiting for database to be ready..." ATTEMPTS_LEFT_TO_REACH_DATABASE=60 until [ $ATTEMPTS_LEFT_TO_REACH_DATABASE -eq 0 ] || DATABASE_ERROR=$(php bin/console dbal:run-sql -q "SELECT 1" 2>&1); do if [ $? -eq 255 ]; then # If the Doctrine command exits with 255, an unrecoverable error occurred ATTEMPTS_LEFT_TO_REACH_DATABASE=0 break fi sleep 1 ATTEMPTS_LEFT_TO_REACH_DATABASE=$((ATTEMPTS_LEFT_TO_REACH_DATABASE - 1)) echo "Still waiting for database to be ready... Or maybe the database is not reachable. $ATTEMPTS_LEFT_TO_REACH_DATABASE attempts left." done if [ $ATTEMPTS_LEFT_TO_REACH_DATABASE -eq 0 ]; then echo "The database is not up or not reachable:" echo "$DATABASE_ERROR" exit 1 else echo "The database is now ready and reachable" fi if ls -A migrations/*.php >/dev/null 2>&1; then echo "Execute migrations" bin/console doctrine:migrations:migrate --no-interaction fi if [ "$APP_ENV" != 'prod' ]; then echo "Load fixtures" bin/console hautelook:fixtures:load --no-interaction fi fi fi exec docker-php-entrypoint "$@"
package com.shareyi.molicode.common.vo.replace; import com.shareyi.molicode.common.enums.DirTransType; import com.shareyi.molicode.common.enums.TouchFileType; import com.shareyi.molicode.common.utils.LogHelper; import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.List; /** * 文件目录接触记录类 * Created by david on 2016/1/1. */ public class TouchFile { /** * 表达式 */ private String expression; private String originExpression; private String targetExpression; List<String> originPathList; List<String> targetPathList; List<DirTrans> dirTransList; private TouchFileType touchFileType; public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } public String getOriginExpression() { return originExpression; } public void setOriginExpression(String originExpression) { this.originExpression = originExpression; } public String getTargetExpression() { return targetExpression; } public void setTargetExpression(String targetExpression) { this.targetExpression = targetExpression; } public List<String> getOriginPathList() { return originPathList; } public void setOriginPathList(List<String> originPathList) { this.originPathList = originPathList; } public List<String> getTargetPathList() { return targetPathList; } public void setTargetPathList(List<String> targetPathList) { this.targetPathList = targetPathList; } public TouchFileType getTouchFileType() { return touchFileType; } public void setTouchFileType(TouchFileType touchFileType) { this.touchFileType = touchFileType; } public int getOriginPathSize() { return originPathList.size(); } public static TouchFile parseExpression(String expression) { expression = StringUtils.trim(expression); if (StringUtils.isEmpty(expression)) { return null; } String[] expSplit = expression.split("="); if (expSplit.length != 2) { return null; } try { TouchFile touchFile = new TouchFile(); touchFile.setExpression(expression); touchFile.setOriginExpression(expSplit[0]); touchFile.setTargetExpression(expSplit[1]); String[] orgPath = touchFile.getOriginExpression().split("/"); String[] tarPath = touchFile.getTargetExpression().split("/"); touchFile.setOriginPathList(parseStrArr2List(orgPath)); touchFile.setTargetPathList(parseStrArr2List(tarPath)); //如果为空,直接返回nuLl if (touchFile.getOriginPathList().isEmpty() || touchFile.getTargetPathList().isEmpty()) { return null; } if (orgPath.length < tarPath.length) { touchFile.setTouchFileType(TouchFileType.EXTEND_DIR); } else if (orgPath.length > tarPath.length) { touchFile.setTouchFileType(TouchFileType.SHORTEN_DIR); } else { touchFile.setTouchFileType(TouchFileType.EXCHANGE_DIR); } touchFile.parseDirTrans(); return touchFile; } catch (Exception e) { LogHelper.EXCEPTION.error("解析touchFile表达式失败,exp={}", expression, e); } return null; } /** * 获取dirTrans */ public void parseDirTrans() { dirTransList = new ArrayList<DirTrans>(originPathList.size()); for (int i = 0; i < originPathList.size(); i++) { String originName = originPathList.get(i); //如果还没有超过目标文件夹的size if (i < targetPathList.size()) { String targetName = targetPathList.get(i); DirTrans dirTrans = new DirTrans(); dirTrans.setOriginDirName(originPathList.get(i)); //如果已经到达末尾 if (originPathList.size() == i + 1) { //如果目标path比原始的长,表示要做延长处理 if (targetPathList.size() > originPathList.size()) { dirTrans.setDirTransType(DirTransType.EXTEND_DIR); dirTrans.setTargetDirList(targetPathList.subList(i, targetPathList.size())); dirTransList.add(dirTrans); continue; } } dirTrans.setTargetDirName(targetPathList.get(i)); if (originName.equals(targetName)) { dirTrans.setDirTransType(DirTransType.NONE); } else { dirTrans.setDirTransType(DirTransType.NAME_CHANGE); } dirTransList.add(dirTrans); } else { //前面全部匹配上,后续为空,表明是删除后面的目录移动到上级目录功能 DirTrans dirTrans = new DirTrans(); dirTrans.setOriginDirName(originPathList.get(i)); dirTrans.setDirTransType(DirTransType.SHORTEN_DIR); dirTransList.add(dirTrans); } } } public static List<String> parseStrArr2List(String[] strArr) { List<String> list = new ArrayList<String>(strArr.length); for (int i = 0; i < strArr.length; i++) { if (StringUtils.isNotEmpty(strArr[i])) { list.add(strArr[i]); } } return list; } public List<DirTrans> getDirTransList() { return dirTransList; } /** * 通过index获取目录转换结果 * * @param index * @return */ public DirTrans getDirTransByIndex(int index) { return dirTransList.get(index); } /** * 获取指定index的转换类型 * * @param index * @return */ public DirTransType getDirTransTypeByIndex(int index) { return dirTransList.get(index).getDirTransType(); } }
<gh_stars>0 package cwe import ( "fmt" "github.com/pkg/errors" "gopkg.in/yaml.v1" "io/ioutil" "os" ) // CallWithEnvironment contains the additional environment variables to pass to the child process type CallWithEnvironment struct { Environment map[string]string `yaml:"env"` // Environment contains additional variables to add to the environment Quiet bool `yaml:"quiet"` // Quiet toggles output of added variables } // NewCallWithEnvironment creates a new instance func NewCallWithEnvironment() (*CallWithEnvironment, error) { if _, err := os.Stat(callWithEnvironmentFileName); os.IsNotExist(err) { return nil, errors.New(fmt.Sprintf("no %s file in directory", callWithEnvironmentFileName)) } var newCWE CallWithEnvironment in, err := ioutil.ReadFile(callWithEnvironmentFileName) if err != nil { return nil, err } err = yaml.Unmarshal(in, &newCWE) if err != nil { return nil, err } return &newCWE, nil }
// // LTFramer.h // Pods // // Created by <NAME> on 21/08/16. // // #import <Foundation/Foundation.h> #import "LTFramerRule.h" #import "LTFramerFrameSettableProtocol.h" #import "LTFramerProtocol.h" @interface LTFramer : NSObject <LTFramer> + (_Nonnull instancetype)framerWithSubject:(_Nonnull LTFramerSubject)subject boundingSize:(CGSize)size; - (void)resetRules; - (void)addRule:(LTFramerRule* _Nonnull)rule; - (NSArray<LTFramerRule*>* _Nonnull)allRules; @end
<gh_stars>0 import React, {Component} from 'react'; import{ Image, View, Text} from 'react-native'; import Strings from '../utils/Strings'; class RestDay extends React.Component { render () { return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#fff'}}> <Text style={{fontSize: 22, fontWeight: 'bold', marginBottom: 8}}>{Strings.ST71.toUpperCase()}</Text> <Text style={{fontSize: 16, marginBottom: 8, color: '#b5b5b5'}}>{Strings.ST72.toUpperCase()}</Text> </View> ) } } export default RestDay;
<filename>util/concurrent/atomic/pointer.h #ifndef UTIL_CONCURRENT_ATOMIC_POINTER_H #define UTIL_CONCURRENT_ATOMIC_POINTER_H #include "util/concurrent/atomic/atomic.h" namespace util { namespace concurrent { namespace atomic { template<typename _T> class pointer { public: // Constructor. pointer(); pointer(_T* ptr); pointer(const pointer& ptr); // Assignment operator. pointer& operator=(_T* ptr); pointer& operator=(const pointer& ptr); // Get pointer. _T* get() const; // Set pointer. void set(_T* ptr); // Pointer operator. _T* operator->() const; // Dereference operator. _T& operator*() const; // Compare and swap. bool compare_and_swap(_T* oldval, _T* newval); private: _T* _M_ptr; }; template<typename _T> inline pointer<_T>::pointer() { } template<typename _T> inline pointer<_T>::pointer(_T* ptr) : _M_ptr(ptr) { } template<typename _T> inline pointer<_T>::pointer(const pointer& ptr) : _M_ptr(ptr._M_ptr) { } template<typename _T> inline pointer<_T>& pointer<_T>::operator=(_T* ptr) { _M_ptr = ptr; return *this; } template<typename _T> inline pointer<_T>& pointer<_T>::operator=(const pointer& ptr) { _M_ptr = ptr._M_ptr; return *this; } template<typename _T> inline _T* pointer<_T>::get() const { return _M_ptr; } template<typename _T> inline void pointer<_T>::set(_T* ptr) { _M_ptr = ptr; } template<typename _T> inline _T* pointer<_T>::operator->() const { return _M_ptr; } template<typename _T> inline _T& pointer<_T>::operator*() const { return *_M_ptr; } template<typename _T> inline bool pointer<_T>::compare_and_swap(_T* oldval, _T* newval) { return util::concurrent::atomic::bool_compare_and_swap<_T*>(&_M_ptr, oldval, newval); } } } } #endif // UTIL_CONCURRENT_ATOMIC_POINTER_H
// https://open.kattis.com/problems/guess #include <iostream> using namespace std; int main() { int a = 1; int b = 1000; while (true) { int t = (a + b) / 2; cout << t << endl;; string r; cin >> r; if (r == "correct") break; if (r == "lower") b = t - 1; else a = t + 1; } }
def sum_upto_x(x): total = 0 for i in range(0, x+1): total += i return total
#!/bin/bash # windows compatible process killer for any stray processes started as #"fallout" something. source $FEISTY_MEOW_SCRIPTS/core/launch_feisty_meow.sh procid="$( psa fallout | tail -n 1 | awk '{ print $1; }' )" if [ ! -z "$procid" ]; then taskkill.exe /f /pid ${procid} fi
// (C) 2020 GoodData Corporation import { IAttribute } from "@gooddata/sdk-model"; import { VisualizationObject } from "@gooddata/api-client-tiger"; import { toDisplayFormQualifier } from "../ObjRefConverter"; export function convertAttribute(attribute: IAttribute, idx: number): VisualizationObject.IAttribute { const alias = attribute.attribute.alias; const aliasProp = alias ? { alias } : {}; const displayFromRef = attribute.attribute.displayForm; return { displayForm: toDisplayFormQualifier(displayFromRef), localIdentifier: attribute.attribute.localIdentifier || `a${idx + 1}`, ...aliasProp, }; }
<reponame>donfyy/AndroidCrowds package com.ytzb.chart; import android.graphics.Canvas; import android.util.SparseArray; import com.ytzb.chart.data.Data; import com.ytzb.chart.data.Entry; import com.ytzb.chart.data.Highlight; import com.ytzb.chart.dataset.IDataSet; /** * Created by xinxin.wang on 18/4/28. */ public interface IMarker { void draw(Canvas canvas, Highlight highlight, Chart<? extends Data<? extends IDataSet>> chart); /** * 绑定浮层要显示的数据项 * * @param entries key表示Entry在DataSet中的索引 * @param data */ void bind(SparseArray<Entry> entries, Data<? extends IDataSet> data); }
<gh_stars>0 package dk.kvalitetsit.hjemmebehandling.service; import dk.kvalitetsit.hjemmebehandling.constants.errors.ErrorDetails; import dk.kvalitetsit.hjemmebehandling.service.exception.ErrorKind; import dk.kvalitetsit.hjemmebehandling.service.exception.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.server.ResponseStatusException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import dk.kvalitetsit.hjemmebehandling.model.PersonModel; public class PersonService { private static final Logger logger = LoggerFactory.getLogger(PersonService.class); @Value("${cpr.url}") private String cprUrl; private RestTemplate restTemplate; public PersonService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } // http://localhost:8080/api/v1/person?cpr=2512489996 public PersonModel getPerson(String cpr) throws JsonProcessingException, ServiceException { PersonModel person = null; try { String result = restTemplate.getForObject(cprUrl+cpr, String.class); person = new ObjectMapper().readValue(result, PersonModel.class); } catch (HttpClientErrorException httpClientErrorException) { httpClientErrorException.printStackTrace(); if (HttpStatus.NOT_FOUND.equals(httpClientErrorException.getStatusCode())) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "entity not found"); } throw new ServiceException(String.format("Could not fetch person from cpr-service"), ErrorKind.BAD_GATEWAY, ErrorDetails.CPRSERVICE_UNKOWN_ERROR); } return person; } }
import pandas as pd def generate_cifar_csv(dict): batch_label = dict[b'batch_label'] labels = dict[b'labels'] data = dict[b'data'] filenames = dict[b'filenames'] length = len(labels) data_index = [i for i in range(length)] class_index = labels csv_dict = {'class_index': class_index, 'data_index': data_index} df = pd.DataFrame(csv_dict) df.to_csv('selected_cifar10.csv', index=False)
curl -T eve-tools-app/target/eve-tools-app-1.0-SNAPSHOT.zip -u $FTP_USER:$FTP_PASS ftp://$FTP_SERVER/eve-tools/eve-tools-app-1.0-SNAPSHOT.zip
#!/bin/bash usage() { echo "Usage: $0 [-c <channelname>]" 1>&2; exit 1; } while getopts ":c:" o; do case "${o}" in c) c=${OPTARG} ;; *) usage ;; esac done shift $((OPTIND-1)) if [ -z "${c}" ] ; then usage fi echo "create channel" DATA=/home/ubuntu/hyperledgerconfig/data export FABRIC_CFG_PATH=$DATA/ PEER_ORGS=("org1" "org2" "org3" "org4" "org5") NUM_PEERS=5 CHANNEL_NAME=${c} CHANNEL_TX_FILE=$DATA/$CHANNEL_NAME.tx echo "Generating channel configuration transaction at $CHANNEL_TX_FILE" $GOPATH/src/github.com/hyperledger/fabric/build/bin/configtxgen -profile SampleSingleMSPChannel -outputCreateChannelTx $CHANNEL_TX_FILE -channelID $CHANNEL_NAME if [ "$?" -ne 0 ]; then echo "Failed to generate channel configuration transaction" fi for ORG in ${PEER_ORGS[*]}; do ANCHOR_TX_FILE=$DATA/orgs/$ORG/anchors.tx echo "Generating anchor peer update transaction for $ORG at $ANCHOR_TX_FILE" $GOPATH/src/github.com/hyperledger/fabric/build/bin/configtxgen -profile SampleSingleMSPChannel -outputAnchorPeersUpdate $ANCHOR_TX_FILE -channelID $CHANNEL_NAME -asOrg $ORG if [ "$?" -ne 0 ]; then echo "Failed to generate anchor peer update for $ORG" fi done echo "join channel to chain" CA_CHAINFILE=${DATA}/org0-ca-cert.pem ORDERER_HOST=orderer0.org0.deevo.com export ORDERER_PORT_ARGS=" -o orderer0.org0.deevo.com:7050 --tls --cafile $CA_CHAINFILE --clientauth" #initPeerVars ${PORGS[0]} 1 PEER_NAME=peer0.org1.deevo.com PEER_HOST=$PEER_NAME export FABRIC_CA_CLIENT=$DATA/$PEER_NAME/ export CORE_PEER_ID=peer0.org1.deevo.com export CORE_PEER_ADDRESS=peer0-org1:7051 export CORE_PEER_LOCALMSPID=org1MSP export CORE_LOGGING_LEVEL=DEBUG export CORE_PEER_TLS_ENABLED=true export CORE_PEER_TLS_CLIENTAUTHREQUIRED=true export CORE_PEER_TLS_ROOTCERT_FILE=$DATA/org1-ca-cert.pem export CORE_PEER_TLS_CLIENTCERT_FILE=$DATA/tls/$PEER_NAME-cli-client.crt export CORE_PEER_TLS_CLIENTKEY_FILE=$DATA/tls/$PEER_NAME-cli-client.key export CORE_PEER_PROFILE_ENABLED=true # gossip variables export CORE_PEER_GOSSIP_USELEADERELECTION=true export CORE_PEER_GOSSIP_ORGLEADER=false export CORE_PEER_GOSSIP_EXTERNALENDPOINT=$PEER_HOST:7051 export ORDERER_CONN_ARGS="$ORDERER_PORT_ARGS --keyfile $CORE_PEER_TLS_CLIENTKEY_FILE --certfile $CORE_PEER_TLS_CLIENTCERT_FILE" echo $ORDERER_CONN_ARGS export CORE_PEER_MSPCONFIGPATH=$DATA/orgs/org1/admin/msp echo "Creating channel '$CHANNEL_NAME' on $ORDERER_HOST ..." $GOPATH/src/github.com/hyperledger/fabric/build/bin/peer channel create --logging-level=DEBUG -c $CHANNEL_NAME -f $CHANNEL_TX_FILE $ORDERER_CONN_ARGS
#!/bin/bash levels=("full-divider_salad" "partial-divider_salad" "open-divider_salad" "full-divider_tomato" "partial-divider_tomato" "open-divider_tomato" "full-divider_tl" "partial-divider_tl" "open-divider_tl") models=("bd" "dc" "fb" "up" "greedy") nagents=2 nseed=20 for seed in $(seq 1 1 $nseed); do for level in "${levels[@]}"; do for model1 in "${models[@]}"; do for model2 in "${models[@]}"; do echo python main.py --num-agents $nagents --seed $seed --level $level --model1 $model1 --model2 $model2 python main.py --num-agents $nagents --seed $seed --level $level --model1 $model1 --model2 $model2 sleep 5 done done done done
<reponame>Th0rN13/sapper-boilerplate<gh_stars>1-10 import { config } from 'dotenv'; config(); export const { EMAIL_HOST, EMAIL_PORT, EMAIL_LOGIN, EMAIL_PASSWORD } = process.env;
#!/bin/bash set -e if [ -z "${BUILD_SETUP_READY}" ] ; then . env-build-setup.sh fi if [ -z "${TGT}" ] ; then echo "ERROR: TGT variable not set." exit 1 fi if [ ! -e ${TGT} ] ; then echo "ERROR: target directory ${TGT} doesn't exist." exit 1 fi PKG="ilmbase" PKG_URL="https://github.com/downloads/openexr/openexr/ilmbase-1.0.3.tar.gz" PKG_FILENAME="ilmbase-1.0.3.tar.gz" PKG_DIR="ilmbase-1.0.3" cd ${TOP_BUILD_DIR} if [ -e ${TOP_BUILD_DIR}/.built.${PKG} ] ; then echo "${PKG} already built" exit 0 fi PKG_LOG_PFX="${LOG_PREFIX}${PKG}" if [ ! -e $PKG_FILENAME ] ; then wget --content-disposition $PKG_URL fi if [ -e $PKG_DIR ] ; then rm -rf $PKG_DIR fi tar xfz $PKG_FILENAME cd $PKG_DIR ./configure --prefix=${TGT} 2>&1 | tee ${PKG_LOG_PFX}-configure.log make 2>&1 | tee ${PKG_LOG_PFX}-make.log make install 2>&1 | tee ${PKG_LOG_PFX}-make-install.log date "+%Y/%m/%d %H:%M:%S" > ${TOP_BUILD_DIR}/.built.${PKG} cd ${TOP_BUILD_DIR} echo "${PKG} built."
grunt jekyll build git add -A && git commit -m'Content updates' && git push origin master
// // _document is only rendered on the server side and not on the client side // Event handlers like onClick can't be added to this file // import Document, { Html, Head, Main, NextScript } from "next/document"; import { css } from "./_document.css"; export default class MyDocument extends Document { public static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps }; } public render() { return ( <Html> <Head> <meta content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="robots" content="noindex, follow"/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="<KEY>" crossOrigin="anonymous" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossOrigin="anonymous" /> <style>{css}</style> </Head> <body> <Main /> <NextScript /> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="<KEY> crossOrigin="anonymous" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossOrigin="anonymous" /> <script dangerouslySetInnerHTML={{ __html:` if (typeof(require) === "undefined") { window.isInElectronRenderer = false; } else { window.isInElectronRenderer = true; window.nodeRequire = require; delete window.exports; delete window.module; } ` }} /> </body> </Html> ); } }
#!/bin/bash # Select cluster sfctl cluster select \ --endpoint http://svcfab1.westus2.cloudapp.azure.com:19080 # Retrieve all applications from the cluster sfctl application list
package com.github.chen0040.leetcode.day18.medium; /** * Created by xschen on 13/8/2017. * * link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ */ public class FindMinimumInRotatedSortedList { public class Solution { public int findMin(int[] nums) { int lo = 0; int hi = nums.length - 1; while(lo <= hi) { int mid = lo + (hi - lo) / 2; if(mid > 0 && nums[mid] < nums[mid-1]) { return nums[mid]; } if(nums[lo] <= nums[mid] && nums[mid] > nums[hi]) { lo = mid + 1; } else { hi = mid - 1; } } return nums[lo]; } } }
#!/bin/bash # This script is meant to be called by the "install" step defined in # .travis.yml. See http://docs.travis-ci.com/ for more details. # The behavior of the script is controlled by environment variabled defined # in the .travis.yml in the top level folder of the project. # License: 3-clause BSD # Travis clone scikit-learn/scikit-learn repository in to a local repository. # We use a cached directory with three scikit-learn repositories (one for each # matrix entry) from which we pull from local Travis repository. This allows # us to keep build artefact for gcc + cython, and gain time set -e # Fix the compilers to workaround avoid having the Python 3.4 build # lookup for g++44 unexpectedly. export CC=gcc export CXX=g++ echo 'List files from cached directories' echo 'pip:' ls $HOME/.cache/pip if [[ "$DISTRIB" == "conda" ]]; then # Deactivate the travis-provided virtual environment and setup a # conda-based environment instead deactivate # Use the miniconda installer for faster download / install of conda # itself pushd . cd mkdir -p download cd download echo "Cached in $HOME/download :" ls -l echo if [[ ! -f miniconda.sh ]] then wget http://repo.continuum.io/miniconda/Miniconda-3.6.0-Linux-x86_64.sh \ -O miniconda.sh fi chmod +x miniconda.sh && ./miniconda.sh -b cd .. export PATH=/home/travis/miniconda/bin:$PATH conda update --yes conda popd # Configure the conda environment and put it in the path using the # provided versions if [[ "$INSTALL_MKL" == "true" ]]; then conda create -n testenv --yes python=$PYTHON_VERSION pip nose \ numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION numpy scipy \ mkl flake8 cython=$CYTHON_VERSION \ ${PANDAS_VERSION+pandas=$PANDAS_VERSION} else conda create -n testenv --yes python=$PYTHON_VERSION pip nose \ numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION \ nomkl cython=$CYTHON_VERSION \ ${PANDAS_VERSION+pandas=$PANDAS_VERSION} fi source activate testenv # Install nose-timer via pip pip install nose-timer elif [[ "$DISTRIB" == "ubuntu" ]]; then # At the time of writing numpy 1.9.1 is included in the travis # virtualenv but we want to use the numpy installed through apt-get # install. deactivate # Create a new virtualenv using system site packages for python, numpy # and scipy virtualenv --system-site-packages testvenv source testvenv/bin/activate pip install nose nose-timer cython elif [[ "$DISTRIB" == "scipy-dev-wheels" ]]; then # Set up our own virtualenv environment to avoid travis' numpy. # This venv points to the python interpreter of the travis build # matrix. virtualenv --python=python ~/testvenv source ~/testvenv/bin/activate pip install --upgrade pip setuptools # We use the default Python virtualenv provided by travis echo "Installing numpy master wheel" pip install --pre --upgrade --no-index --timeout=60 \ --trusted-host travis-dev-wheels.scipy.org \ -f https://travis-dev-wheels.scipy.org/ numpy scipy pip install nose nose-timer cython fi if [[ "$COVERAGE" == "true" ]]; then pip install coverage coveralls fi if [[ "$SKIP_TESTS" == "true" ]]; then echo "No need to build scikit-learn when not running the tests" else # Build scikit-learn in the install.sh script to collapse the verbose # build output in the travis output when it succeeds. python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" python -c "\ try: import pandas print('pandas %s' % pandas.__version__) except ImportError: pass " python setup.py develop fi if [[ "$RUN_FLAKE8" == "true" ]]; then conda install flake8 fi
<reponame>diegoperezl/cf4j package es.upm.etsisi.cf4j.examples.plot; import es.upm.etsisi.cf4j.data.BenchmarkDataModels; import es.upm.etsisi.cf4j.data.DataModel; import es.upm.etsisi.cf4j.data.Item; import es.upm.etsisi.cf4j.util.plot.HistogramPlot; import java.io.IOException; /** * In this example we analyze the average rating of each item that belongs to MovieLens 1M dataset. * We show the results using a HistogramPlot. */ public class HistogramPlotExample { public static void main(String[] args) throws IOException { DataModel datamodel = BenchmarkDataModels.MovieLens1M(); HistogramPlot plot = new HistogramPlot("Item rating average", 10); for (Item item : datamodel.getItems()) { plot.addValue(item.getRatingAverage()); } plot.draw(); plot.exportPlot("exports/histogram-plot.png"); plot.printData(); plot.exportData("exports/histogram-plot-data.csv"); } }
import matplotlib.pyplot as plt def plot_histogram(values_a, values_b, xlabel): fig, axes = plt.subplots(2, 1, gridspec_kw={'hspace': 0.01}, sharex=True) def _plot_hist(ax, values, color): ax.hist(values, color=color) _plot_hist(axes[0], values_a, 'orange') _plot_hist(axes[1], values_b, 'cornflowerblue') axes[1].set_xlabel(xlabel, fontsize='x-small') axes[1].tick_params(axis='x', which='both', labelsize='xx-small', labelrotation=45) axes[1].invert_yaxis() plt.show()
package net.andreaskluth.elefantenstark.consumer; import static java.util.Objects.requireNonNull; import static net.andreaskluth.elefantenstark.consumer.ConsumerQueries.SESSION_SCOPED_MARK_AS_PROCESSED; import static net.andreaskluth.elefantenstark.consumer.ConsumerQueries.SESSION_SCOPED_UNLOCK_ADVISORY_LOCK; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Optional; import net.andreaskluth.elefantenstark.work.WorkItem; import net.andreaskluth.elefantenstark.work.WorkItemContext; class SessionScopedConsumer extends Consumer { SessionScopedConsumer(String obtainWorkQuery) { super(obtainWorkQuery); } @Override public <T> Optional<T> next( Connection connection, java.util.function.Function<WorkItemContext, T> worker) { requireNonNull(connection); requireNonNull(worker); return fetchWorkAndLock(connection) .map( wic -> { try { T result = worker.apply(wic); markAsProcessed(connection, wic); return result; } finally { unlock(connection, wic.workItem()); } }); } private void markAsProcessed(Connection connection, WorkItemContext workItemContext) { try (PreparedStatement statement = connection.prepareStatement(SESSION_SCOPED_MARK_AS_PROCESSED)) { statement.setInt(1, workItemContext.id()); statement.execute(); } catch (SQLException e) { throw new ConsumerException(e); } } private void unlock(Connection connection, WorkItem workItem) { try (PreparedStatement preparedStatement = connection.prepareStatement(SESSION_SCOPED_UNLOCK_ADVISORY_LOCK)) { preparedStatement.setInt(1, workItem.hash()); preparedStatement.execute(); } catch (SQLException e) { throw new ConsumerException(e); } } @Override public boolean supportsStatefulProcessing() { return true; } }
#!/bin/bash #SBATCH --account=def-dkulic #SBATCH --mem=8000M # memory per node #SBATCH --time=23:00:00 # time (DD-HH:MM) #SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/continuous_LunarLanderContinuous-v2_doule_ddpg_hardcopy_action_noise_seed4_run0_%N-%j.out # %N for node name, %j for jobID module load qt/5.9.6 python/3.6.3 nixpkgs/16.09 gcc/7.3.0 boost/1.68.0 cuda cudnn source ~/tf_cpu/bin/activate python ./ddpg_discrete_action.py --env LunarLanderContinuous-v2 --random-seed 4 --exploration-strategy action_noise --summary-dir ../Double_DDPG_Results_no_monitor/continuous/LunarLanderContinuous-v2/doule_ddpg_hardcopy_action_noise_seed4_run0 --continuous-act-space-flag --target-hard-copy-flag
#!/bin/bash true_path="$(dirname "$(realpath "$0")")" root_path=$true_path/.. build_step() { NAME=$1 shift "$@" 2>&1 | sed $'s|^|\x1b[34m['"${NAME}"']\x1b[39m |' } build_error() { build_step HyperOS echo "Building failed!" exit } build_step HyperOS echo "Building image..." pushd "$root_path" >/dev/null || build_error build_step Bash mkdir -p Build || build_error pushd Build >/dev/null || build_error build_step CMake cmake --build . --target image || build_error popd >/dev/null || build_error popd >/dev/null || build_error build_step HyperOS echo "Building image done!"
package main import ( "encoding/hex" "flag" "fmt" "io" "log" "math" "os" "github.com/samuel/go-dsp/dsp" "github.com/samuel/go-dsp/dsp/ax25" ) var flagVerbose = flag.Bool("v", false, "Verbose output") func main() { flag.Parse() rd := os.Stdin if len(flag.Args()) > 0 && flag.Arg(0) != "-" { fi, err := os.Open(flag.Arg(0)) if err != nil { log.Fatal(err) } defer fi.Close() rd = fi } sampleRate := 44100 baud := 1200 window := 4 interp := 1 blockSize := sampleRate / baud goer := dsp.NewGoertzel([]int{1200, 2200}, sampleRate*interp, blockSize*interp) threshold := 50.0 buf := make([]byte, window*2) samples := make([]float32, blockSize*interp) lastSample := float32(0.0) currentTime := float64(0.0) bitClock := 1.0 / float64(baud) windowTime := float64(window) / float64(sampleRate) timeDelta := 0.0 prevBit := 0 transition := false ax := ax25.NewDecoder() for { _, err := rd.Read(buf) if err == io.EOF { break } else if err != nil { log.Fatal(err) } copy(samples, samples[window*interp:]) si := len(samples) - window*interp for i := 0; i < len(buf); i += 2 { s := float32(int16(buf[i])|(int16(buf[i+1])<<8)) / 32768.0 if interp > 1 { d := (s - lastSample) / float32(interp) for j := 1; j < interp; j++ { lastSample += d samples[si] = lastSample si++ } lastSample = s } samples[si] = s si++ } goer.Reset() goer.Feed(samples) mags := goer.Magnitude() diff := mags[0] - mags[1] if math.Abs(float64(diff)) > threshold { b := 1 if diff < 0 { b = 0 } if prevBit != b { transition = true prevBit = b // Align transitions to middle of clock tick timeDelta = bitClock/2.0 - currentTime } } currentTime += windowTime for currentTime >= bitClock { currentTime -= bitClock b := 1 if transition { b = 0 currentTime += timeDelta timeDelta = 0.0 } frame := ax.Feed(b) if frame != nil { if *flagVerbose { fmt.Printf("%+v\n", frame) } else { fmt.Printf("%s to %s", frame.Source, frame.Destination) if len(frame.Repeaters) != 0 { fmt.Print(" via ") for i, r := range frame.Repeaters { if i != 0 { fmt.Print(",") } fmt.Print(r.String()) } } fmt.Println() } fmt.Print(hex.Dump(frame.Info)) } transition = false } } }
<filename>src/com/example/StudentDao.java package com.example; import javax.sound.midi.Soundbank; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Created by bsheen on 4/27/17. */ public class StudentDao { public static void addStudent(Connection connection, Student student) throws SQLException { ResultSet rs = null; PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO student (name) VALUES (?)", Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, student.getName()); preparedStatement.executeUpdate(); rs = preparedStatement.getGeneratedKeys(); rs.next(); student.setId(rs.getInt(1)); System.out.println("Student " + student.getName() + " created with Student ID: " + student.getId()); } public static List<Student> printStudents(Connection connection) throws SQLException { ResultSet rs = null; PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM student"); rs = preparedStatement.executeQuery(); List<Student> studentList = new ArrayList<>(); while (rs.next()) { Student student = new Student(); student.setId(rs.getInt(1)); student.setName(rs.getString(2)); studentList.add(student); } return studentList; } public static void assignStu2Clas(Connection connection, Student student, Clas clas) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO clasassign (student_id, clas_id) VALUES (?, ?)"); preparedStatement.setString(1, String.valueOf(student.getId())); preparedStatement.setString(2, String.valueOf(clas.getId())); preparedStatement.executeUpdate(); } public static Student printStuClas(Connection connection, Student student) throws SQLException { ResultSet rs = null; PreparedStatement preparedStatement = connection.prepareStatement("SELECT s.id, s.name, c.id, c.name FROM student s, clas c, clasassign ca WHERE s.id = ? and s.id = ca.student_id and c.id = ca.clas_id"); preparedStatement.setString(1, String.valueOf(student.getId())); rs = preparedStatement.executeQuery(); while (rs.next()) { Clas clas = new Clas(); clas.setId(rs.getInt(3)); clas.setName(rs.getString(4)); student.getStudentClasList().add(clas); } return student; } public static void deleteStudent(Connection connection, Student student) throws SQLException{ PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM student WHERE student.id = ?"); preparedStatement.setString(1,String.valueOf(student.getId())); preparedStatement.executeUpdate(); } public static void removeStuClas(Connection connection, Student student, Clas clas) throws SQLException{ PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM clasassign WHERE student_id = ? AND clas_id = ?"); preparedStatement.setString(1, String.valueOf(student.getId())); preparedStatement.setString(2, String.valueOf(clas.getId())); preparedStatement.executeUpdate(); } }
python train_comm_game.py \ --ablation "student-no-teacher" \ --train_set "one" \ --learning_rate 0.0005
#!/bin/bash # requires apt packages: aspell, aspell-en, aspell-fr RED='\033[0;31m' GREEN='\033[0;32m' BLUE='\033[0;36m' NC='\033[0m' # No Color MARKDOWN_FILES_CHANGED=`(git diff --name-only $TRAVIS_COMMIT_RANGE || true) | grep .md` if [ -z "$MARKDOWN_FILES_CHANGED" ] then echo -e "$GREEN>> No markdown file to check $NC" exit 0; fi echo -e "$BLUE>> Following markdown files were changed in this pull request (commit range: $TRAVIS_COMMIT_RANGE):$NC" echo "$MARKDOWN_FILES_CHANGED" FOUND_LANGUAGES=`echo "$MARKDOWN_FILES_CHANGED" | xargs cat | grep "permalink: /" | sed -E 's/permalink: \/(fr|en)\/.*/\1/g'` echo -e "$BLUE>> Languages recognized from the permalinks:$NC" echo "$FOUND_LANGUAGES" USE_LANGUAGE='en' echo -e "$BLUE>> Will use this language as main one:$NC" echo "$USE_LANGUAGE" # cat all markdown files that changed TEXT_CONTENT_WITHOUT_METADATA=`cat $(echo "$MARKDOWN_FILES_CHANGED" | sed -E ':a;N;$!ba;s/\n/ /g')` # remove metadata tags TEXT_CONTENT_WITHOUT_METADATA=`echo "$TEXT_CONTENT_WITHOUT_METADATA" | grep -v -E '^(layout:|permalink:|date:|date_gmt:|authors:|categories:|tags:|cover:)(.*)'` # remove { } attributes TEXT_CONTENT_WITHOUT_METADATA=`echo "$TEXT_CONTENT_WITHOUT_METADATA" | sed -E 's/\{:([^\}]+)\}//g'` # remove html TEXT_CONTENT_WITHOUT_METADATA=`echo "$TEXT_CONTENT_WITHOUT_METADATA" | sed -E 's/<([^<]+)>//g'` # remove code blocks TEXT_CONTENT_WITHOUT_METADATA=`echo "$TEXT_CONTENT_WITHOUT_METADATA" | sed -n '/^\`\`\`/,/^\`\`\`/ !p'` # remove links TEXT_CONTENT_WITHOUT_METADATA=`echo "$TEXT_CONTENT_WITHOUT_METADATA" | sed -E 's/http(s)?:\/\/([^ ]+)//g'` echo -e "$BLUE>> Text content that will be checked (without metadata, html, and links):$NC" echo "$TEXT_CONTENT_WITHOUT_METADATA" echo -e "$BLUE>> Checking in 'en' (many technical words are in English anyway)...$NC" MISSPELLED=`echo "$TEXT_CONTENT_WITHOUT_METADATA" | aspell --lang=en --encoding=utf-8 --personal=./.aspell.en.pws list | sort -u` NB_MISSPELLED=`echo "$MISSPELLED" | wc -l` if [ "$NB_MISSPELLED" -gt 0 ] then echo -e "$RED>> Words that might be misspelled, please check:$NC" MISSPELLED=`echo "$MISSPELLED" | sed -E ':a;N;$!ba;s/\n/, /g'` echo "$MISSPELLED" COMMENT="$NB_MISSPELLED words might be misspelled, please check them: $MISSPELLED" exit 1 else COMMENT="No spelling errors, congratulations!" echo -e "$GREEN>> $COMMENT $NC" fi exit 0
#!/bin/bash #SBATCH -n 1 #SBATCH -t 30:00:00 #SBATCH --mem-per-cpu=3000 #SBATCH --array=0-1 module load mne source $MNE_ROOT/bin/mne_setup_sh module load freesurfer source $FREESURFER_HOME/SetUpFreeSurfer.sh export SUBJECTS_DIR=/m/nbe/scratch/braindata/thiedea/smedy/MRI_orig/ cd /m/nbe/scratch/braindata/thiedea/smedy/scripts/ readarray lines < "/m/nbe/scratch/braindata/thiedea/smedy/MRI_orig/files.txt" srun ./freesurfer-synopsis-smedy.sh "${lines[$SLURM_ARRAY_TASK_ID]}"
<filename>src/script/beta/2.0.0/configuration.PowerCreep.js const powerCreepConfiguration = { taskList:{ "default":["rS","rM","oS","oE","_"], "raymond":["oE","oF","_"], "julie":["oE","oF","_"], }, idlePosition:{ "julie":[35,28,"W22N25"], "raymond":[29,24,"W23N25"], }, getTaskInterval:5, renewRemainingTicks:100, } module.exports = powerCreepConfiguration
#!/bin/bash kubectl exec -it kafka-0 -- /bin/bash \ -c 'unset JMX_PORT; /opt/bitnami/kafka/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic alerts --group=unique'
'use script'; const R = require('./ramda.js'); const { isString, isFunction } = require('./utils.js'); const LOG_LEVELS = { ERROR: 'error', INFO: 'info', }; const LOG_LEVEL_NAMES = R.values(LOG_LEVELS); const DEFAULT_LOG_LEVEL = LOG_LEVELS.INFO; const getLevelRank = (level) => { switch (level) { case LOG_LEVELS.ERROR: return 0; case LOG_LEVELS.INFO: return 1; default: return 2; } }; const getLoggerMethod = (logger, level) => { if (!logger) { return () => {}; } const loggerProperty = (() => { switch (level) { case LOG_LEVELS.ERROR: return logger.error; case LOG_LEVELS.INFO: return logger.info; default: return null; } })(); if (isFunction(loggerProperty)) { return loggerProperty; } if (isFunction(logger)) { return message => logger(`${level}: ${message}`); } return () => {}; }; const getLogLevel = (providedThreshold) => { if (!isString(providedThreshold)) { return DEFAULT_LOG_LEVEL; } const threshold = R.find( levelName => levelName.toLowerCase() === providedThreshold.toLowerCase(), LOG_LEVEL_NAMES ); return threshold || DEFAULT_LOG_LEVEL; }; const getLogger = (logger, providedLevel) => { const thresholdLevel = getLogLevel(providedLevel); return ({ level = LOG_LEVELS.INFO, message }) => { const loggerMethod = getLoggerMethod(logger, level); if (loggerMethod && getLevelRank(level) <= getLevelRank(thresholdLevel)) { loggerMethod(message); } }; }; module.exports.LOG_LEVELS = LOG_LEVELS; module.exports.getLogger = getLogger;
<gh_stars>0 import React from "react"; import headshot from "../assets/img/headshot1.png"; import bgHero from "../assets/img/bg-hero.jpg"; export default function Hero() { return ( <div id="ts-hero" className="ts-animate-hero-items"> {/* <!--HERO CONTENT ****************************************************************************************--> */} <div className="container position-relative h-100 ts-align__vertical"> <div className="row w-100"> <div className="col-md-8"> {/* <!--SOCIAL ICONS--> */} <figure className="ts-social-icons mb-4"> {/* <!-- linkedin --> */} <a href="https://www.linkedin.com/in/candracook/" target="_blank" rel="noreferrer" className="mr-3" > <i className="fab fa-linkedin"></i> </a> {/* <!-- github --> */} <a href="https://github.com/candracodes" target="_blank" rel="noreferrer" className="mr-3" > <i className="fab fa-github"></i> </a> </figure> {/* <!-- HEADSHOT --> */} <div className="mobile-headshot center text-center"> <img src={headshot} alt="Candra in Black and White with a hat on." /> </div> {/* <!--TITLE --> */} <h1>I am <NAME></h1> <h1 className="ts-bubble-border"> <span className="ts-title-rotate"> <span className="active">UX/UI Specialist</span> <span>Developer</span> <span>Artist</span> </span> </h1> </div> {/* <!--end col-md-8--> */} </div> {/* <!--end row--> */} {/* <!-- START: DOWN ARROW *********************************** --> */} <a href="#about-me" className="ts-btn-effect position-absolute ts-bottom__0 ts-left__0 ts-scroll ml-3 mb-3" > <span className="ts-visible ts-circle__sm rounded-0 ts-bg-primary"> <i className="fa fa-arrow-down text-white"></i> </span> <span className="ts-hidden ts-circle__sm rounded-0"> <i className="fa fa-arrow-down text-white"></i> </span> </a> {/* <!-- END: DOWN ARROW *********************************** --> */} </div> {/* <!--end container--> */} {/* <!--END HERO CONTENT ************************************************************************************--> */} {/* <!--HERO BACKGROUND *************************************************************************************--> */} <div className="ts-background"> <div className="ts-background-image" data-bg-image={bgHero} ></div> </div> {/* <!--END HERO BACKGROUND *********************************************************************************--> */} </div> ); }