text
stringlengths
27
775k
<?php namespace Coziboy\LogUserActivityForBackpack\Tests; use Orchestra\Testbench\TestCase; class BaseTest extends TestCase { /** * A basic feature test example. * * @return void */ public function test_example() { $this->assertTrue(true); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cocheejm; /** * <h1>DtCoche</h1> * * <p>Clase abstracta que sirve para cualquier tipo de coche</p> * * @author Sanchez Mendez Edmundo Josue * @version 1.0.0 * @since 02-09-2017 */ public abstract class DtCoche { /** * <h3>propietario<h3> * * Método abstracto para implementar la venta de un coche */ private String Nombrep; public abstract void comprar(String Nombrep); public String getNombrep() { return Nombrep; } public void setNombrep(String Nombrep) { this.Nombrep = Nombrep; } }
/* HabitCompletion: Purpose: This is an object that represent any habit completion instance. This way, all the Date and completionNumber is stored in it's own object. Design Rationale: I did this because this makes more sense from an OO perspective. Now we have individual instances we can delete, instead of just strings in a list. Outstanding Issues: I'm Overriding the normal ArrayList<HabitCompletion>.toString() method with my own, that will display my own values. There might be better ways of displaying the data in a ListView, but we used this in lonelyTwitter, so I assumed this would work fine. Copyright 2016 Nathan Storm Kaefer */ package com.example.storm.habittracker; import java.util.Date; /** * Created by Storm on 2016-09-29. */ public class HabitCompletion { private Date completedDate = null; private int completedNumber = 0; HabitCompletion(Integer completedNumber){ this.completedDate = new Date(); this.completedNumber = completedNumber; } //overrides the basic toString function, so HabitCompletion looks correct in listview @Override public String toString(){ return "Completion #" + String.valueOf(completedNumber) + ": on " + completedDate.toString(); } public int getCompletedNumber(){ return this.completedNumber; } }
#=Copyright (c) 2017 Gabriel Goh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.=# # f(x) = ((1 + ((x[1]+x[2]+1)^2)*(19 - 14*x[1]+3*x[1]^2-14*x[2]+6*x[1]*x[2]+3*x[2]^2))* # (30 + ((2*x[1] - 3*x[2])^2)*(18 - 32*x[1] + # 12*x[1]^2 + 48*x[2] - 36*x[1]*x[2] + 27*x[2]^2)) ) # ∇f(x) = ForwardDiff.gradient(f,x) # Beale # f(x) = ( (1.5 - x[1] + x[1]*x[2])^2 # + (2.25 - x[1] + x[1]*x[2]^2)^2 # + (2.625 - x[1] + x[1]*x[2]^3)^2 ) # ∇f(x) = ForwardDiff.gradient(f,x) # Rosenbrock # f(x) = 100*(x[2] - x[1]^2)^2 + (x[1] - 1)^2 # ∇f(x) = ForwardDiff.gradient(f,x) # Monkey Saddle # f(x) = x[1]^3 - 3*x[1]*x[2]^2 # ∇f(x) = [3*x[1] - 3*x[2]^2; -6*x[1]*x[2]] A = diagm([1; 1]) f(x) = 0.5*vecdot(x,A*x) ∇f(x) = A*x α = 1.5; β = 0.51 w = [1;1]; z = zeros(2) N = 2000 fW = zeros(N) wp = w W = zeros(2,N) for i = 1:N if i > 2 #if vecdot(∇f(w), w - wp) > 0; println(i); z = zeros(2); end end W[:,i] = vecdot(∇f(w), w - wp) wp = w z = β*z + ∇f(w) w = w - α*(∇f(w) + β*z) println(f(w)) if abs(f(w)) < 100; fW[i] = f(w); else; fW[i] = NaN; end #W[:,i] = w end plot(fW)
void f(unsigned int counter) { if(counter==0) return; f(counter-1); } int main() { unsigned int x; __CPROVER_assume(x<=10); f(x); }
# gograb Downloads go module dependencies one at a time. This tool is needed when access to a private repos only allows a small number of concurrent connections. This problem occurs during CI/CD pipelines. Golang efficiently pulls dependencies in parallel but this efficiency can break private repos which only allow a small number of concurrent connections per host. Since gograb pulls dependencies one at a time, this should minimize the number of concurrent connections per host.
# eth ## eth 安装 ``` mkdir -p $GOPATH/src/github.com/ethereum/ cd $GOPATH/src/github.com/ethereum/ git clone https://github.com/ethereum/go-ethereum.git sudo add-apt-repository ppa:ethereum/ethereum sudo apt-get update sudo apt-get install -y ethereum ``` ## Remix ``` https://remix.ethereum.org/ ``` ``` sudo apt-get install -y solc cnpm install -g solc ``` ``` docker run ethereum/solc:stable solc --version ``` ## OpenZeppelin ``` mkdir -p $HOME/dev/eth/src/github.com/OpenZeppelin/ cd $HOME/dev/eth/src/github.com/OpenZeppelin/ git clone https://github.com/OpenZeppelin/zeppelin-solidity.git git clone https://github.com/OpenZeppelin/sample-crowdsale-starter.git git clone https://github.com/OpenZeppelin/ethernaut.git git clone https://github.com/OpenZeppelin/openzeppelin-website.git git clone https://github.com/OpenZeppelin/token-vesting-ui.git git clone https://github.com/OpenZeppelin/token-marketplace.git ``` ## truffle ``` cnpm install -g ethereumjs-testrpc truffle embark zeppelin-solidity create-react-app ganache-cli ``` ``` truffle init truffle unbox tutorialtoken truffle unbox pet-shop npm install zeppelin-solidity truffle compile truffle migrate truffle test npm run dev ``` ## embark ``` embark demo embark new AppName embark blockchain embark simulator embark run ``` ``` embark upload ipfs ``` ## eg ``` mkdir -p $HOME/dev/eth/src/github.com/ cd $HOME/dev/eth/src/github.com/ git clone https://github.com/fivedogit/solidity-baby-steps.git git clone https://github.com/dapperlabs/cryptokitties-bounty.git git clone https://github.com/Lunyr/crowdsale-contracts.git ``` ``` mkdir -p $HOME/dev/eth/src/github.com/TokenMarketNet/ cd $HOME/dev/eth/src/github.com/TokenMarketNet/ git clone https://github.com/TokenMarketNet/ico.git ``` ``` mkdir -p $HOME/dev/eth/src/github.com/cryptomingbi/ cd $HOME/dev/eth/src/github.com/cryptomingbi/ git clone https://github.com/cryptomingbi/cryptomingbi-website.git git clone https://github.com/cryptomingbi/cryptomingbi-poster.git git clone https://github.com/cryptomingbi/cryptomingbi-contract.git ```
import 'package:flutter/material.dart'; import 'dart:convert'; import 'dart:async'; import 'package:http/http.dart' as http; import './token.dart'; class LoginPage extends StatefulWidget { @override State<StatefulWidget> createState() { return _LoginState(); } } class _LoginState extends State<LoginPage> { static final _email = TextEditingController(); static final _password = TextEditingController(); String email, password; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text("Log In"), ), body: ListView(children: mainWidgets(context))); } Future<bool> authenticate() async { setState(() { email = _email.text; password = _password.text; }); Map<String, dynamic> data = {}; data["username"] = email; data["password"] = password; var tool = JsonEncoder(); var json = tool.convert(data); // var json = JSON.encode(data); bool acceptance = await makeRequest(json); // Map<String, dynamic> response = // await getJson('JsonInterface/Server_Response/login.json'); // String result = response["Example_responses"][1]["result"]; // if (result == "accepted") { // return true; // } else { // return false; // } return acceptance; } Future<bool> makeRequest(String postJson) async { var response = await http.post( Uri.encodeFull(IP_ADDRESS + 'api/v1/account/api-token-auth/'), body: postJson, headers: { "content-type": "application/json", "accept": "application/json" }); if (response.statusCode == 200) { token = json.decode(response.body)["token"]; print(token); } else { print("UUUU"); } return response.statusCode == 200; } mainWidgets(BuildContext context) { return <Widget>[ SizedBox(height: 100.0), FlutterLogo(size: 70.0), Padding( padding: EdgeInsets.fromLTRB(20.0, 40.0, 20.0, 10.0), child: TextFormField( controller: _email, keyboardType: TextInputType.text, autofocus: false, decoration: InputDecoration( hintText: 'Username', contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)), ), onFieldSubmitted: (value){onSubmit();} )), Padding( padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 40.0), child: TextFormField( controller: _password, obscureText: true, autofocus: false, decoration: InputDecoration( hintText: 'Password', contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)), ), onFieldSubmitted: (value){onSubmit();}, )), Padding( padding: EdgeInsets.symmetric(horizontal: 150.0), child: RaisedButton( color: Theme.of(context).primaryColor, child: Text( 'Log In', style: TextStyle(color: Colors.white), ), onPressed: onSubmit, )), Padding( padding: EdgeInsets.symmetric(horizontal: 150.0), child: RaisedButton( color: Theme.of(context).primaryColor, child: Text( 'Sign Up', style: TextStyle(color: Colors.white), ), onPressed: () async { Navigator.of(context).pushNamed('/signup'); }, )), ]; } void onSubmit() async{ // List events = [ // {"identifier": "c2cd246a-071e-4bbe-aff2-4404f7cf1f0f", // "time": "2018-11-07 08:15:00+00:00", // "tags": [], // "title": "zsfds", // "Iscore": "0.8"}, // {"identifier": "302e8329-d191-487a-9da4-caa82325d8df", // "time": "2018-11-07 08:12:00+00:00", // "tags": ["Anaerobic Digestion","Computational Fluid Dynamics"], // "title": "sadfeg", // "Iscore": "0.5"} // ]; // var selectedTags = ["Computational Fluid Dynamics", "Microalgae"].toSet(); // var eventsSet = events[0]["tags"].toSet(); // print(selectedTags); // print(eventsSet); // print(eventsSet.intersection(selectedTags)); // print(eventsSet.intersection(selectedTags).isEmpty); // print(!events[0]["tags"].toSet().intersection(selectedTags).isEmpty); // events = events.where((m) => !m["tags"].toSet().intersection(selectedTags).isEmpty).toList(); // // events = events.where((m) => m['tags'].contains(selectedTags[0])).toList(); // print(events); if (await authenticate()) { Navigator.of(context).pushNamed('/'); } else { showDialog( context: context, builder: (context) { return AlertDialog( content: Text("Login Failed!"), actions: <Widget>[ RaisedButton( color: Theme.of(context).primaryColor, onPressed: () { Navigator.of(context).pop(); }, child: Text( 'Try Again', style: TextStyle(color: Colors.white), )) ]); }); } } }
import CacheDriver from "../../services/cache/CacheDriver"; import * as fs from "fs"; import {createHash} from "crypto"; import Keyable from "../../types/Keyable"; /** * @author FaSh<[email protected]> * @class FileCache * @implements CacheDriver * A file driver implementation from CacheDriver interface * @see CacheDriver */ class FileCache implements CacheDriver{ /** * Holds path of cache files * @private */ private basePath = process.env.PWD + "/storage/cache"; /** * SHA-256 encoder * @param str * @private * @returns string */ private static toSha256(str: string): string { str = str.toLowerCase() return createHash('sha256').update(str).digest('base64') .replace(/[/+]/g, ''); } async clear(): Promise<void> { await fs.promises.unlink(this.basePath + "/*") } async delete(key: string): Promise<void> { const hashKey = FileCache.toSha256(key); try{ await fs.promises.unlink(this.basePath + "/" + hashKey); } catch (e: any){ console.log("Error Caught when unlinking cache file. Reason: " + e.message); } } async deleteMultiple(keys: Array<string>): Promise<void> { const len = keys.length; for(let i = 0; i < len; i++) await this.delete(keys[i]); } async get(key: string, defaultVal: string | null = null): Promise<any> { const hashedKey = FileCache.toSha256(key); const path = this.basePath + "/" + hashedKey; if(!fs.existsSync(path)) return defaultVal; let data = (await fs.promises.readFile(path)).toString(); let arrayify = data.split("|"); const ttlString = arrayify.shift() ?? "-1"; const ttl = parseInt(ttlString, 10) const timestamp = new Date().getTime(); if(ttl >= 0 && ttl < timestamp) { await this.delete(key); return defaultVal; } data = arrayify.join("|"); return JSON.parse(data); } async getMultiple(keys: Array<string>): Promise<Keyable> { let res: Keyable<string | null> = {}; const keyLen = keys.length; for(let i = 0; i < keyLen; i++){ res[keys[i]] = await this.get(keys[i]); } return res; } async has(key: string): Promise<boolean> { const path = this.basePath + "/" + FileCache.toSha256(key); if(!fs.existsSync(path)) return false; const ttl = await this.getTTL(key); const timestamp = new Date().getTime(); if(ttl >= 0 && ttl < timestamp) { await this.delete(key); return false; } return true; } async set(key: string, val: any, ttl: number | undefined = undefined): Promise<void> { const timestamp = new Date().getTime(); ttl = (typeof ttl === "undefined" || ttl < 0) ? -1 : (timestamp + (ttl * 1000)); const data = ttl.toString() + "|" + JSON.stringify(val); await fs.promises.writeFile(this.basePath + "/" + FileCache.toSha256(key), data); } async setMultiple(keys: Keyable): Promise<void> { for(let key in keys){ if(!keys.hasOwnProperty(key)) continue; await this.set(key, keys[key]); } } async getTTL(key: string): Promise<number> { let data = (await fs.promises.readFile(this.basePath + "/" + FileCache.toSha256(key))).toString(); let arrayify = data.split("|"); const cacheTs = parseInt(arrayify.shift() ?? "-1"); return Math.max(Math.floor((cacheTs - new Date().getTime()) / 1000), -1); } } export default FileCache;
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ICMS.Modules.BaseComponents.Beans { public class ModuleEntity { public virtual string Id { set; get; } public virtual string LineName { set; get; } public virtual string StationCode { set; get; } public virtual string StationName { set; get; } public virtual string AssemblyName { set; get; } public virtual string ModuleNameSpace { set; get; } public virtual string ClassName { set; get; } public virtual string ClientIp { get; set; } public virtual string PortNumber { set; get; } public virtual string EqType { set; get; } }}
import fm.sbt.S3Implicits._ import sbt.Keys.{publishTo, _} import sbt.{AutoPlugin, _} import scoverage.ScoverageKeys._ object Common extends AutoPlugin { override def trigger: PluginTrigger = allRequirements lazy val buildNumber: Option[String] = sys.env.get("BUILD_NUMBER").map(bn => s"b$bn") override lazy val projectSettings: Seq[Setting[_]] = Seq( organization := "uk.co.telegraph", version := "1.0.0-" + buildNumber.getOrElse("SNAPSHOT"), scalaVersion := "2.12.4", isSnapshot := buildNumber.isEmpty, scalacOptions ++= Seq( "-target:jvm-1.8", "-feature", "-encoding", "UTF-8", "-unchecked", "-deprecation", "-Xlint", "-Yno-adapted-args", "-Ywarn-dead-code", "-Xfuture" ), javacOptions ++= Seq( "-Xlint:unchecked" ), parallelExecution in Test := false, coverageFailOnMinimum := false, coverageHighlighting := true, coverageExcludedPackages := ".*Reverse.*;.*Routes.*", autoAPIMappings := true, resolvers += "mvn-tmg-resolver" atS3 "s3://mvn-artifacts/release", publishTo := { if( isSnapshot.value ){ Some("mvn-artifacts" atS3 "s3://mvn-artifacts/snapshot") }else{ Some("mvn-artifacts" atS3 "s3://mvn-artifacts/release") } } ) }
package cn.heroes.yellow.entity; import java.io.OutputStream; /** * The Object which is gave by <code>Intercepter#over()</code>, and used to fill * <code>data</code> into a media specified by <code>info<code>. * * @author Leon Kidd * @version 1.00, 2014-2-11 * @deprecated since v2.0.0 */ public class FillObject<T> { /** * The <code>OutputStream</code> that data save into. */ private OutputStream os; /** * Data to fill. */ private T data; public OutputStream getOutputStream() { return os; } public void setOutputStream(OutputStream os) { this.os = os; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
#if !NETCOREAPP using Amazon.S3; using Amazon.S3.Model; using GroupDocs.Annotation.Models; using GroupDocs.Annotation.Models.AnnotationModels; using System; using System.IO; namespace GroupDocs.Annotation.Examples.CSharp.AdvancedUsage.Loading { /// <summary> /// This example demonstrates loading document from Amazon S3 storage. /// </summary> class LoadDocumentFromAmazonS3 { public static void Run() { string outputPath = Path.Combine(Constants.GetOutputDirectoryPath(), "result" + Path.GetExtension(Constants.INPUT)); string key = "sample.pdf"; using (Annotator annotator = new Annotator(DownloadFile(key))) { AreaAnnotation area = new AreaAnnotation() { Box = new Rectangle(100, 100, 100, 100), BackgroundColor = 65535, }; annotator.Add(area); annotator.Save(outputPath); } Console.WriteLine($"\nDocument saved successfully.\nCheck output in {outputPath}."); } private static Stream DownloadFile(string key) { AmazonS3Client client = new AmazonS3Client(); string bucketName = "my-bucket"; GetObjectRequest request = new GetObjectRequest { Key = key, BucketName = bucketName }; using (GetObjectResponse response = client.GetObject(request)) { MemoryStream stream = new MemoryStream(); response.ResponseStream.CopyTo(stream); stream.Position = 0; return stream; } } } } #endif
'use strict'; var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.urlencoded({ extended:false })); app.use(bodyParser.json()); var server = app.listen(3977, function() { console.log('Listening :)'); server.close(function() { console.log('Doh :('); }); }); module.exports = app;
#!/usr/bin/ruby require "ai4r" require "nokogiri" require "zip" require "rubyXL" excel = RubyXL::Parser.parse ARGV.first real_lines = excel.worksheets[0].extract_data real_columns = real_lines.first.size - 1 net = Ai4r::NeuralNetwork::Backpropagation.new [real_columns, real_columns, 1] (real_lines.size*100).times do real_lines[1..(real_lines.size - 1)].each_with_index do |columns, index| net.train columns[0..(columns.size - 2)].collect{|i| i.to_i}, [columns.last.to_i] end end test_worksheet = excel.worksheets[1] test_lines = test_worksheet.extract_data test_lines[1..(test_lines.size - 1)].each_with_index do |columns, index| result = net.eval(columns[0..(columns.size - 2)].collect{|i| i.to_i}).first test_worksheet[index + 1][columns.size - 1].change_contents result end excel.write ARGV.first
using UnityEngine; using System.Collections; using UnityEngine.UI; public class OptionsMenuNew : MonoBehaviour { // toggle buttons public GameObject fullscreentext; public GameObject shadowofftext; public GameObject shadowofftextLINE; public GameObject shadowlowtext; public GameObject shadowlowtextLINE; public GameObject shadowhightext; public GameObject shadowhightextLINE; public GameObject showhudtext; public GameObject tooltipstext; public GameObject difficultynormaltext; public GameObject difficultynormaltextLINE; public GameObject difficultyhardcoretext; public GameObject difficultyhardcoretextLINE; public GameObject cameraeffectstext; public GameObject invertmousetext; public GameObject vsynctext; public GameObject motionblurtext; public GameObject ambientocclusiontext; public GameObject texturelowtext; public GameObject texturelowtextLINE; public GameObject texturemedtext; public GameObject texturemedtextLINE; public GameObject texturehightext; public GameObject texturehightextLINE; public GameObject aaofftext; public GameObject aaofftextLINE; public GameObject aa2xtext; public GameObject aa2xtextLINE; public GameObject aa4xtext; public GameObject aa4xtextLINE; public GameObject aa8xtext; public GameObject aa8xtextLINE; // sliders public GameObject musicSlider; public GameObject sfxSlider; public GameObject sensitivityXSlider; public GameObject sensitivityYSlider; public GameObject mouseSmoothSlider; private float sliderValue = 0.0f; private float sliderValueSFX = 0.0f; private float sliderValueXSensitivity = 0.0f; private float sliderValueYSensitivity = 0.0f; private float sliderValueSmoothing = 0.0f; public void Start (){ // check difficulty if(PlayerPrefs.GetInt("NormalDifficulty") == 1){ //difficultynormaltext.GetComponent<Text>().text = "NORMAL"; difficultynormaltextLINE.SetActive(true); difficultyhardcoretextLINE.SetActive(false); //difficultyhardcoretext.GetComponent<Text>().text = "hardcore"; } else { //difficultynormaltext.GetComponent<Text>().text = "normal"; //difficultyhardcoretext.GetComponent<Text>().text = "HARDCORE"; difficultyhardcoretextLINE.SetActive(true); difficultynormaltextLINE.SetActive(false); } // check slider values musicSlider.GetComponent<Slider>().value = PlayerPrefs.GetFloat("MusicVolume"); sfxSlider.GetComponent<Slider>().value = PlayerPrefs.GetFloat("SFXVolume"); sensitivityXSlider.GetComponent<Slider>().value = PlayerPrefs.GetFloat("XSensitivity"); sensitivityYSlider.GetComponent<Slider>().value = PlayerPrefs.GetFloat("YSensitivity"); mouseSmoothSlider.GetComponent<Slider>().value = PlayerPrefs.GetFloat("MouseSmoothing"); // check full screen if(Screen.fullScreen == true){ fullscreentext.GetComponent<Text>().text = "on"; } else if(Screen.fullScreen == false){ fullscreentext.GetComponent<Text>().text = "off"; } // check hud value if(PlayerPrefs.GetInt("ShowHUD")==0){ showhudtext.GetComponent<Text>().text = "off"; } else{ showhudtext.GetComponent<Text>().text = "on"; } // check tool tip value if(PlayerPrefs.GetInt("ToolTips")==0){ tooltipstext.GetComponent<Text>().text = "off"; } else{ tooltipstext.GetComponent<Text>().text = "on"; } // check shadow distance/enabled if(PlayerPrefs.GetInt("Shadows") == 0){ QualitySettings.shadowCascades = 0; QualitySettings.shadowDistance = 0; shadowofftext.GetComponent<Text>().text = "OFF"; shadowlowtext.GetComponent<Text>().text = "low"; shadowhightext.GetComponent<Text>().text = "high"; shadowofftextLINE.SetActive(true); shadowlowtextLINE.SetActive(false); shadowhightextLINE.SetActive(false); } else if(PlayerPrefs.GetInt("Shadows") == 1){ QualitySettings.shadowCascades = 2; QualitySettings.shadowDistance = 75; shadowofftext.GetComponent<Text>().text = "off"; shadowlowtext.GetComponent<Text>().text = "LOW"; shadowhightext.GetComponent<Text>().text = "high"; shadowofftextLINE.SetActive(false); shadowlowtextLINE.SetActive(true); shadowhightextLINE.SetActive(false); } else if(PlayerPrefs.GetInt("Shadows") == 2){ QualitySettings.shadowCascades = 4; QualitySettings.shadowDistance = 500; shadowofftext.GetComponent<Text>().text = "off"; shadowlowtext.GetComponent<Text>().text = "low"; shadowhightext.GetComponent<Text>().text = "HIGH"; shadowofftextLINE.SetActive(false); shadowlowtextLINE.SetActive(false); shadowhightextLINE.SetActive(true); } // check vsync if(QualitySettings.vSyncCount == 0){ vsynctext.GetComponent<Text>().text = "off"; } else if(QualitySettings.vSyncCount == 1){ vsynctext.GetComponent<Text>().text = "on"; } // check mouse inverse if(PlayerPrefs.GetInt("Inverted")==0){ invertmousetext.GetComponent<Text>().text = "off"; } else if(PlayerPrefs.GetInt("Inverted")==1){ invertmousetext.GetComponent<Text>().text = "on"; } // check motion blur if(PlayerPrefs.GetInt("MotionBlur")==0){ motionblurtext.GetComponent<Text>().text = "off"; } else if(PlayerPrefs.GetInt("MotionBlur")==1){ motionblurtext.GetComponent<Text>().text = "on"; } // check ambient occlusion if(PlayerPrefs.GetInt("AmbientOcclusion")==0){ ambientocclusiontext.GetComponent<Text>().text = "off"; } else if(PlayerPrefs.GetInt("AmbientOcclusion")==1){ ambientocclusiontext.GetComponent<Text>().text = "on"; } // check texture quality if(PlayerPrefs.GetInt("Textures") == 0){ QualitySettings.masterTextureLimit = 2; texturelowtext.GetComponent<Text>().text = "LOW"; texturemedtext.GetComponent<Text>().text = "med"; texturehightext.GetComponent<Text>().text = "high"; texturelowtextLINE.SetActive(true); texturemedtextLINE.SetActive(false); texturehightextLINE.SetActive(false); } else if(PlayerPrefs.GetInt("Textures") == 1){ QualitySettings.masterTextureLimit = 1; texturelowtext.GetComponent<Text>().text = "low"; texturemedtext.GetComponent<Text>().text = "MED"; texturehightext.GetComponent<Text>().text = "high"; texturelowtextLINE.SetActive(false); texturemedtextLINE.SetActive(true); texturehightextLINE.SetActive(false); } else if(PlayerPrefs.GetInt("Textures") == 2){ QualitySettings.masterTextureLimit = 0; texturelowtext.GetComponent<Text>().text = "low"; texturemedtext.GetComponent<Text>().text = "med"; texturehightext.GetComponent<Text>().text = "HIGH"; texturelowtextLINE.SetActive(false); texturemedtextLINE.SetActive(false); texturehightextLINE.SetActive(true); } } public void Update (){ sliderValue = musicSlider.GetComponent<Slider>().value; sliderValueSFX = sfxSlider.GetComponent<Slider>().value; sliderValueXSensitivity = sensitivityXSlider.GetComponent<Slider>().value; sliderValueYSensitivity = sensitivityYSlider.GetComponent<Slider>().value; sliderValueSmoothing = mouseSmoothSlider.GetComponent<Slider>().value; } public void FullScreen (){ Screen.fullScreen = !Screen.fullScreen; if(Screen.fullScreen == true){ fullscreentext.GetComponent<Text>().text = "on"; } else if(Screen.fullScreen == false){ fullscreentext.GetComponent<Text>().text = "off"; } } public void MusicSlider (){ PlayerPrefs.SetFloat("MusicVolume", sliderValue); } public void SFXSlider (){ PlayerPrefs.SetFloat("SFXVolume", sliderValueSFX); } public void SensitivityXSlider (){ PlayerPrefs.SetFloat("XSensitivity", sliderValueXSensitivity); } public void SensitivityYSlider (){ PlayerPrefs.SetFloat("YSensitivity", sliderValueYSensitivity); } public void SensitivitySmoothing (){ PlayerPrefs.SetFloat("MouseSmoothing", sliderValueSmoothing); Debug.Log(PlayerPrefs.GetFloat("MouseSmoothing")); } // the playerprefs variable that is checked to enable hud while in game public void ShowHUD (){ if(PlayerPrefs.GetInt("ShowHUD")==0){ PlayerPrefs.SetInt("ShowHUD",1); showhudtext.GetComponent<Text>().text = "on"; } else if(PlayerPrefs.GetInt("ShowHUD")==1){ PlayerPrefs.SetInt("ShowHUD",0); showhudtext.GetComponent<Text>().text = "off"; } } // show tool tips like: 'How to Play' control pop ups public void ToolTips (){ if(PlayerPrefs.GetInt("ToolTips")==0){ PlayerPrefs.SetInt("ToolTips",1); tooltipstext.GetComponent<Text>().text = "on"; } else if(PlayerPrefs.GetInt("ToolTips")==1){ PlayerPrefs.SetInt("ToolTips",0); tooltipstext.GetComponent<Text>().text = "off"; } } public void NormalDifficulty (){ //difficultynormaltext.GetComponent<Text>().text = "NORMAL"; //difficultyhardcoretext.GetComponent<Text>().text = "hardcore"; difficultyhardcoretextLINE.SetActive(false); difficultynormaltextLINE.SetActive(true); PlayerPrefs.SetInt("NormalDifficulty",1); PlayerPrefs.SetInt("HardCoreDifficulty",0); } public void HardcoreDifficulty (){ //difficultynormaltext.GetComponent<Text>().text = "normal"; //difficultyhardcoretext.GetComponent<Text>().text = "HARDCORE"; difficultyhardcoretextLINE.SetActive(true); difficultynormaltextLINE.SetActive(false); PlayerPrefs.SetInt("NormalDifficulty",0); PlayerPrefs.SetInt("HardCoreDifficulty",1); } public void ShadowsOff (){ PlayerPrefs.SetInt("Shadows",0); QualitySettings.shadowCascades = 0; QualitySettings.shadowDistance = 0; shadowofftext.GetComponent<Text>().text = "OFF"; shadowlowtext.GetComponent<Text>().text = "low"; shadowhightext.GetComponent<Text>().text = "high"; shadowofftextLINE.SetActive(true); shadowlowtextLINE.SetActive(false); shadowhightextLINE.SetActive(false); } public void ShadowsLow (){ PlayerPrefs.SetInt("Shadows",1); QualitySettings.shadowCascades = 2; QualitySettings.shadowDistance = 75; shadowofftext.GetComponent<Text>().text = "off"; shadowlowtext.GetComponent<Text>().text = "LOW"; shadowhightext.GetComponent<Text>().text = "high"; shadowofftextLINE.SetActive(false); shadowlowtextLINE.SetActive(true); shadowhightextLINE.SetActive(false); } public void ShadowsHigh (){ PlayerPrefs.SetInt("Shadows",2); QualitySettings.shadowCascades = 4; QualitySettings.shadowDistance = 500; shadowofftext.GetComponent<Text>().text = "off"; shadowlowtext.GetComponent<Text>().text = "low"; shadowhightext.GetComponent<Text>().text = "HIGH"; shadowofftextLINE.SetActive(false); shadowlowtextLINE.SetActive(false); shadowhightextLINE.SetActive(true); } public void vsync (){ if(QualitySettings.vSyncCount == 0){ QualitySettings.vSyncCount = 1; vsynctext.GetComponent<Text>().text = "on"; } else if(QualitySettings.vSyncCount == 1){ QualitySettings.vSyncCount = 0; vsynctext.GetComponent<Text>().text = "off"; } } public void InvertMouse (){ if(PlayerPrefs.GetInt("Inverted")==0){ PlayerPrefs.SetInt("Inverted",1); invertmousetext.GetComponent<Text>().text = "on"; } else if(PlayerPrefs.GetInt("Inverted")==1){ PlayerPrefs.SetInt("Inverted",0); invertmousetext.GetComponent<Text>().text = "off"; } } public void MotionBlur (){ if(PlayerPrefs.GetInt("MotionBlur")==0){ PlayerPrefs.SetInt("MotionBlur",1); motionblurtext.GetComponent<Text>().text = "on"; } else if(PlayerPrefs.GetInt("MotionBlur")==1){ PlayerPrefs.SetInt("MotionBlur",0); motionblurtext.GetComponent<Text>().text = "off"; } } public void AmbientOcclusion (){ if(PlayerPrefs.GetInt("AmbientOcclusion")==0){ PlayerPrefs.SetInt("AmbientOcclusion",1); ambientocclusiontext.GetComponent<Text>().text = "on"; } else if(PlayerPrefs.GetInt("AmbientOcclusion")==1){ PlayerPrefs.SetInt("AmbientOcclusion",0); ambientocclusiontext.GetComponent<Text>().text = "off"; } } public void CameraEffects (){ if(PlayerPrefs.GetInt("CameraEffects")==0){ PlayerPrefs.SetInt("CameraEffects",1); cameraeffectstext.GetComponent<Text>().text = "on"; } else if(PlayerPrefs.GetInt("CameraEffects")==1){ PlayerPrefs.SetInt("CameraEffects",0); cameraeffectstext.GetComponent<Text>().text = "off"; } } public void TexturesLow (){ PlayerPrefs.SetInt("Textures",0); QualitySettings.masterTextureLimit = 2; texturelowtext.GetComponent<Text>().text = "LOW"; texturemedtext.GetComponent<Text>().text = "med"; texturehightext.GetComponent<Text>().text = "high"; texturelowtextLINE.SetActive(true); texturemedtextLINE.SetActive(false); texturehightextLINE.SetActive(false); } public void TexturesMed (){ PlayerPrefs.SetInt("Textures",1); QualitySettings.masterTextureLimit = 1; texturelowtext.GetComponent<Text>().text = "low"; texturemedtext.GetComponent<Text>().text = "MED"; texturehightext.GetComponent<Text>().text = "high"; texturelowtextLINE.SetActive(false); texturemedtextLINE.SetActive(true); texturehightextLINE.SetActive(false); } public void TexturesHigh (){ PlayerPrefs.SetInt("Textures",2); QualitySettings.masterTextureLimit = 0; texturelowtext.GetComponent<Text>().text = "low"; texturemedtext.GetComponent<Text>().text = "med"; texturehightext.GetComponent<Text>().text = "HIGH"; texturelowtextLINE.SetActive(false); texturemedtextLINE.SetActive(false); texturehightextLINE.SetActive(true); } }
package io.vehiclehistory.api.model; import java.io.Serializable; /** * Created by dudvar on 2015-03-13. */ public class Vehicle implements Serializable { private Name name; private VehicleType type; private Engine engine; private Plate plate; private String vin; private Production production; private Policy policy; private Boolean stolen; private Registration registration; private Inspection inspection; private Mileage mileage; public Name getName() { return name; } public VehicleType getType() { return type; } public Engine getEngine() { return engine; } public Plate getPlate() { return plate; } public String getVin() { return vin; } public Production getProduction() { return production; } public Policy getPolicy() { return policy; } public Boolean getStolen() { return stolen; } public Registration getRegistration() { return registration; } public Inspection getInspection() { return inspection; } public Mileage getMileage() { return mileage; } }
using System; namespace NoesisLabs.Elve.VenstarColorTouch.Enums { public enum HolidayState { NotObservingHoliday = 0, ObservingHoliday = 1 } }
u.check().then(function(update){}) if(blah==="1"){}
--- description: Contains the information that describes the vertical component of the lines in the stationery used by the Journal note. Used, for example, when the note has grid lines. ms.assetid: af6f485e-13df-41bb-b57a-10d8393b83e7 title: Vertical Element ms.topic: reference ms.date: 05/31/2018 --- # Vertical Element Contains the information that describes the vertical component of the lines in the stationery used by the Journal note. Used, for example, when the note has grid lines. ## Definition ``` syntax <xs:element name="Vertical" type="VerticalType" minOccurs="0" /> ``` ## Parent Elements [**LineLayout**](linelayout-element.md) ## Child Elements None. ## Attributes | Attribute | Type | Required | Description | Possible Values | |-----------|------|----------|-------------|-----------------| | <strong>Style</strong> | <a href="linelayoutstyletype-simple-type.md"><strong>LineLayoutStyleType</strong></a> simpleType | Required | Specifies the type of line to be drawn. | <ul><li>None</li><li>Solid</li><li>Dash</li><li>Dot</li><li>DashDot</li><li>DashDotDot</li><li>Double</li></ul> | | <strong>Color</strong> | <a href="colortype-simple-type.md"><strong>ColorType</strong></a> simpleType | Optional | Color of the element. | A hexadecimal RGB value. Matches the following regular expression: #[0-9a-zA-Z]{6}. For example, #4a79B5.<br /> | | <strong>SpacingBefore</strong> | <strong>xs:nonNegativeInteger</strong> | Optional | Spacing before the element. | Any non-negative integer. | | <strong>SpacingBetween</strong> | <strong>xs:nonNegativeInteger</strong> | Optional | Spacing between this element and surrounding elements. | Any non-negative integer. |   ## Element Information | Element | Value | |--------------|---------------------------------------------------------------| | Element type | [**VerticalType**](verticaltype-complex-type.md) complexType | | Namespace | urn:schemas-microsoft-com:tabletpc:richink | | Schema name | Journal Reader |      
# KeePass (18 December) | CP Information | | |-----------------|------------| | Package | [KeePassXC - Cross-Platform Password Manager](https://keepassxc.org/) | | Script Name | [keepassxc-cp-init-script.sh](build/keepassxc-cp-init-script.sh) | | CP Mount Path | /custom/keepassxc | | CP Size | 100M | | IGEL OS Version (min) | 11.05.133 | | Packaging Notes | Details can be found in the build script [build-keepassxc-cp.sh](build/build-keepassxc-cp.sh) |
#!/usr/bin/perl use warnings; use strict; use App::Paws; use App::Paws::Context; use lib './t/lib'; use App::Paws::Test::Server; use App::Paws::Test::Utils qw(test_setup get_files_in_directory write_message); use Test::More tests => 2; my $server = App::Paws::Test::Server->new(); $server->run(); my $url = 'http://localhost:'.$server->{'port'}; my ($mail_dir, $bounce_dir, $config, $config_path) = test_setup($url); my $paws = App::Paws->new(); $paws->receive(1); my @files = get_files_in_directory($mail_dir); is(@files, 11, 'Got 11 mails'); my $mail = write_message('slackbot', 'im/slackbot', 'asdf'); $paws->send([], $mail); $paws->send_queued(); $paws->receive(20); @files = get_files_in_directory($mail_dir); is(@files, 12, 'Received mail previously sent'); $server->shutdown(); 1;
# Ember-cli-calendar ```bash ember install ember-cli-calendar ```
const { root } = require("cheerio"); class Node { constructor(item) { this.item= item; this.right = null; this.left = null; this.count = 0; }; }; class BST { constructor() { this.root = null; } create(item) { const newNode = new Node(item); if (!this.root) { this.root = newNode; return this; }; let current = this.root; const addSide = side => { if (!current[side]) { current[side] = newNode; return this; }; current = current[side]; }; while (true) { if (item === current.item) { current.count++; return this; }; if (item < current.item) addSide('left'); else addSide('right'); }; }; }; function tree_intersection(root1, root2) { if(this.root === null) { return undefined; } let searchArray1 = []; let searchArray2 = []; // function inorder(root) { // if (root) // inorder(root.left) // console.log(root[key]); // inorder(root.right) // } while(1) { if(root1) { searchArray1.push(root1); root1 = root1.left; } else if (root2) { searchArray2.push(root2); root2 = root2.left; } else if (searchArray1.length !== 0 && searchArray2 !== 0) { root1 = searchArray2[-1]; root2 = searchArray2[-1]; if(root1[key] === root2[key]) { searchArray1.pop(-1); searchArray2.pop(-1); } root1 = root1.right; root2 = root2.right; } } }; let tree1 = new BST(); let tree2 = new BST(); tree1.add(10); tree1.add(4); tree1.add(20); tree1.add(60) tree1.add(20); tree2.add(10); tree2.add(100); tree2.add(20);
#!/usr/bin/env node 'use strict'; var program = require('commander'); var version = require('../package.json').version; var path = require('path'); var _ = require('lodash'); function isExplicitlyRelativeOrAbsolute(path) { return path.startsWith('./') || path.startsWith('../') || path.startsWith('/'); } function getAbsoluteModuleLocation(moduleName, relativePath) { return isExplicitlyRelativeOrAbsolute(moduleName) ? // if this is a relative or absolute path, resolve it relative to // relativePath path.join(relativePath, moduleName) : // otherwise, resolve it relative to the node_modules directory of // relativePath path.join(relativePath, 'node_modules', moduleName); } /** * Mimic `require()` behavior relative to the path on which the CLI was * initiated. * * 1. If module name is an explicitly relative or absolute path (i.e. it begins * with `./`, `../`, or `/`) resolve it relative to the caller's path and * `require()` it. * 2. Otherwise, resolve it relative to the `node_modules` directory of the * caller's path it and `require()` it. */ function requireFrom(moduleName, relativePath) { return require(getAbsoluteModuleLocation(moduleName, relativePath)); } program .version(version) .option('--baseDir <path>', 'Path to pantry of ingredients', process.cwd()) .option('--namespace <name>', 'Pantry namespace') .option('--port [8080]', 'Port the server should listen on', 8080) .option( '--helpers <module paths>', 'require()-able module mapping helper names to function', function (helper, helpers) { return helpers.concat(helper); }, [] ) .on('--help', function () { console.log(` Specifying helpers: Each entry is handled by mimicking the behavior of a require() from the current working directory and is expected to be a module that exports an object mapping helper names to functions. If an entry referenced later in the command exports an object with a name that has already been used by a previous entry, it will be overwritten. `); }) .parse(process.argv); if (!program.namespace) { console.error('namespace is a required parameter'); program.help(); process.exit(1); } var config = { baseDir: program.baseDir, namespace: program.namespace }; // add helpers to config, if present if (program.helpers) { // first, require() everything var helperModules = program.helpers.map( // we need to mimic the behavior of require()ing from process.cwd() function (helperPath) { return requireFrom(helperPath, process.cwd()); } ); // now, merge them into a new object config.helpers = _.assign.apply(null, [{}].concat(helperModules)); } var app = require('../')(config); var server = app.listen(program.port, function () { var host = server.address().address; var port = server.address().port; console.log( 'Serving %s ingredients from %s at http://%s:%s', program.namespace, program.baseDir, host, port ); });
#!/usr/bin/env bash set -e brew update brew cleanup brew cask cleanup brew install \ moreutils \ jq \ shellcheck
//@flow import { SET_ACTIVE_ANALZYE } from '../constants'; type initialType = { id: ?string, title?: string, url?: string, icon?: string, descr?: string, tracking_date?: string, analyze?: { usa: { number_of_mentions: number, airforce: Object, marine: Object, infantry: Object } } }; const initialState = { id: undefined }; export function activeAnazlye( state: initialType = initialState, action: Object ) { switch (action.type) { case SET_ACTIVE_ANALZYE: return { ...state, id: action.payload.id }; default: return state; } }
export { formatBalance } from './formatBalance'; export { FormattedBalance } from './types';
@include('public_blade.top') <div class="header bg-darkorange"> <h5>影院影厅放映管理表</h5> </div> <table class="table table-hover table-striped table-bordered table-condensed"> <thead> <tr> <th>影院ID</th> <th>影院名称</th> <th>影院照片</th> <th>影院地址</th> <th>影厅电话</th> <th>营业时间</th> <th>影院的热度</th> </tr> </thead> <tbody id="tbody"> @foreach ($data as $value) <tr> <td>{{$value->cinema_id}}</td> <td><a href="cinema_num?cinema_id=<?=$value->cinema_id?>">{{$value->cinema_name}}</a></td> <td><img src="{{$value->cinema_img}}" style="width:50px;height: 30px;"></td> <td>{{$value->cinema_site}}</td> <td>{{$value->cinema_tel}}</td> <td>{{$value->cinema_open_hours}}</td> <td>{{$value->cinema_hot}}</td> </tr> @endforeach </tbody> </table> {{ $data->links() }} @include('public_blade.footer')
import React from 'react'; import fetch from 'isomorphic-unfetch'; import { Flex, Box } from 'grid-styled/emotion'; import styled, { css } from 'react-emotion'; import { space } from 'styled-system'; import Layout from '../components/common/layout'; import BannerSection from '../components/common/banner'; import { Container, SubTitle, Button } from '../utils/base.styles'; import { baseEventsURL, futureEventsURL, pastEventsURL, imagePlaceholderURL } from '../utils/urls'; import EventCard from '../components/events/event-card'; import EventLoader from '../components/events/event-content-loader'; const EventsSection = styled.section` ${space}; background: #fff; position: relative; & .loadmore_div { text-align: center; margin-top: 2rem; margin-bottom: 0.8rem; } & .event_type_title { color: #374355; font-weight: bold; } `; export default class Events extends React.Component { state = { pastEvents: [], pastEventsLoadLimit: 2, futureEvents: [], futureEventsLoadLimit: 2, fetchError: null, loading: true, showFutureEvents: true, }; async componentDidMount() { try { let pastEvents; let futureEvents; const pastEventsResponse = await fetch(`${baseEventsURL}${pastEventsURL}`); if (pastEventsResponse.ok) { pastEvents = await pastEventsResponse.json(); } else { throw new Error('Failed to Retrieve past events'); } const futureEventsResponse = await fetch(`${baseEventsURL}${futureEventsURL}`); if (futureEventsResponse.ok) { futureEvents = await futureEventsResponse.json(); } else { throw new Error('Failed to retieve future events'); } this.setState({ pastEvents, futureEvents, fetchError: null, loading: false, }); } catch (err) { console.log(err); this.setState({ pastEvents: null, futureEvents: null, fetchError: err.message, loading: false, }); } } renderEvents(events, loadLimit) { if (this.state.loading) { return [1, 2].map(i => { return <EventLoader key={i} />; }); } if (events.length === 0) { return ( <SubTitle inverted color="#222"> No upcoming events yet, check back later </SubTitle> ); } if (events === null) { return ( <SubTitle inverted color="#222"> Oops! somethings went wrong while fetching the events </SubTitle> ); } return ( <div> {events.slice(0, loadLimit).map(event => { const regexForImageSrc = /<img.*?src="([^">]*\/([^">]*?))".*?>/g; const imgs = regexForImageSrc.exec(event.description); const imageSrc = imgs ? imgs[1] : event.featured_photo ? event.featured_photo.photo_link : imagePlaceholderURL; return ( <EventCard showImg key={event.id} image={imageSrc} name={event.name} location={event.venue ? event.venue.name : 'Online'} online={!event.venue} time={event.time} attendees={event.yes_rsvp_count} tense={event.status} link={event.link} /> ); })} </div> ); } renderLoadMoreButton(eventsTotalLength, loadLimit, isPastEvent) { return loadLimit >= eventsTotalLength ? null : ( <div className="loadmore_div" mb={[5, 5]}> <Button inverted medium onClick={() => this.loadMore(isPastEvent)}> Load more </Button> </div> ); } loadMore(isPastEvent) { return isPastEvent ? this.setState({ pastEventsLoadLimit: this.state.pastEventsLoadLimit + 5 }) : this.setState({ futureEventsLoadLimit: this.state.futureEventsLoadLimit + 5 }); } loadEventsOfThisCategory(category) { this.setState({ showFutureEvents: category === 'upcomingEvents', }); } render() { const { loading } = this.state; return ( <Layout> <BannerSection title="Online & Offline Events" subTitle="Because you cannot change the world alone" /> <EventsSection py={[3, 3]} px={[3, 2]}> <Container> <Flex pb={[2, 2]} flexDirection="column" alignItems="center" justifyContent="center"> <Box width={[1, 0.75]}> <div className={css` text-align: center; `}> <Button medium ghost={this.state.showFutureEvents} onClick={() => this.loadEventsOfThisCategory('upcomingEvents')}> Upcoming Events </Button> <Button medium ghost={!this.state.showFutureEvents} onClick={() => this.loadEventsOfThisCategory('recentEvents')}> Recent Events </Button> </div> </Box> </Flex> <Flex pb={[2, 2]} flexDirection="column" alignItems="center" justifyContent="center"> <Box width={[1, 0.75]}> <h3 className="event_type_title" color="#222"> {this.state.showFutureEvents ? 'Upcoming Events' : 'Recent Events'} </h3> {this.state.showFutureEvents && this.renderEvents(this.state.futureEvents, this.state.futureEventsLoadLimit)} {this.state.showFutureEvents && !loading && this.renderLoadMoreButton(this.state.futureEvents.length, this.state.futureEventsLoadLimit, false)} {!this.state.showFutureEvents && this.renderEvents(this.state.pastEvents, this.state.pastEventsLoadLimit)} {!this.state.showFutureEvents && !loading && this.renderLoadMoreButton(this.state.pastEvents.length, this.state.pastEventsLoadLimit, true)} </Box> </Flex> </Container> </EventsSection> </Layout> ); } }
package com.example.oigami.twimpt.twimpt.token; import com.example.oigami.twimpt.twimpt.TwimptNetException; import org.json.JSONException; import org.json.JSONObject; public class AccessTokenData { public String token; public String secret; public AccessTokenData() {} public AccessTokenData(JSONObject json) throws JSONException, TwimptNetException { if (!json.isNull("error_code")) { throw new TwimptNetException("error_code:" + json.getInt("error_code") + "\n" + json.getString("error_params")); } token = json.getString("access_token"); secret = json.getString("access_token_secret"); } }
addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) val akkaVersion = "2.4.16" val circeVersion = "0.6.1" lazy val root = (project in file(".")). settings( inThisBuild(List( organization := "com.janschulte", scalaVersion := "2.11.8", version := "0.1.0-SNAPSHOT" )), name := "akka.beginner", libraryDependencies ++= Seq( "com.typesafe.akka" %% "akka-actor" % akkaVersion, "com.typesafe.akka" %% "akka-agent" % akkaVersion, "com.typesafe.akka" %% "akka-cluster" % akkaVersion, "com.typesafe.akka" %% "akka-cluster-metrics" % akkaVersion, "com.typesafe.akka" %% "akka-cluster-sharding" % akkaVersion, "com.typesafe.akka" %% "akka-cluster-tools" % akkaVersion, "com.typesafe.akka" %% "akka-contrib" % akkaVersion, "com.typesafe.akka" %% "akka-multi-node-testkit" % akkaVersion, "com.typesafe.akka" %% "akka-persistence" % akkaVersion, "com.typesafe.akka" %% "akka-persistence-tck" % akkaVersion, "com.typesafe.akka" %% "akka-remote" % akkaVersion, "com.typesafe.akka" %% "akka-slf4j" % akkaVersion, "com.typesafe.akka" %% "akka-stream" % akkaVersion, "com.typesafe.akka" %% "akka-stream-testkit" % akkaVersion, "com.typesafe.akka" %% "akka-testkit" % akkaVersion, "com.typesafe.akka" %% "akka-distributed-data-experimental" % akkaVersion, "com.typesafe.akka" %% "akka-typed-experimental" % akkaVersion, "com.typesafe.akka" %% "akka-persistence-query-experimental" % akkaVersion, "com.chuusai" %% "shapeless" % "2.3.2", "com.github.mpilquist" %% "simulacrum" % "0.8.0", "io.circe" %% "circe-core" % circeVersion, "io.circe" %% "circe-generic" % circeVersion, "io.circe" %% "circe-parser" % circeVersion, "org.typelevel" %% "cats" % "0.7.2", "org.specs2" %% "specs2-core" % "3.8.8" % "test", "org.scalacheck" %% "scalacheck" % "1.13.4" % "test" ) )
using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.DependencyInjection; namespace Miru.Html.Tags { [HtmlTargetElement("miru-antiforgery", Attributes = "name", TagStructure = TagStructure.WithoutEndTag)] public class MetaAntiforgeryTagHelper : MiruTagHelper { [HtmlAttributeName("name")] public string Name { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { var httpContextAccessor = RequestServices.GetService<IHttpContextAccessor>(); var antiForgery = RequestServices.GetService<IAntiforgery>(); if (httpContextAccessor.HttpContext != null) { output.TagName = "meta"; output.Attributes.SetAttribute("name", Name); output.Attributes.SetAttribute("content", antiForgery.GetAndStoreTokens(httpContextAccessor.HttpContext).RequestToken); } else { output.SuppressOutput(); } } } }
sbtPlugin := true organization := "com.leobenkel" homepage := Some(url("https://github.com/leobenkel/umlclassdiagram")) licenses := List("MIT" -> url("https://opensource.org/licenses/MIT")) developers := List( Developer( "leobenkel", "Leo Benkel", "", url("https://leobenkel.com") ) ) sonatypeCredentialHost := "oss.sonatype.org" sonatypeRepository := "https://oss.sonatype.org/service/local" val projectName = IO.readLines(new File("PROJECT_NAME")).head name := projectName publishMavenStyle := true // fail to publish without that updateOptions := updateOptions.value.withGigahorse(false) Test / publishArtifact := false pomIncludeRepository := (_ => false) resolvers += Resolver.bintrayRepo("scalameta", "maven") addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.9.2") libraryDependencies += "commons-logging" % "commons-logging" % "1.2" libraryDependencies += "org.reflections" % "reflections" % "0.10.2" // Test libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.12" % Test import org.scoverage.coveralls.Imports.CoverallsKeys.{coverallsFailBuildOnError, coverallsFile} // https://www.scala-sbt.org/1.x/docs/Testing-sbt-plugins.html enablePlugins(SbtPlugin) scriptedLaunchOpts ++= Seq("-Xmx1024M", "-Dplugin.version=" + version.value) scriptedBufferLog := false scriptedParallelInstances := 1 scriptedBatchExecution := false coverageOutputDebug := true coverallsFailBuildOnError := false coverallsFile := baseDirectory.value / "coveralls/coveralls.json" classLoaderLayeringStrategy := ClassLoaderLayeringStrategy.ScalaLibrary allowZombieClassLoaders := false closeClassLoaders := true
import React, { useEffect, useState } from 'react'; import { makeStyles, createStyles, Theme } from '@material-ui/core/styles'; import { Button } from '@material-ui/core'; import Grid from '@material-ui/core/Grid'; import { Redirect, RouteComponentProps } from 'react-router-dom'; import { validateSessionId } from './util'; const useStyles = makeStyles((theme: Theme) => createStyles({ button: { minWidth: 175, minHeight: 125, }, }) ); export type Card = { word: string; card_type: 'Blue' | 'Red' | 'Gray' | 'Black'; }; export type GameState = { session_id: string; updated_timestamp: number; cards: Card[]; }; type SessionParams = { session_id: string; }; type SessionProps = RouteComponentProps<SessionParams>; export function Session({ match }: SessionProps) { const session_id = match.params.session_id; const [gameState, setGameState] = useState<GameState>(); const [redirectHome, setRedirectHome] = useState<boolean>(false); useEffect(() => { if (validateSessionId(session_id)) { fetch(`/session/${session_id}`) .then((response) => response.json()) .then((data: GameState) => setGameState(data)) .catch((error) => { console.log(error); setRedirectHome(true); }); } else { setRedirectHome(true); } }, [session_id]); const classes = useStyles(); function FormRow() { return ( <React.Fragment> <Grid item xs={3}> <Button variant="outlined" className={classes.button}> item </Button> </Grid> <Grid item xs={3}> <Button variant="outlined" className={classes.button}> item </Button> </Grid> <Grid item xs={3}> <Button variant="outlined" className={classes.button}> item </Button> </Grid> <Grid item xs={3}> <Button variant="outlined" className={classes.button}> item </Button> </Grid> <Grid item xs={3}> <Button variant="outlined" className={classes.button}> item </Button> </Grid> </React.Fragment> ); } return ( <div> {redirectHome && <Redirect to={{ pathname: '/' }} />} <Grid container direction="column" spacing={2}> <Grid item sm={12} md> <Grid container direction="row" spacing={3}> <Grid item xs={6} sm={3}> 9 - 8 </Grid> <Grid item xs={6} sm={3}> Blue's Turn </Grid> <Grid item xs={6} sm={3}> Neutrals Remaining: 5 </Grid> <Grid item xs={6} sm={3}> <Button variant="contained"> Spymaster </Button> </Grid> </Grid> </Grid> <Grid item> <Grid wrap="nowrap" container spacing={3} direction="row" justify="center" alignItems="center" > <FormRow /> </Grid> </Grid> <Grid item> <Grid wrap="nowrap" container spacing={3} direction="row" justify="center" alignItems="center" > <FormRow /> </Grid> </Grid> <Grid item> <Grid wrap="nowrap" container spacing={3} direction="row" justify="center" alignItems="center" > <FormRow /> </Grid> </Grid> <Grid item> <Grid wrap="nowrap" container spacing={3} direction="row" justify="center" alignItems="center" > <FormRow /> </Grid> </Grid> <Grid item> <Grid wrap="nowrap" container spacing={3} direction="row" justify="center" alignItems="center" > <FormRow /> </Grid> </Grid> </Grid> <Grid item sm={12}> <Grid container direction="row" spacing={6}> <Grid item xs={6} sm={3}> <Button variant="outlined" onClick={() => { navigator.clipboard .writeText( `${window.location.hostname}:3000/session/${session_id}` ) }} > Copy Game Link </Button> </Grid> <Grid item xs={6} sm={3} /> <Grid item xs={6} sm={3} /> <Grid item xs={6} sm={3}> <Button variant="contained" color="primary"> Next Turn </Button> </Grid> </Grid> </Grid> </div> ); }
using Hurace.Domain; using Hurace.RaceControl.Helpers.MvvmCross; using MvvmCross.Commands; using MvvmCross.Plugin.Messenger; using MvvmCross.ViewModels; namespace Hurace.RaceControl.ViewModels { public class RunEntryViewModel : MvxViewModel { private readonly IMvxMessenger _messenger; private Run _run; public RunEntryViewModel(IMvxMessenger messenger, Run run) { _messenger = messenger; Run = run; DisqualifySkierCommand = new MvxCommand<Run>(r => _messenger.Publish(new DisqualifySkierMessage(this, Run))); } public Run Run { get => _run; set => SetProperty(ref _run, value); } public bool CanDisqualify => Run.Status != RunStatus.Disqualified; public MvxCommand<Run> DisqualifySkierCommand { get; set; } } }
--- title: ScopedTypeVariables下の1ランク多相で型が合わないとき tags: Haskell --- # まとめ  forallを指定してあげると、一連の`a`, `b`が固定されてくれます。 ```haskell f :: forall a b. Eq b => (a -> b) -> (a -> b) -> a -> Bool ``` # 解説  以下のようなコードを書くと ```haskell {-# LANGUAGE ScopedTypeVariables #-} f :: Eq b => (a -> b) -> (a -> b) -> a -> Bool f g h x = let y = g x :: b z = h x :: b in y == z main :: IO () main = pure () ``` 以下のようなエラーがでます。 「`g x`によって推論されたその型`b'`と、指定されたその型`b`が同一ではない」の意です。 意図として 「`g x :: b`の`b`は、`f`の型で指定された`b`そのものである」 ということを指定したつもりなのだけど…。 ``` /tmp/nvimNLJJ6T/148.hs:5:11: error: • Couldn't match expected type ‘b2’ with actual type ‘b’ ‘b’ is a rigid type variable bound by the type signature for: f :: forall b a. Eq b => (a -> b) -> (a -> b) -> a -> Bool at /tmp/nvimNLJJ6T/148.hs:3:6 ‘b2’ is a rigid type variable bound by an expression type signature: forall b2. b2 at /tmp/nvimNLJJ6T/148.hs:5:18 • In the expression: g x :: b In an equation for ‘y’: y = g x :: b In the expression: let y = g x :: b z = h x :: b in y == z • Relevant bindings include h :: a -> b (bound at /tmp/nvimNLJJ6T/148.hs:4:5) g :: a -> b (bound at /tmp/nvimNLJJ6T/148.hs:4:3) f :: (a -> b) -> (a -> b) -> a -> Bool (bound at /tmp/nvimNLJJ6T/148.hs:4:1) /tmp/nvimNLJJ6T/148.hs:6:11: error: • Couldn't match expected type ‘b2’ with actual type ‘b’ ‘b’ is a rigid type variable bound by the type signature for: f :: forall b a. Eq b => (a -> b) -> (a -> b) -> a -> Bool at /tmp/nvimNLJJ6T/148.hs:3:6 ‘b2’ is a rigid type variable bound by an expression type signature: forall b2. b2 at /tmp/nvimNLJJ6T/148.hs:6:18 • In the expression: h x :: b In an equation for ‘z’: z = h x :: b In the expression: let y = g x :: b z = h x :: b in y == z • Relevant bindings include h :: a -> b (bound at /tmp/nvimNLJJ6T/148.hs:4:5) g :: a -> b (bound at /tmp/nvimNLJJ6T/148.hs:4:3) f :: (a -> b) -> (a -> b) -> a -> Bool (bound at /tmp/nvimNLJJ6T/148.hs:4:1) /tmp/nvimNLJJ6T/148.hs:7:6: error: • Could not deduce (Eq a0) arising from a use of ‘==’ from the context: Eq b bound by the type signature for: f :: Eq b => (a -> b) -> (a -> b) -> a -> Bool at /tmp/nvimNLJJ6T/148.hs:3:1-46 The type variable ‘a0’ is ambiguous These potential instances exist: instance Eq Ordering -- Defined in ‘GHC.Classes’ instance Eq Integer -- Defined in ‘integer-gmp-1.0.0.1:GHC.Integer.Type’ instance Eq a => Eq (Maybe a) -- Defined in ‘GHC.Base’ ...plus 22 others ...plus 7 instances involving out-of-scope types (use -fprint-potential-instances to see them all) • In the expression: y == z In the expression: let y = g x :: b z = h x :: b in y == z In an equation for ‘f’: f g h x = let y = ... z = ... in y == z ``` ということで、確かに 「`g x :: b`の`b`は、`f`の型で指定された`b`そのものである」 ということを型検査に伝えてあげます。 ```haskell {-# LANGUAGE ScopedTypeVariables #-} f :: forall a b. Eq b => (a -> b) -> (a -> b) -> a -> Bool f g h x = let y = g x :: b z = h x :: b in y == z main :: IO () main = pure () ``` OK :dog2:  そりゃそうなんですけど、いつも忘れて「!?」ってなりますよね。
-- Since we are adding a value to an existing enum, and since the 'up' -- migration is idempotent, we don't worry about reverting that change
import React from "react" import Layout from "../components/layout" import { PageProps } from "gatsby" const About = ({ location }: PageProps) => { return ( <Layout location={location} title="About"> <p> I hope that I am a hard worker that likes to think creatively in code. I have been working in JavaScript and more recently TypeScript. Working at startups has taught me so much. I will forever be thankful to those who helped get me here. </p> </Layout> ) } export default About
AROUND = [ [0, -1], [0, +1], [-1, 0], [+1, 0], ] def min_step(x, y, xx, yy) @visited = Array.new(@m) { [] } @visited[x][y] = true queue = [[0, x, y]] while !queue.empty? step, x1, y1 = queue.shift return step if x1 == xx && y1 == yy AROUND.each do |i, j| x2, y2 = x1+i, y1+j next if x2 < 0 || x2 >= @m || y2 < 0 || y2 >= @n || @visited[x2][y2] || @forest[x2][y2] == 0 return step+1 if x2 == xx && y2 == yy queue << [step+1, x2, y2] @visited[x2][y2] = true end end -1 end # @param {Integer[][]} forest # @return {Integer} def cut_off_tree(forest) @forest = forest @m, @n = @forest.size, @forest[0].size trees = [] @forest.each_with_index do |row, i| row.each_with_index do |ele, j| trees << [ele, i, j] if ele > 1 end end trees.sort! ans = min_step(0, 0, trees[0][1], trees[0][2]) (trees.size-1).times do |k| step = min_step(trees[k][1], trees[k][2], trees[k+1][1], trees[k+1][2]) return -1 if step == -1 ans += step end ans end
import { ObjectSchema, ArraySchema } from 'pip-services3-commons-node'; import { TypeCode } from 'pip-services3-commons-node'; export class PayoutV1Schema extends ObjectSchema { public constructor() { super(); this.withRequiredProperty('id', TypeCode.String); this.withRequiredProperty('system', TypeCode.String); this.withRequiredProperty('status', TypeCode.String); this.withOptionalProperty('status_details', TypeCode.String); this.withOptionalProperty('account_id', TypeCode.String); this.withOptionalProperty('reversal_id', TypeCode.String); } }
select name, id, type, version, geo_redundant_backup_enabled, user_visible_state, administrator_login, auto_grow_enabled, backup_retention_days, fully_qualified_domain_name, public_network_access, sku_capacity, sku_family, sku_name, sku_tier, ssl_enforcement, storage_mb from azure.azure_mariadb_server where name = '{{ resourceName }}' and resource_group = '{{ resourceName }}';
package org.mgaidamak.cinema.ticket.dao.ticket import org.mgaidamak.cinema.ticket.dao.Ticket /** * DAO for Seat list */ interface ITicketRepo { fun createTicket(ticket: Ticket): Ticket? fun getTickets(session: Int?, bill: Int?): Collection<Ticket> fun getTicket(session: Int, seat: Int): Ticket? fun deleteTicketById(id: Int): Ticket? fun deleteTicketByBill(bill: Int): Collection<Ticket> fun clear() fun total(): Int }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeclarationOfVariables { class DeclarationOfVariables { static void Main() { ushort first = 51130; sbyte second = -115; int third=4825932; byte fourth=97; short fifth=-10000; Console.WriteLine("{0},{1},{2},{3},{4}", first, second, third, fourth, fifth); } } }
CREATE TABLE [dbo].[user] ( [userId] VARCHAR (33) NOT NULL, [userPassword] VARCHAR (33) NULL, [createtime] DATETIME CONSTRAINT [DF_user_createtime] DEFAULT (getdate()) NOT NULL, [userCommentsPublic] NVARCHAR (99) NULL, [userCommentsPrivate] NVARCHAR (99) NULL, [lastLoginTime] DATETIME NULL, [modifytime] DATETIME CONSTRAINT [DF_user_modifytime] DEFAULT (getdate()) NOT NULL, [hintQuestion] NVARCHAR (99) NULL, [hintAnswer] NVARCHAR (99) NULL, [deleteTime] DATETIME2 (7) NULL, [deleteBy] VARCHAR (33) NULL, CONSTRAINT [PK_user] PRIMARY KEY CLUSTERED ([userId] ASC) );
namespace LockHandler.Constants { public static class MessagePropertyNames { public const string LockToken = "lockToken"; public const string QueueName = "queueName"; public const string RetryCount = "retryCount"; public const string RenewalIntervalInSeconds = "renewalIntervalInSeconds"; public const string MaxRetryNumber = "maxRetryNumber"; } }
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class SettingTableSeeder_2016_08_28 extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $settings = array( array( 'name' => 'Homepage Title', 'code' => 'homepage_title', 'type' => \App\Models\Setting::SITE, 'value' => 'Advertising Agency | Creative & Branding Agency In Malaysia & Singapore', ), array( 'name' => 'Homepage Featured Project', 'code' => 'homepage_featured_project', 'type' => \App\Models\Setting::SITE, 'value' => '1,2,3,5', ), ); foreach ($settings as $setting) { \App\Models\Setting::create($setting); } } }
require File.expand_path('../commentable', __FILE__) class Module::ClassDoc include Module::Commentable FIELD_PUBLIC = "public" FIELD_PROTECTED = "protected" FIELD_PRIVATE = "private" attr_accessor :data, :field_hash, :method_hash, :metainfo def initialize(data) # puts "Got ClassType: #{data[:name]} extends #{data[:baseType]}" self.data = data self.method_hash = parseMethods self.field_hash = parseFields self.metainfo = parseMetainfo end # all superclasses of this class def superclasses superclasses = [] iterating_class = self while(1) break if iterating_class.nil? || iterating_class.data[:name] == "Object" # Iterate onto this class's base class. iterating_class = $classes_by_package_path[ iterating_class.data[:baseType] ] superclasses << iterating_class end superclasses.delete_if { |x| x == nil } superclasses end # The immediate superclass of this class def superclass $classes_by_package_path[data[:baseType]] end # Extract all fields of a type from a class. def get_fields( field_type ) all_fields = field_hash superclasses.each do |superclass_doc| all_fields.merge! superclass_doc.field_hash end if field_type.nil? all_fields else Hash[ all_fields.select { |key, f| f[:fieldattributes].include?(field_type) && !(f[:fieldattributes].include? "const") && !(f[:docString].include? "@private") && !hidden_from_inherited(f) } ] end end # Extract all constants in this class def get_constants all_constants = field_hash superclasses.each do |superclass_doc| all_constants.merge! superclass_doc.field_hash end Hash[ all_constants.select { |key, f| f[:fieldattributes].include?("const") && !(f[:docString].include? "@private") && !hidden_from_inherited(f) } ] end # Extract all methods of a type from a class. def get_methods( method_type ) all_methods = method_hash superclasses.each do |superclass_doc| all_methods.merge! superclass_doc.method_hash end if method_type.nil? all_methods else Hash[ all_methods.select { |key, m| m[:methodattributes].include?(method_type) && !(m[:docString].include? "@private") && !hidden_from_inherited(m) } ] end end def get_events all_events = metainfo[:event] || [] superclasses.each do |superclass_doc| all_events += (superclass_doc.metainfo[:event] || []) end all_events end # def hidden_from_inherited(attribute) attribute[:defined_by] != self && (attribute[:docString].include? "@hide-from-inherited") end # Determine whether or not the class is native. def get_is_native() !metainfo[:native].nil? end def deprecated_message metainfo[:deprecated][0][:msg] unless metainfo[:deprecated].nil? end # Determine whether the class is public, private, or protected. def get_access_modifier() data[:classattributes].first end # Determine whether this is a class, interface, delegate or enum. def get_type() data[:type].downcase end # Check if any attributes are inherited. def has_inherited_fields( fields ) fields.each do |field| if package_path != field[:defined_by].package_path return true end end false end # Check if any functions are inherited. def has_inherited_methods( methods ) methods.each do |method| if package_path != method[:defined_by].package_path return true end end false end def url(relative_base) "#{relative_base}/api/#{package_path.split('.').join('/')}.html" end def package_path "#{data[:package]}.#{data[:name]}" end def to_s data[:name] end def self.full_classpath_to_url(path, relative_base) "#{relative_base}/api/#{path.split('.').join('/')}.html" end def object_type(parent_attribute, relative_base) str = "" if parent_attribute[:type] == "system.NativeDelegate" delegate_type = native_delegate_type(parent_attribute) str = "<a href='#{Module::ClassDoc.full_classpath_to_url(delegate_type, relative_base)}'>#{delegate_type.split(".").last}</a>" if delegate_type elsif !parent_attribute[:templatetypes].nil? str += vector_dictionary_links(parent_attribute[:templatetypes], relative_base) else class_type = parent_attribute[:returntype] || parent_attribute[:type] str = "<a href='#{Module::ClassDoc.full_classpath_to_url(class_type, relative_base)}'>#{class_type.split(".").last}</a>" end str end def native_delegate_type( attribute ) if attribute[:metainfo] delegate_meta = attribute[:metainfo][:OriginalType] if delegate_meta return delegate_meta[0][1] else return "system.NativeDelegate" end end end def vector_dictionary_links(parent_attribute, relative_base) class_type = parent_attribute[:type] str = "<a href='#{Module::ClassDoc.full_classpath_to_url(class_type, relative_base)}'>#{class_type.split(".").last}</a>.&#60;" parent_attribute[:types].each_with_index do |value, index| if value.kind_of? Hash str += vector_dictionary_links(value, relative_base) else str += "<a href='#{Module::ClassDoc.full_classpath_to_url(value, relative_base)}'>#{value.split(".").last}</a>" str += ", " if index < parent_attribute[:types].length - 1 end end str += "&#62; " end private def parseMethods return_hash = {} data[:methods].each do |method| method[:defined_by] = self return_hash[method[:name]] = method end return_hash end def parseFields return_hash = {} data[:fields].each do |field| field[:defined_by] = self return_hash[field[:name]] = field end data[:properties].each do |p| p[:defined_by] = self p[:fieldattributes] = p[:propertyattributes] return_hash[p[:name]] = p end return_hash end def parseMetainfo return {} if data[:metainfo].nil? serialized_metainfo = {} data[:metainfo].each do |key, entries| next if !key.is_a? String serialized_metainfo[key.downcase.to_sym] = [] entries.each do |raw_entry| serialized_entry = {} raw_entry.each_slice(2) do |key_value| serialized_entry[key_value[0].downcase.to_sym] = key_value[1] end serialized_metainfo[key.downcase.to_sym] << serialized_entry end end serialized_metainfo end end
#!/bin/sh -e echo " # The legacy build support script" echo " # -------------------------------" set -- if [ -e build.sh ]; then echo " ### Detected 'build.sh' executing it with bash. ###" set -- /bin/bash build.sh elif [ -e Makefile ] && grep -qsE '^SPHINXBUILD' Makefile && grep -qsE '^html:' Makefile; then echo " ### Detected sphinx Makefile. Running 'make html'. Add nop 'build.sh' to disable this! ###" set -- html if grep -qsE '^touchrst:' Makefile; then set -- touchrst "$@" fi set -- make "$@" else echo " ### No build.sh or sphinx Makefile. Not building the course. ###" fi if [ "$1" ]; then echo " # Executing: $@" exec "$@" fi exit 0
private async Task<IList<jsTreeNode>> GetHubsAsync() { IList<jsTreeNode> nodes = new List<jsTreeNode>(); // the API SDK HubsApi hubsApi = new HubsApi(); hubsApi.Configuration.AccessToken = Credentials.TokenInternal; var hubs = await hubsApi.GetHubsAsync(); foreach (KeyValuePair<string, dynamic> hubInfo in new DynamicDictionaryItems(hubs.data)) { // check the type of the hub to show an icon string nodeType = "hubs"; switch ((string)hubInfo.Value.attributes.extension.type) { case "hubs:autodesk.core:Hub": nodeType = "hubs"; break; case "hubs:autodesk.a360:PersonalHub": nodeType = "personalHub"; break; case "hubs:autodesk.bim360:Account": nodeType = "bim360Hubs"; break; } // create a treenode with the values jsTreeNode hubNode = new jsTreeNode(hubInfo.Value.links.self.href, hubInfo.Value.attributes.name, nodeType, true); nodes.Add(hubNode); } return nodes; } private async Task<IList<jsTreeNode>> GetProjectsAsync(string href) { IList<jsTreeNode> nodes = new List<jsTreeNode>(); // the API SDK ProjectsApi projectsApi = new ProjectsApi(); projectsApi.Configuration.AccessToken = Credentials.TokenInternal; // extract the hubId from the href string[] idParams = href.Split('/'); string hubId = idParams[idParams.Length - 1]; var projects = await projectsApi.GetHubProjectsAsync(hubId); foreach (KeyValuePair<string, dynamic> projectInfo in new DynamicDictionaryItems(projects.data)) { // check the type of the project to show an icon string nodeType = "projects"; switch ((string)projectInfo.Value.attributes.extension.type) { case "projects:autodesk.core:Project": nodeType = "a360projects"; break; case "projects:autodesk.bim360:Project": nodeType = "bim360projects"; break; } // create a treenode with the values jsTreeNode projectNode = new jsTreeNode(projectInfo.Value.links.self.href, projectInfo.Value.attributes.name, nodeType, true); nodes.Add(projectNode); } return nodes; } private async Task<IList<jsTreeNode>> GetProjectContents(string href) { IList<jsTreeNode> nodes = new List<jsTreeNode>(); // the API SDK ProjectsApi projectApi = new ProjectsApi(); projectApi.Configuration.AccessToken = Credentials.TokenInternal; // extract the hubId & projectId from the href string[] idParams = href.Split('/'); string hubId = idParams[idParams.Length - 3]; string projectId = idParams[idParams.Length - 1]; var folders = await projectApi.GetProjectTopFoldersAsync(hubId, projectId); foreach (KeyValuePair<string, dynamic> folder in new DynamicDictionaryItems(folders.data)) { nodes.Add(new jsTreeNode(folder.Value.links.self.href, folder.Value.attributes.displayName, "folders", true)); } return nodes; } private async Task<IList<jsTreeNode>> GetFolderContents(string href) { IList<jsTreeNode> nodes = new List<jsTreeNode>(); // the API SDK FoldersApi folderApi = new FoldersApi(); folderApi.Configuration.AccessToken = Credentials.TokenInternal; // extract the projectId & folderId from the href string[] idParams = href.Split('/'); string folderId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId); foreach (KeyValuePair<string, dynamic> folderContentItem in new DynamicDictionaryItems(folderContents.data)) { string displayName = folderContentItem.Value.attributes.displayName; jsTreeNode itemNode = new jsTreeNode(folderContentItem.Value.links.self.href, displayName, (string)folderContentItem.Value.type, true); nodes.Add(itemNode); } return nodes; } private async Task<IList<jsTreeNode>> GetItemVersions(string href) { IList<jsTreeNode> nodes = new List<jsTreeNode>(); // the API SDK ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = Credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = href.Split('/'); string itemId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var versions = await itemApi.GetItemVersionsAsync(projectId, itemId); foreach (KeyValuePair<string, dynamic> version in new DynamicDictionaryItems(versions.data)) { DateTime versionDate = version.Value.attributes.lastModifiedTime; string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { urn = "not_available"; } // some BIM 360 versions don't have viewable jsTreeNode node = new jsTreeNode(urn, versionDate.ToString("dd/MM/yy HH:mm:ss"), "versions", false); nodes.Add(node); } return nodes; } public class jsTreeNode { public jsTreeNode(string id, string text, string type, bool children) { this.id = id; this.text = text; this.type = type; this.children = children; } public string id { get; set; } public string text { get; set; } public string type { get; set; } public bool children { get; set; } }
# frozen_string_literal: true require 'aws-sdk-secretsmanager' require 'json' require 'fsecret_loader/version' require 'fsecret_loader/configuration' # FSecretLoader module module FSecretLoader class << self def config yield configuration end def load # require 'pry'; binding.pry return if configuration.secret_id.nil? secrets.each_pair do |key, value| ENV[key.to_s] = value.to_s end end def configuration @configuration ||= Configuration.new end def reset @configuration = nil end private def secrets JSON.parse( configuration .secret_client .get_secret_value(secret_id: configuration.secret_id) .secret_string ) end end end
{-# LANGUAGE OverloadedStrings #-} module Main where import Hedgehog import Test1 ( tests ) main :: IO Bool main = checkParallel tests
package com.fly.kotlin.practice /** * Created by Fj on 2018/6/21. */ class InnerClass { private val bar: Int = 1 //第一种内部类 class Nested { fun foo() = 2 } //第二种内部类 inner class Inner { fun foo() = bar } } fun main(args: Array<String>) { //两种内部类的声明,对应两种调用方式 InnerClass.Nested().foo() InnerClass().Inner().foo() }
using System.Collections.Generic; using System.IO; namespace DigitalFlare.Data.Csv { public interface ICsvDataTableParser { ICsvDataTable Parse(TextReader inputTextReader); IEqualityComparer<string> ColumnNameEqualityComparer { get; } IComparer<string> ColumnNameComparer { get; } } }
<?php namespace App\Support\Filesystem\Storages; use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Support\Str; use SplFileInfo; class PublicStorage extends LocalStorage implements IHasUrlDiskStorage, IPublicPublishableStorage { use HasUrlDiskStorage; public const NAME = 'public'; public function __construct() { parent::__construct('public'); $this->setVisibility(Filesystem::VISIBILITY_PUBLIC); } public function setFile(string|SplFileInfo $file): static { if (is_string($file) && Str::startsWith($file, $rootUrl = $this->getRootUrl() . '/')) { return $this->setRelativeFile(Str::after($file, $rootUrl)); } return parent::setFile($file); } }
<?php // Copyright (C) 2010-2011 Aron Racho <[email protected]> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. if ( file_exists($viewBean->_view_body) ) { require_once($viewBean->_view_body); } ?>
import { sagas as cognitoSagas } from 'modules/cognito-users' export const startSaga = (store, { key, saga }) => { if (!store.runningSagas[key]) { store.runningSagas[key] = store.sagaMiddleware.run(saga) } } /* sync sagas = ones that run from the first page load rather than async */ export const syncSagas = { 'cognito-users': cognitoSagas.main } export const syncSagasStart = (store) => { for (const key of Object.keys(syncSagas)) { startSaga(store, { key, saga: syncSagas[key] }) } }
package com.realworld.springmongo.security import helpers.ImportAppSecurity import helpers.authorizationToken import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Primary import org.springframework.http.HttpStatus import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBody import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController import reactor.core.publisher.Mono @WebFluxTest(controllers = [SecurityTest.TestController::class]) @ImportAppSecurity internal class SecurityTest( @Autowired val client: WebTestClient, @Autowired val signer: JwtSigner, ) { @Test fun `should return 201`() { val status = client.get() .uri("/permitAll") .exchange() .expectBody<String>() .returnResult() .status assertThat(status).isEqualTo(HttpStatus.OK) } @Test fun `should return 401`() { val status = client.get() .uri("/authenticated") .exchange() .expectBody<String>() .returnResult() .status assertThat(status).isEqualTo(HttpStatus.UNAUTHORIZED) } @Test fun `should return user id`() { val userId = "1" val token = signer.generateToken(userId) val result = client.get() .uri("/authenticated") .authorizationToken(token) .exchange() .expectBody(TokenPrincipal::class.java) .returnResult() val status = result.status val body = result.responseBody!! assertThat(status).isEqualTo(HttpStatus.OK) assertThat(body.userId).isEqualTo(userId) assertThat(body.token).isEqualTo(token) } @TestConfiguration class Configuration { @Bean fun testController() = TestController() @Bean @Primary fun testEndpointsConfig() = EndpointsSecurityConfig { http -> http.pathMatchers("/permitAll").permitAll() .pathMatchers("/authenticated").authenticated() } } @RestController class TestController { @GetMapping("/authenticated") fun token(@AuthenticationPrincipal principalMono: Mono<TokenPrincipal>): Mono<TokenPrincipal> { return principalMono } @GetMapping("/permitAll") fun free() { } } }
package main // github.com/EndlessCheng/codeforces-go func minOperations(n int) (ans int) { for i := 1; i < n; i += 2 { ans += n - i } return }
/* * Copyright (c) 2014 Daniel Lo Nigro (Daniel15) * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ using JSPool.Exceptions; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading; namespace JSPool { /// <summary> /// Handles acquiring JavaScript engines from a shared pool. This class is thread-safe. /// </summary> /// <typeparam name="TOriginal">Type of class contained within the pool</typeparam> /// /// <typeparam name="TPooled">Type of <see cref="PooledObject{T}"/> that wraps the <typeparamref name="TOriginal"/></typeparam> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class JsPool<TPooled, TOriginal> : IJsPool<TPooled> where TPooled : PooledObject<TOriginal>, new() { /// <summary> /// Configuration for this engine pool. /// </summary> protected readonly JsPoolConfig<TOriginal> _config; /// <summary> /// Engines that are currently available for use. /// </summary> protected readonly BlockingCollection<TPooled> _availableEngines = new BlockingCollection<TPooled>(); /// <summary> /// Registered engines (ment to be used as a concurrent hash set). /// Engines which are not in the set will get disposed when returned to the pool. /// </summary> protected readonly ConcurrentDictionary<TPooled, byte> _registeredEngines = new ConcurrentDictionary<TPooled, byte>(); /// <summary> /// Factory method used to create engines. /// </summary> protected readonly Func<TOriginal> _engineFactory; /// <summary> /// Handles watching for changes to files, to recycle the engines if any related files change. /// </summary> protected IFileWatcher _fileWatcher; /// <summary> /// Used to cancel threads when disposing the class. /// </summary> protected readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); /// <summary> /// Lock object used when creating a new engine /// </summary> private readonly object _engineCreationLock = new object(); /// <summary> /// Occurs when any watched files have changed (including renames and deletions). /// </summary> public event EventHandler Recycled; /// <summary> /// Creates a new JavaScript engine pool /// </summary> /// <param name="config"> /// The configuration to use. If not provided, a default configuration will be used. /// </param> public JsPool(JsPoolConfig<TOriginal> config) { _config = config; _engineFactory = CreateEngineFactory(); PopulateEngines(); InitializeWatcher(); } /// <summary> /// Gets a factory method used to create engines. /// </summary> protected virtual Func<TOriginal> CreateEngineFactory() { return _config.EngineFactory; } /// <summary> /// Initializes a <see cref="FileWatcher"/> if enabled in the configuration. /// </summary> protected virtual void InitializeWatcher() { if (!string.IsNullOrEmpty(_config.WatchPath)) { _fileWatcher = new FileWatcher { DebounceTimeout = _config.DebounceTimeout, Path = _config.WatchPath, Files = _config.WatchFiles, }; _fileWatcher.Changed += (sender, args) => Recycle(); _fileWatcher.Start(); } } /// <summary> /// Ensures that at least <see cref="JsPoolConfig{T}.StartEngines"/> engines have been created. /// </summary> protected virtual void PopulateEngines() { while (EngineCount < _config.StartEngines) { var engine = CreateEngine(); _availableEngines.Add(engine); } } /// <summary> /// Creates a new JavaScript engine and adds it to the list of all available engines. /// </summary> protected virtual TPooled CreateEngine() { var engine = new TPooled { InnerEngine = _engineFactory(), }; engine.ReturnEngineToPool = () => ReturnEngineToPoolInternal(engine); _config.Initializer(engine.InnerEngine); _registeredEngines.TryAdd(engine, 0); return engine; } /// <summary> /// Gets an engine from the pool. This engine should be disposed when you are finished with it - /// disposing the engine returns it to the pool. /// If an engine is free, this method returns immediately with the engine. /// If no engines are available but we have not reached <see cref="JsPoolConfig{T}.MaxEngines"/> /// yet, creates a new engine. If MaxEngines has been reached, blocks until an engine is /// avaiable again. /// </summary> /// <param name="timeout"> /// Maximum time to wait for a free engine. If not specified, defaults to the timeout /// specified in the configuration. /// </param> /// <returns>A JavaScript engine</returns> /// <exception cref="JsPoolExhaustedException"> /// Thrown if no engines are available in the pool within the provided timeout period. /// </exception> public virtual TPooled GetEngine(TimeSpan? timeout = null) { TPooled engine; // First see if a pooled engine is immediately available if (_availableEngines.TryTake(out engine)) { return TakeEngine(engine); } // If we're not at the limit, a new engine can be added immediately if (EngineCount < _config.MaxEngines) { lock (_engineCreationLock) { if (EngineCount < _config.MaxEngines) { return TakeEngine(CreateEngine()); } } } // At the limit, so block until one is available if (!_availableEngines.TryTake(out engine, timeout ?? _config.GetEngineTimeout)) { throw new JsPoolExhaustedException(string.Format( "Could not acquire JavaScript engine within {0}", _config.GetEngineTimeout )); } return TakeEngine(engine); } /// <summary> /// Increases the engine's usage count /// </summary> /// <param name="engine"></param> protected virtual TPooled TakeEngine(TPooled engine) { engine.IncreaseUsageCount(); return engine; } /// <summary> /// Returns an engine to the pool so it can be reused /// </summary> /// <param name="engine">Engine to return</param> [Obsolete("Disposing the engine will now return it to the pool. Prefer disposing the engine to explicitly calling ReturnEngineToPool.")] public virtual void ReturnEngineToPool(TPooled engine) { ReturnEngineToPoolInternal(engine); } /// <summary> /// Returns an engine to the pool so it can be reused /// </summary> /// <param name="engine">Engine to return</param> protected virtual void ReturnEngineToPoolInternal(TPooled engine) { if (!_registeredEngines.ContainsKey(engine)) { // This engine was from another pool. This could happen if a pool is recycled // and replaced with a different one (like what ReactJS.NET does when any // loaded files change). Let's just pretend we never saw it. if (engine.InnerEngine is IDisposable) { ((IDisposable)engine.InnerEngine).Dispose(); } return; } if (_config.MaxUsagesPerEngine > 0 && engine.UsageCount >= _config.MaxUsagesPerEngine) { // Engine has been reused the maximum number of times, recycle it. DisposeEngine(engine); return; } if ( _config.GarbageCollectionInterval > 0 && engine.UsageCount % _config.GarbageCollectionInterval == 0 ) { CollectGarbage(engine.InnerEngine); } _availableEngines.Add(engine); } /// <summary> /// Disposes the specified engine. /// </summary> /// <param name="engine">Engine to dispose</param> /// <param name="repopulateEngines"> /// If <c>true</c>, a new engine will be created to replace the disposed engine /// </param> public virtual void DisposeEngine(TPooled engine, bool repopulateEngines = true) { if (engine.InnerEngine is IDisposable) { ((IDisposable)engine.InnerEngine).Dispose(); } _registeredEngines.TryRemove(engine, out _); if (repopulateEngines) { // Ensure we still have at least the minimum number of engines. PopulateEngines(); } } /// <summary> /// Disposes all engines in this pool. Note that this will only dispose the engines that /// are *currently* available. Engines that are in use will be disposed when the user /// attempts to return them. /// </summary> protected virtual void DisposeAllEngines() { TPooled engine; while (_availableEngines.TryTake(out engine)) { DisposeEngine(engine, repopulateEngines: false); } // Also clear registered engines, so that engines which are currently in use will // get disposed on return. _registeredEngines.Clear(); } /// <summary> /// Disposes all engines in this pool, and creates new engines in their place. /// </summary> public virtual void Recycle() { Recycled?.Invoke(this, null); DisposeAllEngines(); PopulateEngines(); } /// <summary> /// Disposes all the JavaScript engines in this pool. /// </summary> public virtual void Dispose() { DisposeAllEngines(); _cancellationTokenSource.Cancel(); _fileWatcher?.Dispose(); } /// <summary> /// Runs garbage collection for the specified engine /// </summary> /// <param name="engine"></param> protected virtual void CollectGarbage(TOriginal engine) { // No-op by default } #region Statistics and debugging /// <summary> /// Gets the total number of engines in this engine pool, including engines that are /// currently busy. /// </summary> public virtual int EngineCount => _registeredEngines.Count; /// <summary> /// Gets the number of currently available engines in this engine pool. /// </summary> public virtual int AvailableEngineCount => _availableEngines.Count; /// <summary> /// Gets a string for displaying this engine pool in the Visual Studio debugger. /// </summary> private string DebuggerDisplay => $"Engines = {EngineCount}, Available = {AvailableEngineCount}, Max = {_config.MaxEngines}"; #endregion } }
import kotlin.test.assertEquals enum class Season { WINTER SPRING SUMMER AUTUMN } fun foo(x : Any) : String { return when (x) { Season.WINTER -> "winter" Season.SPRING -> "spring" Season.SUMMER -> "summer" else -> "other" } } fun box() : String { assertEquals("winter", foo(Season.WINTER)) assertEquals("spring", foo(Season.SPRING)) assertEquals("summer", foo(Season.SUMMER)) assertEquals("other", foo(Season.AUTUMN)) assertEquals("other", foo(123)) return "OK" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.any23.vocab; import org.eclipse.rdf4j.model.IRI; import java.util.HashMap; import java.util.Map; /** * Vocabulary class for <a href="http://gmpg.org/xfn/11">XFN</a>, as per * <a href="http://vocab.sindice.com/xfn/guide.html">Expressing XFN in RDF</a>. * * @author Richard Cyganiak ([email protected]) */ public class XFN extends Vocabulary { public static final String NS = "http://vocab.sindice.com/xfn#"; private static XFN instance; public static XFN getInstance() { if(instance == null) { instance = new XFN(); } return instance; } public final IRI contact = createProperty("contact"); public final IRI acquaintance = createProperty("acquaintance"); public final IRI friend = createProperty("friend"); public final IRI met = createProperty("met"); public final IRI coWorker = createProperty("co-worker"); public final IRI colleague = createProperty("colleague"); public final IRI coResident = createProperty("co-resident"); public final IRI neighbor = createProperty("neighbor"); public final IRI child = createProperty("child"); public final IRI parent = createProperty("parent"); public final IRI spouse = createProperty("spouse"); public final IRI kin = createProperty("kin"); public final IRI muse = createProperty("muse"); public final IRI crush = createProperty("crush"); public final IRI date = createProperty("date"); public final IRI sweetheart = createProperty("sweetheart"); public final IRI me = createProperty("me"); public final IRI mePage = createProperty(NS, "mePage"); private Map<String, IRI> PeopleXFNProperties; private Map<String, IRI> HyperlinkXFNProperties; public IRI getPropertyByLocalName(String localName) { return PeopleXFNProperties.get(localName); } public IRI getExtendedProperty(String localName) { return HyperlinkXFNProperties.get(localName); } public boolean isXFNLocalName(String localName) { return PeopleXFNProperties.containsKey(localName); } public boolean isExtendedXFNLocalName(String localName) { return PeopleXFNProperties.containsKey(localName); } private IRI createProperty(String localName) { if(HyperlinkXFNProperties == null) { HyperlinkXFNProperties = new HashMap<String, IRI>(); } if(PeopleXFNProperties == null) { PeopleXFNProperties = new HashMap<String, IRI>(); } IRI result = createProperty(NS, localName + "-hyperlink"); HyperlinkXFNProperties.put(localName, result); result = createProperty(NS, localName); PeopleXFNProperties.put(localName, result); return result; } private XFN(){ super(NS); } }
-- show engines SHOW ENGINES; /* Default Storage Engine is InnoDB Others Engines are: MyISAM, MEMORY, CSV, BLACKHOLE, ARCHIVE, MERGE_MYISAM, performance, FEDERATED */ CREATE TABLE IF NOT EXISTS test( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) )ENGINE = InnoDB; -- check engine information of a schema SELECT table_name, engine FROM information_schema.tables WHERE table_schema='movies';
package amf.core.vocabulary object ValueType { def apply(ns: Namespace, name: String) = new ValueType(ns, name) def apply(iri: String): ValueType = if (iri.contains("#")) { val pair = iri.split("#") val name = pair.last val ns = pair.head + "#" new ValueType(Namespace(ns), name) } else if (iri.replace("://", "_").contains("/")) { val name = iri.split("/").last val ns = iri.replace(name, "") new ValueType(Namespace(ns), name) } else { new ValueType(Namespace(iri), "") } } /** Value type. */ case class ValueType(ns: Namespace, name: String) { def iri(): String = ns.base + name }
pub mod driver; pub mod script; pub mod script_system; // pub use crate::driver; pub mod prelude{ pub use crate::script; pub use crate::driver; pub use crate::script_system; }
//Figura 6.9: JogoDeDados.java --> tradução em ingles Craps.java //A classe Craps simula o jogo de dados craps. import java.util.Random; public class JogoDeDados { //cria gerador de números aleatorios para uso no metodo rolagem de dados private static final Random numerosAleatorios = new Random(); //enumeração com constantes que representam o status do jogo private enum Status {CONTINUE, WON, LOST}; //constantes que representam lançamentos comuns dos dados private static final int SNAKE_EYES = 2; private static final int TREY = 3; private static final int SEVEN = 7; private static final int YO_LEVEN = 11; private static final int BOX_CARS = 12; //jogar um partida de JogoDeDados public void jogar() { int meuPonto = 0; //pontos se não ganhar ou perder na 1a. rolagem Status gameStatus; //pode conter CONTINUE, WON ou LOST int somaDosDados = rolagemDados(); //primeira rolagem de dados //determina o status do jogo e a pontuação com base no primeiro lançamento switch(somaDosDados) { case SEVEN: //ganha com 7 no primeiro lançamento case YO_LEVEN: //ganha com 11 no primeiro lançamento gameStatus = Status.WON; break; case SNAKE_EYES: //perde com 2 no primeiro lançamento case TREY: //perde com 3 no primeiro lançamento case BOX_CARS: //perde com 12 no primeiro lançamento gameStatus = Status.LOST; break; default: //não ganhou nem perdeu, então registra a pontuação gameStatus = Status.CONTINUE; //jogo não terminou meuPonto = somaDosDados; //informa a pontuação System.out.printf("Ponto é %d\n", meuPonto); break; //opcional no final do switch }//fim do switch //enquanto o jogo não estiver completo while(gameStatus == Status.CONTINUE) //nem WON nem LOST { somaDosDados = rolagemDados(); //lança os dados novamente //determina o status do jogo if(somaDosDados == meuPonto) //vitoria por pontuação gameStatus = Status.WON; else if(somaDosDados == SEVEN) //perde obtendo 7 antes de atingir a pontuação gameStatus = Status.LOST; }//fim do while //exibe uma mensagem ganhou ou perdeu if(gameStatus == Status.WON) System.out.println("Jogador ganhou"); else System.out.println("Jogador perdeu"); }//fim do método jogar //lança os dados, calcula a soma e exibe os resultados public int rolagemDados() { //seleciona valores aleatórios do dados int o_dado1 = 1 + numerosAleatorios.nextInt(6); //Primeiro lançamento do dado int o_dado2 = 1 + numerosAleatorios.nextInt(6); //Segundo lançamento do dado int soma = o_dado1 + o_dado2; //soma dos valores dos dados //exibe os resultados desse lançamento System.out.printf("Jogador rolou %d + %d = %d\n", o_dado1, o_dado2, soma); return soma; //retorna a soma dos dados }//fim do método rolagemDados }//fim da classe JogoDeDados
--- title: AEM Dynamic Media Classic IPS APIs description: Introduction to Dynamic Media Classic IPS APIs. version: Cloud Service role: Developer level: Intermediate feature: Dynamic Media Classic, APIs topic: Development index: y exl-id: ef4fd51c-975a-400c-8427-555b77897a09 --- # AEM Dynamic Media Classic IPS APIs This video walks through the Dynamic Media classic IPS APIs. >[!VIDEO](https://video.tv.adobe.com/v/335453?quality=9&learn=on)
package db import ( "errors" "fmt" "os" "strconv" "strings" ) func createDirIfNotExist(dir string) error { if _, err := os.Stat(dir); err == nil { return nil } err := os.Mkdir(dir, 0755) return err } func mergeToExisting(array []interface{}, entity interface{}) ([]interface{}, error) { array = append(array, entity) return array, nil } // getNestedValue fetch nested value from node func getNestedValue(input interface{}, node string) (interface{}, error) { pp := strings.Split(node, ".") for _, n := range pp { if isIndex(n) { // find slice/array if arr, ok := input.([]interface{}); ok { indx, err := getIndex(n) if err != nil { return input, err } arrLen := len(arr) if arrLen == 0 || indx > arrLen-1 { return empty, errors.New("empty array") } input = arr[indx] } } else { // find in map validNode := false if mp, ok := input.(map[string]interface{}); ok { input, ok = mp[n] validNode = ok } // find in group data if mp, ok := input.(map[string][]interface{}); ok { input, ok = mp[n] validNode = ok } if !validNode { return empty, fmt.Errorf("invalid node name %s", n) } } } return input, nil } func getIndex(in string) (int, error) { if !isIndex(in) { return -1, fmt.Errorf("invalid index") } is := strings.TrimLeft(in, "[") is = strings.TrimRight(is, "]") oint, err := strconv.Atoi(is) if err != nil { return -1, err } return oint, nil } func isIndex(in string) bool { return strings.HasPrefix(in, "[") && strings.HasSuffix(in, "]") } // toFloat64 converts interface{} value to float64 if value is numeric else return false func toFloat64(v interface{}) (float64, bool) { var f float64 flag := true // as Go convert the json Numeric value to float64 switch u := v.(type) { case int: f = float64(u) case int8: f = float64(u) case int16: f = float64(u) case int32: f = float64(u) case int64: f = float64(u) case float32: f = float64(u) case float64: f = u default: flag = false } return f, flag } // length return length of strings/array/map func length(v interface{}) (int, error) { if val, ok := v.(string); ok { return len(val), nil } else if val, ok := v.([]interface{}); ok { return len(val), nil } else if val, ok := v.(map[string]interface{}); ok { return len(val), nil } return -1, errors.New("invalid type for length") }
module.exports = { siteName: 'Lightwave', locale: 'en', images: { lazyload: true, }, };
# Launch a new Debian VM with this startup script # # First, update the pack list apt update # # We will need git to fetch the codelab sources apt install -y git # # claat will convert markdown source to web pages wget https://github.com/googlecodelabs/tools/releases/download/v2.1.2/claat-linux-amd64 chmod +x claat-linux-amd64 export PATH=$PATH:`pwd` # # Deploy with firebase CLI, which requires npm to install curl -sL https://deb.nodesource.com/setup_12.x | bash - apt install -y nodejs # # Install the firebase CLI npm install -g firebase-tools # # Run the script to get source, build site, and deploy # (here)
# -*- coding: utf-8 -*- # import copy class LineBase(object): _ID = 0 dimension = 1 def __init__(self, id0=None): if id0: self.id = id0 else: self.id = 'l{}'.format(LineBase._ID) LineBase._ID += 1 return def __neg__(self): neg_self = copy.deepcopy(self) neg_self.id = '-' + neg_self.id return neg_self
package com.dowhile.android.dorahasin; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import io.flic.lib.FlicManager; public class MainApplication extends Application { private static Context context; @Override public void onCreate() { super.onCreate(); MainApplication.context = getApplicationContext(); FlicManager.setAppCredentials("doRahasin", "879cfb06-454f-44bb-bc67-49cf4d513c97", "doRahasin"); //FlicManager.setAppCredentials("[doRahasin]", "[879cfb06-454f-44bb-bc67-49cf4d513c97]", "[doRahasin]"); } public static SharedPreferences getPreferenceManager() { return PreferenceManager.getDefaultSharedPreferences(MainApplication.context); } public static Context getAppContext() { return MainApplication.context; } }
using System; namespace Common.Messages { public class WorkerStatusMessage { public string Message { get; set; } public string Source { get; set; } public string TaskId { get; set; } public DateTime TimeStamp { get; set; } = DateTime.UtcNow; public long Ticks { get; set; } = DateTime.UtcNow.Ticks; public Type PayLoadType { get; set; } public object PayLoad { get; set; } public WorkerStatusMessage() { } } }
package exporter import ( "log" "net" "github.com/oschwald/geoip2-golang" ) var ( dbPath string database = &GeoIPDatabase{} internalSubnets = []string{ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", } ) type GeoIPDatabase struct { db *geoip2.Reader fileHandler string } func SetGeoIPPath(path string) { dbPath = path } func openIPDatabase() (*GeoIPDatabase, error) { if database.db != nil { return database, nil } var err error database.db, err = geoip2.Open(dbPath) database.fileHandler = "open" return database, err } func (db *GeoIPDatabase) Close() { if db.fileHandler == "open" { db.db.Close() db.fileHandler = "closed" } } func GetIpLocationDetails(ipAddress string) (city *geoip2.City, err error) { db, err := openIPDatabase() if err != nil { log.Fatal(err) } ip := net.ParseIP(ipAddress) city, err = db.db.City(ip) if err != nil { return city, err } return city, nil } func isInternalIP(ip string) bool { for _, subnet := range internalSubnets { _, ipNet, _ := net.ParseCIDR(subnet) if ipNet.Contains(net.ParseIP(ip)) { return true } } return false }
package com.design.patterns.structural.facade.solution; public class Client1 { public static void main(String[] args) { VideoConversionFacade facade = new VideoConversionFacade(); facade.convertVideo("youtubevideo.mp4", "mp4"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fonlow.SyncML.OpenContacts { /// <summary> /// This class is for binding without using configuration and reflection, as program's configuration cares /// only DataSource, not Provider. /// </summary> public class OpenContactsDataSource : OCLocalDataSource { public OpenContactsDataSource(string exchangeType):base(new OCPlatformProvider(), exchangeType) { } } }
import {PrivilegesConstants} from "../constants/actions-types" export default (state={}, action) => { switch (action.type) { case PrivilegesConstants.GET_PRIVILEGES: return { ...state, privileges: action.privileges } case PrivilegesConstants.CLEAR_PRIVILEGES: const { privileges, ...stateWithoutRoles } = state return { ...stateWithoutRoles } case PrivilegesConstants.GET_PRIVILEGE: return { ...state, role: action.privilege } case PrivilegesConstants.CLEAR_PRIVILEGE: const { privilege, ...stateWithoutRole } = state return { ...stateWithoutRole } case PrivilegesConstants.PRIVILEGE_LOADING: return { ...state, loading: true } case PrivilegesConstants.PRIVILEGE_LOADING_FINISH: return { ...state, loading: false } case PrivilegesConstants.PRIVILEGE_NOTIFICATION: return { ...state, notification: action.notification } default: return state } }
-- the insert Statement --1 always desc the table before making any insert to know the columns and the constraints DESC DEPARTMENTS; --2 try to have a look on table constraints --go to tables from the tree on the left, select the table, and then see the constraints --note: the constraint will be discussed in details later --3 --list the columns in same table order, then put Related values ( this is the Recommendation ) INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID) VALUES (71,'Development 1',100,1700); commit; -- use the commit command to save the changes --you can make insert without puting the columns names, but the order in values should be same order of table --this way of insert you need to put values for all the tables INSERT INTO DEPARTMENTS VALUES (72,'Development 2',100,1700); COMMIT; --you can change the order as you like when put the columns names, but you should mapp the values same INSERT INTO DEPARTMENTS (DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID,DEPARTMENT_ID) VALUES ('Development 3',100,1700,73); COMMIT; --4 inserting rows with null values --the Implicit method: dont put the column in the list, make sure the column can have null value --the oracle server automatically make the value null --so the MANAGER_ID,LOCATION_ID will be null in below insert INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME) VALUES (74,'Development 4'); --the explicit method, done by the user by soecify the NULL keyword INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID ) VALUES (75,'Development 5',null,null); --5 inserting special values like sysdate, or some other functions INSERT INTO EMPLOYEES (EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,HIRE_DATE ,JOB_ID) VALUES (1,'khaled','khudari','[email protected]',SYSDATE,'IT_PROG' ); INSERT INTO EMPLOYEES (EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,HIRE_DATE ,JOB_ID) VALUES (2,'Samer','ali','[email protected]',to_date('20-07-2015','dd-mm-yyyy'),'IT_PROG' ); --6 using the & with insert INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME) VALUES (&dpet_id,'&dname'); --7 you can make insert with subquery --lets create table xx_emp CREATE TABLE XX_EMP (EMPNO NUMBER, FNAME VARCHAR2(100), SALARY NUMBER ); SELECT * FROM XX_EMP; --so you insert into XX_EMP using select INSERT INTO XX_EMP(EMPNO,FNAME,SALARY) SELECT EMPLOYEE_ID,FIRST_NAME,SALARY FROM EMPLOYEES; SELECT * from XX_EMP; -------------------------------------------------------------------------------------------------------------- --now lets see some errors in inserting --1 inserting existing value, and this value is PK --DEPARTMENT_ID=10 INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID) VALUES (10,'Development 1',100,1700); --2 inserting FK value not exists in the reference table --LOCATION_ID=1 INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID) VALUES (5,'Development 1',100,1); --3 inserting missmatch data type --LOCATION_ID='D1' INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID) VALUES (5,'Development 1',100,'D1'); --4 inserting value too long --DEPARTMENT_NAME=' The development and research department' INSERT INTO DEPARTMENTS (DEPARTMENT_ID,DEPARTMENT_NAME,MANAGER_ID,LOCATION_ID) VALUES (5,'The development and research department',100,1700);
<?php namespace Application\Controller; class EnviadosController extends CrudController { public function __construct() { parent::__construct('enviado'); $this->setFormWithEntityManager(TRUE); } public function indexAction($filtro = [], array $orderBy = [], \Doctrine\ORM\QueryBuilder $list = null) { return parent::indexAction([],['dateEnviado' => 'DESC']); } }
--- layout: rsk title: RIF Marketplace Testnet tags: rif, marketplace, testnet --- You can access the Marketplace on the RSK Testnet: [marketplace.testnet.rifos.org](https://marketplace.testnet.rifos.org/) ## Wallet Setup 1. Download a browser wallet. Recommended: [Nifty Wallet](https://chrome.google.com/webstore/detail/nifty-wallet/jbdaocneiiinmjbjlgalhcelgbejmnid) 2. Connect your wallet to RSK Testnet. You can do it with the top left selector on Nifty Wallet. 3. (optional) List tRIF token balance using this address: [`0x19F64674D8A5B4E652319F5e239eFd3bc969A1fE`](https://explorer.testnet.rsk.co/address/0x19F64674D8A5B4E652319F5e239eFd3bc969A1fE). In Nifty wallet do this in Tokens tab. 4. Browse to [RSK faucet](https://faucet.testnet.rsk.co) to get some gas. 5. Browse the [tRIF faucet](https://faucet.rifos.org) to get some test RIF tokens. 6. Browse the [RIF Marketplace - Testnet](https://marketplace.testnet.rifos.org) to access the available services. ## Smart contracts ### Name Services - NFTS Placements NFTS Proxy: [`0xfa5aDE767A422c66cAFD94c3710F5B92467fb85E`](https://explorer.testnet.rsk.co/address/0xfa5ade767a422c66cafd94c3710f5b92467fb85e) NFTS ProxyAdmin: [`0xE660A209c733ba0C1331E9997cb31309e7c28A52`](https://explorer.testnet.rsk.co/address/0xe660a209c733ba0c1331e9997cb31309e7c28a52) NFTS Implementation: [`0xcEd09738227b611b4681a1Aa05CDb0D72ebFbEA5`](https://explorer.testnet.rsk.co/address/0xced09738227b611b4681a1aa05cdb0d72ebfbea5) ### Storage Services - Manager Storage Proxy: [`0x839856c0ec1aa2AED25d47Fd3DDb7a14DAC3e76d`](https://explorer.testnet.rsk.co/address/0x839856c0ec1aa2aed25d47fd3ddb7a14dac3e76d) Storage ProxyAdmin: [`0xB0Ec8d94d53b336Eca5b7280a52Ce3D241C98e11`](https://explorer.testnet.rsk.co/address/0xb0ec8d94d53b336eca5b7280a52ce3d241c98e11) Storage Implementation: [`0xFAd0FDd942a5330594E7BBA270460EF8fA8579eC`](https://explorer.testnet.rsk.co/address/0xfad0fdd942a5330594e7bba270460ef8fa8579ec) ### Staking (Storage) Staking: [`0x11Be792f8fcfc84897b88E149dD3Fb66B422256f`](https://explorer.testnet.rsk.co/address/0x11be792f8fcfc84897b88e149dd3fb66b422256f) ## RNS Manager (to register and manage RNS Domains) [testnet.manager.rns.rifos.org](https://testnet.manager.rns.rifos.org/)
namespace MassEffect.GameObjects.Projectiles { using Interfaces; public class Laser : Projectile { public Laser(int damage) : base(damage) { } public override void Hit(IStarship ship) { var remainder = this.Damage - ship.Shields; ship.Shields -= this.Damage; if (remainder > 0) { ship.Health -= remainder; } } } }
import logging from webexteamssdk.models.cards import Colors, TextBlock, FontWeight, FontSize, Column, AdaptiveCard, ColumnSet, \ ImageSize, Image, Fact from webexteamssdk.models.cards.actions import Submit from webex_bot.models.command import Command, COMMAND_KEYWORD_KEY from webex_bot.models.response import response_from_adaptive_card log = logging.getLogger(__name__) HELP_COMMAND_KEYWORD = "help" class HelpCommand(Command): def __init__(self, bot_name, bot_help_subtitle, bot_help_image): self.commands = None super().__init__( command_keyword=HELP_COMMAND_KEYWORD, help_message="Get Help", card=None) self.card_callback = self.build_card self.card_populated = False self.bot_name = bot_name self.bot_help_subtitle = bot_help_subtitle self.bot_help_image = bot_help_image def execute(self, message, attachment_actions, activity): pass def build_card(self, message, attachment_actions, activity): """ Construct a help message for users. :param message: message with command already stripped :param attachment_actions: attachment_actions object :param activity: activity object :return: """ heading = TextBlock(self.bot_name, weight=FontWeight.BOLDER, wrap=True, size=FontSize.LARGE) subtitle = TextBlock(self.bot_help_subtitle, wrap=True, size=FontSize.SMALL, color=Colors.LIGHT) image = Image( url=self.bot_help_image, size=ImageSize.SMALL) header_column = Column(items=[heading, subtitle], width=2) header_image_column = Column( items=[image], width=1, ) actions, hint_texts = self.build_actions_and_hints() card = AdaptiveCard( body=[ColumnSet(columns=[header_column, header_image_column]), # ColumnSet(columns=[Column(items=[subtitle])]), # FactSet(facts=hint_texts), ], actions=actions) return response_from_adaptive_card(adaptive_card=card) def build_actions_and_hints(self): # help_card = HELP_CARD_CONTENT help_actions = [] hint_texts = [] if self.commands is not None: # Sort list by keyword sorted_commands_list = sorted(self.commands, key=lambda command: ( command.command_keyword is not None, command.command_keyword)) for command in sorted_commands_list: if command.help_message and command.command_keyword != HELP_COMMAND_KEYWORD: action = Submit( title=f"{command.help_message}", data={COMMAND_KEYWORD_KEY: command.command_keyword} ) help_actions.append(action) hint = Fact(title=command.command_keyword, value=command.help_message) hint_texts.append(hint) return help_actions, hint_texts
import React, { useEffect } from "react"; import * as THREE from "three"; import "./ballModel.css"; import * as dat from "dat.gui"; let scene, camera, renderer, sphere; function BallModell() { useEffect(() => { document.querySelector("section.ballModel").appendChild(init()); animate(); }); function init() { //creating scene scene = new THREE.Scene(); // Loading const textureLoader = new THREE.TextureLoader(); const normalTexture = textureLoader.load("assets/textures/normalMap.jpg"); // Debug const gui = new dat.GUI(); const sizes = { width: window.innerWidth, height: window.innerHeight, }; window.addEventListener("resize", () => { // Update sizes sizes.width = window.innerWidth; sizes.height = window.innerHeight; // Update camera camera.aspect = sizes.width / sizes.height; camera.updateProjectionMatrix(); // Update renderer renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); }); //add camera camera = new THREE.PerspectiveCamera( 75, sizes.width / sizes.height, 0.1, 100 ); camera.position.x = 0; camera.position.y = 3; camera.position.z = 2; //renderer renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); //add geometry let sphereGeometry = new THREE.SphereBufferGeometry(0.5, 64, 64); let material = new THREE.MeshStandardMaterial(); material.metalness = 0.7; material.roughness = 0.2; material.normalMap = normalTexture; material.color = new THREE.Color(0x292929); material.color = new THREE.Color(0xff0000); sphere = new THREE.Mesh(sphereGeometry, material); scene.add(sphere); // Lights and GUI folders const redLightFolder = gui.addFolder("Red Light"); const blueLightFolder = gui.addFolder("Blue Light"); // standar poinlight const pointLight = new THREE.PointLight(0xffffff, 0.1); pointLight.position.x = 2; pointLight.position.y = 3; pointLight.position.z = 4; scene.add(pointLight); // red point light const redPointLight = new THREE.PointLight(0x377ba0, 2); redPointLight.position.set(10, 0, 0); redPointLight.intensity = 3; scene.add(redPointLight); redLightFolder.add(redPointLight.position, "y").min(-10).max(10).step(1); redLightFolder.add(redPointLight.position, "x").min(-10).max(10).step(1); redLightFolder.add(redPointLight.position, "z").min(-10).max(10).step(1); redLightFolder.add(redPointLight, "intensity").min(0).max(10).step(0.1); // blue point light const blueLightColor = { color: 0xffff, }; const bluePointLight = new THREE.PointLight(blueLightColor.color, 2); bluePointLight.position.set(-10, -5, -4); bluePointLight.intensity = 10; scene.add(bluePointLight); blueLightFolder.add(bluePointLight.position, "y").min(-10).max(10).step(1); blueLightFolder.add(bluePointLight.position, "x").min(-10).max(10).step(1); blueLightFolder.add(bluePointLight.position, "z").min(-10).max(10).step(1); blueLightFolder.add(bluePointLight, "intensity").min(0).max(10).step(0.1); // to add a set color on the GUI blueLightFolder.addColor(blueLightColor, "color").onChange(() => { bluePointLight.color.set(blueLightColor.color); }); return renderer.domElement; } const clock = new THREE.Clock(); // this is for make the geometry response on mouseMove on the screen document.addEventListener("mousemove", onDocumentMouseMove); let mouseX = 0; let mouseY = 0; let targetX = 0; let targetY = 0; const windowHalfX = window.innerHeight / 2; const windowHalfY = window.innerHeight / 2; function onDocumentMouseMove(event) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } // This is for responsive Scroll animations const updateSphere = (event) => { sphere.position.y = window.scrollY * 0.002; }; window.addEventListener("scroll", updateSphere); //animation function animate() { requestAnimationFrame(animate); const elapsedTime = clock.getElapsedTime(); targetX = mouseX * 0.001; targetY = mouseY * 0.001; // Update objects sphere.rotation.y = 0.5 * elapsedTime; sphere.rotation.y += 0.5 * (targetX - sphere.rotation.y); sphere.rotation.x += 0.5 * (targetY - sphere.rotation.x); sphere.position.z += -0.5 * (targetY - sphere.rotation.x); renderer.render(scene, camera); } return <section className="ballModel"></section>; } export default BallModell;
/** * Copyright 2017, 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. */ 'use strict'; function setupImplicit() { // [START error_reporting_setup_implicit] // Imports the Google Cloud client library const ErrorReporting = require('@google-cloud/error-reporting') .ErrorReporting; // On Node 6+ the following syntax can be used instead: // const {ErrorReporting} = require('@google-cloud/error-reporting'); // With ES6 style imports via TypeScript or Babel, the following // syntax can be used instead: // import {ErrorReporting} from '@google-cloud/error-reporting'; // Instantiates a client const errors = new ErrorReporting(); // Reports a simple error errors.report('Something broke!'); // [END error_reporting_setup_implicit] } function setupExplicit() { // [START error_reporting_setup_explicit] // Imports the Google Cloud client library const ErrorReporting = require('@google-cloud/error-reporting') .ErrorReporting; // On Node 6+ the following syntax can be used instead: // const {ErrorReporting} = require('@google-cloud/error-reporting'); // With ES6 style imports via TypeScript or Babel, the following // syntax can be used instead: // import {ErrorReporting} from '@google-cloud/error-reporting'; // Instantiates a client const errors = new ErrorReporting({ projectId: 'your-project-id', keyFilename: '/path/to/key.json', }); // Reports a simple error errors.report('Something broke!'); // [END error_reporting_setup_explicit] } function manual() { // [START error_reporting_manual] // Imports the Google Cloud client library const ErrorReporting = require('@google-cloud/error-reporting') .ErrorReporting; // On Node 6+ the following syntax can be used instead: // const {ErrorReporting} = require('@google-cloud/error-reporting'); // With ES6 style imports via TypeScript or Babel, the following // syntax can be used instead: // import {ErrorReporting} from '@google-cloud/error-reporting'; // Instantiates a client const errors = new ErrorReporting(); // Use the error message builder to customize all fields ... const errorEvent = errors.event(); // Add error information errorEvent.setMessage('My error message'); errorEvent.setUser('root@nexus'); // Report the error event errors.report(errorEvent, () => { console.log('Done reporting error event!'); }); // Report an Error object errors.report(new Error('My error message'), () => { console.log('Done reporting Error object!'); }); // Report an error by provided just a string errors.report('My error message', () => { console.log('Done reporting error string!'); }); // [END error_reporting_manual] } function express() { // [START error_reporting_express] const express = require('express'); // Imports the Google Cloud client library const ErrorReporting = require('@google-cloud/error-reporting') .ErrorReporting; // On Node 6+ the following syntax can be used instead: // const {ErrorReporting} = require('@google-cloud/error-reporting'); // With ES6 style imports via TypeScript or Babel, the following // syntax can be used instead: // import {ErrorReporting} from '@google-cloud/error-reporting'; // Instantiates a client const errors = new ErrorReporting(); const app = express(); app.get('/error', (req, res, next) => { res.send('Something broke!'); next(new Error('Custom error message')); }); app.get('/exception', () => { JSON.parse('{"malformedJson": true'); }); // Note that express error handling middleware should be attached after all // the other routes and use() calls. See the Express.js docs. app.use(errors.express); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); console.log('Press Ctrl+C to quit.'); }); // [END error_reporting_express] } // The command-line program const cli = require(`yargs`) .demand(1) .command( 'setup-implicit', 'Reports a simple error using implicit credentials.', {}, setupImplicit ) .command( 'setup-explicit', 'Reports a simple error using explicit credentials.', {}, setupExplicit ) .command('manual', 'Manually reports errors.', {}, manual) .command( 'express', 'Starts and Express service with integrated error reporting.', {}, express ) .example( 'node $0 setup-implicit', 'Reports a simple error using implicit credentials.' ) .example( 'node $0 setup-explicit', 'Reports a simple error using explicit credentials.' ) .example('node $0 manual', 'Manually report some errors.') .example( 'node $0 express', 'Starts and Express service with integrated error reporting.' ) .wrap(120) .recommendCommands() .epilogue( `For more information, see https://cloud.google.com/error-reporting/docs` ) .help() .strict(); if (module === require.main) { cli.parse(process.argv.slice(2)); }
use uptown_funk::{Executor, HostFunctions}; use crate::api::channel::ChannelReceiver; use crate::module::LunaticModule; use crate::api::{channel, networking, process, wasi}; pub struct DefaultApi { context_receiver: Option<ChannelReceiver>, module: LunaticModule, } impl DefaultApi { pub fn new(context_receiver: Option<ChannelReceiver>, module: LunaticModule) -> Self { Self { context_receiver, module, } } } impl HostFunctions for DefaultApi { type Return = (); #[cfg(feature = "vm-wasmtime")] fn add_to_linker<E>(self, executor: E, linker: &mut wasmtime::Linker) where E: Executor + Clone + 'static, { let channel_state = channel::api::ChannelState::new(self.context_receiver); let process_state = process::api::ProcessState::new(self.module, channel_state.clone()); let networking_state = networking::TcpState::new(channel_state.clone()); let wasi_state = wasi::api::WasiState::new(); channel_state.add_to_linker(executor.clone(), linker); process_state.add_to_linker(executor.clone(), linker); networking_state.add_to_linker(executor.clone(), linker); wasi_state.add_to_linker(executor, linker); } #[cfg(feature = "vm-wasmer")] fn add_to_wasmer_linker<E>( self, executor: E, linker: &mut uptown_funk::wasmer::WasmerLinker, store: &wasmer::Store, ) -> () where E: Executor + Clone + 'static, { let channel_state = channel::api::ChannelState::new(self.context_receiver); let process_state = process::api::ProcessState::new(self.module, channel_state.clone()); let networking_state = networking::TcpState::new(channel_state.clone()); let wasi_state = wasi::api::WasiState::new(); channel_state.add_to_wasmer_linker(executor.clone(), linker, store); process_state.add_to_wasmer_linker(executor.clone(), linker, store); networking_state.add_to_wasmer_linker(executor.clone(), linker, store); wasi_state.add_to_wasmer_linker(executor, linker, store); } }
<?php // Veritabanı bilgileri Laravel .env dosyasından çekilmektedir. $env = file_get_contents('../.env'); preg_match_all('/=(.*)/i',$env,$conf); $dbname = trim($conf[1][7]); $dbuser = trim($conf[1][8]); $dbpass = trim($conf[1][9]); try { $db = new PDO('mysql:host=localhost;dbname='.$dbname.';charset=utf8',$dbuser,$dbpass); } catch(PDOException $e) { print $e->getMessage(); } // Xml formatına dönüştürüyoruz header('Content-Type: text/xml'); // Site ayarlarını çekiyoruz $qAyarlar = $db->query("SELECT * FROM ayarlar",PDO::FETCH_ASSOC); foreach($qAyarlar as $rA) { if($rA['name'] == 'title') { $title = $rA['value']; } else if($rA['name'] == 'description') { $description = $rA['value']; } else if($rA['name'] == 'url') { $url = $rA['value']; } } // Rss ana tanımlamaları yapıyoruz echo '<?xml version="1.0"?> <rss xmlns:g="http://base.google.com/ns/1.0" version="2.0"> <channel> <title>'.$title.'</title> <description>'.$description.'</description> <link>'.$url.'</link>'; // Site ayarlarını çekiyoruz $qBlog = $db->query("SELECT * FROM urun where xmlurun=1 ORDER BY ID DESC",PDO::FETCH_ASSOC); foreach($qBlog as $rB) { echo ' <item> <g:id>'.$rB['ID'].'</g:id> <title><![CDATA['.$rB['Baslik'].']]></title> <g:description><![CDATA['.$rB['description'].']]></g:description> <link>https://zirvesapka.com/'.$rB['refurl'].'-u-'.$rB['ID'].'.html</link> <g:image_link>https://zirvesapka.com/upload/images/'.$rB['Resim'].'</g:image_link> <g:mobile_link></g:mobile_link> <g:availability>stokta</g:availability> <g:price>'.$rB['IndirimliFiyati'].' TRY</g:price> <g:google_product_category>241</g:google_product_category> <g:brand>Zirve Şapka</g:brand> <g:gtin></g:gtin> <g:identifier_exists>hayır</g:identifier_exists> <g:mpn>ZİRVE'.$rB['ID'].'ZİRVESAPKA</g:mpn> <g:condition>yeni</g:condition> <g:adult>hayır</g:adult> <g:multipack>2</g:multipack> <g:is_bundle>evet</g:is_bundle> <g:age_group>yetişkinler</g:age_group> <g:color></g:color> <g:gender>unisex</g:gender> <g:material></g:material> <g:pattern>Düz</g:pattern> <g:size></g:size> <g:item_group_id></g:item_group_id> <g:shipping> <g:country>TR</g:country> <g:region>MA</g:region> <g:service>Kargo</g:service> <g:price>'.$rB['IndirimliFiyati'].' TRY</g:price> </g:shipping> </item> '; } echo '</channel></rss>';
RSpec.describe NVidiaSMI do subject { described_class.new(binary_path: nil, query_list: nil, name_prefix: nil) } describe '#parser' do it { expect(subject.parse(fixture_load('nvidia-smi-1.csv'))).to eq(JSON.load(fixture_load('parsed-1.json'))) } it { expect(subject.parse(fixture_load('nvidia-smi-2.csv'))).to eq(JSON.load(fixture_load('parsed-2.json'))) } end end
package utils; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; /** * BaseServlet用来作为其它Servlet的父类 * * @author qdmmy6 * * 一个类多个请求处理方法,每个请求处理方法的原型与service相同! 原型 = 返回值类型 + 方法名称 + 参数列表 */ @SuppressWarnings("serial") public class BaseServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");//处理响应编码 request.setCharacterEncoding("UTF-8"); /** * 1. 获取method参数,它是用户想调用的方法 2. 把方法名称变成Method类的实例对象 3. 通过invoke()来调用这个方法 */ String methodName = request.getParameter("method"); Method method = null; /** * 2. 通过方法名称获取Method对象 */ try { method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); } catch (Exception e) { throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", e); } /** * 3. 通过method对象来调用它 */ try { String result = (String)method.invoke(this, request, response); if(result != null && !result.trim().isEmpty()) {//如果请求处理方法返回不为空 int index = result.indexOf(":");//获取第一个冒号的位置 if(index == -1) {//如果没有冒号,使用转发 request.getRequestDispatcher(result).forward(request, response); } else {//如果存在冒号 String start = result.substring(0, index);//分割出前缀 String path = result.substring(index + 1);//分割出路径 if(start.equals("f")) {//前缀为f表示转发 request.getRequestDispatcher(path).forward(request, response); } else if(start.equals("r")) {//前缀为r表示重定向 response.sendRedirect(request.getContextPath() + path); } } } } catch (Exception e) { throw new RuntimeException(e); } } }
import chalk from "chalk" import { Compiler, MultiCompiler, Configuration } from "webpack" import webpackHotMiddleware from "webpack-hot-middleware" import { compose } from "compose-middleware" import { compilationMiddleware } from "./middleware/compilation-middleware" import { devMiddleware } from "./middleware/dev-middleware" import { reportErrorMiddleware } from "./middleware/report-error-middleware" import { universalCompiler } from "./webpack-universal/universal-compiler" import { startReportingWebpackIsomorphic } from "./webpack-universal/universal-compiler-reporter" import { startNotifying } from "./utils/os-notifications" import { checkHashes } from "./utils/check-hashes" import { MiddlewareOptions } from "./types/middleware" import { isMiddlewareOptions, isMultiCompiler, isSingleCompiler, isMultiConfig, isSingleConfiguration, } from "./types/type-guards" import { NotifierOptions } from "./utils/os-notifications" function parseOptions(options: MiddlewareOptions) { options = { inMemoryFilesystem: true, watchDelay: 0, hot: false, watchOptions: undefined, report: { stats: "once" }, notify: true, headers: { "Cache-Control": "max-age=0, must-revalidate" }, ...options, } options.report = options.report === true ? {} : options.report options.notify = options.notify === true ? {} : options.notify return options } function parseArgs( args: [ MultiCompiler | Compiler | Configuration | [Configuration, Configuration], (Configuration | Compiler | MiddlewareOptions)?, MiddlewareOptions? ] ) { const [argOne, argTwo, argThree] = args if (isMultiCompiler(argOne) && isMiddlewareOptions(argTwo)) { return { compiler: universalCompiler(argOne.compilers[0], argOne.compilers[1]), options: parseOptions(argTwo), } } if (isMultiConfig(argOne) && isMiddlewareOptions(argTwo)) { return { compiler: universalCompiler(argOne[0], argOne[1]), options: parseOptions(argTwo), } } if ( isSingleConfiguration(argOne) && isSingleConfiguration(argTwo) && isMiddlewareOptions(argThree) ) { return { compiler: universalCompiler(argOne, argTwo), options: parseOptions(argThree), } } if ( isSingleCompiler(argOne) && isSingleCompiler(argTwo) && isMiddlewareOptions(argThree) ) { return { compiler: universalCompiler(argOne, argTwo), options: parseOptions(argThree), } } if ( (isSingleConfiguration(argOne) || isSingleCompiler(argOne)) && isMiddlewareOptions(argTwo) ) { console.log( chalk.red.bold( "You passed in only a single Compiler or Configuration, you must pass both a Server and Client\n\n" + "const configs = [Client, Server]\n\n" ) ) } throw new TypeError("Config Error") } export function universalMiddleware( ...args: [ MultiCompiler | Compiler | Configuration | [Configuration, Configuration], (Configuration | Compiler | MiddlewareOptions)?, MiddlewareOptions? ] ) { const { compiler, options } = parseArgs(args) if (options.inMemoryFilesystem) { require("./utils/build-filesystem").buildInMemoryFileSystem( compiler.client, compiler.server ) } if (typeof options.report !== "undefined" && options.report !== false) { options.report = startReportingWebpackIsomorphic( compiler, options.report ).options } if (options.notify && options.notify !== false) { options.notify = startNotifying( compiler, options.notify as NotifierOptions ).options } options.inMemoryFilesystem && checkHashes(compiler, options) const middleware = [ compilationMiddleware(compiler, options), devMiddleware(compiler, options), reportErrorMiddleware(compiler, options), ...(options.hot ? [webpackHotMiddleware(compiler.client.webpackCompiler)] : []), ] compiler.watch() return Object.assign(compose(middleware), { compiler, }) }
import { getEnvironmentFeatureState, getEnvironmentFeatureStates, getIdentityFeatureState, getIdentityFeatureStates } from '../../../flagsmith-engine'; import { CONSTANTS } from '../../../flagsmith-engine/features/constants'; import { FeatureModel, FeatureStateModel } from '../../../flagsmith-engine/features/models'; import { TraitModel } from '../../../flagsmith-engine/identities/traits/models'; import { environment, environmentWithSegmentOverride, feature1, getEnvironmentFeatureStateForFeature, getEnvironmentFeatureStateForFeatureByName, identity, identityInSegment, segmentConditionProperty, segmentConditionStringValue } from './utils'; test('test_identity_get_feature_state_without_any_override', () => { const feature_state = getIdentityFeatureState(environment(), identity(), feature1().name); expect(feature_state.feature).toStrictEqual(feature1()); }); test('test_identity_get_feature_state_without_any_override_no_fs', () => { expect(() => { getIdentityFeatureState(environment(), identity(), 'nonExistentName'); }).toThrowError('Feature State Not Found'); }); test('test_identity_get_all_feature_states_no_segments', () => { const env = environment(); const ident = identity(); const overridden_feature = new FeatureModel(3, 'overridden_feature', CONSTANTS.STANDARD); env.featureStates.push(new FeatureStateModel(overridden_feature, false, 3)); ident.identityFeatures = [new FeatureStateModel(overridden_feature, true, 4)]; const featureStates = getIdentityFeatureStates(env, ident); expect(featureStates.length).toBe(3); for (const featuresState of featureStates) { const environmentFeatureState = getEnvironmentFeatureStateForFeature( env, featuresState.feature ); const expected = environmentFeatureState?.feature == overridden_feature ? true : environmentFeatureState?.enabled; expect(featuresState.enabled).toBe(expected); } }); test('test_identity_get_all_feature_states_with_traits', () => { const trait_models = new TraitModel(segmentConditionProperty, segmentConditionStringValue); const featureStates = getIdentityFeatureStates( environmentWithSegmentOverride(), identityInSegment(), [trait_models] ); expect(featureStates[0].getValue()).toBe('segment_override'); }); test('test_identity_get_all_feature_states_with_traits_hideDisabledFlags', () => { const trait_models = new TraitModel(segmentConditionProperty, segmentConditionStringValue); const env = environmentWithSegmentOverride(); env.project.hideDisabledFlags = true; const featureStates = getIdentityFeatureStates( env, identityInSegment(), [trait_models] ); expect(featureStates.length).toBe(0); }); test('test_environment_get_all_feature_states', () => { const env = environment(); const featureStates = getEnvironmentFeatureStates(env); expect(featureStates).toBe(env.featureStates); }); test('test_environment_get_feature_states_hides_disabled_flags_if_enabled', () => { const env = environment(); env.project.hideDisabledFlags = true; const featureStates = getEnvironmentFeatureStates(env); expect(featureStates).not.toBe(env.featureStates); for (const fs of featureStates) { expect(fs.enabled).toBe(true); } }); test('test_environment_get_feature_state', () => { const env = environment(); const feature = feature1(); const featureState = getEnvironmentFeatureState(env, feature.name); expect(featureState.feature).toStrictEqual(feature); }); test('test_environment_get_feature_state_raises_feature_state_not_found', () => { expect(() => { getEnvironmentFeatureState(environment(), 'not_a_feature_name'); }).toThrowError('Feature State Not Found'); });
--- name: 🚀 Feature Request about: Suggest an idea for a new feature to improve SlackClean. title: '' labels: 'Feature' assignees: '' --- Feature Requests Must Include: = As much detail as possible for what should be added, what's missing, why it's important to SlackCleaner. _( I'd love for you to share any thoughts you may have on how/what the new feature should be immplemented )_ - Relevant links to any documentation, screenshots, or live demos, whenever possible. - Add any other additional context, screenshots or details about the feature request here. **Description** It would be great if ... **Relevant Resources** - **Additional Context**
package xyz.hshuai.forum.mapper; import xyz.hshuai.forum.dto.TalkQueryDTO; import xyz.hshuai.forum.model.Talk; import org.springframework.stereotype.Component; /** * @author Hshuai * @version 1.0 * @date 2020/12/24 21:53 * @site hschool.hshuai.xyz */ @Component public interface TalkExtMapper { Integer count(TalkQueryDTO talkQueryDTO); int updateByPrimaryKeySelective(Talk talk); }
{-# LANGUAGE Rank2Types, FlexibleContexts, ScopedTypeVariables #-} -- Serialization/deserialization ("serdes") tests module Tests.Serdes ( qcProps ) where import Data.Serialize hiding (label) import Data.Time.Clock import Test.QuickCheck hiding (numTests) import Test.QuickCheck.Monadic import Halfs.Classes import Halfs.Directory import Halfs.HalfsState import Halfs.Inode import Halfs.SuperBlock import System.Device.BlockDevice import Tests.Instances () import Tests.Types import Tests.Utils -------------------------------------------------------------------------------- -- BlockDevice properties -- go = mapM (uncurry quickCheckWithResult) (qcProps True) qcProps :: Bool -> [(Args, Property)] qcProps quick = [ serdes prop_serdes 100 "SuperBlock" (arbitrary :: Gen SuperBlock) , serdes prop_serdes 100 "UTCTime" (arbitrary :: Gen UTCTime) , serdes prop_serdes 100 "DirectoryEntry" (arbitrary :: Gen DirectoryEntry) , mkMemDevExec quick "Serdes" 100 "Ext" propM_extSerdes , mkMemDevExec quick "Serdes" 100 "Inode" propM_inodeSerdes ] where numTests n = (,) $ if quick then stdArgs{maxSuccess = n} else stdArgs serdes pr n s g = numTests n $ label ("Serdes: " ++ s) $ forAll g pr prop_serdes x = either (const False) (== x) $ decode $ encode x -- We special case inode serdes property because we want to test equality of the -- inodes' transient fields when possible. This precludes the use of the pure -- decode function. propM_inodeSerdes :: HalfsCapable b UTCTime r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_inodeSerdes _g dev = forAllM (arbitrary :: Gen (Inode UTCTime)) $ \i -> do -- NB: We fill in the numAddrs field of the arbitrary Inode based on the -- device geometry rather than using the value given to us by the generator, -- which is arbitrary. nAddrs <- computeNumAddrs (bdBlockSize dev) minInodeBlocks =<< computeMinimalInodeSize (inoCreateTime i) sizes <- run $ computeSizes (bdBlockSize dev) let dummyEnv = HalfsState inv inv inv inv sizes inv inv inv inv inv inv inv inv = error "Internal: dummy state, value undefined" runH dummyEnv (decodeInode (encode i)) >>= assert . either (const False) (eq i nAddrs) where eq inode na = (==) inode{ inoExt = (inoExt inode){ numAddrs = na } } propM_extSerdes :: HalfsCapable b UTCTime r l m => BDGeom -> BlockDevice m -> PropertyM m () propM_extSerdes _g dev = forAllM (arbitrary :: Gen Ext) $ \ext -> do -- NB: We fill in the numAddrs field of the arbitrary Ext here based on the -- device geometry rather than using the value given to us by the generator, -- which is arbitrary. nAddrs <- computeNumAddrs (bdBlockSize dev) minExtBlocks =<< minimalExtSize runHNoEnv (decodeExt (bdBlockSize dev) (encode ext)) >>= assert . either (const False) (== ext{ numAddrs = nAddrs })
// Fill out your copyright notice in the Description page of Project Settings. #include "MVCPlayerState.h" #include "Engine/Engine.h" AMVCPlayerState::AMVCPlayerState() { PropertyMap.Add(TEXT("Speed"), 0); } int32 AMVCPlayerState::GetProperty(FString Key) { if (PropertyMap.Find(Key) != nullptr) { return PropertyMap[Key]; } else { return -1; } } void AMVCPlayerState::AddProperty(FString Key) { if (PropertyMap.Find(Key) != nullptr) { PropertyMap[Key] += 1; if (GEngine != nullptr) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, FString::FromInt(PropertyMap[Key])); } } } void AMVCPlayerState::SubtractProperty(FString Key) { if (PropertyMap.Find(Key) != nullptr) { PropertyMap[Key] -= 1; if (PropertyMap[Key] < 0) { PropertyMap[Key] = 0; } if (GEngine != nullptr) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, FString::FromInt(PropertyMap[Key])); } } }
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.konan.blackboxtest.support.util import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.nextLeaf import org.jetbrains.kotlin.psi.psiUtil.prevLeaf internal fun PsiElement.ensureSurroundedByWhiteSpace(): PsiElement = ensureHasWhiteSpaceBefore().ensureHasWhiteSpaceAfter() private fun PsiElement.ensureHasWhiteSpaceBefore(): PsiElement { val (fileBoundaryReached, whiteSpaceBefore) = whiteSpaceBefore() if (!fileBoundaryReached and !whiteSpaceBefore.endsWith(" ")) { parent.addBefore(KtPsiFactory(project).createWhiteSpace(" "), this) } return this } private fun PsiElement.ensureHasWhiteSpaceAfter(): PsiElement { val (fileBoundaryReached, whiteSpaceAfter) = whiteSpaceAfter() if (!fileBoundaryReached and !whiteSpaceAfter.startsWith(" ")) { parent.addAfter(KtPsiFactory(project).createWhiteSpace(" "), this) } return this } private fun PsiElement.whiteSpaceBefore(): Pair<Boolean, String> { var fileBoundaryReached = false fun PsiElement.prevWhiteSpace(): PsiWhiteSpace? = when (val prevLeaf = prevLeaf(skipEmptyElements = true)) { null -> { fileBoundaryReached = true null } else -> prevLeaf as? PsiWhiteSpace } val whiteSpace = buildString { generateSequence(prevWhiteSpace()) { it.prevWhiteSpace() }.toList().asReversed().forEach { append(it.text) } } return fileBoundaryReached to whiteSpace } private fun PsiElement.whiteSpaceAfter(): Pair<Boolean, String> { var fileBoundaryReached = false fun PsiElement.nextWhiteSpace(): PsiWhiteSpace? = when (val nextLeaf = nextLeaf(skipEmptyElements = true)) { null -> { fileBoundaryReached = true null } else -> nextLeaf as? PsiWhiteSpace } val whiteSpace = buildString { generateSequence(nextWhiteSpace()) { it.nextWhiteSpace() }.forEach { append(it.text) } } return fileBoundaryReached to whiteSpace }
package com.krossovochkin.core.presentation.result import android.os.Bundle import android.os.Parcelable private const val KEY_RESULT = "result" fun <T : Parcelable> Bundle.toResultParcelable(): T { return this.getParcelable(KEY_RESULT)!! } fun Parcelable.toResultBundle(): Bundle { return Bundle().apply { putParcelable(KEY_RESULT, this@toResultBundle) } }
require 'spec_helper' require 'fileutils' RSpec.describe MicroBlitz::FileFinder do subject { MicroBlitz::FileFinder.new } let(:directory) { subject.directory } let!(:micro_blitz_config) do { frequency: 1, recurrence: 1, chaoticness: 2, directory: "test_dir" } end before do configure end context "#initialize" do it "has been instantiated" do expect(subject).to be_an(MicroBlitz::FileFinder) end it "has a directory assigned" do expect(subject.directory).to eq(micro_blitz_config.fetch(:directory)) end end context "#walk" do let(:valid_response) { ["#{directory}/foo.rb", "#{directory}/bar.rb"] } let(:invalid_response) { ["#{directory}/foo.rb", "#{directory}/bar.rb", "#{directory}/baz.txt"] } it "only returns a list of files with valid extensions" do expect(subject.walk).to match_array(valid_response) end it "excludes files with invalid extensions" do expect(subject.walk).to_not match_array(invalid_response) end end def configure Stubs.micro_blitz_config(overrides=micro_blitz_config) Stubs.setup_directory(directory) end end
var_in_invalid_list_variable_file = 'Not got into use due to error below' LIST__invalid_list = 'This is not a list and thus importing this file fails'
package model // 运行时设备信息 type DeviceInfo struct { CPUs int `json:"CPUs"` PlatformFamily string `json:"platformFamily"` KernelArch string `json:"kernelArch"` } // 处理器信息 type Processor struct { Cores int32 `json:"cores"` Name string `json:"name"` Mhz float64 `json:"Mhz"` CacheSize int32 `json:"cacheSize"` Microcode string `json:"microcode"` } // 运行时设备信息 type RunTimeDeviceInfo struct { Name string `json:"name"` Num string `json:"num"` DevelopmentLocation string `json:"developmentLocation"` AssociationTime string `json:"associationTime"` Usage string `json:"usage"` CPUUsedPercent string `json:"CPUUsedPercent"` AgentID string `json:"agentID"` MacID string `json:"macID"` UID string `json:"uid"` NetInterface []struct { MTU int `json:"mtu"` Name string `json:"name"` Flags []string `json:"flags"` AddrGroup []string `json:"addrGroup"` } `json:"interface"` CPUs []Processor `json:"CPUs"` Memory struct { Total uint64 `json:"total"` Available uint64 `json:"available"` Used uint64 `json:"used"` UsedPercent float64 `json:"usedPercent"` Free uint64 `json:"free"` } `json:"memory"` FS struct { Path string `json:"path"` FSType string `json:"FSType"` Total uint64 `json:"total"` UsedPercent float64 `json:"usedPercent"` Free uint64 `json:"free"` Used uint64 `json:"used"` } `json:"FS"` System struct { Hostname string `json:"hostname"` OS string `json:"os"` Platform string `json:"platform"` PlatformFamily string `json:"platformFamily"` PlatformVersion string `json:"platformVersion"` KernelVersion string `json:"kernelVersion"` KernelArch string `json:"kernelArch"` HostId string `json:"hostId"` } `json:"system"` }
import logging import os import tempfile from clipmanager import __name__, __org__ if os.name == 'nt': from win32event import CreateMutex from win32api import CloseHandle, GetLastError from winerror import ERROR_ALREADY_EXISTS else: import commands import os logger = logging.getLogger(__name__) class SingleInstance: """Limits application to a single instance. References - https://github.com/josephturnerjr/boatshoes/blob/master/boatshoes/SingleInstance.py - https://github.com/csuarez/emesene-1.6.3-fixed/blob/master/SingleInstance.py """ def __init__(self): self.last_error = False self.pid_path = os.path.normpath( os.path.join( tempfile.gettempdir(), '{}-{}.lock'.format(__name__.lower(), self._get_username()) ) ) if os.name == 'nt': # HANDLE WINAPI CreateMutex( # _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes, # _In_ BOOL bInitialOwner, # _In_opt_ LPCTSTR lpName # ); # # DWORD WINAPI GetLastError(void); self.mutex_name = '{}.{}'.format(__org__, __name__) self.mutex = CreateMutex(None, False, self.mutex_name) self.last_error = GetLastError() else: if os.path.exists(self.pid_path): pid = open(self.pid_path, 'r').read().strip() pid_running = commands.getoutput( 'ls /proc | grep {}'.format(pid) ) if pid_running: self.last_error = True if not self.last_error: f = open(self.pid_path, 'w') f.write(str(os.getpid())) f.close() def __del__(self): self.destroy() @staticmethod def _get_username(): return os.getenv('USERNAME') or os.getenv('USER') def is_running(self): """Check if application is running. :return: True if instance is running. :rtype: bool """ if os.name == 'nt': # ERROR_ALREADY_EXISTS # 183 (0xB7) # Cannot create a file when that file already exists. return self.last_error == ERROR_ALREADY_EXISTS else: return self.last_error def destroy(self): """Close mutex handle or delete pid file. :return: None :rtype: None """ if os.name == 'nt' and self.mutex: # BOOL WINAPI CloseHandle( # _In_ HANDLE hObject # ); CloseHandle(self.mutex) else: try: os.unlink(self.pid_path) except OSError as err: logger.error(err)