language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
762
2.5625
3
[ "Apache-2.0" ]
permissive
package io.github.gdggarage.worldproblems.entity; public class Problem { private int id; private String text; private String author; private String source; private String url; private String submitter; public Problem() { }; public Problem(int id, String text, String author, String source, String url, String submitter) { this.id = id; this.text = text; this.author = author; this.source = source; this.url = url; this.submitter = submitter; } public int getId() { return id; } public String getText() { return text; } public String getAuthor() { return author; } public String getSource() { return source; } public String getUrl() { return url; } public String getSubmitter() { return submitter; } }
Swift
UTF-8
1,887
2.859375
3
[ "MIT" ]
permissive
// // AlbumCell.swift // FYPhotoPicker // // Created by xiaoyang on 2020/7/30. // import UIKit class AlbumCell: UITableViewCell { fileprivate let coverImage = UIImageView() fileprivate let nameLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) coverImage.contentMode = .scaleAspectFill coverImage.clipsToBounds = true contentView.addSubview(coverImage) contentView.addSubview(nameLabel) coverImage.translatesAutoresizingMaskIntoConstraints = false nameLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ coverImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15), coverImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), coverImage.widthAnchor.constraint(equalToConstant: 50), coverImage.heightAnchor.constraint(equalToConstant: 50) ]) NSLayoutConstraint.activate([ nameLabel.leadingAnchor.constraint(equalTo: coverImage.trailingAnchor, constant: 10), nameLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(image: UIImage, title: String) { coverImage.image = image nameLabel.text = title } var cover: UIImage? { willSet { coverImage.image = newValue setNeedsDisplay() } } var name: String? { willSet { nameLabel.text = newValue setNeedsDisplay() } } }
Markdown
UTF-8
4,173
3.140625
3
[]
no_license
# 适配问题 怎么适配iphone6 1px问题 ### 为什么页面与设计稿会出现偏差? `dpr=设备像素/ css像素`,只有dpr等于1的时候,实际效果和设计稿的尺寸比例才是1:1。 因为iPhone6的DPR(设备像素比)为2,设备像素为750,所以iPhone6的理想视口尺寸为375px。 因为设计稿是基于设备像素,页面是基于css像素的。css中的宽度是基于理想视口的(宽度375px),设计图上是基于设备宽度750px,所以尺寸不对。 ------- ###### 怎么处理? `init-scale=0.5` 。 缺陷:但是宽度不能自适应 ------- ## ⭐️rem大法 基于`html`标签的`font-size`设置的 ### 手淘的做法: 把缩放尺寸设置成dpr的倒数。 读设备宽度,动态设置meta标签的 content属性中的`maximun`,`minimum`,`user-scable`值 ``` <html> <head> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="" /> <style> body{ margin: 0; padding: 0; } .box{ width: 2.66666667rem; height: 2.66666667rem; background: red; } </style> </head> <body> <div class="box"></div> <script> var scale = 1 / window.devicePixelRatio; document.querySelector('meta[name="viewport"]').setAttribute('content','width=device-width,initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'); document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + 'px'; </script> </body> </html> ``` ### 网易的做法 现在的设计稿都是750px宽度(p6的宽),那要想实现 `css样式:设计图=1:100` 这种比较方便的折算方式,font-size就要设置成7.5px; 也就是说` 1rem = 7.5px` ``` <html> <head> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" /> <style> body{ margin: 0; padding: 0; } .box{ width: 2rem; height: 2rem; background: red; } </style> </head> <body> <div class="box"></div> <script> document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px'; </script> </body> </html> ``` #### 总结 rem是为了实现移动端自适应布局。通过在`html`元素下设置`font-size`定义。 另外,**手淘的做法**是通过判断设备的dpr,将缩放规模scale设置为dpr的倒数,再用js动态设置`meta`标签的`content`属性和font-size基准值的大小。 **网易的做法**是,禁用用户缩放,scale始终为1,将font-size设置为625%,即 1rem=100px。 ------- ### 1px问题 如何实现移动端的1px边框 ##### 方法一:`transformY:scale(50%)` ##### 方法二: ``` border-width:0 0 2px 0; border-image:url("xxx.png") 0 0 2 0 stretch // 图片地址 上下剪切 左右剪切 上下边宽 左右边宽 图片拉伸 ``` ------- ## vm/vh+rem大法 vm/vh是未来的趋势 ##### rem方式弊端:需要动态计算根字体大小 #### 做法:用vm/vh来计算根字体大小,剩下的自适应布局依旧按照rem的方法 ``` .wh(@width,@height){ width: @width/100rem; height: @height/100rem; } ``` [用vm/vh做适配页面](https://aotu.io/notes/2017/04/28/2017-4-28-CSS-viewport-units/index.html) ### ⭐️关于vm/vh ##### 1. 与%百分比的区别 vm/vh 是基于视窗的 %基于父元素 ##### 2. 使用场景 随着页面不同,文字图片缩小放大(适配页面) ##### 3. 与rem的区别 vm/vh没有最大、最小宽大的限制(设备很小的时候,图文会缩得特别特别小……) ###### 措施: 1.解决背景过小问题 ``` body{ min-width:xxx px; max-width: xxx px; } ``` 2.媒体查询限制根文字大小(解决文字过小问题) ```html { font-size: ($vw_fontsize / ($vw_design / 2)) * 100vw; // 同时,通过Media Queries 限制根元素最大最小值 @media screen and (max-width: 320px) { font-size: 64px; } @media screen and (min-width: 540px) { font-size: 108px; } } ```
Java
UTF-8
822
2.296875
2
[]
no_license
package assets.minecessity.items; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class ItemCeilLamp extends MagicItem { public ItemCeilLamp(Block blockID) { super(blockID); } @Override public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int i, int j, int k, int l, float f1, float f2, float f3) { //super.onItemUse(itemStack,player,world,i,j,k,l, f1, f2, f3); if (l == 0) j--; if (l == 1) j++; if (l == 2) k--; if (l == 3) k++; if (l == 4) i--; if (l == 5) i++; if (!world.isAirBlock(i, j + 1, k)) world.setBlock(i, j, k, field_150939_a); if (world.getBlock(i, j, k) == field_150939_a) itemStack.stackSize--; return true; } }
TypeScript
UTF-8
4,428
2.578125
3
[ "MIT" ]
permissive
import fs = require ('fs'); import { log, LogEntry } from "./log"; import settings from "./logger-settings"; const colors = { black: '\x1b[30m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', blue: '\x1b[34m', magenta: '\x1b[35m', cyan: '\x1b[36m', white: '\x1b[37m', dim: '\x1b[2m', reset: '\x1b[0m' }; var maxNameLength: number = 0; function logEntry (name : string, timestamp : number, msg : string, color? : 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white') { if (!color) color = 'white'; const entry : LogEntry = { n: name, t: timestamp, m: msg, c: color }; log.push (entry); settings.appendToLogfile (entry); if (log.length > settings.linesInMemory) { log.splice (0, settings.chopSize); } } function isNodeJSModule (obj : NodeJS.Module|any) : obj is NodeJS.Module { var keys = Object.keys (obj); return keys.includes ('filename') && keys.includes ('id') && keys.includes ('exports'); } function isError (obj : Error|any) : obj is Error { var e = new Error ('asdf'); if (typeof (obj) !== 'object') return false; if (obj instanceof Error) return true; var keys = Object.keys (obj); return keys.includes ('message') && keys.includes ('name'); } function Logger (loggerID: string|NodeJS.Module|{toString: ()=>string}, defaultColor : 'black'|'red'|'green'|'yellow'|'blue'|'magenta'|'cyan'|'white' = null) { var name = ''; if (typeof (loggerID) === 'string') name = loggerID; else if (isNodeJSModule (loggerID)) { name = loggerID.filename; name = name.substr (name.lastIndexOf ('/') + 1); if (name.endsWith ('.js')) name = name.substr (0, name.length - 3); } else if (loggerID.toString) { name = loggerID.toString (); } else { name = loggerID + ''; } if (name.length > maxNameLength) maxNameLength = name.length; const defaultCol = defaultColor || settings.defaultColor; const defaultC = colors[defaultCol]; const bracedName = `[${name}]`; function LogRegular (msg: string|number|Error|object, color: 'black'|'red'|'green'|'yellow'|'blue'|'magenta'|'cyan'|'white' = null) { const d = new Date (); const c = color ? colors[color] : defaultC; const strMsg = stringifyMessage (msg); logEntry (name, d.getTime (), strMsg, color || defaultCol); const cr = c === '' ? '' : colors.reset; if (settings.useSystemStringification) { console.log (c + timestamp (d) + cr + c + '|' + fixedLengthString (name, maxNameLength, '.') + cr + c + ': ', msg, cr); } else { console.log (c + timestamp (d) + cr + c + '|' + fixedLengthString (name, maxNameLength, '.') + cr + c + ': ' + strMsg + cr); } } function LogProduction (msg: string|number|Error|object, color: 'black'|'red'|'green'|'yellow'|'blue'|'magenta'|'cyan'|'white' = null) { const strMsg = stringifyMessage (msg); logEntry (name, Date.now (), strMsg, color || defaultCol); console.log (bracedName, msg); } return (settings.isProductionMode && !settings.useColorsInProduction) ? LogProduction : LogRegular; } function stringifyMessage (msg: string | number | object | Error) { if (typeof (msg) === 'string') { return msg; } if (isError(msg)) { return msg.name + ': ' + msg.message + (msg.stack ? ('\n' + msg.stack) : ''); } let strMsg = String(msg); if (typeof (strMsg) !== 'string' || strMsg.startsWith('[object ')) { strMsg = JSON.stringify(msg); } return strMsg; } function timestamp (d) { return digits (d.getHours (), 2) + ':' + digits (d.getMinutes (), 2) + ':' + digits (d.getSeconds (), 2) + colors.dim + '.' + digits (d.getMilliseconds (), 3) + colors.reset; } function digits (n, digits) { var sn = ('' + n); while (sn.length < digits) sn = '0' + sn; return sn; } function fixedLengthString (str, len, fillChar) { if (!fillChar) fillChar = ' '; var s = ('' + str); var se = ''; for (var i = s.length; i < len; i++) se += fillChar; if (fillChar !== ' ') se = colors.dim + se + colors.reset; return s + se; } function loggerExpressEndpoint (req, res, next) { if (req.url === '/') { res.sendFile (__dirname + '/log.html'); } else if (req.url.startsWith ('/since/')) { var t1 = parseInt (req.url.substr ('/since/'.length)); for (var i = 0; i < log.length; i++) { if (log[i].t > t1) { res.json (log.slice (i)); return; } } res.json ([]); } else { next (); } }; export { Logger, loggerExpressEndpoint, colors as LoggingColor, settings as LoggerSettings }; export default Logger;
Java
UTF-8
3,540
2.234375
2
[]
no_license
package com.ihomefnt.o2o.intf.domain.product.doo; import lombok.Data; import java.util.ArrayList; import java.util.List; /** * Created by shirely_geng on 15-1-18. */ @Data public class ProductInfomationResponse { /** 主鍵 */ private Long productId; private String name; private List<String> pictureUrlOriginal; private double priceCurrent; private double priceMarket; private String productModel; private String standardLong; private String standardWidth; private String standardHigh; private String feature; private String brand; private String madeIn; private String deliveryCity; private String graphicDescription; private String firstContentsName; //TODO: this should be removed in next iteration private String secondContentsName; //TODO: this should be removed in next iteration private Integer status; private List<String> detailList; private List<ProductDetail> mainDetails = new ArrayList<ProductDetail>();//主要参数 private List<ProductDetail> adnexalDetails;//附加参数 2.0之前版本 private List<ProductDetailGroup> productDetailGroups;//属性 2.0以后版本 private int priceHide;//0表示价格不隐藏,1表示价格隐藏 private int sales; private String productType; public ProductInfomationResponse(ProductInfomation product) { this.productId = product.getProductId(); this.name = product.getName(); this.priceCurrent = product.getPriceCurrent(); this.priceMarket = product.getPriceMarket(); this.productModel = product.getProductModel()+product.getSerialNo();//前台要求特殊处理 this.standardLong = product.getStandardLong(); this.standardWidth = product.getStandardWidth(); this.standardHigh = product.getStandardHigh(); this.feature = product.getFeature(); this.brand = product.getBrand(); this.madeIn = product.getMadeIn(); this.deliveryCity = product.getDeliveryCity(); this.graphicDescription = product.getGraphicDescription(); this.secondContentsName = product.getSecondContentsName(); this.status = product.getStatus(); this.priceHide = product.getPriceHide(); this.sales = product.getSales(); this.productType = product.getProductType(); //1.规格 2.特点 3.品牌 4.产地 if (standardLong != null && standardWidth != null && standardHigh != null) { ProductDetail specifications = new ProductDetail(); specifications.setDetailKey("规格"); specifications.setDetailValue(standardLong + "*" + standardWidth + "*" + standardHigh + "mm(长*宽*高)"); this.mainDetails.add(specifications); } if (product.getFeature() != null && product.getFeature().trim().length() > 0) { ProductDetail feature = new ProductDetail(); feature.setDetailKey("特点"); feature.setDetailValue(product.getFeature()); this.mainDetails.add(feature); } if (product.getBrand() != null && product.getBrand().trim().length() > 0) { ProductDetail brand = new ProductDetail(); brand.setDetailKey("品牌"); brand.setDetailValue(product.getBrand()); this.mainDetails.add(brand); } if (product.getMadeIn() != null && product.getMadeIn().trim().length() > 0) { ProductDetail madeIn = new ProductDetail(); madeIn.setDetailKey("产地"); madeIn.setDetailValue(product.getMadeIn()); this.mainDetails.add(madeIn); } } }
Java
UTF-8
2,926
2.484375
2
[ "MIT" ]
permissive
package com.osotnikov.examples.spring.shell.stringcompare; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.shell.jline.InteractiveShellApplicationRunner; import org.springframework.shell.jline.ScriptShellApplicationRunner; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest(properties = { // Disable spring shell so it won't kick in during tests. InteractiveShellApplicationRunner.SPRING_SHELL_INTERACTIVE_ENABLED + "=false", ScriptShellApplicationRunner.SPRING_SHELL_SCRIPT_ENABLED + "=false" }) public class StringCompareServiceTest { private static final String EXPECTED_5 = "ABCDΩ"; private static final String ACTUAL_VALID_5 = "ABCDΩ"; private static final String ACTUAL_INVALID_5_1 = "AXCDΩ"; private static final String ACTUAL_INVALID_5_2 = "AXΩDΩ"; private static final String ACTUAL_INVALID_5_5 = "ZΩZΩZ"; private static final String ACTUAL_INVALID_6 = "ABCDΩA"; private static final String DIFFERENT_LENGTH_STRINGS_EXCEPTION_MSG = "Arguments are of different lengths!"; @Autowired StringCompareService stringCompareService; @Test public void findNumberOfDifferencesInEqualLengthStrings_Success() { int diffs = stringCompareService.findNumberOfDifferencesInEqualLengthStrings(EXPECTED_5, ACTUAL_VALID_5); Assertions.assertEquals(0, 0); diffs = stringCompareService.findNumberOfDifferencesInEqualLengthStrings(EXPECTED_5, ACTUAL_INVALID_5_1); Assertions.assertEquals(1, diffs); diffs = stringCompareService.findNumberOfDifferencesInEqualLengthStrings(EXPECTED_5, ACTUAL_INVALID_5_2); Assertions.assertEquals(2, diffs); diffs = stringCompareService.findNumberOfDifferencesInEqualLengthStrings(EXPECTED_5, ACTUAL_INVALID_5_5); Assertions.assertEquals(5, diffs); } @Test public void findNumberOfDifferencesInEqualLengthStrings_NullArgument_Fail() { Assertions.assertThrows(NullPointerException.class, () -> { stringCompareService.findNumberOfDifferencesInEqualLengthStrings(null, ACTUAL_VALID_5); }); Assertions.assertThrows(NullPointerException.class, () -> { stringCompareService.findNumberOfDifferencesInEqualLengthStrings(EXPECTED_5, null); }); Assertions.assertThrows(NullPointerException.class, () -> { stringCompareService.findNumberOfDifferencesInEqualLengthStrings(null, null); }); } @Test public void findNumberOfDifferencesInEqualLengthStrings_DifferentLengths_Fail() { Assertions.assertThrows(IllegalArgumentException.class, () -> { stringCompareService.findNumberOfDifferencesInEqualLengthStrings(EXPECTED_5, ACTUAL_INVALID_6); }, DIFFERENT_LENGTH_STRINGS_EXCEPTION_MSG); } }
Markdown
UTF-8
928
3.4375
3
[]
no_license
# Snippets-code Snippets code about calculate something simple and other stuff - Calculate! for calculate your dog age as a human age - lifeinweeks-challenge is a function that tell us how many days, weeks, and months we have until 90 years old - method-slice for getting a consisten name from user, based on user input (this input only using prompt) - whos-paying : challenge to get a random name in array to buy lunch - FizzBuzz : a function that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. - 99-bottles : solution for a challenge to print 99 bottles of bear lyric using loop - Fibonacci : a function that using fibonacci sequence where every number is the sum of two previous ones (e.g. : 0, 1, 1, 2, 3, 5, ....) and push it into array
C++
UTF-8
2,971
2.96875
3
[]
no_license
#include "common/runtime/MemoryPool.hpp" #include "common/runtime/Memory.hpp" #include <new> #include <stdexcept> using std::runtime_error; namespace runtime { GlobalPool::GlobalPool() { current = newChunk(allocSize); start = (int8_t*)current + sizeof(Chunk); end = start + allocSize; } GlobalPool::~GlobalPool() { for (auto chunk = current; chunk;) { auto c = chunk; chunk = chunk->next; // read first, then free mem::free_huge(c, c->size + sizeof(Chunk)); } current = nullptr; } GlobalPool::Chunk* GlobalPool::newChunk(size_t size) { return new (mem::malloc_huge(size + sizeof(Chunk))) Chunk(size); } void* GlobalPool::allocate(size_t size) { int8_t* start_; int8_t* end_; int8_t* alloc; restart: do { start_ = start.load(); end_ = end.load(); if (start_ + size >= end_) { { std::lock_guard<std::mutex> lock(refill); // recheck condition start_ = start.load(); end_ = end.load(); if (start_ + size >= end_) { // set available space to 0 so that no other thread can // get memory do { end_ = end.load(); } while (!start.compare_exchange_weak(start_, end_)); // Add a new chunk if space isn't sufficient allocSize = std::max(allocSize * 2, size); if(size>AllocSizeUpper){ throw std::runtime_error("allocate too large memory"); }else { allocSize = std::min(allocSize,AllocSizeUpper); } auto chunk = newChunk(allocSize); chunk->next = current; start_ = (int8_t*)chunk + sizeof(Chunk); end_ = start_ + allocSize; // order is important due to above conditions in if if (chunk < current) { end = end_; start = start_; } else { start = start_; end = end_; } current = chunk; } else goto restart; } } alloc = start_; } while (!start.compare_exchange_weak(start_, start_ + size)); return alloc; } GlobalPool* Allocator::setSource(GlobalPool* source) { auto previousSource = memorySource; memorySource = source; if (source) { start = (uint8_t*)memorySource->allocate(allocSize); free = allocSize; } return previousSource; } void ResetableAllocator::setSource(Allocator* source) { memorySource = source; if (source) { auto created = (uint8_t*)memorySource->allocate(allocSize + sizeof(Chunk)); auto chunk = new (created) Chunk(); chunk->size = allocSize; current = chunk; first = chunk; free = current->size; start = reinterpret_cast<uint8_t*>(current) + sizeof(Chunk); } } } // namespace runtime
C
UTF-8
361
2.9375
3
[]
no_license
// objdump -dM intel loop | grep -A 20 '<main>:' // gcc -std=c11 -o loop loop.c #include <stdio.h> int main(void) { //unsigned int i = 0; //unsigned int i; for (unsigned i=0; i < 3; i++) { printf("O valor de i eh: %u\n", i); } /* imprimir: printf("O valor de i eh: %u\n", i); i++; if (i < 3) goto imprimir; */ return 0; }
C#
UTF-8
2,645
2.765625
3
[ "MIT" ]
permissive
using System.Linq; using System.Collections.Generic; using GameplayAbilitySystem.Enums; using GameplayAbilitySystem.GameplayEffects; namespace GameplayAbilitySystem.Interfaces { /// <summary> /// This is used to define how long the <see cref="GameplayEffect"/> lasts, and what it does (e.g. how much damage) /// </summary> public interface IGameplayEffectPolicy { /// <summary> /// Whether the <see cref="GameplayEffect"/> lasts for some finite time, infinite time, or is applied instantly /// </summary> /// <value></value> EDurationPolicy DurationPolicy { get; } /// <summary> /// Duration of the <see cref="GameplayEffect"/>, if this lasts for some finite time /// </summary> /// <value></value> float DurationMagnitude { get; } /// <summary> /// How the <see cref="GameplayEffect"/> affects attributes /// </summary> /// <value></value> List<GameplayEffectModifier> Modifiers { get; } } /// <summary> /// Gameplay effect tags /// </summary> public interface IGameplayEffectTags { /// <summary> /// <see cref="GameplayTag"/> the <see cref="GameplayEffect"/> has /// </summary> /// <value></value> GameplayEffectTagContainer AssetTags { get; } /// <summary> /// <see cref="GameplayTag"/> that are given to the <see cref="IGameplayAbilitySystem"/> /// </summary> /// <value></value> GameplayEffectTagContainer GrantedTags { get; } /// <summary> /// <see cref="GameplayTag"/> that are required on the <see cref="IGameplayAbilitySystem"/> for the <see cref="GameplayEffect"> to have an effect. /// If these <see cref="GameplayTag"/> are not on the <see cref="IGameplayAbilitySystem"/>, the effect is "disabled" until these <see cref="GameplayTag"/> are present. /// </summary> /// <value></value> GameplayEffectTagContainer OngoingTagRequirements { get; } /// <summary> /// These <see cref="GameplayTag"/> are required to apply the <see cref="GameplayEffect"/>. Once the <see cref="GameplayEffect"/> is applied, /// this has no effect. /// </summary> /// <value></value> GameplayEffectTagContainer ApplicationTagRequirements { get; } /// <summary> /// Removes any existing <see cref="GameplayEffect"/> that have these <see cref="GameplayTag"/>. /// </summary> /// <value></value> GameplayEffectTagContainer RemoveGameplayEffectsWithTag { get; } } }
Java
UTF-8
5,355
2.546875
3
[]
no_license
package com.healthcare; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; import static com.healthcare.Main.ROOTPATH; import static com.healthcare.XsdXpathGenerator.getAllXpaths; public class DataMapperMediator { List<Source> sourceList=new ArrayList<>(); List<OutputPosition> outputPositions =new ArrayList<>(); List <InputElement> inputElements =new ArrayList<>(); List<OutputResolver> resolvers=new ArrayList<>(); Map<OutputPosition,OutputResolver> map = new LinkedHashMap<>(); Destination output; //temp String inputFileName ; String outputFileName; public void loadInput(String type, String inputPayload ,String inputFileName) { this.inputFileName=inputFileName; UUID uuid=UUID.randomUUID(); String srcId=uuid.toString(); Source src=new Source(inputPayload); src.setType(type); src.setId(srcId); setSourceList(src); } public void loadOutput(String type,String outputPayload,String outputFileName){ this.outputFileName =outputFileName; UUID uuid=UUID.randomUUID(); String destId =uuid.toString(); Destination dest =new Destination(outputPayload); dest.setId(destId); dest.setType(type); this.output=dest; File file= new File(ROOTPATH+outputFileName); createElementList(output.getId(),output.getType(),file,false); if(outputPositions.size()>0)System.out.println("---Output Element List created:"+outputPositions.size()); } public void setSourceList(Source src) { sourceList.add(src); System.out.println("Source List : "); for (Object source:sourceList){ System.out.println(source); } if (sourceList.size()>0) System.out.println("---Source List created----"); File file =new File(ROOTPATH+inputFileName); createElementList(src.getId(),src.getType(),file,true); if(inputElements.size()>0) System.out.println("---Input Element List created:"+inputElements.size()); } public void createElementList(String id,String type,File file,boolean isSource){ ElementFactory elementFactory =new ElementFactory(); Map<String,String>pathResults=elementFactory.generatePath(type,file); // for xml files Map<String,String> xpathfromXsd = getAllXpaths(file);// for xsd files for (Map.Entry<String, String> entry : pathResults.entrySet()) { System.out.println(entry.getKey() + " --> " + entry.getValue()); InputElement inputElement=elementFactory.getInputElement(type); OutputPosition outputPosition=elementFactory.getOutputElement(type); if(isSource) { inputElement.setPath(entry.getKey()); inputElement.setSourceId(id); inputElement.setElement(entry.getValue()); inputElement.setType(type); inputElements.add(inputElement); } else{ outputPosition.setPath(entry.getKey()); outputPosition.setElement(entry.getValue()); outputPosition.setType(type); outputPosition.setId(id); outputPositions.add(outputPosition); } } } public void doMapping(File file){ String line; try { FileInputStream inputStream=new FileInputStream(file); Scanner sc =new Scanner(inputStream); do{ line =sc.nextLine(); int i=line.indexOf('='); String input =line.substring(0,i).trim(); String output = line.substring(i+1).trim(); for (OutputPosition position : outputPositions) { if (position.getPath().equals(output)) { for(InputElement element:inputElements){ if (element.getPath().equals(input)) { OutputResolver resolver = new OutputResolver(); resolver.elementList.add(element); resolvers.add(resolver); map.put(position, resolver); } } } } }while(sc.hasNextLine()); System.out.println("---Map : "+map.size()); for (Map.Entry<OutputPosition,OutputResolver> entry : map.entrySet()) { System.out.println(entry.getKey() +" --> " + entry.getValue()); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public void evaluateRequest(File request) { List<String> values; String value; for (Map.Entry<OutputPosition, OutputResolver> entry : map.entrySet()) { value = ""; values = entry.getValue().getFinalValue(request); for (String item : values) { value = value.concat(item).concat(","); } entry.getKey().setValue(value); } System.out.println("---Result----"); for (OutputPosition output : outputPositions) { System.out.println("Element:" + output.getElement() + " value:" + output.getValue()); } } }
C
UTF-8
1,456
4.03125
4
[]
no_license
// warmup.c // By Matthew Rundle // for cse20211.01 // Fall 2012 #include <stdio.h> #include <stdlib.h> #include <math.h> // print array void print_array(double x[],int size) { int i; for(i=0;i<size;i++){ printf(" %.2lf",x[i]); } } // Compute average of the list void avg_and_stddev(double x[],int size) { int i; // Compute Average double sum=0; double avg; for(i=0;i<size;i++){ sum+=x[i]; } avg=sum/size; printf("\nThe average of the array is: %.2lf\n",avg); // Compute Standard Deviation double stddev=0; for(i=0;i<size;i++){ stddev+=(x[i]-avg)*(x[i]-avg); } stddev=stddev/(size-1); stddev=sqrt(stddev); printf("\nThe standard deviation of the array is: %.2lf\n",stddev); } void bubble_sort(double x[],int size) { int i,j,temp; //sort for (i=(size-1);i>0;i--){ for(j=1;j<=i;j++){ if(x[j-1]>x[j]){ temp=x[j-1]; x[j-1]=x[j]; x[j]=temp; } } } //print printf("\nThe sorted array is: {"); for (i=0;i<size;i++){ printf(" %.2lf",x[i]); } printf(" }\n\n"); } int main (void) { int size=10; double x[size]; // read in values printf("\nEnter ten values to populate the array.\n"); printf("The average, standard deviation, and sorted listing will be displayed.\n"); int i; for(i=0;i<size;i++){ printf("%d: ",i+1); scanf("%lf",&x[i]); } // output data printf("\nYou entered: {"); print_array(x,size); printf(" }\n"); avg_and_stddev(x,size); bubble_sort(x,size); return 0; }
Markdown
UTF-8
1,109
3.296875
3
[]
no_license
# 4.15 数据转换/格式化 Thymeleaf为变量表达式(`${...}`)和选择表达式(`*{...}`)定义了一个双括号的语法,它允许我们通过配置的转化服务对数据进行转化。 形式基本如下: ``` <td th:text="${{user.lastAccessDate}}">...</td> ``` 注意这里的双括号`${{...}}`,这里实际上将`user.lastAccessDate`的值在渲染至模板上之前传递给 *转化服务* 并让其执行 **格式化服务**(将其转化为`String`)。 假设`user.lastAccessDate`是`java.util.Calendar`类,如果现有一个注册了的转化服务(`即IStandardConversionService的实现类`)并且这个服务中包含`Calendar -> String`的转化功能,那么这个服务就会启动。 `IStandardConversionService`接口的默认实现(即`StandardConversionService`类)仅仅是在所有对象上调用`.toString()`方法将对象转化为`String`。想要了解更多关于如何注册一个自定义的转化服务,可以去查看[关于配置的更多内容](http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#more-on-configuration)章节。
Python
UTF-8
5,127
2.640625
3
[]
no_license
import os, pickle#, visualize import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from matplotlib.pyplot import figure class PlotResults: def __init__(self, algorithms=["GA_package", "NEAT", "Island"], enemies=[[1,3,6]]): self.algorithms = algorithms self.enemies = enemies sns.set() self.generate_combined_fitness_plots() # self.other_graphs() def other_graphs(self): all_evals = [] for algorithm in self.algorithms: mean_best_fitness = [] std_best_fitness = [] mean_mean_fitness = [] std_mean_fitness = [] for i in self.enemies: best_fitness_list = [] mean_fitness_list = [] for j in range(1,11): final_fitness_list = self.get_last_generation_data(algorithm, i, j) best_fitness_list.append(max(final_fitness_list)) mean_fitness_list.append(np.mean(final_fitness_list)) mean_best_fitness.append(np.mean(best_fitness_list)) std_best_fitness.append(np.std(best_fitness_list)) mean_mean_fitness.append(np.mean(mean_fitness_list)) std_mean_fitness.append(np.std(mean_fitness_list)) print('the mean best fitness of algorithm %s for enemy %s is %f' % (algorithm,i,np.mean(best_fitness_list))) all_evals.append(mean_best_fitness) all_evals.append(std_best_fitness) all_evals.append(mean_mean_fitness) all_evals.append(std_mean_fitness) #figure(figsize=(2, 3)) cheat_solution = -.3 for i, algorithm in enumerate(self.algorithms): df = pd.DataFrame({ "enemy": str(self.enemies), "algorithm": algorithm, "best":all_evals[i*4], "sd":all_evals[i*4+1]}) #print(df['enemy']+.1) print(all_evals[i*2]) plt.errorbar(df['enemy']+cheat_solution, df['best'], yerr=df['sd'], ls='None', marker='o', label=algorithm) cheat_solution += .3 ax = plt.gca() ax.xaxis.set_ticks(self.enemies) plt.xlabel("enemy") plt.ylabel("best fitness") plt.legend() plt.savefig(os.path.join(os.path.dirname(__file__), "../combined_plots/algorithms_best.png")) plt.show() #figure(figsize=(2, 3)) cheat_solution = -.3 for i, algorithm in enumerate(self.algorithms): df = pd.DataFrame({ "enemy": self.enemies, "algorithm": algorithm, "mean":all_evals[i*4+2], "sd":all_evals[i*4+3]}) plt.errorbar(df['enemy']+cheat_solution, df['mean'], yerr=df['sd'], ls='None', marker='o', label=algorithm) cheat_solution += .3 ax = plt.gca() ax.xaxis.set_ticks(self.enemies) plt.xlabel("enemy") plt.ylabel("mean fitness") plt.legend() plt.savefig(os.path.join(os.path.dirname(__file__), "../combined_plots/algorithms_mean.png")) plt.show() def get_all_data(self, algorithm, enemy, trial): if algorithm=='Island': fitness_record = pickle.load(open(os.path.join(os.path.dirname(__file__), "../{}_{}_{}/all_fitnesses.pkl".format(algorithm, enemy, trial)), "rb")) final_fitness_list = [[k[0] for k in fitness_row] for fitness_row in fitness_record] else: final_fitness_list = pickle.load(open(os.path.join(os.path.dirname(__file__), "../{}_{}_{}/all_fitnesses.pkl".format(algorithm, enemy, trial)), "rb")) return final_fitness_list def get_last_generation_data(self, algorithm, enemy, trial): if algorithm=='Island': fitness_record = pickle.load(open(os.path.join(os.path.dirname(__file__), "../{}_{}_{}/all_fitnesses.pkl".format(algorithm, enemy, trial)), "rb")) final_fitness_list = [k[0] for k in fitness_record[-1]] else: final_fitness_list = pickle.load(open(os.path.join(os.path.dirname(__file__), "../{}_{}_{}/all_fitnesses.pkl".format(algorithm, enemy, trial)), "rb"))[-1] return final_fitness_list def generate_combined_fitness_plots(self): algorithm_colors = sns.color_palette()[:3] for enemy in self.enemies: for algorithm, algorithm_color in zip(self.algorithms, algorithm_colors): combined_data = [] for generation in range(1, 51): combined_data.append([]) for trial in range(1, 11): trial_data = self.get_all_data(algorithm, enemy, trial) for i, generation in enumerate(trial_data): if algorithm=='Island': if i%3==0: combined_data[i//3] += [g for g in generation] else: if i < 50: combined_data[i] += generation mean_data = [] std_minus_data = [] std_plus_data = [] best_data = [] for generation in combined_data: best_data.append(np.max(generation)) calculated_mean = np.mean(generation) calculated_std = np.std(generation) mean_data.append(calculated_mean) std_minus_data.append(calculated_mean - calculated_std) std_plus_data.append(calculated_mean + calculated_std) print('best_data=',best_data) plt.plot(mean_data, label=algorithm) plt.plot(std_minus_data, linestyle='--', color=algorithm_color) plt.plot(std_plus_data, linestyle='--', color=algorithm_color) plt.plot(best_data, linestyle=':', color=algorithm_color) plt.legend() plt.xlabel('Fitness evaluation') plt.ylabel('Fitness score') plt.savefig(os.path.join(os.path.dirname(__file__), "../combined_plots/enemy_{}.png".format(enemy))) plt.close()
Java
UTF-8
1,789
1.789063
2
[]
no_license
package br.edu.GEP.Domain.Commands.CronogramaCommand.Inputs; import br.edu.GEP.Domain.Commands.BaseCommand; import br.edu.GEP.Domain.Entity.GEP_CRONOGRAMA; import br.edu.GEP.Domain.Entity.GEP_STATUS; import br.edu.GEP.Domain.Entity.UsuarioEntity; import lombok.Data; import java.util.Date; @Data public class AtualizarCronogramaCommand implements BaseCommand { public GEP_CRONOGRAMA GEP_CRONOGRAMA; public GEP_STATUS GEP_STATUS; public UsuarioEntity liderUser; private String NOME; public String ORIGEM; public String DESCRICAO; public Date DT_INICIO_PREV; public Date DT_FIM_PREV; public Date DT_INICIO; public Date DT_FIM; @Override public void configuration() { this.GEP_CRONOGRAMA.setNOME(this.NOME == null ? this.GEP_CRONOGRAMA.getNOME() : this.NOME); this.GEP_CRONOGRAMA.setORIGEM(this.ORIGEM == null ? this.GEP_CRONOGRAMA.getORIGEM() : this.ORIGEM); this.GEP_CRONOGRAMA.setLIDER(this.liderUser == null ? this.GEP_CRONOGRAMA.getLIDER() : this.liderUser); this.GEP_CRONOGRAMA.setDESCRICAO(this.DESCRICAO == null ? this.GEP_CRONOGRAMA.getDESCRICAO() : this.DESCRICAO); this.GEP_CRONOGRAMA.setGEP_STATUS(this.GEP_STATUS == null ? this.GEP_CRONOGRAMA.getGEP_STATUS() : this.GEP_STATUS); this.GEP_CRONOGRAMA.setDT_INICIO_PREV(this.DT_INICIO_PREV == null ? this.GEP_CRONOGRAMA.getDT_INICIO_PREV() : this.DT_INICIO_PREV); this.GEP_CRONOGRAMA.setDT_FIM_PREV(this.DT_FIM_PREV == null ? this.GEP_CRONOGRAMA.getDT_FIM_PREV() : this.DT_FIM_PREV); this.GEP_CRONOGRAMA.setDT_INICIO(this.DT_INICIO == null ? this.GEP_CRONOGRAMA.getDT_INICIO() : this.DT_INICIO); this.GEP_CRONOGRAMA.setDT_FIM(this.DT_FIM == null ? this.GEP_CRONOGRAMA.getDT_FIM() : this.DT_FIM); } }
PHP
UTF-8
3,810
2.5625
3
[]
no_license
<?php namespace Application\Controller; use Zend\View\Model\ViewModel; use Core\Controller\ActionController; use Application\Model\Setor; use Application\Form\Setor as SetorForm; use Doctrine\ORM\EntityManager; /** * Controlador que gerencia o cadastro de Setores * * @category Application * @package Controller * @author William Gerenutti <williamgerenuttidm@gmail.com> * */ class SetorController extends ActionController { /** * * @var Doctrine\ORM\EntityManager */ protected $em; public function setEntityManager(EntityManager $em) { $this->em = $em; } public function getEntityManager() { if (null === $this->em) { $this->em = $this->getServiceLocator ()->get ( 'doctrine.entitymanager.orm_default' ); } return $this->em; } /** * Mostra os Setores cadastrados * * @return void */ public function indexAction() { $setores = $this->getEntityManager ()->getRepository ( "Application\Model\Setor" )->findAll ( array (), array ( 'nome' => 'ASC' ) ); // adiciona o arquivo jquery.dataTable.min.js // ao head da p�gina $renderer = $this->getServiceLocator ()->get ( 'Zend\View\Renderer\PhpRenderer' ); $renderer->headScript ()->appendFile ( '/js/jquery.dataTables.min.js' ); return new ViewModel ( array ( 'setores' => $setores ) ); } /** * Cria ou edita um Setor * * @return void */ public function saveAction() { $form = new SetorForm ( $this->getEntityManager () ); $request = $this->getRequest (); // Hidratar classe $form->setHydrator ( new \Zend\Stdlib\Hydrator\ClassMethods ( false ) ); if ($request->isPost ()) { $setor = new Setor (); $form->setInputFilter ( $setor->getInputFilter () ); $form->setData ( $request->getPost () ); if ($form->isValid ()) { $data = $form->getData (); unset ( $data ['submit'] ); $matricula = $this->params ()->fromPost ( "gerente" ); $participantes = $this->params ()->fromPost ( 'participantes' ); if (isset ( $data ['id'] ) && $data ['id'] > 0) { $setor = $this->getEntityManager ()->find ( 'Application\Model\Setor', $data ['id'] ); } $setor->getParticipantes ()->clear (); foreach ( $participantes as $participanteId ) { $participante = $this->getEntityManager ()->find ( "Application\Model\Empregado", $participanteId ); $setor->getParticipantes ()->add ( $participante ); } $gerente = $this->getEntityManager ()->find ( 'Application\Model\Empregado', $matricula ); unset ( $data ['gerente'] ); $setor->setData ( $data ); $setor->setGerente ( $gerente ); $this->getEntityManager ()->persist ( $setor ); $this->getEntityManager ()->flush (); return $this->redirect ()->toUrl ( '/application/setor' ); } } $id = ( int ) $this->params ()->fromRoute ( 'id', 0 ); if ($id > 0) { $setor = $this->getEntityManager ()->find ( 'Application\Model\Setor', $id ); $form->bind ( $setor ); $form->get ( 'submit' )->setAttribute ( 'value', 'Edit' ); $empregados = $setor->getParticipantes(); } $renderer = $this->getServiceLocator ()->get ( 'Zend\View\Renderer\PhpRenderer' ); $renderer->headScript ()->appendFile ( '/js/jquery.dataTables.min.js' ); $renderer->headScript ()->appendFile ( '/js/setor.js' ); return new ViewModel ( array ( 'form' => $form, 'empregados' => $empregados ) ); } /** * Exclui um Setor * * @return void */ public function deleteAction() { $id = ( int ) $this->params ()->fromRoute ( 'id', 0 ); if ($id == 0) { throw new \ErrorException ( "C�digo obrigat�rio" ); } $setor = $this->getEntityManager ()->find ( 'Application\Model\Setor', $id ); if ($setor) { $this->getEntityManager ()->remove ( $setor ); $this->getEntityManager ()->flush (); } return $this->redirect ()->toUrl ( '/application/setor' ); } }
Java
UTF-8
2,984
3.0625
3
[]
no_license
package geometries; import primitives.Color; import primitives.Point3D; import primitives.Ray; import primitives.Vector; import java.util.ArrayList; import java.util.List; public class Box extends Geometry { private List<Square> squares = new ArrayList<>(); public Box(Color emission, int Shininess, double Kd, double Ks, double Kr, double Kt, Point3D p1, Vector v1, Vector v2, double length) { super(emission, Shininess, Kd, Ks, Kr, Kt); if (v1.dotProduct(v2) != 0) throw new IllegalArgumentException("Vectors must be orthogonal"); v1 = v1.normalize(); v2 = v2.normalize(); Vector v3 = v1.crossProduct(v2); squares.add(new Square(emission, get_material(), p1, v1, v2, length)); squares.add(new Square(emission, get_material(), p1, v1, v3, length)); squares.add(new Square(emission, get_material(), p1, v2, v3, length)); Point3D p2 = p1.add(v1.scale(length)); squares.add(new Square(emission, get_material(), p2, v2, v3, length)); p2 = p1.add(v2.scale(length)); squares.add(new Square(emission, get_material(), p2, v1, v3, length)); p2 = p1.add(v3.scale(length)); squares.add(new Square(emission, get_material(), p2, v1, v2, length)); } @Override public Vector getNormal(Point3D p) { return null; } @Override public List<GeoPoint> findIntersections(Ray myRay) { List<GeoPoint> intersectionPoints = new ArrayList<>(); for (Square s : squares) { List<GeoPoint> tempList = s.findIntersections(myRay); if (tempList != null) intersectionPoints.addAll(tempList); } return intersectionPoints.isEmpty() ? null : intersectionPoints; } @Override public double getMaxX() { double max = squares.get(0).getMaxX(); for (Square s : squares) max = Double.max(max, s.getMaxX()); return max; } @Override public double getMinX() { double min = squares.get(0).getMinX(); for (Square s : squares) min = Double.min(min, s.getMinX()); return min; } @Override public double getMaxY() { double max = squares.get(0).getMaxY(); for (Square s : squares) max = Double.max(max, s.getMaxY()); return max; } @Override public double getMinY() { double min = squares.get(0).getMinY(); for (Square s : squares) min = Double.min(min, s.getMinY()); return min; } @Override public double getMaxZ() { double max = squares.get(0).getMaxZ(); for (Square s : squares) max = Double.max(max, s.getMaxZ()); return max; } @Override public double getMinZ() { double min = squares.get(0).getMinZ(); for (Square s : squares) min = Double.min(min, s.getMinZ()); return min; } }
JavaScript
UTF-8
1,197
2.8125
3
[]
no_license
import {fromJS} from 'immutable'; import * as constants from './constants'; //state的状态是不可以被改变的,为了避免他被改变 //在初始化state的时候就把它创建为immutable的对象 const defaultState=fromJS({ topicList:[], articleList:[], recommendList:[], articlePage: 1, showScroll: false }); const changeHomeData = (state, action) =>{ return state.merge({ topicList: fromJS(action.topicList), articleList:fromJS(action.articleList), recommendList:fromJS(action.recommendList) }) } const addArticleList = ( state, action ) => { return state.merge ({ 'articleList': state.get('articleList').concat(action.list), 'articlePage':action.nextPage }) } const reducer = (state=defaultState,action)=>{ switch(action.type){ case constants.CHANGE_HOME_DATA: return changeHomeData(state, action); case constants.ADD_ARTICLE_LIST: return addArticleList( state, action); case constants.TOGGLE_SCROLL_SHOW: return state.set('showScroll', action.show); default: return state; } } export default reducer;
Markdown
UTF-8
3,538
2.90625
3
[ "CC-BY-SA-4.0", "Apache-2.0" ]
permissive
[#]: subject: "sssnake – A Super Addictive Snake Game for Linux Terminal" [#]: via: "https://www.debugpoint.com/sssnake-game-linux/" [#]: author: "Arindam https://www.debugpoint.com/author/admin1/" [#]: collector: "lkxed" [#]: translator: " " [#]: reviewer: " " [#]: publisher: " " [#]: url: " " sssnake – A Super Addictive Snake Game for Linux Terminal ====== Try out this fun sssnake game in your Linux terminal. Spending too much time on Linux, in general can be counter-productive. Our brain is not designed to work continuously. That’s why you need some activities to free up your mind. Some take walks, have coffee breaks, and go for a drive. But for some who can’t leave the desktop – there are very few choices to relax. Here’s a classic snake game which only requires a terminal for you. Whil;e it may not be the ultimate solution, but hey, give it a try. ### sssnake game for Linux terminal The sssnaks is one of variant of [classic snake game][1]. The classic snake game is famous since the Nokia 3300 device, before the smartphone revolution. This game requires the ncurses-devel package for compilation from Git. So, fire up a terminal and run the following command to install the ncurses. * Ubuntu Linux and other similar distros: ``` sudo apt install git libncurses-dev ``` * For Fedora and related distros: ``` sudo dnf install git ncurses-devel ``` * Arch folks, use this: ``` sudo pacman -S ncurses ``` After installation, clone the [official Git repo][2] and compile. ``` git clone https://github.com/AngelJumbo/sssnake.gitcd sssnakemakesudo make install ``` ![Installing sssnake game in Linux (Fedora)][3] That’s it. It’s now time to play the game. ### Playing the sssnake game in Linux Since it’s a terminal-based game, run the below command to verify whether it got installed. It outputs the help and instructions (if you want to read them). ``` sssnake -h ``` Alright, its time to play. Run the following to start the game normally. You can steer the snake head with keys – WASD or HJKL from the keyboard. sssnake * You can use the option `-a` for autoplay mode. It can play itself, and you can watch it. * Use the option `-S` for set it as screensaver. * Control the speed using `-s` and followed by number for speed. * And add random blocks for difficult with option `-j`. ![sssnake game in terminal in Fedora Linux][4] Ready? Here are some commands for you to try. * Use this for standard speed. ``` sssnake -s 13 ``` * The following command gives you some blocks to avoid. ``` sssnake -a -s 13 -j 5 ``` * And finally, run this and see the computer plays for you. ``` sssnake -a -s 13 -j 5 ``` * You can combine above commands as per your comfort and difficulty level. Cheers. -------------------------------------------------------------------------------- via: https://www.debugpoint.com/sssnake-game-linux/ 作者:[Arindam][a] 选题:[lkxed][b] 译者:[译者ID](https://github.com/译者ID) 校对:[校对者ID](https://github.com/校对者ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 [a]: https://www.debugpoint.com/author/admin1/ [b]: https://github.com/lkxed [1]: https://www.debugpoint.com/tag/snake-game [2]: https://github.com/AngelJumbo/sssnake [3]: https://www.debugpoint.com/wp-content/uploads/2022/08/Installing-sssnake-game-in-Linux-Fedora.jpg [4]: https://www.debugpoint.com/wp-content/uploads/2022/08/sssnake-game-in-terminal-in-Fedora-Linux-1.jpg
Markdown
UTF-8
4,800
3.078125
3
[ "MIT" ]
permissive
--- layout: page weight: 400 title: Multi User Credentials navigation: show: true --- Multi User Credentials allow you to have multiple people who can log into the same subuser account, using a different username and password. This way, you don't have to worry if someone goes out of town and you can control who has access to the account. {% anchor h2 %} Get All Subuser Multiple Credentials {% endanchor %} GET a new subuser credential. {% parameters get %} {% parameter task Yes 'Must be set to <code>get</code>' 'Task to get all subuser credentials' %} {% parameter user Yes 'The subuser name' 'The subuser whose multi cred users you are looking for' %} {% endparameters %} {% apiexample get POST https://api.sendgrid.com/apiv2/customer.credential api_user=apikey&api_key=your_sendgrid_password&task=get&user=subuser_name %} {% response json %} [ {"id":12345,"name":"subuser_cred_1","permissions":{"web":1,"api":0,"mail":1}}, {"id":67890,"name":"subuser_cred_2","permissions":{"mail":1,"api":1,"web":1}} ] {% endresponse %} {% response xml %} <result> <credential> <id>12345</id> <name>subuser_cred_1</name> <permissions> <permission> <web>1</web> <api>0</api> <mail>1</mail> </permission> </permissions> </credential> <credential> <id>67890</id> <name>subuser_cred_2</name> <permissions> <permission> <web>1</web> <api>1</api> <mail>1</mail> </permission> </permissions> </credential> </result> {% endresponse %} {% endapiexample %} * * * * * {% anchor h2 %} Add a Subuser Multiple Credential {% endanchor %} Create a new subuser credential. {% parameters add %} {% parameter task Yes 'Must be set to <code>add</code>' 'Task to create a subuser credential' %} {% parameter user Yes 'The subuser name' 'The subuser whose multi cred users you are looking for' %} {% parameter credential_name Yes 'The new user name, unique for your account' 'The subuser whose multi cred users you are looking for' %} {% parameter credential_password Yes 'The password for your credential. See the [SendGrid password requirements]({{root_url}}{{site.password_requirements}})' 'The password for your subuser credential' %} {% endparameters %} {% apiexample add POST https://api.sendgrid.com/apiv2/customer.credential api_user=apikey&api_key=your_sendgrid_password&task=create&user=subuser_name&credential=new_user_name&credential_password=new_credential_password %} {% response json %} { "message" : "success" } {% endresponse %} {% response xml %} <result> <message>success</message> </result> {% endresponse %} {% endapiexample %} * * * * * {% anchor h2 %} Edit Subuser Multiple Credential {% endanchor %} Edit a subuser credential. {% parameters edit %} {% parameter task Yes 'Must be set to <code>edit</code>' 'Task to edit a subuser credential' %} {% parameter user Yes 'The subuser name' 'The subuser whose multi cred users you are looking for' %} {% parameter credential_name Yes 'The credential name' 'The current name of the credential' %} {% parameter new_credential_password Yes 'The password for your credential. See the [SendGrid password requirements]({{root_url}}{{site.password_requirements}})' 'The password for your subuser credential' %} {% endparameters %} {% apiexample edit POST https://api.sendgrid.com/apiv2/customer.credential api_user=apikey&api_key=your_sendgrid_password&task=edit&user=subuser_name&credential_name=credential_name&new_credential_password=credential_password %} {% response json %} { "message" : "success" } {% endresponse %} {% response xml %} <result> <message>success</message> </result> {% endresponse %} {% endapiexample %} * * * * * {% anchor h2 %} Delete Subuser Multiple Credential {% endanchor %} Delete a subuser credential. {% parameters delete %} {% parameter task Yes 'Must be set to <code>delete</code>' 'Task to delete a subuser credential' %} {% parameter user Yes 'The subuser name' 'The subuser whose multi cred users you are looking for' %} {% parameter credential_name Yes 'The credential name' 'The current name of the credential' %} {% endparameters %} {% apiexample delete POST https://api.sendgrid.com/apiv2/customer.credential api_user=apikey&api_key=your_sendgrid_password&task=delete&user=subuser_name&credential_name=credential_name %} {% response json %} { "message" : "success" } {% endresponse %} {% response xml %} <result> <message>success</message> </result> {% endresponse %} {% endapiexample %}
Python
UTF-8
17,895
2.609375
3
[]
no_license
# Anthony Kuntz # Kayle Damage and Build Calculator, with UI # Returns the DPS of a specific build given certain limitations and stats def calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList): mana = 322.2 + 40 * level AP = 6 + 0.89 * level CDR = 5 flatPen = 0 perPen = 12 + 6 critChance = 0 flatArmorPen = 0 perArmorPen = 12 + 6 AD = 56.004 + 2.8 * level AS = 0.638 * 1.022**level * 1.025 if runesList != None: AP += int(runesList[0]) if runesList[0] != "" else 0 CDR += int(runesList[1]) if runesList[1] != "" else 0 flatPen += int(runesList[2]) if runesList[2] != "" else 0 perPen += int(runesList[3]) if runesList[3] != "" else 0 flatArmorPen += int(runesList[4]) if runesList[4] != "" else 0 perArmorPen += int(runesList[5]) if runesList[5] != "" else 0 AS *= ( 1 + int(runesList[6]) / 100.0) if runesList[6] != "" else 1 AD += int(runesList[7]) if runesList[7] != "" else 0 masteryAP = 1.05 arcaneBlade = .05 for item in itemList: try: AD += item["AD"] except: pass try: critChance += item["Crit"] except: pass try: AS *= (1 + item["AS"] / 100.0) except: pass try: AP += item["AP"] except: pass try: CDR += item["CDR"] except: pass try: mana += item["mana"] except: pass try: flatPen += item["mPen"] if item["Name"] == "Sorcs" else 0 except: pass # Tries included incase stat is not in the dictionary if CDR < neededCDR: return 0 if liandries in itemList: flatPen += 15 if voidstaff in itemList: perPen += 35 if lw in itemList: perArmorPen += 35 if bc in itemList: perArmorPen += 15 if youmuu in itemList: flatArmorPen += 20 # Unique passives applied as such so that they don't double count AP *= masteryAP if deathcap in itemList: AP *= 1.35 if aaa in itemList: AP += mana * .03 eDmg = 20 if level > 3: eDmg = 30 if level > 4: eDmg = 40 if level > 6: eDmg = 50 if level > 8: eDmg = 60 # Damage of Kayle's E assuming it is maxed first eDmg += AP * .30 hasIE = ie in itemList critFactor = 2 + .5 * (hasIE) critChance /= 100.0 if critChance > 1: critChance = 1 if AS > 2.5: AS = 2.5 # Stat caps pureAD = ((AD * critFactor * critChance) + (AD * (1 - critChance))) * AS purePhysOnHitDmg = enemyHP * .04 if botrk in itemList else 0 pureMagOnHitDmg = 42 if witsend in itemList else 0 pureMagOnHitDmg += 60 if devourer in itemList else 0 pureMagOnHitDmg += eDmg pureMagOnHitDmg += (15 + AP * 0.15) if nashors in itemList else 0 pureMagOnHitDmg *= 1.5 if devourer in itemList else 1 totalPureAD = pureAD + purePhysOnHitDmg * AS totalPureAP = ( pureMagOnHitDmg + (AP * arcaneBlade)) * AS enemyMR -= enemyMR * ( perPen / 100.0 ) enemyMR -= flatPen enemyMR -= 15 if witsend in itemList else 0 if enemyMR < 0: enemyMR = 0 enemyArmor -= enemyArmor * ( perArmorPen / 100.0 ) enemyArmor -= flatArmorPen if enemyArmor < 0: enemyArmor = 0 redAD = round( totalPureAD * ( 100.0 / (100 + enemyArmor)) , 2 ) redAP = round( totalPureAP * ( 100.0 / (100 + enemyMR)) , 2 ) dps = redAP + redAD return dps # Dictionaries for the stats of every item added thus far voidstaff = { "AP" : 80, "CDR" : 0, "mana" : 0, "mPen" : 35.0, "MS" : 0, "Name" : "Void Staff"} abyssal = { "AP" : 70, "CDR" : 0, "mana" : 0, "mPen" : 20, "MS" : 0, "Name" : "Abyssal"} liandries = { "AP" : 80, "CDR" : 0, "mana" : 0, "mPen" : 15, "MS" : 0, "Name" : "Liandries"} ludens = { "AP" : 100, "CDR" : 0, "mana" : 0, "mPen" : 0, "MS" : 10.0, "Name" : "Ludens"} deathcap = { "AP" : 120, "CDR" : 0, "mana" : 0, "mPen" : 0, "MS" : 0, "Name" : "Deathcap"} roa = { "AP" : 100, "CDR" : 0, "mana" : 800, "mPen" : 0, "MS" : 0, "Name" : "ROA"} athenes = { "AP" : 60, "CDR" : 20, "mana" : 0, "mPen" : 0, "MS" : 0, "Name" : "Athenes"} lichbane = { "AP" : 80, "CDR" : 0, "mana" : 250, "mPen" : 0, "MS" : 5.0, "Name" : "Lich Bane"} nashors = { "AP" : 80, "CDR" : 20, "mana" : 0, "mPen" : 0, "MS" : 0, "Name" : "Nashors"} wota = { "AP" : 80, "CDR" : 10, "mana" : 0, "mPen" : 0, "MS" : 0, "Name" : "WOTA"} twinshadows = { "AP" :80 , "CDR" : 10, "mana" : 0, "mPen" : 0, "MS" : 6.0, "Name" : "Twin Shadows"} morello = { "AP" : 80, "CDR" : 20, "mana" : 0, "mPen" : 0, "MS" : 0, "Name" : "Morello"} aaa = { "AP" : 80, "CDR" : 0, "mana" : 1000, "mPen" : 0, "MS" : 0, "Name" : "AAA"} zhonyas = { "AP" : 100, "CDR" : 0, "mana" : 0, "mPen" : 0, "MS" : 0, "Name" : "Zhonyas"} sorcs = { "AP" : 0, "CDR" : 0, "mana" : 0, "mPen" : 15, "MS" : 45, "Name" : "Sorcs"} zerks = { "AS" : 25, "MS" : 45, "Bonus" : ["Better Hops"] , "Name" : "Zerks"} ie = { "AD" : 80, "Crit" : 20, "Bonus" : ["ieCrits"], "Name" : "IE"} botrk = { "AD" : 25, "AS" : 40, "LS" : 10, "Bonus" : ["botrkDmg", "botrkActive"], "Name" : "BotRK"} pd = { "AS" : 50, "Crit" : 35, "MS" : 5.0, "Bonus" : ["moveThrough"], "Name" : "PD"} shiv = { "AS" : 40, "Crit" : 20, "MS" : 6.0, "Bonus" : ["shivDmg"], "Name" : "Shiv"} youmuu = { "AD" : 30, "Crit" : 15, "aPen" : 20, "Bonus" : ["youmuuActive"], "Name" : "Youmuus"} hurricane = { "AS" : 70, "Bonus" : ["bolts"], "Name" : "Hurricane"} lw = { "AD" : 40, "aPen" : 35.0, "Name" : "LW"} frozMal = { "AD" : 30, "Bonus" : ["Slow"], "Name" : "Frozen Mallet"} mercScim = { "AD" : 80, "Bonus" : ["QSS"], "Name" : "Merc Scimitar"} witsend = {"AS" : 50, "Name" : "Wits End"} devourer = {"AS" : 50, "Name" : "Sated Devourer"} essreav = {"AD" : 80, "CDR" : 10, "Name" : "Essence Reaver"} bc = {"AD" : 40, "CDR" : 10, "Name" : "BC"} # Brute forces every possible build, returning the build with the highest DPS def bestKayle(requiredItems, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList): # Only viable items were included below allItems = [voidstaff, abyssal, liandries, deathcap, nashors, aaa, ie, botrk, pd, youmuu, hurricane, lw, witsend, devourer, bc] bestBuild = [] bestDmg = 0 if numberOfItems == 6: for a in allItems: for b in allItems: for c in allItems: for d in allItems: for e in allItems: for f in allItems: flag = True itemList = [a, b, c, d, e, f] for item in requiredItems: if item not in itemList: flag = False if flag == False: continue dmg = calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList) if dmg > bestDmg: bestDmg = dmg bestBuild = itemList elif numberOfItems == 5: for a in allItems: for b in allItems: for c in allItems: for d in allItems: for e in allItems: flag = True itemList = [a, b, c, d, e] for item in requiredItems: if item not in itemList: flag = False if flag == False: continue dmg = calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList) if dmg > bestDmg: bestDmg = dmg bestBuild = itemList elif numberOfItems == 4: for a in allItems: for b in allItems: for c in allItems: for d in allItems: flag = True itemList = [a, b, c, d] for item in requiredItems: if item not in itemList: flag = False if flag == False: continue dmg = calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList) if dmg > bestDmg: bestDmg = dmg bestBuild = itemList elif numberOfItems == 3: for a in allItems: for b in allItems: for c in allItems: flag = True itemList = [a, b, c] for item in requiredItems: if item not in itemList: flag = False if flag == False: continue dmg = calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList) if dmg > bestDmg: bestDmg = dmg bestBuild = itemList elif numberOfItems == 2: for a in allItems: for b in allItems: flag = True itemList = [a, b] for item in requiredItems: if item not in itemList: flag = False if flag == False: continue dmg = calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList) if dmg > bestDmg: bestDmg = dmg bestBuild = itemList elif numberOfItems == 1: for a in allItems: flag = True itemList = [a] for item in requiredItems: if item not in itemList: flag = False if flag == False: continue dmg = calculateKayle(itemList, level, neededCDR, enemyMR, enemyArmor, enemyHP, numberOfItems, runesList) if dmg > bestDmg: bestDmg = dmg bestBuild = itemList return bestBuild, bestDmg from Tkinter import * import tkMessageBox import tkSimpleDialog import os # Buttons for Stats class MyDialog2(tkSimpleDialog.Dialog): def body(self, master): canvas.modalResult = None Label(master, text="Level:").grid(row=0) Label(master, text="Required CDR:").grid(row=1) Label(master, text="Enemy Armor:").grid(row=2) Label(master, text="Enemy MR:").grid(row=3) Label(master, text="Enemy HP").grid(row=4) Label(master, text="Number of Items:").grid(row=5) self.e1 = Entry(master) self.e2 = Entry(master) self.e3 = Entry(master) self.e4 = Entry(master) self.e5 = Entry(master) self.e6 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e3.grid(row=2, column=1) self.e4.grid(row=3, column=1) self.e5.grid(row=4, column=1) self.e6.grid(row=5, column=1) return self.e1 # initial focus def apply(self): first = self.e1.get() second = self.e2.get() third = self.e3.get() fourth = self.e4.get() fifth = self.e5.get() sixth = self.e6.get() global canvas canvas.modalResult2 = (first, second, third, fourth, fifth, sixth) # Buttons for required items class MyDialog(tkSimpleDialog.Dialog): def body(self, master): canvas.modalResult = None Label(master, text="Required Item:").grid(row=0) Label(master, text="Required Item:").grid(row=1) Label(master, text="Required Item:").grid(row=2) Label(master, text="Required Item:").grid(row=3) Label(master, text="Required Item:").grid(row=4) self.e1 = Entry(master) self.e2 = Entry(master) self.e3 = Entry(master) self.e4 = Entry(master) self.e5 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e3.grid(row=2, column=1) self.e4.grid(row=3, column=1) self.e5.grid(row=4, column=1) return self.e1 # initial focus def apply(self): first = self.e1.get() second = self.e2.get() third = self.e3.get() fourth = self.e4.get() fifth = self.e5.get() global canvas canvas.modalResult = (first, second, third, fourth, fifth) # Buttons for Runes class MyDialog3(tkSimpleDialog.Dialog): def body(self, master): canvas.modalResult = None Label(master, text="AP from Runes:").grid(row=0) Label(master, text="CDR from Runes:").grid(row=1) Label(master, text="Flat Magic Pen from Runes:").grid(row=2) Label(master, text="Percent Magic Pen from Runes:").grid(row=3) Label(master, text="Flat Armor Pen from Runes:").grid(row=4) Label(master, text="Percent Armor Pen from Runes:").grid(row=5) Label(master, text="AS from Runes:").grid(row=6) Label(master, text="AD from Runes:").grid(row=7) self.e1 = Entry(master) self.e2 = Entry(master) self.e3 = Entry(master) self.e4 = Entry(master) self.e5 = Entry(master) self.e6 = Entry(master) self.e7 = Entry(master) self.e8 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.e3.grid(row=2, column=1) self.e4.grid(row=3, column=1) self.e5.grid(row=4, column=1) self.e6.grid(row=5, column=1) self.e7.grid(row=6, column=1) self.e8.grid(row=7, column=1) return self.e1 # initial focus def apply(self): first = self.e1.get() second = self.e2.get() third = self.e3.get() fourth = self.e4.get() fifth = self.e5.get() sixth = self.e6.get() seventh = self.e7.get() eight = self.e8.get() global canvas canvas.modalResult3 = (first, second, third, fourth, fifth, sixth, seventh, eight) def showDialog3(canvas): MyDialog3(canvas) return canvas.modalResult3 def showDialog(canvas): MyDialog(canvas) return canvas.modalResult def button1Pressed(): global canvas message = str(showDialog(canvas)) # And update and redraw our canvas canvas.message = message if canvas.message == "('', '', '', '', '')": canvas.message = "None" canvas.create_text(10, 175, text = "Required Items: " + canvas.message, fill = "white", anchor = W) def buttonRunesPressed(): global canvas canvas.runes = str(showDialog3(canvas)) def button0Pressed(): global canvas canvas.stats = str(showDialog2(canvas)) def showDialog2(canvas): MyDialog2(canvas) return canvas.modalResult2 def button2Pressed(): # When the Calculate button is pressed, the following runs global canvas requiredItems = [] if canvas.runes != None: # edit the list-formatted string into something readable canvas.runes = canvas.runes[1:-2] canvas.runes = canvas.runes.replace("'", "") canvas.runesList = canvas.runes.split(", ") if canvas.stats != None: # edit the list-formatted string into something readable canvas.stats = canvas.stats[1:-2] canvas.stats = canvas.stats.replace("'", "") canvas.statsList = canvas.stats.split(", ") # edit the list-formatted string into something readable canvas.message = canvas.message[1:-2] canvas.message = canvas.message.replace("'", "") canvas.list = canvas.message.split(", ") for itemName in canvas.list: # Include all required items for item in canvas.allItems: if item["Name"] == itemName: requiredItems.append(item) # Use provided stats if provided, otherwise use defaults try: level = int(canvas.statsList[0]) except: level = 18 try: neededCDR = int(canvas.statsList[1]) except: neededCDR = 0 try: enemyArmor = int(canvas.statsList[2]) except: enemyArmor = 100 try: enemyMR = int(canvas.statsList[3]) except: enemyMR = 70 try: enemyHP = int(canvas.statsList[4]) except: enemyHP = 2000 try: numItems = int(canvas.statsList[5]) except: numItems = 6 # Find the best build and its actual DPS build, dmg = bestKayle(requiredItems, level, neededCDR, enemyMR, enemyArmor, enemyHP, numItems, canvas.runesList) print build x = 30 try: canvas.p1 = PhotoImage( file = "Pictures" + os.sep + build[0]["Name"] + ".gif") canvas.create_image(x, 265, image = canvas.p1, anchor = W) except: pass x += 75 try: canvas.p2 = PhotoImage( file = "Pictures" + os.sep + build[1]["Name"] + ".gif") canvas.create_image(x, 265, image = canvas.p2, anchor = W) except: pass x += 75 try: canvas.p3 = PhotoImage( file = "Pictures" + os.sep + build[2]["Name"] + ".gif") canvas.create_image(x, 265, image = canvas.p3, anchor = W) except: pass x += 75 try: canvas.p4 = PhotoImage( file = "Pictures" + os.sep + build[3]["Name"] + ".gif") canvas.create_image(x, 265, image = canvas.p4, anchor = W) except: pass x += 75 try: canvas.p5 = PhotoImage( file = "Pictures" + os.sep + build[4]["Name"] + ".gif") canvas.create_image(x, 265, image = canvas.p5, anchor = W) except: pass x += 75 try: canvas.p6 = PhotoImage( file = "Pictures" + os.sep + build[5]["Name"] + ".gif") canvas.create_image(x, 265, image = canvas.p6, anchor = W) except: pass x += 75 dmg = int(dmg) canvas.create_text(250, 310, text = "DPS: " + str(dmg), fill = "White", font = "Arial 15 bold") # Create the pictures and text for the build returned ^ def init(root, canvas): # Starts or restarts everything initPix(canvas) canvas.stats = None canvas.runesList = None canvas.runes = None canvas.message = "None" canvas.allItems = [voidstaff, abyssal, lichbane, liandries, ludens, deathcap, roa, nashors, aaa, sorcs, athenes, zhonyas, zerks, ie, botrk, pd, youmuu, hurricane, lw, witsend, devourer, essreav, witsend, bc] buttonFrame = Frame(root) b1 = Button(buttonFrame, text="Set Required Items", command=button1Pressed) b1.grid(row=0,column=2) b2 = Button(buttonFrame, text="Calculate Build", command=button2Pressed) b2.grid(row=0,column=3) b0 = Button(buttonFrame, text="Set Level and Stats", command=button0Pressed) b0.grid(row=0,column=1) bR = Button(buttonFrame, text="Enter Runes", command= buttonRunesPressed) bR.grid(row=0,column=0) buttonFrame.pack(side=TOP) canvas.pack() def main(): global root root = Tk() global canvas canvas = Canvas(root, width = 500, height = 500, bg = "steel blue") canvas.pack() root.canvas = canvas.canvas = canvas root.bind("<Button-1>", onMousePressed) root.bind("<Key>", onKeyPressed) init(root, canvas) root.mainloop() def onMousePressed(event): if isinstance(event.widget, Button): return canvas = event.widget.canvas def onKeyPressed(event): canvas = event.widget.canvas if event.keysym == "r": canvas.message = "" canvas.stats = "" canvas.delete(ALL) initPix(canvas) def initPix(canvas): # Used to redraw everything on a restart canvas.create_text(10,10, anchor = NW, text = "Welcome to the Kayle Build Calculator! \nEnter info in the buttons below to begin.", fill = "white") canvas.create_text(10,50, anchor = NW, text = "Please be patient when calculating. \nThe calculator can take up to 2 minutes.", fill = "white") canvas.create_text(10,350, anchor = NW, text = "Finally, please realize that spelling matters. \n\nItem names must be spelled as follows: \ \n\nAAA, Abyssal, Athenes, Deathcap, Liandries, Lich Bane, \ \nLudens, Morello, Nashors, ROA, Sorcs, Twin Shadows, Void Staff", fill = "white") canvas.logo = PhotoImage( file = "Pictures" + os.sep + "logo.gif") canvas.create_image(510,-10, anchor = NE, image = canvas.logo) canvas.create_text(490,475, anchor = NE, text = "Press r to restart.", fill = "white") main() # Open and run the UI
Markdown
UTF-8
9,891
3.03125
3
[]
no_license
# 手动写 AIDL 过程 ### 1. bean 文件 aidl 中可传递的类型有基本数据类型,string,list,map 等,但不是所有都可以,对于一些自定义的 bean 需要实现 Parcelable 接口 ``` public class Book implements Parcelable { private int price; private String name; public Book(int price, String name) { this.price = price; this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(price); dest.writeString(name); } // 需要注意顺序,要与 writeToParcel 一致 protected Book(Parcel in) { price = in.readInt(); name = in.readString(); } public static final Creator<Book> CREATOR = new Creator<Book>() { @Override public Book createFromParcel(Parcel in) { return new Book(in); } @Override public Book[] newArray(int size) { return new Book[size]; } }; @Override public String toString() { return "Book{" + "price=" + price + ", name='" + name + '\'' + '}'; } } ``` ### 2. stub 类 这个类运行时已经在 server 端了,是 抽象类,负责调度功能接口。 ``` public abstract class Stub extends Binder implements BookManager { public static final String DESCRIPTOR = "com.xiaocai.messageclient.ipc.server.BookManager"; public static final int TRANSAVTION_getBooks = IBinder.FIRST_CALL_TRANSACTION; public static final int TRANSAVTION_addBook = IBinder.FIRST_CALL_TRANSACTION + 1; public Stub() { attachInterface(this, DESCRIPTOR); } @Override public IBinder asBinder() { return this; } /** * 给 Client 方调用的,用来转换为需要的 Server 对象(在同一进程的情况)或者是其代理对象(跨进程时) * * 当 Client 端在创建和服务端的连接, 调用 bindService 时需要创建一个 ServiceConnection 对象作为入参。 * 在 ServiceConnection 的回调方法 onServiceConnected 中 会通过这个 asInterface(IBinder binder) 拿到 BookManager 对象, * 这个 IBinder 类型的入参 binder 是驱动传给我们的,正如你在代码中看到的一样, * 方法中会去调用 binder.queryLocalInterface() 去查找 Binder 本地对象, * 如果找到了就说明 Client 和 Server 在同一进程,那么这个 binder 本身就是 Binder 本地对象,可以直接使用。 * 否则说明是 binder 是个远程对象,也就是 BinderProxy。因此需要我们创建一个代理对象 Proxy, * 通过这个代理对象来是实现远程访问。 */ public static BookManager asInterface(IBinder binder) { if (binder == null) { return null; } IInterface iInterface = binder.queryLocalInterface(DESCRIPTOR); if (iInterface != null && iInterface instanceof BookManager) { return (BookManager) iInterface; } return new Proxy(binder); } /** * 以 addBook 为例: * Client 端调用 addBook --> binder 代理调用 addBook --> 一系列中间层调用后,找到了 Server 端对应的 Binder 对象 * --> Binder 对象的 transact --> 来到这个 Stub 来的 onTransact,判断了是 addBook 方法 --> 调用具体实现 Server 类的 addBook */ @Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case INTERFACE_TRANSACTION: reply.writeString(DESCRIPTOR); return true; case TRANSAVTION_getBooks: data.enforceInterface(DESCRIPTOR); List<Book> books = this.getBooks(); reply.writeNoException(); reply.writeTypedList(books); return true; case TRANSAVTION_addBook: data.enforceInterface(DESCRIPTOR); Book book = null; if (data.readInt() != 0) { book = Book.CREATOR.createFromParcel(data); } this.addBook(book); reply.writeNoException(); return true; } return super.onTransact(code, data, reply, flags); } } ``` ### 3. 代理类 Proxy 这个类运行时还是在 Client 端,负责跟 Binder 进行对接,掉起 Binder。 ``` public class Proxy implements BookManager { public static final String DESCRIPTOR = "com.xiaocai.messageclient.ipc.server.BookManager"; IBinder mRemote; public Proxy(IBinder binder) { this.mRemote = binder; } public String getInterfaceDescriptor() { return DESCRIPTOR; } @Override public List<Book> getBooks() throws RemoteException { Parcel data = Parcel.obtain(); Parcel replay = Parcel.obtain(); List<Book> result = null; try { data.writeInterfaceToken(DESCRIPTOR); mRemote.transact(Stub.TRANSAVTION_getBooks, data, replay, 0); replay.readException(); result = replay.createTypedArrayList(Book.CREATOR); } finally { data.recycle(); replay.recycle(); } return result; } @Override public void addBook(Book book) throws RemoteException { Parcel data = Parcel.obtain(); Parcel replay = Parcel.obtain(); try { data.writeInterfaceToken(DESCRIPTOR); if (book != null) { data.writeInt(1); book.writeToParcel(data, 0); } else { data.writeInt(0); } mRemote.transact(Stub.TRANSAVTION_addBook, data, replay, 0); replay.readException(); } finally { data.recycle(); replay.recycle(); } } @Override public IBinder asBinder() { return mRemote; } } ``` ### 4. 服务端具体实现 RemoteService 在清单文件中需要 process,让其在另一个进程中运行。在 onBind 中返回 Stub 对象。 ``` public class RemoteService extends Service { private List<Book> mBooks = new ArrayList<>(); { mBooks.add(new Book(100, "深入理解 java")); mBooks.add(new Book(200, "深入理解 android")); mBooks.add(new Book(300, "深入理解 JavaScript")); } public RemoteService() { } @Override public IBinder onBind(Intent intent) { return stub; } private final Stub stub = new Stub() { @Override public List<Book> getBooks() throws RemoteException { synchronized (this) { if (mBooks != null) return mBooks; return new ArrayList<Book>(); } } @Override public void addBook(Book book) throws RemoteException { synchronized (this) { if (book == null) return; if (mBooks == null) { mBooks = new ArrayList<>(); } mBooks.add(book); } } }; } ``` ### 5. 客户端 ClientActivity 正常的 bind 方式使用即可 ``` public class ClientActivity extends AppCompatActivity { BookManager mBookManager; TextView tv_content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_client); tv_content = findViewById(R.id.tv_content); } public void startBookManager(View view) { Intent intent = new Intent(this, RemoteService.class); bindService(intent, conn, Context.BIND_AUTO_CREATE); } ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mBookManager = Stub.asInterface(service); Toast.makeText(ClientActivity.this,"连接上了",Toast.LENGTH_SHORT).show(); } @Override public void onServiceDisconnected(ComponentName name) { mBookManager = null; Toast.makeText(ClientActivity.this,"断开连接",Toast.LENGTH_SHORT).show(); } }; public void addBook(View view) { Random random = new Random(); int price = random.nextInt(100); String name = "name of price " + price; Book book = new Book(price, name); try { mBookManager.addBook(book); } catch (RemoteException e) { e.printStackTrace(); } } public void getBooks(View view) { synchronized (this) { try { List<Book> books = mBookManager.getBooks(); if (books == null) return; StringBuilder sb = new StringBuilder(); for (Book book : books) { if (book != null) sb.append(book.toString() + "\r\n"); } showContent(sb.toString()); } catch (RemoteException e) { e.printStackTrace(); } } } private void showContent(String content) { tv_content.setText(content); } @Override protected void onDestroy() { super.onDestroy(); if (mBookManager != null) { unbindService(conn); } } } ```
Python
UTF-8
4,404
3.09375
3
[]
no_license
def labelslider(): global count,sliderwords text='Welcome To Typing Speed Test Game ' if(count >=len(text)): count = 0 sliderwords='' sliderwords+=text[count] count+=1 fontlable1.configure(text=sliderwords) fontlable1.after(200,labelslider) def time(): global timeleft,score,miss if(timeleft>0): timeleft-=1 timerlabelcounter.configure(text=timeleft) timerlabelcounter.after(1000,time) else: instruction.configure(text='Hit = {} | Miss = {} | TotalScore = {}'.format(score,miss,(score-miss))) rr = messagebox.askretrycancel('Notification',"For play again hit Retry button") if(rr==True): score=0 timeleft=60 miss=0 timerlabelcounter.configure(text=timeleft) wordlabel.configure(text=words[0]) scorelabelcounter.configure(text=score) instruction.configure(text='Type Word And Hit Enter') # else: # root.quit() def startgame(event): global score,miss if (timeleft==60): time() timerlabelcounter.configure(fg='red') instruction.configure(text='') if(wordentry.get()==wordlabel['text']): score +=1 scorelabelcounter.configure(text=score) else: miss +=1 random.shuffle(words) wordlabel.configure(text=words[0]) wordentry.delete(0,END) def onclick(): mixer.music.pause() def onclickf(): mixer.music.play() #------------------Root------------------------------------- from tkinter import * import random from pygame import mixer from tkinter import messagebox mixer.init() root = Tk() root.geometry('800x590+270+70') root.configure(bg='black') root.title('Typing Speed Test') mixer.music.load('audio.wav') mixer.music.play(-1) btn=Button(root,text='music off',command=onclick) btn.place(x=630,y= 550) btn1=Button(root,text='music on',command=onclickf) btn1.place(x=550,y= 550) #-------------------variable-------------------------------- score = 0 miss=0 timeleft=60 count=0 sliderwords='' words=["apple","banana","grapes","kiwi","coconut","lion","tiger" ,"zebra","dog","cat","bike","car","boat","trains","computer","furious", "turbo","wikipedia","adobe","google","abundant","adorable","anxious","awesome" ,"beautiful","boring","camera","careful","careless","cartoon","damage", "delicate","delicious","diamond","different","easter","energy","fairly","faithful", "famous","fancy","generously","gentle","handsome","healthy","huge","humorous", "hungry","island","India","juice","jealous","king","kiss","knife", "library","magazine","monkey","narrow","nasty","obey","ocean","offend", "official","paint","parrot","queen","quick","quiet","rain","rainbow", "safety","software","sea","surface","talented","tasty","teaching","touch","technique", "transformer","ugly","uniform","utopia","umbrella","universe","violet","vulture", "violent","window","wire","wax","wise","xenic","xenon","xeroxes","xanatahes", "young","youthful","yowls","you","york","yoghourt","zaag","zany","zap","zapper"] #-------------------lable----------------------------------- fontlable1=Label(root,text='',font= ('airal',25,'italic bold'),bg = 'black',fg='red',width=35) fontlable1.place(x= 10,y=10) labelslider() random.shuffle(words) wordlabel=Label(root,text=words[0],font= ('airal',25,' bold'),bg = 'black',fg='green') wordlabel.place(x=330,y= 250) scorelabel=Label(root,text='Your Score :',font= ('airal',25,' bold'),bg = 'black',fg='dark green') scorelabel.place(x=10,y=80) scorelabelcounter=Label(root,text=score,font= ('airal',25,' bold'),bg = 'black',fg='dark green') scorelabelcounter.place(x=80,y=130) timerlabel=Label(root,text='Time Left :',font= ('airal',25,'bold'),bg = 'black',fg='green') timerlabel.place(x=600,y=80) timerlabelcounter=Label(root,text=timeleft,font= ('airal',25,'bold'),bg = 'black',fg='green') timerlabelcounter.place(x=650,y=130) instruction=Label(root,text='Type Word And Hit Enter',font= ('airal',25,' bold'),bg = 'black',fg='green') instruction.place(x=200,y=400) #-----------------entry-------------------------------------- wordentry= Entry(root,font= ('airal',25,'bold'),bd = 10,justify='center') wordentry.place(x=220,y=310) wordentry.focus_set() #################################################################### root.bind('<Return>',startgame) root.mainloop()
SQL
UTF-8
3,430
3.1875
3
[]
no_license
/****************************************************************************** VERSION: 1.0 FECHA: 10/06/2015 AUTOR: ownk FUNCION: Detalle Comparacion Archivo Recaudo ******************************************************************************/ set define '&' define Indices=TS_IRECAUDOS Prompt Prompt Creando tabla CP_TDCPAR Prompt CREATE TABLE "FS_RECAUDOS_US"."CP_TDCPAR" ( "DCPAR_CPAR" NUMBER constraint NN_CP_TDCPAR_CPAR not null, "DCPAR_ID_REG_ORIG" NUMBER constraint NN_CP_TDCPAR_ID_REG_ORIG not null, "DCPAR_FUENTE" VARCHAR2(10 BYTE) constraint NN_CP_TDCPAR_FUENTE not null, "DCPAR_FRECA_NORM" DATE constraint NN_CP_TDCPAR_FRECA_NORM not null, "DCPAR_FRECA_ORIG" VARCHAR2(100 BYTE) constraint NN_CP_TDCPAR_FRECA_ORIG not null, "DCPAR_TRECA_NORM" VARCHAR2(1000 BYTE) constraint NN_CP_TDCPAR_TRECA_NORM not null, "DCPAR_TRECA_ORIG" VARCHAR2(1000 BYTE) constraint NN_CP_TDCPAR_TRECA_ORIG not null, "DCPAR_OFIC_NORM" VARCHAR2(1000 BYTE) constraint NN_CP_TDCPAR_TOFIC_NORM not null, "DCPAR_OFIC_ORIG" VARCHAR2(1000 BYTE) constraint NN_CP_TDCPAR_TOFIC_ORIG not null, "DCPAR_REFERENCIA" VARCHAR2(1000 BYTE) constraint NN_CP_TDCPAR_REFERENCIA not null, "DCPAR_OBSERV" VARCHAR2(1000 BYTE) constraint NN_CP_TDCPAR_APORTANTE not null, "DCPAR_VALOR" NUMBER(21, 2) constraint NN_CP_TDCPAR_VALOR not null, "DCPAR_FCREA" DATE constraint NN_CP_TDCPAR_FCREA not null ) storage( initial 10k next 10k pctincrease 0 ) / COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_CPAR" IS 'Identificador unico del comparacion de archivos'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_ID_REG_ORIG" IS 'Consecutivo de registro de archivo fuente '; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_FUENTE" IS 'Fecha de recaudo: PLANO / INTERNET'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_FRECA_NORM" IS 'Fecha normalizada de recaudo'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_FRECA_ORIG" IS 'Fecha orignal de recaudo especificada en el archivo fuente '; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_TRECA_NORM" IS 'Tipo de recuado normalizado'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_TRECA_ORIG" IS 'Tipo de recaudo original espeficiado en el archivo fuente'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_OFIC_NORM" IS 'Oficina normalizada'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_OFIC_ORIG" IS 'Oficina original especificada en el archivo fuente'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_REFERENCIA" IS 'Referencia de recaudo'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_OBSERV" IS 'Observacion'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_VALOR" IS 'Valor de recaudo'; COMMENT ON COLUMN "FS_RECAUDOS_US"."CP_TDCPAR"."DCPAR_FCREA" IS 'Fecha de creacion del registro'; COMMENT ON TABLE "FS_RECAUDOS_US"."CP_TDCPAR" IS 'Tabla que almacena el detalle comparacion archivo de recaudo'; prompt Llave Primaria alter table "FS_RECAUDOS_US"."CP_TDCPAR" add constraint "PK_CP_TDCPAR" primary key ("DCPAR_CPAR", "DCPAR_ID_REG_ORIG", "DCPAR_FUENTE", "DCPAR_TRECA_NORM" ) using index tablespace &Indices;
Java
UTF-8
383
2.1875
2
[]
no_license
package com.example.lgggggggx.shiyanzhou; /** * Created by Lgggggggx on 2016/11/1. */ public class Store { public int sto_id; public String sto_name; public String sto_pic; public int sto_type; public Store(int id,String name,String pic,int ty){ this.sto_id=id; this.sto_name=name; this.sto_pic=pic; this.sto_type=ty; } }
Java
UTF-8
624
1.78125
2
[]
no_license
package ru.drudenko.dnd5.webapi.monster.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import ru.drudenko.dnd5.webapi.common.dto.PaginationParametersDto; @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class MonsterSearchDto { private String name; private String cr; private String biom; private String type; private String order; private Boolean favorite = false; private String userName; private PaginationParametersDto paginationParams = new PaginationParametersDto(); }
C++
UTF-8
1,130
3.0625
3
[]
no_license
/* * Inventory.cpp * * Created on: Jan 27, 2013 * Author: hmarasigan */ #include "Inventory.h" Inventory::Inventory() { food=0; cannon=0; chain=0; scatter=0; explosive=0; booze=0; repair=0; sum(); } Inventory::~Inventory() { delete Inventory(); } void Inventory::setfood(int x) { food=x; } void Inventory::setcannon(int x) { cannon=x; } void Inventory::setchain(int x) { chain=x; } void Inventory::setscatter(int x) { scatter=x; } void Inventory::setexplosive(int x) { explosive=x; } void Inventory::setbooze(int x) { booze=x; } void Inventory::setrepair(int x) { repair=x; } int Inventory::getfood() { return food; } int Inventory::getcannon() { return cannon; } int Inventory::getchain() { return chain; } int Inventory::getscatter() { return scatter; } int Inventory::getexplosive() { return explosive; } int Inventory::getbooze() { return booze; } int Inventory::getrepair() { return repair; } //functions int Inventory::sum() { int sum=food+cannon+chain+scatter+explosive+booze+repair; return sum; } bool Inventory::check() { if (sum<100) return true; else return false; }
JavaScript
UTF-8
1,455
3.9375
4
[]
no_license
// 45. Jump Game II // Medium // 3857 // 174 // Add to List // Share // Given an array of non-negative integers nums, you are initially positioned at the first index of the array. // Each element in the array represents your maximum jump length at that position. // Your goal is to reach the last index in the minimum number of jumps. // You can assume that you can always reach the last index. // Example 1: // Input: nums = [2,3,1,1,4] // Output: 2 // Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. // Example 2: // Input: nums = [2,3,0,1,4] // Output: 2 function s(nums) { // on2, time, space const dp = Array(nums.length).fill(Infinity); dp[0] = 0; for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j <= i + nums[i] && j < nums.length; j++) { dp[j] = Math.min(dp[j], dp[i] + 1); } } return dp; } console.log(s([2, 3, 1, 1, 4])); function s2(nums) { let ladder = nums[0]; let stairs = nums[0]; let jumps = 1; for (let i = 1; i < nums.length; i++) { if (i === nums.length - 1) return jumps; if (i + nums[i] > ladder) { // build up ladder ladder = i + nums[i]; } // use up stairs stairs--; if (!stairs) { // no stairs, jump to next ladder jumps++; // get new ladder stairs = ladder - i; } } return jumps; } console.log(s2([2, 3, 1, 1, 4]));
C++
UTF-8
3,569
3.109375
3
[]
no_license
#ifndef _OUTP_ #define _OUTP_ void print_cartesian_dims(int * dims, int rank, int print_rank = 0) { if(rank == print_rank){ cout << dims[0] << "\t " << dims[1] << endl; } } void print_neighbours(int rank, int left, int right, int top, int bottom, int size) { MPI_Barrier( MPI_COMM_WORLD); for(unsigned i=0; i< size; i++){ if(i==rank){ std::cout << "Rank " << rank << " has neighbours (l,r,t,b) " << left << ", " << right << ", " << top << ", " << bottom << std::endl; } MPI_Barrier( MPI_COMM_WORLD); } } void print_center(int rank, int * center,int centerrank, int print_rank=0) { if(rank==print_rank){ cout << "the center rank is: " << centerrank << endl; cout << "cartesian coords of centerrank: " << center[0] << "\t" << center[1] << "\t" << center[2] << endl; } } void print_offsets(int rank,int size, double offsetx, double offsety, double offsetz) { for(unsigned i=0; i< size; i++){ if(i==rank){ cout << "i am rank " << rank << endl; cout << "my local offsets are: " << offsetx << "\t" << offsety << "\t" << offsetz << endl; } MPI_Barrier( MPI_COMM_WORLD); } } void stepcount(int iterations, int rank){ MPI_Barrier( MPI_COMM_WORLD); if(rank==0){ cout << "\n\n\n" << "Starting new step (" << iterations << ")" << endl << endl; } MPI_Barrier( MPI_COMM_WORLD); } void print_abc(MatrixXd &A,MatrixXd &B, MatrixXd &C_step, int size, int rank){ for(unsigned i=0; i< size; i++){ MPI_Barrier( MPI_COMM_WORLD); if(i==rank){ cout << "i am rank " << rank << endl; cout << "my A Matrix is: " << endl << A << endl; cout << "my B Matrix is: " << endl << B << endl; cout << "my C Matrix is: " << endl << C_step << endl; } MPI_Barrier( MPI_COMM_WORLD); } } void print_sizes(vector<int> & sizes, vector<int> & sizes_new, vector<int> & local_sizes,int rank){ MPI_Barrier( MPI_COMM_WORLD); if(rank == 0 ){ cout << "global size is: " << sizes[0] << "x" << sizes[1] << "\t"; cout << sizes[1] << "x" << sizes[2] << endl << endl; cout << "reshaped size is: " << sizes_new[0] << "x" << sizes_new[1] << "\t"; cout << sizes_new[1] << "x" << sizes_new[2] << endl << endl; cout << "local sizes are: " << local_sizes[0] << "x"; cout << local_sizes[1] << "\t" << local_sizes[1] << "x" << local_sizes[2] << endl; } MPI_Barrier( MPI_COMM_WORLD); } void print_coordiantes(int * mycoords, int rank, int cart_rank, int size){ for(unsigned i=0; i< size; i++){ MPI_Barrier( MPI_COMM_WORLD); if(i==rank){ cout << "Global Rank " << rank <<" has cart rank " <<cart_rank << "and cartesian coordinates (" << mycoords[0] << "," << mycoords[1] <<")" << endl; } MPI_Barrier( MPI_COMM_WORLD); } } void print_solutions_easy(int * mycoords, int * dims, MatrixXd &C,int rank){ for(int xcoord = 0; xcoord < dims[0]; xcoord++){ for(int ycoord = 0; ycoord < dims[1]; ycoord++){ MPI_Barrier(MPI_COMM_WORLD); // if(rank == 0) // cout << "tada" << endl; if(mycoords[0]==xcoord && mycoords[1]==ycoord){ cout << "i am rank: " << rank << endl; cout << "my coords are: " << mycoords[0] << "\t" << mycoords[1] << endl; cout << C << endl << endl; } MPI_Barrier(MPI_COMM_WORLD); } } } void print_matrix_distribution(int rank, int size, MatrixXd & A_loc, MatrixXd & A_glob) { //print matrix destribution for (int i=0; i<size; ++i) { MPI_Barrier(MPI_COMM_WORLD); if (rank==i) { if(rank ==0) cout <<"A_glob = " << endl << A_glob << endl; cout << "Rank " << rank << " stores A=" << endl; cout << A_loc << endl; } } } #endif
C++
ISO-8859-1
3,743
2.6875
3
[]
no_license
/*NGL v1.0 - Nology Game Library Copyright (C) 2003, 2004 Nology Softwares SC Ltda. Todos os direitos reservados O uso desta biblioteca de software em forma de cdigo fonte ou arquivo binrio, com ou sem modificaes, permitido contanto que sejam atendidas as seguintes condies: 1. A redistribuio deste software em qualquer forma, seu uso comercial e em treinamentos de qualquer natureza esto sujeitos a aprovao prvia por escrito da Nology Softwares, estando estas aes proibidas em quaisquer outras condies. 2. A alterao do contedo deste software est autorizada contanto que sejam mantidas as informaes de copyright dos arquivos originais. 3. O uso deste software permitido para uso educacional livre de quaisquer obrigaes desde que seja atendida a condio nmero 1. 4. A Nology Softwares, detentora dos direitos autorais sobre este software, no oferece nenhuma garantia de funcionamento e no pode ser responsabilizada por quaisquer danos diretos, indiretos, acidentais, especiais ou especficos causados pelo uso deste software. */ #ifndef _CNGLVECTOR_ #define _CNGLVECTOR_ #include "NGLObject.h" //!CNGLVector /*! Classe utilizada para posicionamento de objetos e clculos matemticos. */ class CNGLVector : public CNGLObject { public: //!Eixo X do vetor. float fx; //!Eixo Y do vetor. float fy; public: /*! Construtor com parmetros. \param ix: posio em X. \param iy: posio em Y. */ CNGLVector(int ix, int iy); /*! Construtor com parmetros. \param fxPam: posio em X. \param fyPam: posio em Y. */ CNGLVector(float fxPam, float fyPam); /*! Construtor padro. */ CNGLVector(void); /*! Destrutor padro. */ ~CNGLVector(void); /*! Finaliza a classe. Deve ser implementada nas classes filhas. \return verdadeiro se a operao foi bem sucedida, caso contrrio retorna falso. */ bool Release() { return true; }; /*! Operador de comparao por igualdade. \param cv: vetor a comparar. */ bool operator ==(const CNGLVector & cv); /*! Operador de comparao por diferena. \param cv: vetor a comparar. */ bool operator !=(const CNGLVector & cv); /*! Calcula o mdulo do vetor. \return Mdulo do vetor. */ float Magnitude(void); /*! Transforma este vetor em vetor unitrio mantendo a direo. */ void Normalize(void); /*! Operao de subtrao de dois vetores. \param cv: vetor a subtrair. */ CNGLVector operator-(const CNGLVector & cv); /*! Operao de soma de dois vetores. \param cv: vetor a somar. */ CNGLVector operator +(const CNGLVector & cv); /*! Soma outro vetor a este. \param cv: vetor a somar. */ void operator+=(const CNGLVector & cv); /*! Subtrai outro vetor deste. \param cv: vetor a subtrair. */ void operator -=(const CNGLVector & cv); /*! Operao de multiplicao deste vetor por uma constante. \param cfVal: constante da multiplicao. */ CNGLVector operator*(const float cfVal); /*! Operao de diviso deste vetor por constante. \param cfVal: constante da diviso. */ CNGLVector operator/(const float cfVal); /*! Multiplica o vetor por uma constante \param cfVal: constante da multiplicao */ void operator *=(const float cfVal); /*! Divide este vetor por uma constante. \param cfVal: contante da diviso. */ void operator /=(const float cfVal); /*! Retorna o produto escalar dos dois vetores. \param cv: vetor para calcular o produto escalar. */ float DotProduct(const CNGLVector & cv); /*! Elimina as casas decimais dos elementos do vetor. */ void Floor(void); /*! Arredonda para cima os elementos do vetor. */ void Ceil(void); }; #endif
JavaScript
UTF-8
1,567
3.265625
3
[]
no_license
// APIを叩く async function callApi(url, params) { const query = new URLSearchParams(params); // URLSearchParamsは連想配列からクエリパラメータを作成してくれる標準APIです。 const response = await fetch(url + query); const data = await response.json(); return data; } // callApi関数から受け取ったデータをhtmlにレンダリングする async function renderHtml() { const url = "https://app.rakuten.co.jp/services/api/Travel/HotelRanking/20170426?"; const params = { applicationId: "ご自身のアプリIDを入力してください", // アプリID genre: "onsen", // ジャンル指定 }; const data = await callApi(url, params); const fragment = document.createDocumentFragment(); const template = document.getElementById("template"); for (let i = 0; i < data.Rankings[0].Ranking.hotels.length; i++) { const hotel = data.Rankings[0].Ranking.hotels[i].hotel; const clone = template.content.cloneNode(true); clone.querySelector("h3").textContent = hotel.rank + "位" + " " + hotel.middleClassName; // 順位 + 施設の所在都道府県 clone.querySelector("img").src = hotel.hotelImageUrl; // 施設画像URL clone.querySelector("a").textContent = hotel.hotelName; // 施設名 clone.querySelector("a").href = hotel.hotelInformationUrl; // 施設情報ページURL clone.querySelector("p").innerHTML = hotel.userReview; // お客様の声 fragment.appendChild(clone); } document.querySelector("ul").appendChild(fragment); } renderHtml();
C#
UTF-8
1,802
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using MultiLayeredPerceptron.Extensions; namespace MultiLayeredPerceptron { public class Perceptron : IPerceptron { private readonly IList<double> _weights; public Perceptron(int inputsCount) { ValidateAtLeastOneInput(inputsCount); var inputsCountWithBias = inputsCount + 1; _weights = PopulateWeights(inputsCountWithBias); } public double Result { get; private set; } public double CalculateError(double expectedValue) { return expectedValue - Result; } public double Classify(IList<double> trainingEntry, Func<double, double> activationFunction) { var trainingEntryWithBias = getTrainingEntryWithBias(trainingEntry); var guess = CalculateGuess(trainingEntryWithBias); var result = activationFunction(guess); return result; } private IList<double> getTrainingEntryWithBias(IList<double> trainingEntry) { trainingEntry.Add(1.0); return trainingEntry; } private static IList<double> PopulateWeights(int inputsCount) { var list = new List<double>(); for (var i = 0; i < inputsCount; i++) list.Add(GetInitialWeight()); return list; } private static void ValidateAtLeastOneInput(int inputsCount) { if (inputsCount == 0) throw new ArgumentException(); } private static double GetInitialWeight() { return DoubleExtension.GetRandomNumber(-5, 5); } private double CalculateGuess(IList<double> trainingEntry) { return trainingEntry.Select((inputValue, index) => inputValue * _weights[index]) .Sum(); } } }
PHP
UTF-8
26,876
2.609375
3
[]
no_license
<?php require_once '../../include/api.php'; require_once '../../include/user.php'; require_once '../../include/city.php'; require_once '../../include/country.php'; define('CURRENT_VERSION', 0); class ApiPage extends OpsApiPageBase { //------------------------------------------------------------------------------------------------------- // login //------------------------------------------------------------------------------------------------------- private static function _login($user_id) { $remember = -1; if (isset($_REQUEST['remember'])) { if ($_REQUEST['remember']) { $remember = 1; } else { $remember = 0; } } if (!login($user_id, $remember)) { throw new Exc(get_label('Login attempt failed')); } } function login_op() { if (!isset($_REQUEST['username'])) { db_log(LOG_DETAILS_LOGIN, 'no user name'); throw new Exc(get_label('Login attempt failed')); } $user_name = $_REQUEST['username']; $user_id = NULL; $log_message = 'user not found'; if (isset($_REQUEST['proof'])) { if (!isset($_SESSION['login_token'])) { db_log(LOG_OBJECT_LOGIN, 'no token', NULL, $user_id); throw new Exc(get_label('Login attempt failed'), 'No token'); } $proof = $_REQUEST['proof']; $query = new DbQuery('SELECT id, password FROM users WHERE name = ? OR email = ? ORDER BY games DESC, id', $user_name, $user_name); while ($row = $query->next()) { list ($user_id, $password_hash) = $row; /*throw new Exc( 'password: ' . $password_hash . '; token: ' . $_SESSION['login_token'] . '; proof: ' . md5($password_hash . $_SESSION['login_token'] . $user_name) . '; clientProof: ' . $proof);*/ if (md5($password_hash . $_SESSION['login_token'] . $user_name) == $proof) { ApiPage::_login($user_id); return; } else { $log_message = 'invalid password'; } } } else if (isset($_POST['password'])) { $password = $_POST['password']; $query = new DbQuery('SELECT id, password FROM users WHERE name = ? OR email = ? ORDER BY games DESC, id', $user_name, $user_name); while ($row = $query->next()) { list ($user_id, $password_hash) = $row; if (md5($password) == $password_hash) { ApiPage::_login($user_id); return; } else { $log_message = 'invalid password'; } } } else { db_log(LOG_OBJECT_LOGIN, 'no proof, no password', NULL, $user_id); throw new Exc(get_label('Login attempt failed'), 'No proof, no password'); } $log_details = new stdClass(); $log_details->name = $user_name; db_log(LOG_OBJECT_LOGIN, $log_message, $log_details); throw new Exc(get_label('Login attempt failed'), $log_message); } function login_op_help() { $help = new ApiHelp(PERMISSION_EVERYONE, 'Log in. Session id is returned in a cookie <q>auth_key</q>. Use it in all the next requests.'); $help->request_param('username', 'User name or email.'); $help->request_param('proof', 'Security proof generated by formula: md5(md5(password) + token + user_name). Where user_name and password are obvious. Token is a token returned by <a href="account.php?help&op=get_token">get_token</a> request.', '<q>password</q> must be set'); $help->request_param('password', 'Raw user password. It is used only when <q>proof</q> is not set. Use it only using https and only using post method. This is a simplified login but it is absolutely not secure using either http or get method.', '<q>proof</q> must be set'); $help->request_param('remember', 'Set it to 1 for making session cookie permanent. Set it to 0 to make session cookie temporary.', 'everything as it was in the last session.'); return $help; } //------------------------------------------------------------------------------------------------------- // logout //------------------------------------------------------------------------------------------------------- function logout_op() { logout(); } function logout_op_help() { $help = new ApiHelp(PERMISSION_USER, 'Log out.'); return $help; } //------------------------------------------------------------------------------------------------------- // get_token //------------------------------------------------------------------------------------------------------- function get_token_op() { $token = md5(rand_string(8)); $_SESSION['login_token'] = $token; $this->response['token'] = $token; } function get_token_op_help() { $help = new ApiHelp(PERMISSION_EVERYONE, '<p>Return login token. Client combines this token with the username and password: md5(md5(password) + token + user_name) and send this value in <q>id</q> paramerer of <q>login</q> request.</p> <p>Another method for logging-in is just setting http headers <q>username</q> and <q>password</q> to the apropriate values. But this is not safe for http - the password is not encrypted.</p>'); $help->response_param('token', 'The token.'); return $help; } //------------------------------------------------------------------------------------------------------- // create //------------------------------------------------------------------------------------------------------- function create_op() { $name = trim(get_required_param('name')); $email = trim(get_required_param('email')); if ($email == '') { throw new Exc(get_label('Please enter [0].', get_label('email address'))); } create_user($name, $email); echo '<p>' . get_label('Thank you for signing up on [0]!', PRODUCT_NAME) . '<br>' . get_label('We have sent you a confirmation email to [0].', $email) . '</p><p>' . get_label('Click on the confirmation link in the email to complete your sign up.') . '</p>'; } function create_op_help() { $help = new ApiHelp(PERMISSION_EVERYONE, 'Create new user account.'); $help->request_param('address_id', 'Address id.'); $help->request_param('name', 'Account login name. This name is also used in the scoring tables. The name should be unique in <?php echo PRODUCT_NAME; ?>'); $help->request_param('email', 'Account email. Currently it does not have to be unique.'); $help->response_param('message', 'Localized user message sayings that the account is created.'); return $help; } //------------------------------------------------------------------------------------------------------- // edit //------------------------------------------------------------------------------------------------------- function edit_op() { global $_profile, $_lang_code; check_permissions(PERMISSION_USER); $name = $_profile->user_name; if (isset($_REQUEST['name'])) { $name = trim($_REQUEST['name']); if ($name != $_profile->user_name) { check_user_name($name); } } if (isset($_REQUEST['email'])) { $email = trim($_REQUEST['email']); if ($email != $_profile->user_email) { if (empty($email)) { throw new Exc(get_label('Please enter [0].', get_label('email address'))); } else if (!is_email($email)) { throw new Exc(get_label('[0] is not a valid email address.', $email)); } send_activation_email($_profile->user_id, $_profile->user_name, $email); echo get_label('You are trying to change your email address. Please check your email and click a link in it to finalize the change.'); } } $club_id = $_profile->user_club_id; if (isset($_REQUEST['club_id'])) { $club_id = (int)$_REQUEST['club_id']; if ($club_id <= 0) { $club_id = NULL; } } $country_id = $_profile->country_id; if (isset($_REQUEST['country_id'])) { $country_id = (int)$_REQUEST['country_id']; } else if (isset($_REQUEST['country'])) { $country_id = retrieve_country_id($_REQUEST['country']); } $city_id = $_profile->city_id; if (isset($_REQUEST['city_id'])) { $city_id = (int)$_REQUEST['city_id']; } else if (isset($_REQUEST['city'])) { $city_id = retrieve_city_id($_REQUEST['city'], $country_id, get_timezone()); } $langs = $_profile->user_langs; if (isset($_REQUEST['langs'])) { $langs = (int)$_REQUEST['langs']; } $phone = $_profile->user_phone; if (isset($_REQUEST['phone'])) { $phone = $_REQUEST['phone']; } $flags = $_profile->user_flags; if (isset($_REQUEST['message_notify'])) { if ($_REQUEST['message_notify']) { $flags |= USER_FLAG_MESSAGE_NOTIFY; } else { $flags &= ~USER_FLAG_MESSAGE_NOTIFY; } } if (isset($_REQUEST['photo_notify'])) { if ($_REQUEST['photo_notify']) { $flags |= USER_FLAG_PHOTO_NOTIFY; } else { $flags &= ~USER_FLAG_PHOTO_NOTIFY; } } if (isset($_REQUEST['male'])) { if ($_REQUEST['male']) { $flags |= USER_FLAG_MALE; } else { $flags &= ~USER_FLAG_MALE; } } Db::begin(); if (isset($_REQUEST['pwd1'])) { $password1 = $_REQUEST['pwd1']; $password2 = get_required_param('pwd2'); check_password($password1, $password2); Db::exec(get_label('user'), 'UPDATE users SET password = ? WHERE id = ?', md5($password1), $_profile->user_id); if ($flags & USER_FLAG_NO_PASSWORD) { $flags = $flags & ~USER_FLAG_NO_PASSWORD; } else { db_log(LOG_OBJECT_USER, 'changed password', NULL, $_profile->user_id); } } $update_clubs = false; Db::exec( get_label('user'), 'UPDATE users SET name = ?, flags = ?, city_id = ?, languages = ?, phone = ?, club_id = ? WHERE id = ?', $name, $flags, $city_id, $langs, $phone, $club_id, $_profile->user_id); if (Db::affected_rows() > 0) { if ($club_id != NULL && !isset($_profile->clubs[$club_id])) { Db::exec(get_label('membership'), 'INSERT INTO user_clubs (user_id, club_id, flags) values (?, ?, ' . USER_CLUB_NEW_PLAYER_FLAGS . ')', $_profile->user_id, $club_id); db_log(LOG_OBJECT_USER, 'joined club', NULL, $_profile->user_id, $club_id); $update_clubs = true; } $log_details = new stdClass(); if ($_profile->user_flags != $flags) { $log_details->flags = $flags; } if ($_profile->user_name != $name) { $log_details->flags = $flags; } if ($_profile->city_id != $city_id) { $log_details->city_id = $city_id; } if ($_profile->user_langs != $langs) { $log_details->langs = $langs; } if (!is_null($club_id)) { list ($club_name) = Db::record(get_label('club'), 'SELECT name FROM clubs WHERE id = ?', $club_id); $log_details->club_id = $club_id; $log_details->club = $club_name; } db_log(LOG_OBJECT_USER, 'changed', $log_details, $_profile->user_id); } Db::commit(); $_profile->user_name = $name; $_profile->user_flags = $flags; $_profile->user_langs = $langs; $_profile->user_phone = $phone; $_profile->user_club_id = $club_id; if ($_profile->city_id != $city_id) { list ($_profile->country_id) = Db::record(get_label('city'), 'SELECT country_id FROM cities WHERE id = ?', $city_id); $_profile->city_id = $city_id; } if ($update_clubs) { $_profile->update_clubs(); } } function edit_op_help() { $help = new ApiHelp(PERMISSION_USER, 'Change account settings.'); $help->request_param('country_id', 'Country id.', 'remains the same unless <q>country</q> is set'); $help->request_param('country', 'Country name. An alternative to <q>country_id</q>. It is used only if <q>country_id</q> is not set.', 'remains the same unless <q>country_id</q> is set'); $help->request_param('city_id', 'City id.', 'remains the same unless <q>city</q> is set'); $help->request_param('city', 'City name. An alternative to <q>city_id</q>. It is used only if <q>city_id</q> is not set.', 'remains the same unless <q>city_id</q> is not set'); $help->request_param('club_id', 'User main club. If set to 0 or negative, user main club is set to none.', 'remains the same'); $help->request_param('phone', 'User phone.', 'remains the same'); $help->request_param('langs', 'User languages. A bit combination of 1 (English) and 2 (Russian). Other languages are not supported yet.', 'remains the same'); $help->request_param('male', '1 for male, 0 for female.', 'remains the same'); $help->request_param('pwd1', 'User password.', 'remains the same'); $help->request_param('pwd2', 'Password confirmation. Must be the same as <q>pwd1</q>. Must be set when <q>pwd1</q> is set. Ignored when <q>pwd1</q> is not set.', '-'); $help->request_param('message_notify', '1 to notify user when someone replies to his/her message, 0 to turn notificetions off.', 'remains the same'); $help->request_param('photo_notify', '1 to notify user when someone comments on his/her photo, 0 to turn notificetions off.', 'remains the same'); $help->response_param('message', 'Localized user message when there is something to tell user.'); return $help; } //------------------------------------------------------------------------------------------------------- // password_reset //------------------------------------------------------------------------------------------------------- function password_reset_op() { $name = get_required_param('name'); $email = get_required_param('email'); $query = new DbQuery('SELECT id FROM users WHERE name = ? AND email = ?', $name, $email); if (!($row = $query->next())) { throw new Exc(get_label('Your login name and email do not match. You are using different email for this account.') . $sql); } list ($id) = $row; $password = rand_string(8); Db::begin(); Db::exec(get_label('user'), 'UPDATE users SET password = ? WHERE id = ?', md5($password), $id); if (Db::affected_rows() > 0) { db_log(LOG_OBJECT_USER, 'reset password', NULL, $id); } Db::commit(); $body = get_label('Your password at') . ' <a href="' . PRODUCT_URL . '">' . PRODUCT_NAME .'</a> ' . get_label('has been reset to') . ' <b>' . $password . '</b>'; $text_body = get_label('Your password at') . ' ' . PRODUCT_URL . ' ' . get_label('has been reset to') . ' ' . $password . "\r\n\r\n"; send_email($email, $body, $text_body, 'Mafia'); echo get_label('Your password has been reset. Please check your email for the new password.'); } function password_reset_op_help() { $help = new ApiHelp(PERMISSION_EVERYONE, 'Reset user password.'); $help->request_param('name', 'User name.'); $help->request_param('email', 'User email.'); $help->response_param('message', 'Localized user message sayings that the password is reset, and the email with it is sent.'); return $help; } //------------------------------------------------------------------------------------------------------- // password_change //------------------------------------------------------------------------------------------------------- function password_change_op() { global $_profile; check_permissions(PERMISSION_USER); $old_pwd = get_required_param('old_pwd'); $pwd1 = get_required_param('pwd1'); $pwd2 = get_required_param('pwd2'); check_password($pwd1, $pwd2); Db::begin(); Db::exec(get_label('user'), 'UPDATE users SET password = ? WHERE id = ? AND password = ?', md5($pwd1), $_profile->user_id, md5($old_pwd)); if (Db::affected_rows() != 1) { throw new Exc(get_label('Wrong password.')); } db_log(LOG_OBJECT_USER, 'changed password', NULL, $_profile->user_id); Db::commit(); echo get_label('Your password has been changed.'); } function password_change_op_help() { $help = new ApiHelp(PERMISSION_USER, 'Change user password.'); $help->request_param('old_pwd', 'Current password.'); $help->request_param('pwd1', 'New password.'); $help->request_param('pwd2', 'New password confirmation.'); $help->response_param('message', 'Localized user message sayings that the password is changed.'); return $help; } //------------------------------------------------------------------------------------------------------- // join_club //------------------------------------------------------------------------------------------------------- function join_club_op() { global $_profile; check_permissions(PERMISSION_USER); $club_id = get_required_param('club_id'); list ($count) = Db::record(get_label('membership'), 'SELECT count(*) FROM user_clubs WHERE user_id = ? AND club_id = ?', $_profile->user_id, $club_id); if ($count == 0) { Db::begin(); Db::exec(get_label('membership'), 'INSERT INTO user_clubs (user_id, club_id, flags) values (?, ?, ' . USER_CLUB_NEW_PLAYER_FLAGS . ')', $_profile->user_id, $club_id); db_log(LOG_OBJECT_USER, 'joined club', NULL, $_profile->user_id, $club_id); Db::commit(); $_profile->update_clubs(); } } function join_club_op_help() { $help = new ApiHelp(PERMISSION_USER, 'Make current user a club member.'); $help->request_param('club_id', 'Club id.'); return $help; } //------------------------------------------------------------------------------------------------------- // quit_club //------------------------------------------------------------------------------------------------------- function quit_club_op() { global $_profile; $club_id = get_required_param('club_id'); check_permissions(PERMISSION_CLUB_MEMBER, $club_id); Db::begin(); Db::exec(get_label('membership'), 'DELETE FROM user_clubs WHERE user_id = ? AND club_id = ?', $_profile->user_id, $club_id); if (Db::affected_rows() > 0) { db_log(LOG_OBJECT_USER, 'left club', NULL, $_profile->user_id, $club_id); } Db::commit(); $_profile->update_clubs(); } function quit_club_op_help() { $help = new ApiHelp(PERMISSION_CLUB_MEMBER, 'Exclude current user from the members of the club.'); $help->request_param('club_id', 'Club id.'); return $help; } //------------------------------------------------------------------------------------------------------- // suggest_club //------------------------------------------------------------------------------------------------------- function suggest_club_op() { global $_profile; check_permissions(PERMISSION_USER); $langs = $_profile->user_langs; if (isset($_REQUEST['langs'])) { $langs = (int)$_REQUEST['langs']; } $city_id = -1; $country_id = -1; $area_id = -1; if (isset($_REQUEST['city'])) { $city_name = $_REQUEST['city']; $query = new DbQuery('SELECT id, country_id, area_id FROM cities WHERE name_en = ? OR name_ru = ?', $city_name, $city_name); // $this->response['sql-01'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($city_id, $country_id, $area_id) = $row; } } if ($country_id < 0 && isset($_REQUEST['country'])) { $country_name = $_REQUEST['country']; $query = new DbQuery('SELECT id FROM countries WHERE name_en = ? OR name_ru = ?', $country_name, $country_name); // $this->response['sql-02'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($country_id) = $row; } } $club_id = -1; if ($city_id > 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE c.city_id = ? AND c.langs = ? AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $city_id, $langs); // $this->response['sql-03'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE c.city_id = ? AND (c.langs & ?) <> 0 AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $city_id, $langs); // $this->response['sql-04'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE c.city_id = ? AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $city_id); // $this->response['sql-05'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($area_id != NULL) { if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE (c.city_id = ? OR c.city_id IN (SELECT id FROM cities WHERE area_id = ?)) AND c.langs = ? AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $area_id, $area_id, $langs); // $this->response['sql-06'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE (c.city_id = ? OR c.city_id IN (SELECT id FROM cities WHERE area_id = ?)) AND (c.langs & ?) <> 0 AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $area_id, $area_id, $langs); // $this->response['sql-07'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE (c.city_id = ? OR c.city_id IN (SELECT id FROM cities WHERE area_id = ?)) AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $area_id, $area_id); // $this->response['sql-08'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } } } if ($club_id <= 0 && $country_id > 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE c.city_id IN (SELECT id FROM cities WHERE country_id = ?) AND c.langs = ? AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $country_id, $langs); // $this->response['sql-09'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE c.city_id IN (SELECT id FROM cities WHERE country_id = ?) AND (c.langs & ?) <> 0 AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $country_id, $langs); // $this->response['sql-10'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE c.city_id IN (SELECT id FROM cities WHERE country_id = ?) AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $country_id); // $this->response['sql-11'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id AND c.langs = ? AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $langs); // $this->response['sql-12'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id AND (c.langs & ?) <> 0 AND (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC', $langs); // $this->response['sql-13'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } if ($club_id <= 0) { $query = new DbQuery('SELECT c.id FROM clubs c LEFT JOIN games g ON g.club_id = c.id WHERE (c.flags & ' . CLUB_FLAG_RETIRED . ') = 0 GROUP BY c.id ORDER BY count(g.id) DESC'); // $this->response['sql-14'] = $query->get_parsed_sql(); if ($row = $query->next()) { list($club_id) = $row; } } $this->response['club_id'] = $club_id; } function suggest_club_op_help() { $help = new ApiHelp(PERMISSION_USER, 'Suggest a club for the current user account, considering user city/country and the languages he/she knows.'); $help->request_param('langs', 'User languages. A bit mask where 1 is English; 2 is Russian. Their combination (3 = 1 | 2) means both. Other languages are not supported yet.', 'profile languages are used.'); $help->request_param('city', 'User city name.', 'profile city is used.'); $help->request_param('country', 'User country name.', 'profile country is used.'); $help->response_param('club_id', 'The most sutable club for the current user account.'); return $help; } //------------------------------------------------------------------------------------------------------- // site_style //------------------------------------------------------------------------------------------------------- function site_style_op() { global $_agent; switch ((int)get_required_param('style')) { case SITE_STYLE_DESKTOP: if ($_agent != AGENT_BROWSER || (isset($_SESSION['mobile']) && $_SESSION['mobile'])) { $_SESSION['mobile'] = false; } break; case SITE_STYLE_MOBILE: if ($_agent == AGENT_BROWSER || (isset($_SESSION['mobile']) && !$_SESSION['mobile'])) { $_SESSION['mobile'] = true; } break; } } function site_style_op_help() { $help = new ApiHelp(PERMISSION_EVERYONE, 'Set prefered site style for user.'); $help->request_param('style', '0 for desktop style. 1 for mobile style.'); return $help; } //------------------------------------------------------------------------------------------------------- // browser_lang //------------------------------------------------------------------------------------------------------- function browser_lang_op() { global $_profile, $_lang_code; $browser_lang = get_required_param('lang'); $_lang_code = $_SESSION['lang_code'] = $browser_lang; if (isset($_profile) && $_profile != NULL) { $_profile->user_def_lang = get_lang_by_code($browser_lang); Db::begin(); Db::exec(get_label('user'), 'UPDATE users SET def_lang = ? WHERE id = ?', $_profile->user_def_lang, $_profile->user_id); if (Db::affected_rows() > 0) { $log_details = new stdClass(); $log_details->def_lang = $_profile->user_def_lang; db_log(LOG_OBJECT_USER, 'changed', $log_details, $_profile->user_id); } Db::commit(); $_profile->update(); } } function browser_lang_op_help() { $help = new ApiHelp(PERMISSION_EVERYONE, 'Set preferable language for viewing ' . PRODUCT_NAME . '.'); $help->request_param('lang', 'Language code: <q>ru</q> for Russian; <q>en</q> for English; other languages are not supported yet.'); return $help; } } $page = new ApiPage(); $page->run('Account Operations', CURRENT_VERSION, PERM_ALL); ?>
Markdown
UTF-8
3,479
2.984375
3
[ "Apache-2.0" ]
permissive
# Infinispan Embedded Tutorial: Weather App ## Overview This is a tutorial which explains how to use Infinispan embedded in your own application. The application will retrieve the current weather conditions for some cities and store them in a cache, for quicker retrieval. It will also show how to configure the cache for expiration, so that entries get removed as they age. It will then demonstrate how to cluster multiple nodes together and reacting to events in the cluster. Finally, a computation of average temperatures per country will show the power of the map/reduce functionality. Each tagged commit is a separate lesson teaching a single aspect of Infinispan. The tutorial instructions are at http://infinispan.org/tutorials/embedded/ N.B. The tutorial connects to OpenWeatherMap (http://openweathermap.org) to retrieve current weather data. The service requires obtaining a free API key. Before launching the application, ensure you've set the OWMAPIKEY environment variable to your API key. If you don't want to register for the service, if you don't have an Internet connection or you are having trouble connecting to the service, just don't set the environment variable, and it will use the RandomWeatherService. ## Prerequisites ### Git - A good place to learn about setting up git is [here][git-github] - Git [home][git-home] (download, documentation) ### JDK - Get a [JDK][jdk-download]. You will need version 1.8 or higher ### Maven - Get [Maven][maven-download]. You will need version 3.2 or higher ## Commits / Tutorial Outline You can check out any point of the tutorial using git checkout step-? To see the changes between any two lessons use the git diff command. git diff step-?..step-? ### step-0/setup - The initial implementation of the Weather application ### step-1/cache-manager - Adding Infinispan to the project and initializing a cache manager ### step-2/cache-put-get - Add caching to the weather service ### step-3/expiration - Store the entries in the cache with an expiration time ### step-4/cachemanager-configuration - Configure the features of the default cache ### step-5/clustering - Add a transport to the CacheManager so that it supports clustering ### step-6/cachemanager-listener - Use CacheManager events to detect changes in the cluster ### step-7/cache-listener - Detect changes to the cache with a clustered listener ### step-8/grouping - Group related entries on the same nodes for efficiency ### step-9/externalizer - Implement a custom externalizer for our value class ### step-10/mapreduce - Use Map/Reduce to compute temperature averages per country ### step-11/declarative-configuration - Use the XML configuration instead of the programmatic API ## Building and running the tutorial - Run `mvn clean package` to rebuild the application - Run `mvn exec:exec` to execute the application. In case you're running a clustered step, run this from multiple terminals, where each instance will represent a node ## Application Directory Layout src/ --> main/ --> java/ --> resources/ --> ## Contact For more information on Infinispan please check out http://infinispan.org/ [jdk-download]: http://www.oracle.com/technetwork/articles/javase/index-jsp-138363.html [git-home]: http://git-scm.com [git-github]: http://help.github.com/set-up-git-redirect [maven-download]: http://maven.apache.org/download.html
PHP
UTF-8
409
2.6875
3
[]
no_license
<?php namespace Didslm\FileUpload\Factory; use Didslm\FileUpload\Stream; use Psr\Http\Message\StreamInterface; class StreamFactory { public static function createStreamFromFile(string $file): StreamInterface { return new Stream($file, 'r'); } public function createStream(string $fileName): StreamInterface { return new Stream($fileName, 'r'); } }
Java
UTF-8
4,569
2.796875
3
[]
no_license
package gfx; import java.awt.*; import java.awt.image.*; import java.net.URL; public class ImageUtils { public static BufferedImage getBufferedImage(java.awt.Component c, String aFile) { return ImageUtils .getBufferedImage(c, aFile, BufferedImage.TYPE_INT_RGB); } public static BufferedImage getBufferedImage(java.awt.Component c, String aFile, int aType) { // Image image = c.getToolkit(). // System.out.println("Load file: " + aFile); URL completeImageURL = ImageUtils.completeURL(c.getClass(), aFile); // Image image = java.awt.Toolkit.getDefaultToolkit().getImage(aFile); // Image image = // Toolkit.getDefaultToolkit().createImage(completeFileName); // System.out.println(aFile + " " + c.getToolkit() + " " + // c.getToolkit().createImage(completeFileName)); Image image = c.getToolkit().createImage(completeImageURL); // System.out.println(completeFileName); if (!waitForImage(c, image, aFile)) return null; BufferedImage bufferedImage = new BufferedImage(image.getWidth(c), image.getHeight(c), aType); Graphics2D temp = bufferedImage.createGraphics(); temp.drawImage(image, 0, 0, c); bufferedImage.flush(); return bufferedImage; } public static BufferedImage getBufferedImageAbsolute(java.awt.Component c, String aFile) { return ImageUtils .getBufferedImageAbsolute(c, aFile, BufferedImage.TYPE_INT_RGB); } public static BufferedImage getBufferedImageAbsolute(java.awt.Component c, String aFile, int aType) { Image image = c.getToolkit().createImage(aFile); // System.out.println(completeFileName); if (!waitForImage(c, image, aFile)) return null; BufferedImage bufferedImage = new BufferedImage(image.getWidth(c), image.getHeight(c), aType); Graphics2D temp = bufferedImage.createGraphics(); temp.drawImage(image, 0, 0, c); bufferedImage.flush(); return bufferedImage; } public static boolean waitForImage(java.awt.Component c, Image image, String aFile) { MediaTracker tracker = new MediaTracker(c); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } if (tracker.isErrorAny()) { System.err.println("Error loading " + aFile); return false; } return true; } // Returns the filename relative to a given class' location public static URL completeURL(Class classIndex, String relativeFileName) { URL url = classIndex.getResource(relativeFileName); // System.out.println("Class: " + classIndex.getName()); // System.out.println("classloader: " + classIndex.getClassLoader()); // System.out.println("Filename: " + relativeFileName); // System.out.println("URL: " + url); return url; } public static String completePath(Class classIndex, String relativeFileName) { URL url = ImageUtils.completeURL(classIndex, relativeFileName); if (url == null) return ""; else return url.getFile(); } /** Convenience Methods */ public static TexturePaint getTexturePaint(java.awt.Component c, String aFile, double x, double y, double width, double height) { BufferedImage image = getBufferedImage(c, aFile); return new TexturePaint(image, new java.awt.geom.Rectangle2D.Double(x, y, width, height)); } public static TexturePaint getTexturePaint(java.awt.Component c, String aFile) { BufferedImage image = getBufferedImage(c, aFile); return new TexturePaint(image, new java.awt.geom.Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight())); } public static TexturePaint getTexturePaint(java.awt.Component c, String aFile, double x, double y, float scaleX, float scaleY) { BufferedImage image = getBufferedImage(c, aFile); return new TexturePaint(image, new java.awt.geom.Rectangle2D.Double(x, y, image.getWidth() * scaleX, image.getHeight() * scaleY)); } // public java.awt.geom.Rectangle2D.Double getBounds() { // return _bounds; // } // rawImage.getScaledInstance( // 200,-1,Image.SCALE_AREA_AVERAGING); }
Markdown
UTF-8
7,630
3.796875
4
[]
no_license
<h1>Recursion in C</h1> <span class="jr-highlight-yellow" id="jr-1551451997974">Recursion</span> is a programming technique that allows the programmer to express operations in terms of themselves. I<span class="jr-highlight-yellow" id="jr-1551452007919">n C, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process".</span> <span class="jr-highlight-yellow" id="jr-1551452067207">This makes it sound very similar to a loop because it repeats the same code, and in some ways it </span><em><span class="jr-highlight-yellow" id="jr-1551452067208">is</span></em><span class="jr-highlight-yellow" id="jr-1551452067208"> similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call. One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the "build wall" function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.</span> <p></p><p> A simple example of recursion would be: <h2> </p><p>void recurse()<br>{<br> recurse(); /* Function calls itself */<br>}<br><br>int main()<br>{<br> recurse(); /* Sets off the recursion */<br> return 0;<br>}<br></p> </h2> This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without ending, the program will crash. Why not write a program to see how many times the function is called before the program terminates? <h2> <p>#include &lt;stdio.h&gt;<br><br>void recurse ( int count ) /* Each call gets its own copy of count */<br>{<br> printf( "%d\n", count );<br> /* It is not necessary to increment count since each function's<br> variables are separate (so each count will be initialized one greater)<br> */<br> recurse ( count + 1 );<br>}<br><br>int main()<br>{<br> recurse ( 1 ); /* First function call, so it starts at one */<br> return 0;<br>}<br></p> </h2> </h2> habeen called by initializing each individual function call's count variable one greater than it was previous by passing in count + 1. Keep in mind that it is not a function call restarting itself; it is hundreds of function calls that are each unfinished. </span><p></p><p><span class="jr-highlight-yellow" id="jr-1551451533437"> The best way to think of recursion is that each function call is a "process" being carried out by the computer. If we think of a program as being carried out by a group of people who can pass around information about the state of a task and instructions on performing the task, each recursive function call is a bit like each person asking the next person to follow the same set of instructions on some part of the task while the first person waits for the result. </span></p><p><span class="jr-highlight-yellow" id="jr-1551451533437"> At some point, we're going to run out of people to carry out the instructions, just as our previous recursive functions ran out of space on the stack. There needs to be a way to avoid this! To halt a series of recursive calls, a recursive function will have a condition that controls when the function will finally stop calling itself. The condition where the function will not call itself is termed the base case of the function. Basically, it will usually be an if-statement that checks some variable for a condition (such as a number being less than zero, or greater than some other number) and if that condition is true, it will not allow the function to call itself again. (Or, it could check if a certain condition is true and only then allow the function to call itself). </span></p><p> A quick example:<h2></p><p><span class="jr-highlight-green" id="jr-1551451578502">void count_to_ten ( int count )</span><br><span class="jr-highlight-green" id="jr-1551451578502">{</span><br><span class="jr-highlight-green" id="jr-1551451578502"> /* we only keep counting if we have a value less than ten</span><br><span class="jr-highlight-green" id="jr-1551451578502"> if ( count &lt; 10 ) </span><br><span class="jr-highlight-green" id="jr-1551451578502"> {</span><br><span class="jr-highlight-green" id="jr-1551451578502"> count_to_ten( count + 1 );</span><br><span class="jr-highlight-green" id="jr-1551451578502"> }</span><br><span class="jr-highlight-green" id="jr-1551451578502">}</span><br><span class="jr-highlight-green" id="jr-1551451578502">int main()</span><br><span class="jr-highlight-green" id="jr-1551451578502">{</span><br><span class="jr-highlight-green" id="jr-1551451578502"> count_to_ten ( 0 ); </span><br><span class="jr-highlight-green" id="jr-1551451578502">}</span><br></p></h2> This program ends when we've counted to ten, or more precisely, when count is no longer less than ten. This is a good base case because it means that if we have an input greater than ten, we'll stop immediately. If we'd chosen to stop when count equaled ten, then if the function were called with the input 11, it would run out of memory before stopping. <p></p><p> Notice that so far, we haven't done anything with the result of a recursive function call. Each call takes place and performs some action that is then ignored by the caller. It is possible to get a value back from the caller, however. It's also possible to take advantage of the side effects of the previous call. In either case, once a function has called itself, it will be ready to go to the next line after the call. It can still perform operations. <span class="jr-highlight-yellow" id="jr-1551451816049">One function you could write could print out the numbers 123456789987654321</span>. How can you use recursion to write a function to do this? S<span class="jr-highlight-yellow" id="jr-1551451822359">imply have it keep incrementing a variable passed in, and then output the variable twice: once before the function recurses, and once after.<h2></span> </p><p>void printnum ( int begin )<br>{<br> printf( "%d", begin );<br> if ( begin &lt; 9 ) /* The base case is when begin is no longer */<br> { /* less than 9 */<br> printnum ( begin + 1 ); <br> }<br> /* display begin again after we've already printed everything from 1 to 9<br> * and from 9 to begin + 1 */<br> printf( "%d", begin );<br>}<br></p> </h2> This function works because it will go through and print the numbers begin to 9, and then as each printnum function terminates it will continue printing the value of begin in each function from 9 to begin. <p></p><p> This is, however, just touching on the usefulness of recursion. Here's a little challenge: use recursion to write a program that returns the factorial of any number greater than 0. (Factorial is number * (number - 1) * (number - 2) ... * 1). </p><p> Hint: Your function should recursively find the factorial of the smaller numbers first, i.e., it takes a number, finds the factorial of the previous number, and multiplies the number times that factorial...have fun. :-) <a href="https://plus.google.com/113987539774523532573?rel=author">By Alex Allain</a> <a href="//https://www.cprogramming.com/tutorial/c/lesson16.html"> Source</a>
PHP
UTF-8
3,313
3.109375
3
[]
no_license
<?php // Added by Taylor to prevent double login, check through using index and utils //if ( is_logged_in() ) //exit( 'You are already logged in!!' ); // Insert variables for login and db and tbl selection $host = "localhost"; // Host name $sqlusername = "root"; // Mysql username $sqlpassword = "Buick"; // Mysql password $db_name = "users"; // Database name $tbl_name = "users"; // Table name // Connect to server and select database. mysql_connect("$host", "$sqlusername", "$sqlpassword")or die("cannot connect to mysql"); mysql_select_db("$db_name")or die("cannot select DB"); // If the form has been submitted if (isset($_POST['submit'])) { // makes sure they filled it in if(!$_POST['username'] | !$_POST['password']) { die('You did not fill in a required field <br /><br /> <a href=login.php>Click here to return to the login page</a>'); } // Sanitize the username. Otherwise could mess up the db query or inject something hazardous function sanitize_username( $username ) { return preg_replace( '/[^a-z0-9]/i', '', $username ); } $safe_username = sanitize_username($_POST['username']); //Need to do the following below after register new user is setup function sanitize_password( $password ) { return preg_replace( '/[\t\'"%<>\-\(\)\n\r]/i', '', $password ); } $hash_password = md5($_POST['password']); $safe_password = sanitize_password($hash_password); //Check for username $user_check1 = "SELECT * FROM $tbl_name WHERE username = '$safe_username'"; $user_check2 = mysql_query($user_check1) or die(mysql_error()); //Counts rows from result above and gives user error if user dosen't exist $user_count = mysql_num_rows($user_check2); if ($user_count == 0) { die('That user does not exist in our database.<br /><br /> <a href=login.php>Click here to login</a>'); } while($info = mysql_fetch_array( $user_check2 )) { //gives error if the password is wrong if ($safe_password != $info['password']) { die('Incorrect password, please try again.<br /><br /> <a href=login.php>Click here to login</a>'); } //uses else to contradict not equal and redirect to success page //Should I use sessions or cookies? Uncomment sessions if not cookies else { $hour = time() + 3600; setcookie(username, $safe_username, $hour); setcookie(password, $safe_password, $hour); header("location:login_success.php"); } } exit; } /**Original code from version 0 below that ONLY returns wrong username OR password error *Good to prevent malicious users from knowing if a certain username exists *Incorporate if needed and comment above strings */ //Run the query. It will return a result if I get have a match //$sql="SELECT * FROM $tbl_name WHERE username='$safe_username' and password='$safe_password'"; //$result=mysql_query($sql); //Count the returned rows //$count=mysql_num_rows($result); // If result matched $username and $password, table row must be 1 row //if($count == 1){ // Register $myusername, $mypassword and redirect to file "login_success.php" //session_register("username"); //session_register("password"); //header("location:login_success.php"); //} //else { //echo "Wrong Username or Password"; //} // Halt execution of code. //exit; //} ?>
PHP
UTF-8
2,433
2.703125
3
[ "MIT" ]
permissive
<?php /** * This file is part of the jigius/acc-core-pdata library * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Copyright (c) 2020 Jigius <jigius@gmail.com> * @link https://github.com/jigius/acc-core-pdata GitHub */ declare(strict_types=1); namespace Acc\Core\PersistentData; use Acc\Core\MediaInterface; use Acc\Core\PrinterInterface; use LogicException; /** * Class VanillaRegistry * @package Acc\Core\PersistentData */ final class VanillaRegistry implements RegistryInterface { /** * @var array An input data */ private array $i; /** * @var array|null A prepared data for printing */ private ?array $o = null; /** * VanillaEntityOptions constructor. */ public function __construct() { $this->i = []; } /** * @inheritDoc * @return PrinterInterface */ public function with(string $key, $val): PrinterInterface { if ($this->o !== null) { throw new LogicException("print job is already finished"); } $obj = $this->blueprinted(); $obj->i[$key] = $val; return $obj; } /** * @inheritDoc * @return MediaInterface */ public function finished(): RegistryInterface { if ($this->o !== null) { throw new LogicException("print job is already finished"); } $obj = $this->blueprinted(); $obj->o = $this->i; $obj->i = []; return $obj; } /** * @inheritDoc */ public function printed(PrinterInterface $printer) { if ($this->o === null) { throw new LogicException("print job has not been finish"); } foreach ($this->o as $key => $val) { $printer = $printer->with($key, $val); } return $printer->finished(); } /** * @inheritDoc * @param string $key * @param null $default * @return mixed|null */ public function value(string $key, $default = null) { if (!array_key_exists($key, $this->i)) { return $default; } return $this->i[$key]; } /** * Clones the instance * @return $this */ private function blueprinted(): self { $obj = new self(); $obj->i = $this->i; return $obj; } }
Python
UTF-8
2,466
3.125
3
[ "MIT" ]
permissive
import asyncio class CouriersOrdersResolver: def __init__(self, orders_, max_weight, values_=None): self.orders = {} i = 1 for k, v in orders_.items(): # as weight is a float number, convert to int by multiplying by 100 and rounding # (minimal value is 0.01, so it'll be converted to 1) self.orders[i] = {'id': k, 'weight': int(v * 100)} i += 1 self.w = int(max_weight * 100) self.n = len(orders_) self.val = [1 for i in range(len(orders_))] if values_ is None else values_ self.k = [[0 for x in range(self.w + 1)] for x in range(self.n + 1)] self.ans = [] async def resolve_orders(self): """ main method for resolver :return: items ids """ await self.solve_knapsack_problem() await self.find_ans(self.n, self.w) ids_ = [] for item in self.ans: ids_.append(self.orders[item]['id']) ids_.sort() return ids_ async def solve_knapsack_problem(self): """ Build table k[][] in bottom up manner :return: last value in table, which is the biggest sum of p """ for i in range(self.n + 1): for w in range(self.w + 1): if i == 0 or w == 0: self.k[i][w] = 0 elif self.orders[i]['weight'] <= w: self.k[i][w] = \ max(self.val[i - 1] + self.k[i - 1][w - self.orders[i]['weight']], self.k[i - 1][w]) else: self.k[i][w] = self.k[i - 1][w] return self.k[self.n][self.w] async def find_ans(self, k, s): """ forms list ans of items that for the biggest sum of p :param k: :param s: :return: """ if self.k[k][s] == 0: return if self.k[k - 1][s] == self.k[k][s]: await self.find_ans(k - 1, s) else: await self.find_ans(k - 1, s - self.orders[k]['weight']) self.ans.append(k) if __name__ == "__main__": # test case for algorithm orders = {0: 3.1, 1: 4.1, 2: 5.1, 3: 8.1, 4: 9.1} values = [1, 6, 4, 7, 6] max_w = 13.5 resolver = CouriersOrdersResolver(orders_=orders, values_=values, max_weight=max_w) loop = asyncio.get_event_loop() ids = loop.run_until_complete(resolver.resolve_orders()) loop.close() print(ids)
Python
UTF-8
614
3.671875
4
[]
no_license
# First line of input contains integer L # Second line contains integer D # Third line contains integer X L = int(input()) D = int(input()) X = int(input()) # Check minimal condition for i in range(L, D + 1, 1): originalDigit = i sumOfDigits = 0 while i: sumOfDigits += i % 10 i //= 10 if sumOfDigits == X: print(originalDigit) break # Check maximal condition for i in range(D, L - 1, -1): originalDigit = i sumOfDigits = 0 while i: sumOfDigits += i % 10 i //= 10 if sumOfDigits == X: print(originalDigit) break
C#
UTF-8
8,578
2.671875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; /// <summary> /// <para>t_start is in range (-PI, PI], /// sign(t_end - t_start) is determined by clockdir</para> /// </summary> public class Arc : Curve { Vector2[] controlPoints; public Vector2 Center { get { return controlPoints[1]; } private set { controlPoints[1] = value; } } public Vector2 Start { get { return controlPoints[0]; } private set { controlPoints[0] = value; } } public Vector2 End { get { return controlPoints[2]; } private set { controlPoints[2] = value; } } // Once initialized, cannot change public float Radius { get; private set; } public override bool IsValid { get { return !float.IsInfinity(Center.x) && !float.IsInfinity(Start.x) && !float.IsInfinity(End.x) && !Algebra.isclose(Start, End); } } protected override void Invalidate() { Center = Start = End = Vector2.negativeInfinity; } public static Curve GetDefault() { var rtn = new Arc(); rtn.Invalidate(); return rtn; } public Arc(Vector2 _center, Vector2 start, float angle) { Debug.Assert(Mathf.Abs(angle) < Mathf.PI * 2); controlPoints = new Vector2[3]; Center = _center; Radius = (start - _center).magnitude; var radialDir = start - _center; t_start = Mathf.Atan2(radialDir.y, radialDir.x); t_end = t_start + angle; Start = GetTwodPos(0f); End = GetTwodPos(1f); } Arc() { controlPoints = new Vector2[3]; } /// <summary> /// <para> start turns angle clockwise around center and arrives at end</para> /// </summary> /// <param name="angle">Can be negative</param> public Arc(Vector2 start, float angle, Vector2 end) { Debug.Assert(Mathf.Abs(angle) < Mathf.PI * 2); controlPoints = new Vector2[3]; var bottom_angle = (Mathf.PI - angle) * 0.5f; Center = start + Algebra.RotatedY(end - start, -bottom_angle) * 0.5f / Mathf.Sin(angle / 2); Radius = (Center - start).magnitude; var radialDir = start - Center; t_start = Mathf.Atan2(radialDir.y, radialDir.x); t_end = t_start + angle; Start = GetTwodPos(0f); End = GetTwodPos(1f); } public override List<Vector2> ControlPoints { get { return controlPoints.ToList(); } set { if (value[1] != Center && !float.IsInfinity(Start.x) && !float.IsInfinity(End.x)) { // Only move center: keep endings. Projects control point to vertical split line. Center = Algebra.ProjectOn(value[1], (Start + End) / 2, Algebra.RotatedY((End - Start).normalized, Mathf.PI / 2)); var startRadialDir = Start - Center; var endRadialDir = End - Center; Radius = startRadialDir.magnitude; float new_t_start = Mathf.Atan2(startRadialDir.y, startRadialDir.x); float new_t_end = Mathf.Atan2(endRadialDir.y, endRadialDir.x); // preserve clockwise property if (t_start < t_end && new_t_start < new_t_end || t_start > t_end && new_t_start > new_t_end) { // already preserved } else { if (t_start < t_end && new_t_start > new_t_end) { new_t_end = new_t_end + 2 * Mathf.PI; } else { new_t_end = new_t_end - 2 * Mathf.PI; } } t_start = new_t_start; t_end = new_t_end; NotifyShapeChanged(); } else if (Start != value[0] || End != value[2]) { // move ending, make default (angle=90). Notify only when all valid Start = value[0]; End = value[2]; if (!float.IsInfinity(Start.x) && !float.IsInfinity(End.x)) { Center = (Start + End) / 2 + Algebra.RotatedY((End - Start) / 2, - Mathf.PI / 2); var startRadialDir = Start - Center; Radius = startRadialDir.magnitude; t_start = Mathf.Atan2(startRadialDir.y, startRadialDir.x); t_end = t_start - Mathf.PI / 2; NotifyShapeChanged(); } } } } protected override Vector2 _GetFrontDir(float t) { t = toGlobalParam(t); Vector2 radian_dir = new Vector2(Mathf.Cos(t), Mathf.Sin(t)); return t_end > t_start ? Algebra.RotatedY(radian_dir, Mathf.PI / 2) : Algebra.RotatedY(radian_dir, -Mathf.PI / 2); } protected override float _GetLength() { return Mathf.Abs(t_end - t_start) * Radius; } protected override Vector2 _GetTwodPos(float t) { t = toGlobalParam(t); return Center + Radius * new Vector2(Mathf.Cos(t), Mathf.Sin(t)); } protected override float? _ParamOf(Vector2 p) { Vector2 normalizedWorldDir = (p - Center) / Radius; if (!Algebra.isclose(normalizedWorldDir.magnitude, 1.0f)) { return null; } float worldAngle = Mathf.Atan2(normalizedWorldDir.y, normalizedWorldDir.x); /// Since end_t falls in (-3PI, 3PI], /// we should test every possible worldAngle in (-3PI, 3PI], /// i.e. expand (-PI, PI] by 2 PI to both side float[] candidates = {worldAngle - Mathf.PI * 2, worldAngle, worldAngle + Mathf.PI * 2}; foreach(var candidate in candidates) { if (Algebra.approximatelySmaller((candidate - t_end) * (candidate - t_start), 0f)) { return Algebra.approximateTo01(toLocalParam(candidate), Length); } } // out or range: return an arbitary one outside [0,1] return Algebra.approximateTo01(toLocalParam(candidates[1]), Length); } protected override float _ToParamt(float unscaled_t) { return unscaled_t; } protected override float _ToUnscaledt(float t) { return t; } public override float GetMaximumCurvature => 1f / Radius; public override Vector2 GetAttractedPoint(Vector2 p, float attract_radius) { if ((p - Center).magnitude > attract_radius + Radius) { return p; } if (Algebra.isclose(Center, p) && attract_radius <= Radius) { return Center; } // ray (center -> p) intersects with arc Vector2 projected_p = Center + (p - Center).normalized * Radius; Vector2 closest_p; if (Contains(projected_p)) { closest_p = projected_p; } else { closest_p = (p - Start).sqrMagnitude < (p - End).sqrMagnitude ? Start : End; } if ((closest_p - p).sqrMagnitude <= attract_radius * attract_radius) { return closest_p; } else { return p; } } public override Curve Clone() { Arc copy = new Arc(); copy.Center = Center; copy.Radius = Radius; copy.t_start = t_start; copy.t_end = t_end; copy.NotifyShapeChanged(); return copy; } public override void ShiftRight(float distance) { if (t_end > t_start) { Radius += distance; } else { Radius -= distance; } if (Radius <= 0) { Invalidate(); } else { NotifyShapeChanged(); } } protected override void NotifyShapeChanged() { Start = GetTwodPos(0f); End = GetTwodPos(1f); base.NotifyShapeChanged(); } public override string ToString() { return "Arc centered at " + Center + " Start = " + Start + " ,End = " + End; } }
Shell
UTF-8
530
3.453125
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # ---------------------------- # https://www.codewars.com/kata/56e3cd1d93c3d940e50006a4/solutions/shell # How Green Is My Valley # ---------------------------- makevalley() { sorted=($(echo "$1" | xargs -n1 | sort -n -r)) n=${#sorted[@]} for i in $(seq 1 $n); do item=${sorted[$i - 1]} if [ ${#l[@]} == ${#r[@]} ]; then l+=($item) else r+=($item) fi done echo "${l[@]} $(echo ${r[@]} | xargs -n1 | sort -n | tr '\n' ' ')" } makevalley "$1"
C++
UTF-8
807
3.015625
3
[ "MIT" ]
permissive
#ifndef LIFE_HH #define LIFE_HH #include <vector> enum Generation { Current, Previous }; class Game { public: Game(int rows, int cols) : rows(rows), cols(cols), board(rows * cols, false) {} int GetRows() const; int GetCols() const; const std::vector<bool>& GetBoard() const; bool At(const int row, const int col, Generation generation=Current) const; void Activate(const int row, const int col); void Deactivate(const int row, const int col); void Toggle(const int row, const int col); void Evolve(); void Print() const; inline int Translate(const int row, const int col) const; private: void Set(const int row, const int col, bool value); int rows; int cols; std::vector<bool> board; std::vector<bool> previous; }; #endif
Python
UTF-8
2,217
2.765625
3
[]
no_license
import h5py from sklearn.utils import check_random_state import numpy as np from modeling.utils import balanced_class_weights from keras.utils import np_utils class HDF5FileDataset(object): def __init__(self, file_path, data_name, target_name, batch_size, one_hot=True, random_state=17): assert isinstance(data_name, (list,tuple)) assert isinstance(target_name, (list,tuple)) random_state = check_random_state(random_state) self.__dict__.update(locals()) del self.self self._load_data() self._check_data() def _load_data(self): self.hdf5_file = h5py.File(self.file_path) self.n_classes = {} for target_name in self.target_name: self.n_classes[target_name] = np.max(self.hdf5_file[target_name])+1 def _check_data(self): self.n = None for data_name in self.data_name: if self.n is None: self.n = len(self.hdf5_file[data_name]) else: assert len(self.hdf5_file[data_name]) == self.n for target_name in self.target_name: assert len(self.hdf5_file[target_name]) == self.n def __getitem__(self, name): return self.hdf5_file[name].value def class_weights(self, class_weight_exponent, target): return balanced_class_weights( self.hdf5_file[target], 2, class_weight_exponent) def generator(self, one_hot=None, batch_size=None): if one_hot is None: one_hot = self.one_hot if batch_size is None: batch_size = self.batch_size while 1: idx = self.random_state.choice(self.n, size=batch_size, replace=False) batch = {} for data_name in self.data_name: batch[data_name] = self.hdf5_file[data_name].value[idx] for target_name in self.target_name: target = self.hdf5_file[target_name].value[idx] if one_hot: batch[target_name] = np_utils.to_categorical(target, self.n_classes[target_name]) else: batch[target_name] = target yield batch
Java
UTF-8
205
1.703125
2
[]
no_license
package com.zoo.repository; import com.zoo.model.Dragon; import org.springframework.data.mongodb.repository.MongoRepository; public interface DragonRepository extends MongoRepository<Dragon, String> { }
JavaScript
UTF-8
4,619
2.75
3
[]
no_license
import compareAsc from 'date-fns/compareAsc'; import { cloneDeep } from 'lodash'; import statesAbbrv from '@/assets/json-data/states_abbrv.json'; const cutOffDate = '2/25/20'; const filterByRegion = (data = [], countryRegion = 'US') => data.filter(dt => dt['Country/Region'] === countryRegion); const getMostRecentCases = data => { const keysToExclude = ['Province/State', 'Country/Region', 'Lat', 'Long']; const keys = Object.keys(data).filter(key => keysToExclude.indexOf(key) < 0); const mostRecent = keys[keys.length - 1]; // temp handling the data return parseInt(data[mostRecent]); }; const addMostRecentRegion = data => { return data.map((st) => { const sum = getMostRecentCases(st); const state = cloneDeep(st); state.sum = sum || 0; return state; }); }; const arraySum = arr => arr.reduce((a, b) => a + b, 0); const getMaxMin = (statesData = []) => { const stateNumbers = statesData.map(state => state.sum); const nationalTotal = arraySum(stateNumbers); const max = Math.max(...stateNumbers); const highestState = statesData.find((st) => st.sum === max); return { nationalTotal, highestState, max, min: Math.min(...stateNumbers), totalStates: statesData.length }; }; const getMarker = (data, scale) => { const sizeScale = Math.ceil(data.sum / scale) + 2; return { position: { lat: parseFloat(data.Lat), lng: parseFloat(data.Long) }, icon: { scale: Math.min(sizeScale, 30), fillColor: data.sum > 2000 ? 'black' : data.sum > 1000 ? '#404040' : 'red', strokeWeight: 2, fillOpacity: 1 }, sum: data.sum, ...data }; }; const getUsStates = cases => { return cases.filter(itm => { const stateName = itm['Province/State']; const region = itm['Country/Region']; return region === 'US' && stateName.split(',').length === 1; }); }; const processData = (cases, scale = 10) => { const usCases = getUsStates(cases); const states = addMostRecentRegion(usCases); return { maxMin: getMaxMin(states), markers: states.map(st => getMarker(st, scale)) }; }; const findRegionLatest = (cases, regionName) => { const region = cases.find( cases => cases['Province/State'] === regionName && cases['Country/Region'] === 'US' ); return region ? getMostRecentCases(region) : 0; }; const dailyUsTotal = cases => { const statesData = getUsStates(cases); const keys = Object.keys(statesData[0]); const usData = {}; keys.forEach(key => { if (compareAsc(new Date(key), new Date(cutOffDate)) > 0) { const numbers = statesData.map(state => parseInt(state[key] || 0, 10)); usData[key] = arraySum(numbers); } }); return usData; }; const mapData = (confirmed, death, recovered) => { const dataItems = []; const dataKeys = Object.keys(confirmed); dataKeys.forEach(key => { const data = {}; data.date = key; data.confirmed = +confirmed[key]; data.death = +death[key]; data.recovered = +recovered[key]; data.active = data.confirmed - data.death - data.recovered; dataItems.push(data); }); return dataItems; }; const getStateData = (cases, stateName) => { const data = cases.find(st => st['Province/State'] === stateName); const dataClone = cloneDeep(data); if (dataClone) { delete dataClone['Province/State']; delete dataClone['Country/Region']; delete dataClone['Lat']; delete dataClone['Long']; } return dataClone; }; const getCountiesByState = (cases, stateName) => { const stateAbrv = statesAbbrv.find(st => st.name === stateName); if (!stateAbrv) { return []; } const usCases = filterByRegion(cases, 'US'); return usCases.filter(st => { const regionName = st['Province/State']; const names = regionName.split(','); if (names.length > 1) { return stateAbrv.abbreviation === names[1].trim(); } }); }; const customSort = (items, sortBys, isDescs) => { const [sortBy] = sortBys; const [isDesc] = isDescs; items.sort((a, b) => { if (sortBy === 'date') { const dateA = new Date(a.date); const dateB = new Date(b.date); if (!isDesc) { return compareAsc(dateA, dateB); } return compareAsc(dateB, dateA); } if (!isDesc) { return a[sortBy] < b[sortBy] ? -1 : 1; } return b[sortBy] < a[sortBy] ? -1 : 1; }); return items; }; export const dataSrv = { customSort, getCountiesByState, getUsStates, getStateData, dailyUsTotal, mapData, findRegionLatest, getMostRecentCases, processData, filterByRegion, addMostRecentRegion, getMaxMin };
Go
UTF-8
5,133
2.515625
3
[]
no_license
package gate import ( "errors" "os" "os/signal" "fmt" "github.com/colefan/config" "github.com/colefan/sailfish/log" "github.com/colefan/sailfish/network" ) const ( // DefaultMaxNum 默认最大用户数 DefaultMaxNum int = 5000 ) const ( TagProd = "prod" TagDev = "dev" TagTest = "test" ) //Gate a gate for routing and load balance type Gate struct { MaxClientConnNum int LittleEndian bool //大小字节 proxyServer *network.Server certFile string keyFile string clientServer *network.Server bInit bool clientHandler network.SessionHandler //面向客户端的handler serverHandler network.SessionHandler //面向服务端的handler clientProtocol network.Protocol serverProtocol network.Protocol conf *config.IniConfig Tag string } //GetClientServerSessionMgr get session manager func (g *Gate) GetClientServerSessionMgr() *network.SessionMgr { if g.clientServer != nil { return g.clientServer.GetSessionMgr() } return nil } //GetProxyServerSessionMgr get proxy server manager func (g *Gate) GetProxyServerSessionMgr() *network.SessionMgr { if g.proxyServer != nil { return g.proxyServer.GetSessionMgr() } return nil } //RegisterClientHandler register client handler func (g *Gate) RegisterClientHandler(handler network.SessionHandler) { g.clientHandler = handler } //RegisterProxyServerHandler register server handler func (g *Gate) RegisterProxyServerHandler(handler network.SessionHandler) { g.serverHandler = handler } //SetClientProtocol setter func (g *Gate) SetClientProtocol(p network.Protocol) { g.clientProtocol = p } //SetServerProtocol setter func (g *Gate) SetServerProtocol(p network.Protocol) { g.serverProtocol = p } //SetConfig setter func (g *Gate) SetConfig(cnf *config.IniConfig) { g.conf = cnf } //Config getter func (g *Gate) Config() *config.IniConfig { return g.conf } //Init init gate func (g *Gate) Init() error { log.Info("log starting...") //读取配置 if g.conf == nil { g.conf = config.NewIniConfig() } err := g.conf.Parse("./config/gate.ini") if err != nil { log.Error("parse ./gate.ini error " + err.Error()) return err } g.Tag = g.conf.String("tag") log.Info("gate config parsing success.") g.clientHandler = new(ClientHandler) g.serverHandler = new(ProxyInnerHandler) g.bInit = true return nil } //Run gate func (g *Gate) Run() error { //启动服务 if !g.bInit { return errors.New("gate has not inited") } log.Info("gate run ...") if g.clientHandler == nil || g.serverHandler == nil { return errors.New("gate client handler or server handler not registed") } //g.logger.Info("%v", g.clientProtocol) if g.clientProtocol == nil || g.serverProtocol == nil { //g.logger.Error("gate client protocol or server protocol is nill") return errors.New("gate client protocol or server protocol is nill") } var err error log.Info("proxy listener:" + g.conf.String("serverListener")) g.proxyServer = network.NewTCPServer(g.conf.String("serverListener"), network.MsgHandleModeHandler, g.serverProtocol) g.proxyServer.SetSendChannelSize(10240) g.proxyServer.SetSessionHandler(g.serverHandler) clientServerNetworkType := g.conf.String("clientNetwork") switch clientServerNetworkType { case network.NetWorkTypeTCP: g.clientServer = network.NewTCPServer(g.conf.String("clientListener"), network.MsgHandleModeHandler, g.clientProtocol) case network.NetWorkTypeWS: g.clientServer = network.NewWSServer(g.conf.String("clientListener"), network.MsgHandleModeHandler, g.clientProtocol) case network.NetWorkTypeWSS: g.clientServer = network.NewWSServer(g.conf.String("clientListener"), network.MsgHandleModeHandler, g.clientProtocol) g.keyFile = g.conf.String("keyFile") g.certFile = g.conf.String("certFile") g.clientServer.SetKeyFilePath(g.keyFile) g.clientServer.SetCrtFilePath(g.certFile) default: err = errors.New("unknow client network type:" + clientServerNetworkType) } if err != nil { log.Error("clientListener create error " + err.Error()) return err } log.Info("client listener:" + g.conf.String("clientListener")) g.clientServer.SetSessionHandler(g.clientHandler) g.clientServer.SetSendChannelSize(256) g.clientServer.SetCheckPerSecond(true) if err := g.clientServer.Run(); err != nil { return err } if err := g.proxyServer.Run(); err != nil { return err } GetBroadCast().Run() return nil } //Daemon daemon func (g *Gate) Daemon() { signalChan := make(chan os.Signal) signal.Notify(signalChan) //closec := make(chan int) for { select { case s := <-signalChan: fmt.Printf("receive sigal:%v", s) if s == os.Kill || s == os.Interrupt { g.ShutDown() return } } } log.Info("system quit") // select {} } //ShutDown shutdown gate server func (g *Gate) ShutDown() { log.Info("shutdown route server") if g.proxyServer != nil { g.proxyServer.Stop() } log.Info("shutdown client server ") if g.clientServer != nil { g.clientServer.Stop() } log.Info("finish") } // HandleMsgFunc handle msg func type HandleMsgFunc func(pack network.PackInf)
C#
UTF-8
1,166
2.515625
3
[ "MIT" ]
permissive
using Genesis; using Genesis.Generation; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Genesis.Output.CachedRepo { public class CachedRepositoryGenerator : Generator { public override string CommandText => "aspnet-repo-cached"; public override string Description => "Implements a simple cached repository"; public override string FriendlyName => "Asp.Net Cached Repository"; public CachedRepoConfig Config { get; set; } protected override void OnInitilized() { Config = (CachedRepoConfig)Configuration; } public override async Task<ITaskResult> Execute(GenesisContext genesis, string[] args) { var result = new OutputTaskResult(); foreach (var obj in genesis.Objects) { await ExecuteGraph(obj); } return result; } private async Task ExecuteGraph(ObjectGraph objGraph) { await Task.CompletedTask; //Template.Raw.Replace } } }
JavaScript
UTF-8
5,169
2.703125
3
[]
no_license
const Inc = (function(ItemInc, StorageCtrl, UIInc){ const income = 'income'; // Load event listeners const loadEventListeners = function(){ // Get UI selectors const UISelectors = UIInc.getSelectors(); // Add item event document.querySelector(UISelectors.addBtn).addEventListener('click', itemAddSubmit); // Disable submit on enter document.addEventListener('keypress', function(e){ if(e.keyCode === 13 || e.which === 13){ e.preventDefault(); return false; } }); document.querySelector(UISelectors.itemList).addEventListener('click', itemEditClick); document.querySelector(UISelectors.updateBtn).addEventListener('click', itemUpdateSubmit); document.querySelector(UISelectors.deleteBtn).addEventListener('click', itemDeleteSubmit); document.querySelector(UISelectors.backBtn).addEventListener('click', UIInc.clearEditState); document.querySelector(UISelectors.clearBtn).addEventListener('click', clearAllItemsClick); } const itemAddSubmit = function(e){ // Get form input from UI Controller const input = UIInc.getItemInput(); // Check for name and calorie input if(input.name !== '' && input.cad !== ''){ // Add item const newItem = ItemInc.addItem(input.name, input.cad); // Add item to UI list UIInc.addListItem(newItem); // Get total cad const totalCad = ItemInc.getTotalCad(); UIInc.showTotalCad(totalCad); const total = ItemInc.getTotalCad() - ItemCtrl.getTotalCad(); UIInc.showTotal(total); //Store in localStorage StorageCtrl.storeItem(newItem, income); // Clear fields UIInc.clearInput(); } e.preventDefault(); } const itemEditClick = function(e){ if(e.target.classList.contains('edit-item-inc')){ // Get list item id (item-0, item-1) const listId = e.target.parentNode.parentNode.id; // Break into an array const listIdArr = listId.split('-'); // Get the actual id const id = parseInt(listIdArr[1]); // Get item const itemToEdit = ItemInc.getItemById(id); // Set current item ItemInc.setCurrentItem(itemToEdit); // Add item to form UIInc.addItemToForm(); } e.preventDefault(); } const itemUpdateSubmit = function(e){ // Get item input const input = UIInc.getItemInput(); // Update item const updatedItem = ItemInc.updateItem(input.name, input.cad); // Update UI UIInc.updateListItem(updatedItem); // Get total cad const totalCad = ItemInc.getTotalCad(); UIInc.showTotalCad(totalCad); const total = ItemInc.getTotalCad() - ItemCtrl.getTotalCad(); UIInc.showTotal(total); // Update local storage StorageCtrl.updateItemStorage(updatedItem, income); UIInc.clearEditState(); e.preventDefault(); } const itemDeleteSubmit = function(e){ // Get current item const currentItem = ItemInc.getCurrentItem(); // Delete from data structure ItemInc.deleteItem(currentItem.id); // Delete from UI UIInc.deleteListItem(currentItem.id); // Get total cad const totalCad = ItemInc.getTotalCad(); UIInc.showTotalCad(totalCad); const total = ItemInc.getTotalCad() - ItemCtrl.getTotalCad(); UIInc.showTotal(total); // Delete from local storage StorageCtrl.deleteItemFromStorage(currentItem.id, income); UIInc.clearEditState(); e.preventDefault(); } const clearAllItemsClick = function(){ // Delete all items from data structure ItemInc.clearAllItems(); // Get total cad const totalCad = ItemInc.getTotalCad(); UIInc.showTotalCad(totalCad); const total = ItemInc.getTotalCad() - ItemCtrl.getTotalCad(); UIInc.showTotal(total); // Remove from UI UIInc.removeItems(); // Clear from local storage StorageCtrl.clearItemsFromStorage(income); // Hide UL UIInc.hideList(); } return { init: function(){ // Clear edit state / set initial set UIInc.clearEditState(); // Fetch items from data structure const items = ItemInc.getItems(); // Check if any items if(items.length === 0){ UIInc.hideList(); } else { // Populate list with items UIInc.populateItemList(items); } // Get total cad const totalCad = ItemInc.getTotalCad(); UIInc.showTotalCad(totalCad); const total = ItemInc.getTotalCad() - ItemCtrl.getTotalCad(); UIInc.showTotal(total); // Load event listeners loadEventListeners(); } } })(ItemInc, StorageCtrl, UIInc); Inc.init();
Java
GB18030
925
3.28125
3
[]
no_license
package com.tong.stream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * FileOutputStream * @author Administrator * */ public class FileOutputStreamTest { public static void main(String[] args) { FileOutputStream fos = null; try { fos= new FileOutputStream("d:\\hello.txt",true);//trueԭ String str = "\n"; byte[] b=str.getBytes();//ַתֽ fos.write(b); System.out.println("дɹ"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(fos!=null){ fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
C++
UTF-8
363
2.546875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n,res=0,r; cin>>n; while(n>=10) { while(n) { r=n%10; n=n/10; res=r*r+res; } n=res; res=0; } if(n==1) cout<<"happy number"; else cout<<"not happy number"; }
Python
UTF-8
2,077
4.21875
4
[]
no_license
#############список и цикл for############### ## for magician(вводится новая переменная) magicians = ['alice', 'david', 'carolina'] for magician in magicians: ## новая переменная magician print(magician) #тут к ней обращается компилятор print(magician.title()+"that was a great trick") print("i can't wait for your next trick "+magician.title()) #цикл будет работать до последнего значения в списке my_pizza = ['pepperoni','muchacho','karbonara'] for mylove in my_pizza: print(mylove) print("I really love "+mylove.title()) print("i really love pizza") #########функция range()########### for value in range (1,10): print(value) ################################### numbers = list(range(1,6)) #преобразование в числовой список (массив) print(numbers) #########список четных чисел####### numbers = list(range(2,21,2)) #####здесь третья двойка показывает на число, на которое будет увеличиваться, первая - с какого начинается print(numbers) ########Возведение в степень и добавление к массиву######### squares =[] for value in range(2,21,2): square=value**2 squares.append(square) print(squares) #########генератор списка########!!!!!!!! squares = [value**3 for value in range(2,20,2)] print(squares) ###задание### ##вывести числа от 1 до 20 chisla = [] for value in range(1,21): print(value) ########от 1 до 1кк####### ##chisla = [value for value in range(1,1000001)] ##print(chisla) ##########Суммирование миллиона чисел########## chisla = [value for value in range(1,1000002)] print(min(chisla)) print(max(chisla)) print(sum(chisla)) ###памятка # squares = [] # for value in range(1,11): # square = value**2 # squares.append(square) # print(squares)
Markdown
UTF-8
17,784
2.640625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
> *The following text is extracted and transformed from the livefyre.com privacy policy that was archived on 2015-03-18. Please check the [original snapshot on the Wayback Machine](https://web.archive.org/web/20150318005457id_/http%3A//legal.livefyre.com/privacy) for the most accurate reproduction.* # Privacy Policy - Livefyre Legal Livefyre’s Privacy Policy is designed to help you understand how we collect and use the personal information you share with us, and help you make informed decisions when using Livefyre services, which are located at livefyre.com and its directly associated domains or as made available by its partners at their domains and via their services (collectively, “Livefyre” or “Site”). By using or accessing Livefyre, you are accepting the practices described in this Privacy Policy. We built Livefyre to make it easy for you to share your opinions with your friends and cohorts online. We understand you may not want everyone in the world to have the profile information you share on Livefyre; that is why we give you control of your profile information. You choose what information you put in your profile and have the ability to block people from seeing your profile. Posts submitted within conversations on the Site are public and cannot be deleted. Recent posts you have made on Livefyre show up in your profile by default. ## The Information We Collect When you visit Livefyre you provide us with two types of information: personal information you knowingly choose to disclose that is collected by us and Web Site use information collected by us as you interact with our Site. When you enter Livefyre, we collect your browser type and IP address. This information is gathered for all Livefyre visitors. In addition, we store certain information from your browser using “cookies.” A cookie is a piece of data stored on the user’s computer tied to information about the user. We use session ID cookies to confirm that users are logged in. These cookies terminate once the user closes the browser. By default, we use a persistent cookie that stores your login ID (but not your password) to make it easier for you to login when you come back to Livefyre. You can remove or block this cookie using the settings in your browser if you want to disable the convenience of this feature. When you use Livefyre, you may set up your personal profile, perform searches and participate in conversations. We collect information about what you do when you use Livefyre so that we can provide you the Livefyre service and offer personalized features. When you update information, we usually keep a backup copy of the prior version for a reasonable period of time to enable reversion to the prior version of that information. You post User Content (as defined in the Livefyre Terms of Use) on the Site at your own risk. We cannot control the actions of other Users with whom you may choose to share your pages and information. Therefore, we cannot and do not guarantee that User Content you post on the Site will not be viewed by unauthorized persons. We are not responsible for circumvention of any privacy settings or security measures contained on the Site. You understand and acknowledge that, even after removal, copies of User Content may remain viewable in cached and archived pages of the Site or if other Users have copied or stored your User Content. Any improper collection or misuse of information provided on Livefyre is a violation of the Livefyre Terms of Service and should be reported through the form on our privacy help page. If you choose to use our invitation service to tell a friend about our site, we will ask you for information needed to send the invitation, such as that person’s email address, Facebook username or Twitter username. By providing us with the information of third parties, you represent that you have all necessary rights to share that information with us. Livefyre stores this information to send invitations and reminders and to track the success of our referral program. Your friend may contact us at contact@livefyre.com to request that we remove this information from our database. Livefyre may also collect information about you from other sources, such as newspapers, blogs, instant messaging services, and other users of the Livefyre service through the operation of the service in order to provide you with more useful information and a more personalized experience. By using Livefyre, you are consenting to have your personal data transferred to and processed in the United States. ## Children Under Age 13 Livefyre does not knowingly collect or solicit personal information from anyone under the age of 13 or knowingly allow such persons to register. If you are under 13, please do not attempt to register for Livefyre or send any information about yourself to us, including your name, address, telephone number, or email address. No one under age 13 may provide any personal information to or on Livefyre. In the event that we learn that we have collected personal information from a child under age 13 without verification of parental consent, we will delete that information as quickly as possible. If you believe that we might have any information from or about a child under 13, please contact us at privacy@livefyre.com. ## Children Between the Ages of 13 and 18 We recommend that minors 13 years of age or older ask their parents for permission before sending any information about themselves to anyone over the Internet. ## Use of Information Obtained by Livefyre When you register with Livefyre, you create your own profile. Your profile information is displayed to the public to enable you to connect with people on Livefyre. We may occasionally use your name, Livefyre username, Twitter username or email address to send you notifications regarding new services offered by Livefyre that we think you may find valuable. Profile information is used by Livefyre primarily to be presented back to and edited by you when you access the service and to be presented to others permitted to view that information in accordance with your privacy settings. Profile information you submit to Livefyre will be available to users of Livefyre. Your profile information will be available in search results across the Livefyre network and it may also be made available to third party search engines. This is primarily so people with like interests can find you and connect with you on Livefyre. By submitting profile information to Livefyre, you expressly consent to the uses of that personal information that are described above. Livefyre may send you service-related announcements from time to time through the general operation of the service. Livefyre may use information in your profile without identifying you as an individual to third parties. We do this for purposes such as aggregating how many people in a network like a band or movie and personalizing advertisements and promotions so that we can provide you Livefyre. We believe this benefits you. We may use information about you that we collect from other sources, including but not limited to newspapers and Internet sources such as blogs, instant messaging services, Livefyre Platform developers, Twitter, Facebook and other users of Livefyre, to supplement your profile. Where such information is used, we generally allow you to specify in your privacy settings that you do not want this to be done or to take other actions that limit the connection of this information to your profile. ## Sharing Your Information with Third Parties We share your information with third parties only in limited circumstances where we believe such sharing is 1) reasonably necessary to offer the service, 2) legally required or, 3) permitted by you as specified in this Privacy Policy. For example: We may provide information to service providers to help us bring you the services we offer. Specifically, we may use third parties to facilitate our business, such as to host the service at a co-location facility for servers, to send out email updates about Livefyre, to remove repetitive information from our user lists, to process payments for products or services, to offer an online job application process, or to provide search results or links (including sponsored links). In connection with these offerings and business operations, our service providers may have access to your personal information for use for a limited time in connection with these business activities. Where we utilize third parties for the processing of any personal information, we implement reasonable contractual and technical protections limiting the use of that information to the Livefyre-specified purposes. We occasionally provide demonstration accounts that allow non-users a glimpse into the Livefyre world. Such accounts have only limited capabilities and passwords are changed regularly to limit possible misuse. We may be required to disclose user information pursuant to lawful requests, such as subpoenas or court orders, or in compliance with applicable laws. We do not reveal information until we have a good faith belief that an information request by law enforcement or private litigants meets applicable legal standards. Additionally, we may share account or other information when we believe it is necessary to comply with law, to protect our interests or property, to prevent fraud or other illegal activity perpetrated through the Livefyre service or using the Livefyre name, or to prevent bodily harm. This may include sharing information with other companies, lawyers, agents or government agencies. We may provide services jointly with other companies on Livefyre. You can tell when another company is involved in any service provided on Livefyre, and by using a joint service, you agree that we may share customer information with that company in connection with your use of that service. If the ownership of all or substantially all of the Livefyre business, or individual business units owned by Livefyre, Inc., were to change, your user information may be transferred to the new owner so the service can continue operations. When you use Livefyre, all information you post or share in public areas such as personal information or other information, may be shared with other users. All such sharing of information is done at your own risk. Please keep the open nature of the Livefyre platform in mind when disclosing personal information and opinions. ## Links Livefyre may contain links to other web sites. We are not responsible for the privacy practices of other web sites. We encourage our users to be aware when they leave our site to read the privacy statements of each and every web site that collects personally identifiable information. This Privacy Policy applies solely to information collected by Livefyre. ## Third Party Advertising Advertisements that appear in connection with Livefyre may be delivered (or “served”) directly to users by third party advertisers. When advertisements are served directly by third party advertisers, they automatically receive your IP address and may also download cookies to your computer, or use other technologies such as JavaScript and “web beacons” (also known as “1×1 gifs”) to measure the effectiveness of their ads and to personalize advertising content. Livefyre does not have access to or control of the cookies that may be placed by the third party advertisers. Third party advertisers have no access to your contact information stored on Livefyre unless you choose to share it with them. This privacy policy covers the use of cookies by Livefyre and does not cover the use of cookies or other tracking technologies by any of its advertisers. ## Changing or Removing Information Access and control over most personal information on Livefyre is readily available through the profile editing tools. Livefyre users may modify or delete profile information at any time by logging into their account. Information will be updated immediately. Removed information may persist in backup copies for a reasonable period of time but will not be generally available to members of Livefyre. Where you make use of the communication features of the service to share information with other individuals on Livefyre, however, you may not be able to “unshared” or remove all communications. ## Security Livefyre takes appropriate precautions to protect our users’ information. Please do not send private information to us by email or instant messaging services. If you have any questions about the security of Livefyre Web Site, please contact us at privacy@livefyre.com. ## Terms of Use, Notices and Revisions Your use of Livefyre, and any disputes arising from it, is subject to this Privacy Policy as well as our Terms of Use and all of its dispute resolution provisions including arbitration, limitation on damages and choice of law. We reserve the right to change our Privacy Policy and our Terms of Use at any time. Non-material changes and clarifications will take effect immediately, and material changes will take effect within 30 days of their posting on this site. If we make material changes to this policy, we will notify you here, by email, or through notice on our home page. We encourage you to refer to this policy on an ongoing basis so that you understand our current privacy policy. Unless stated otherwise, our current privacy policy applies to all information that we have about you and your account. ## Contacting the Web Site If you have any questions about this privacy policy, please email us at privacy@livefyre.com. ## Safety Livefyre aspires to be an environment where people can interact safely with their friends and the people around them. Children under 13 years old are not permitted access to Livefyre. In addition, parents of children 13 years and older should consider whether their child should be supervised during the child’s use of the Livefyre site. Despite Livefyre’s safety and privacy controls, Livefyre cannot guarantee that its site is entirely free of illegal, offensive, pornographic or otherwise inappropriate material, or that its members will not encounter inappropriate or illegal conduct from other members. Consequently, you may encounter such content and conduct. You can help Livefyre by notifying us of any nudity or pornography, or harassment or unwelcome contact by emailing us at safety@livefyre.com. We need all users to report suspicious people and inappropriate content they encounter on Livefyre. And we strongly encourage users under the age of 18 to talk to their parents or a responsible adult immediately if someone online says or does something to make them feel uncomfortable or threatened in any way. Remember that although using fake names is a violation of the Livefyre Terms of Use, people are not always who they say they are. You should always be careful when contacting people you do not know in the real world. And it is always risky to meet anyone in person whom you don’t know through real world friends. Always follow these important safety tips when using Livefyre: * • Never share your password with anyone; * • Be cautious about posting and sharing personal information, especially information that could be used to identify you or locate you offline; * • Report users and content that violate our Terms of Use; and * • Block and report anyone that sends you unwanted or inappropriate communications. ## For Parents: Livefyre strongly urges parents to talk to their children about the dangers they may encounter online, and to make sure their children are using Livefyre in a safe manner. Parents may want to install monitoring software on home computers if they are concerned about what their children are doing online. Children must know that they should report any inappropriate or offensive Livefyre content to their parents and to Livefyre using the tools made available through the site. Parents should always remind their children to follow the important safety tips listed on this page when using Livefyre. More information regarding Internet safety can be found on the following sites: * • OnguardOnline.gov * • WiredSafety.org * • Commonsense.com * • Ncmec.org * • TRUSTe.org * • ConnectSafely.org * • NetSmartz.org * • WebWiseKids.org ## U.S.-EU Safe Harbor Framework Livefyre complies with the U.S.-EU Safe Harbor Framework as set forth by the U.S. Department of Commerce regarding the collection, use, and retention of personal information from European Union member countries. Livefyre has certified that it adheres to the Safe Harbor Privacy Principles of notice, choice, onward transfer, security, data integrity, access, and enforcement. To learn more about the Safe Harbor program, and to view our certification page, please visit http://www.export.gov/safeharbor/. Privacy Complaints by European Union Citizens: In compliance with the Safe Harbor Principles, Livefyre commits to resolve complaints about your privacy and our collection or use of your personal information. European Union citizens with inquiries or complaints regarding this privacy policy should first contact Livefyre at: Livefyre Legal Department – Attention: Privacy 360 Third Street Suite 700 San Francisco, CA 94107 privacy@livefyre.com Livefyre has further committed to refer unresolved privacy complaints under the US-EU Safe Harbor Principles to an independent dispute resolution mechanism, the BBB EU SAFE HARBOR, operated by the Council of Better Business Bureaus. If you do not receive timely acknowledgment of your complaint, or if your complaint is not satisfactorily addressed by Livefyre, please visit the BBB EU SAFE HARBOR web site for more information and to file a complaint. * * *
PHP
UTF-8
2,919
2.59375
3
[ "X11", "MIT" ]
permissive
<?php /** * 2014 - 2022 Watt Is It * * NOTICE OF LICENSE * * This source file is subject to the MIT License X11 * that is bundled with this package in the file LICENSE.md. * It is also available through the world-wide-web at this URL: * https://opensource.org/licenses/mit-license.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to contact@paygreen.fr so we can send you a copy immediately. * * @author PayGreen <contact@paygreen.fr> * @copyright 2014 - 2022 Watt Is It * @license https://opensource.org/licenses/mit-license.php MIT License X11 * @version 2.6.1 * */ namespace PGI\Module\PGModule\Services\Officers; use PGI\Module\PGModule\Entities\Setting; use PGI\Module\PGModule\Interfaces\Entities\SettingEntityInterface; use PGI\Module\PGModule\Interfaces\Officers\SettingsOfficerInterface; use PGI\Module\PGModule\Services\Managers\SettingManager; use PGI\Module\PGShop\Services\Handlers\ShopHandler; /** * Class SettingsDatabaseOfficer * @package PGModule\Services\Officers */ class SettingsDatabaseOfficer implements SettingsOfficerInterface { /** @var Setting[] */ private $settings = null; /** @var SettingManager */ private $settingManager; /** @var ShopHandler */ private $shopHandler; public function __construct( SettingManager $settingManager, ShopHandler $shopHandler = null ) { $this->settingManager = $settingManager; $this->shopHandler = $shopHandler; } protected function init() { if ($this->settings === null) { $this->settings = $this->settingManager->getAllByShop($this->getCurrentShop()); } } protected function getCurrentShop() { return ($this->shopHandler !== null) ? $this->shopHandler->getCurrentShop() : null; } public function clean() { $this->settings = null; } public function getOption($key, $defaultValue = null) { $this->init(); return isset($this->settings[$key]) ? $this->settings[$key]->getValue() : $defaultValue; } public function setOption($key, $value) { $this->init(); $result = true; if (isset($this->settings[$key])) { $this->settings[$key]->setValue($value); $result = $this->settingManager->update($this->settings[$key]); } else { $this->settingManager->insert($key, $value, $this->getCurrentShop()); } return $result; } public function unsetOption($key) { $this->init(); $result = true; if (isset($this->settings[$key])) { $result = $this->settingManager->delete($this->settings[$key]); } return $result; } public function hasOption($key) { $this->init(); return isset($this->settings[$key]); } }
Python
UTF-8
1,434
3.875
4
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2020/5/12 19:04 # @Author : tianyunzqs # @Description : """ 152. Maximum Product Subarray Medium Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. """ class Solution: def maxProduct(self, nums: list) -> int: max_product = nums[0] imax, imin = 1, 1 for i, num in enumerate(nums): # 如果num为负数,那么之前的最大值乘以负数就成了最小值,故需要交换 if num < 0: imax, imin = imin, imax # imax主要是记录到nums[i-1]的最大值, # 当运行到nums[i]时,有两种选择: # 1.将当前数nums[i]累乘到imax; # 2.重新开始 imax = max(imax * num, num) # imin主要是为了防止负数的存在,对最大值的影响 imin = min(imin * num, num) max_product = max(max_product, imax) return max_product if __name__ == '__main__': print(Solution().maxProduct([2, 3, -2, 4, 0, 2, -3])) print(Solution().maxProduct([-2, 0, -1])) print(Solution().maxProduct([-2, 0, -2, 5]))
C#
UTF-8
7,138
2.546875
3
[]
no_license
using CarpentyStore2.Domain.Abstract; using CarpentyStore2.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CarpentryStore2.Controllers { public class AdminController : Controller { private IDoorRepository repository; public AdminController (IDoorRepository repo) { repository = repo; } // GET: Admin public ActionResult Index() { return View(repository.Doors); } public ActionResult Edit(int doorId) { Door door = repository.Doors .FirstOrDefault(d => d.DoorId == doorId); return View(door); } [HttpPost] public ActionResult Edit(Door door, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) { door.ImageMimeType = image.ContentType; door.ImageData = new byte[image.ContentLength]; image.InputStream.Read(door.ImageData, 0, image.ContentLength); } repository.SaveDoor(door); TempData["message"] = string.Format("{0} has been saved ", door.TypeDoor); return RedirectToAction("Index"); } else { return View(door); } } // Добавление нового товара в Doors public ViewResult Create() { return View("Edit", new Door()); } public ViewResult CreateLand() { return View("EditLand", new Land()); } public ActionResult LandIndex() { return View(repository.Lands); } public ActionResult EditLand(int landId) { Land land = repository.Lands. FirstOrDefault(l => l.LandId == landId); return View(land); } // EditLand для редактирования таблицы Lands. [HttpPost] public ActionResult EditLand(Land land, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) { land.ImageMimeType = image.ContentType; land.ImageData = new byte[image.ContentLength]; image.InputStream.Read(land.ImageData, 0, image.ContentLength); } repository.SaveLand(land); TempData["message"] = string.Format("{0} has been saved", land.TypeOfLand); return RedirectToAction("LandIndex"); } else { return View(land); } } [HttpPost] public ActionResult DeleteLand(int LandId) { Land deletedLand = repository.DeleteLand(LandId); if (deletedLand != null) { TempData["message"] = String.Format("{0} was deleted", deletedLand.TypeOfLand); } return RedirectToAction("LandIndex"); } [HttpPost] public ActionResult Delete(int DoorId) { Door deletedDoor = repository.DeleteDoor(DoorId); if (deletedDoor != null) { TempData["message"] = String.Format("{0} was deleted", deletedDoor.TypeDoor); } return RedirectToAction("Index"); } public ActionResult ArmchairIndex() { return View(repository.Armchairs); } public ActionResult EditArmchair(int ArmchairId) { Armchair armchair = repository.Armchairs. FirstOrDefault(l => l.ArmchairId == ArmchairId); return View(armchair); } // EditLand для редактирования таблицы Armchairs. [HttpPost] public ActionResult EditArmchair(Armchair armchair, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) { armchair.ImageMimeType = image.ContentType; armchair.ImageData = new byte[image.ContentLength]; image.InputStream.Read(armchair.ImageData, 0, image.ContentLength); } repository.SaveArmchair(armchair); TempData["message"] = string.Format("{0} has been saved", armchair.TypeOfArmchair); return RedirectToAction("ArmchairIndex"); } else { return View(armchair); } } public ViewResult CreateArmchair() { return View("EditArmchair", new Land()); } [HttpPost] public ActionResult DeleteArmchair(int ArmchairId) { Armchair deletedArmchair = repository.DeleteArmchair(ArmchairId); if (deletedArmchair != null) { TempData["message"] = String.Format("{0} was deleted", deletedArmchair.TypeOfArmchair); } return RedirectToAction("ArmchairIndex"); } public ActionResult TableIndex() { return View(repository.Tables); } public ActionResult EditTable(int TableId) { Table table = repository.Tables. FirstOrDefault(l => l.TableId == TableId); return View(table); } // EditLand для редактирования таблицы Armchairs. [HttpPost] public ActionResult EditTable(Table table, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null) { table.ImageMimeType = image.ContentType; table.ImageData = new byte[image.ContentLength]; image.InputStream.Read(table.ImageData, 0, image.ContentLength); } repository.SaveTable(table); TempData["message"] = string.Format("{0} has been saved", table.TypeOfTable); return RedirectToAction("TableIndex"); } else { return View(table); } } [HttpPost] public ActionResult DeleteTable (int TableId) { Table deletedTable = repository.DeleteTable(TableId); if (deletedTable != null) { TempData["message"] = String.Format("{0} was deleted", deletedTable.TypeOfTable); } return RedirectToAction("TableIndex"); } } }
JavaScript
UTF-8
2,664
2.546875
3
[]
no_license
/** * @author CallMeMrSam */ const Client = require('../../../structure/Client'); const Language = require('../../../structure/Language'); const { Command, Embed } = require('../../../structure/Bot'); const { Message } = require('discord.js'); const dayjs = require('dayjs'); module.exports = class extends Command { /** * Command * @param {Client} client */ constructor(client) { super(client, { name: "userinfo", aliases: ['ui'], usage: ['userinfo', 'userinfo <@user>'] }); } /** * Exécuter la commande * @param {Language} language * @param {Message} message * @param {String[]} args */ async run(language, message, args) { let user = this.client.users.cache.get(args[0]) || message.mentions.users.first() || message.author; let badges = message.author.badges; if(user.id !== message.author.id) badges = this.client.globalBadges.getUserBadges(user, this.client, await this.client.db.getUser(message.author.id)) let avatarURL = user.avatarURL(); let username = user.username; let tag = user.discriminator; let id = user.id; let creationDate = dayjs(user.createdAt).format(language.get('general', 'time.format')).toString(); let infos = new Embed(this.client, 'main', language) .setAuthor(user.tag, avatarURL) .addField(language.get('commands', 'userinfo.username'), `> \`${username}\``, true) .addField(language.get('commands', 'userinfo.tag'), `> \`${tag}\``, true) .addField(language.get('commands', 'userinfo.id'), `> \`${id}\``, true) if(badges.length > 0) infos.setDescription(language.get('general', 'global_badges', { b: badges.join(' ') })) if(message.guild.members.cache.get(id)) { let member = message.guild.members.cache.get(id); let rolesSize = member.roles.cache.filter(x => x.id !== x.guild.id).size; let roles = member.roles.cache.filter(x => x.id !== x.guild.id).sort((a, b) => a.position - b.position).map(x => ['#2f3136'].includes(x.hexColor.toLowerCase()) ? `@${x.name}` : x).join(', ') if(!roles) roles = language.get('commands', 'userinfo.no_role'); let joinDate = dayjs(member.joinedAt).format(language.get('general', 'time.format')).toString(); infos .setColor(member.displayHexColor) .addField(language.get('commands', 'userinfo.roles') + ` (${rolesSize})`, `> ${roles}`) .addField(language.get('commands', 'userinfo.join_date'), `> ${joinDate}`) } infos .addField(language.get('commands', 'userinfo.creation_date'), `> ${creationDate}`) .sender(message.author) .sendIn(message.channel) } }
Python
UTF-8
186
3.015625
3
[]
no_license
class StringExpression: def __init__(self, x): self.x = x def __truediv__(self, other): result = int(self.x) + 2 * (int(other.x)) return result
Java
UTF-8
160
2.171875
2
[]
no_license
public class SinhVienRepository extends AbstractRepository<Student, Long> { public SinhVienRepository() { super(Student.class, Long.class); } }
C#
UTF-8
882
3.25
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; namespace CSharpExcel { class Program { static void Main(string[] args) { var personList = new List<Person> { new Person("Ksenia", "Данилкина", 28, "79612213455"), new Person("Karina", "Ivanova", 29, "79682213455"), new Person("Ivan", "Ivanov", 55, "79682217855"), new Person("Oleg", "Zykov", 49, "79786213455") }; var table = new ExcelGenerator().Generate(personList); try { File.WriteAllBytes("Students.xlsx", table); } catch (IOException) { Console.WriteLine("Возникла ошибка при выводе данных в файл."); } } } }
Java
UTF-8
3,263
2.21875
2
[]
no_license
package com.example.nhnent.myprogress; import android.app.ProgressDialog; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { ProgressBar progressBar; SeekBar seekBar; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); textView = (TextView) findViewById(R.id.textView); progressBar = (ProgressBar) findViewById(R.id.progressBar); seekBar = (SeekBar) findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { textView.setText("설정된 값 : " + progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } public void onButton1Clicked(View v){ progressBar.setProgress(50); } public void onButton2Clicked(View v){ ProgressDialog dialog = new ProgressDialog(this); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle("진행상태"); dialog.setMessage("데이터를 확인하는 중입니다"); dialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } else if ( id == R.id.action_search){ Toast.makeText(MainActivity.this, "Search Menu Selected", Toast.LENGTH_LONG).show(); return true; } return super.onOptionsItemSelected(item); } }
TypeScript
UTF-8
1,114
3.15625
3
[]
no_license
export const POINTER = (duraction: number): string => { const segundos = duraction / 1000; const minutos = segundos / 60; const horas = minutos / 60; return POINTER_FORMAT(`${horas}:${minutos}:${segundos}`); } export const POINTER_FULL = (duraction: string): number => { const timeFull = duraction.split(':'); const horas = parseInt(timeFull[0]) * 3600; const minutos = parseInt(timeFull[1]) * 60; const segundos = parseInt(timeFull[2]); const total = horas + minutos + segundos; return total; } const POINTER_FORMAT = (timer: string): string => { const array: string[] = []; const arrayTime = timer.split(':'); arrayTime.forEach(number => { if (parseInt(number.split('.')[0]) < 10) { array.push(`0${parseInt(number.split('.')[0])}`); } else { array.push(`${parseInt(number.split('.')[0])}`); } }); const second = POINTER_FORMAT_SECOND(array[2]); return `${array[0]}:${array[1]}:${second}`; } const POINTER_FORMAT_SECOND = (second: string): string => { const caracter = second.split(''); return `${caracter[0]}${caracter[1]}`; }
JavaScript
UTF-8
2,131
2.546875
3
[]
no_license
import AudioManager from "./audioManager.js"; import InputManager from "./inputManager.js"; import Population from "./population.js"; const startGame = () => { document.getElementById("click-overlay").style.display = "none"; window.removeEventListener("click", startGame); const canvas = document.getElementById("game"); const context = canvas.getContext("2d"); const inputManager = new InputManager(canvas); const populationManager = new Population(6, inputManager, canvas); const dpi = window.devicePixelRatio; const state = { currentSongInfo: null, elapsedTicks: 0 }; window.state = state; window.game = populationManager; context.webkitImageSmoothingEnabled = false; context.mozImageSmoothingEnabled = false; context.imageSmoothingEnabled = false; const fixDPI = () => { const styleHeight = +getComputedStyle(canvas).getPropertyValue("height").slice(0, -2); const styleWidth = +getComputedStyle(canvas).getPropertyValue("width").slice(0, -2); canvas.setAttribute("height", styleHeight * dpi); canvas.setAttribute("width", styleWidth * dpi); }; const tick = () => { state.elapsedTicks++; fixDPI(); context.clearRect(0, 0, canvas.width, canvas.height); populationManager.update(state.elapsedTicks, canvas, state.currentSongInfo); populationManager.draw(canvas, context); // state.currentLevel?.update(state.elapsedTicks, canvas, inputManager); // state.currentLevel?.draw(canvas, context); window.requestAnimationFrame(tick); }; const onPlay = songInfo => { state.currentSongInfo = songInfo; }; const onTimeUpdate = ({ gain, analyser }) => { //gain.gain.value = Math.random(); //if (state.audioVisualizer) //analyser.getByteTimeDomainData(state.audioVisualizer.dataArray); }; const audioManager = new AudioManager(); audioManager.startPlaylist({ timeupdate: onTimeUpdate, play: onPlay }); tick(); }; window.addEventListener("click", startGame);
C#
UTF-8
399
3.1875
3
[]
no_license
using System; namespace calculator_oop { public class Extraction : IOneArgumentCalculator { public double calculate(double firstNumber) { if (firstNumber < 0) { throw new Exception("Х не долженбыть отрицательным"); } return Math.Sqrt(firstNumber); } } }
Java
UTF-8
1,422
2.3125
2
[]
no_license
package com.lq.po; /** * 招聘信息持久类 * @author 27602 * */ public class Recruit { private int rec_id; private String rec_name; private int rec_number; private String rec_sex; private String rec_describe; private String rec_city; private int rec_pay; public int getRec_id() { return rec_id; } public void setRec_id(int rec_id) { this.rec_id = rec_id; } public String getRec_name() { return rec_name; } public void setRec_name(String rec_name) { this.rec_name = rec_name; } public int getRec_number() { return rec_number; } public void setRec_number(int rec_number) { this.rec_number = rec_number; } public String getRec_sex() { return rec_sex; } public void setRec_sex(String rec_sex) { this.rec_sex = rec_sex; } public String getRec_describe() { return rec_describe; } public void setRec_describe(String rec_describe) { this.rec_describe = rec_describe; } public String getRec_city() { return rec_city; } public void setRec_city(String rec_city) { this.rec_city = rec_city; } public int getRec_pay() { return rec_pay; } public void setRec_pay(int i) { this.rec_pay = i; } /*@Override public String toString() { return "Recruit [rec_id=" + rec_id + ", rec_name=" + rec_name + ", rec_number=" + rec_number + ", rec_sex=" + rec_sex + ", rec_describe=" + rec_describe + ", rec_city=" + rec_city + ", rec_pay=" + rec_pay + "]"; }*/ }
Swift
UTF-8
3,933
3
3
[]
no_license
// // Extensions.swift // SongDemon // // Created by Tommy Fannon on 8/10/14. // Copyright (c) 2014 crazy8dev. All rights reserved. // import MediaPlayer extension String { var length: Int { return self.characters.count } // Swift 1.2 } extension MPMediaItem { var songInfo: String { //return "\(self.albumArtist ?? "") - \(self.albumTitle!) : \(self.albumTrackNumber). \(self.title!)" return "\(self.albumArtist ?? "") - \(self.albumTitle ?? "") : \(self.albumTrackNumber). \(self.title ?? "")" } var year : String { let yearAsNum = self.value(forProperty: "year") as! NSNumber if yearAsNum.isKind(of: NSNumber.self) { return yearAsNum == 0 ? "" : "\(yearAsNum.int32Value)" } return "" } func getArtworkWithSize(_ frame : CGSize) -> UIImage? { //return self.artwork != nil ? self.artwork!.imageWithSize(frame) : nil return self.artwork?.image(at: frame) } var playTime : TimeStruct { get { let totalPlaybackTime = Int(self.playbackDuration) let hours = (totalPlaybackTime / 3600) let mins = ((totalPlaybackTime/60) - hours*60) let secs = (totalPlaybackTime % 60 ) return TimeStruct(hours: hours, mins: mins, seconds: secs) } } var safeArtist: String { if let ret = self.albumArtist { return ret } if let ret = self.artist { return ret } return "" } var safeAlbum: String { if let ret = self.albumTitle { return ret } return "" } var safeTitle: String { return self.title ?? "" // if let ret = self.title { // return ret // } // return "" } //provides a way to persist var hashKey: String { return self.persistentID.description; } var albumHashKey : String { return self.albumPersistentID.description; } var artistHashKey: String { return self.artistPersistentID.description } } extension UIViewController { func alert(title: String? = nil, message:String = "") { let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in })) DispatchQueue.main.async { self.present(alert, animated: true) } } } extension UISlider { var timeValue : TimeStruct { get { return TimeStruct(totalSeconds: self.value) } set(time) { self.value = Float(time.totalSeconds) } } } extension Array { func find(_ includedElement: (Element) -> Bool) -> Int? { for (idx, element) in self.enumerated() { if includedElement(element) { return idx } } return nil } //shuffle the array in place mutating func shuffle() { for i in 0..<(count - 1) { let j = Int(arc4random_uniform(UInt32(count - i))) + i swap(&self[i], &self[j]) } } } extension Dictionary { init(_ elements: [Element]){ self.init() for (k, v) in elements { self[k] = v } } func map<U>(_ transform: (Value) -> U) -> [Key : U] { return Dictionary<Key, U>(self.map({ (key, value) in (key, transform(value)) })) } func map<T : Hashable, U>(_ transform: (Key, Value) -> (T, U)) -> [T : U] { return Dictionary<T, U>(self.map(transform)) } func filter(_ includeElement: (Element) -> Bool) -> [Key : Value] { return Dictionary(self.filter(includeElement)) } func reduce<U>(_ initial: U, combine: (U, Element) -> U) -> U { return self.reduce(initial, combine: combine) } }
JavaScript
UTF-8
1,577
2.65625
3
[ "MIT" ]
permissive
#!/usr/bin/env node const fs = require('fs'); const path = require('path'); const argv = require('optimist').argv; const find = require('../index.js'); function usage() { console.log('Usage: [flag] <path>\n'); console.log('Flags:'); console.log(' --name The name of the callee. default: console\n'); console.log('Example:'); console.log(' $ jscode-find-callee --name myCall source.js'); } if (process.argv.length === 2) { usage() process.exit(1) } let name = 'console' if (argv.name) { name = argv.name } let input = '' if (argv._.length === 0) { input = '.' } else { input = argv._[0] } /** * process the given input path and check if input is a file or folder * @param {string} input The input path */ function processing(input) { if (fs.lstatSync(input).isDirectory()) { processingDir(input) } else { processingFile(input) } } /** * process the given input file * @param {string} input The input path */ function processingFile(input) { if (path.extname(input) === '.js') { fs.readFile(input, function(err, data) { if (err) { console.log('Error:', err.message); process.exit(1) } find(input, data.toString('utf8'), name); }) } } /** * process the given input folder * @param {string} input The input path */ function processingDir(input) { fs.readdir(input, function(err, files) { if (err) { console.log('Error:', err.message); process.exit(1) } files.forEach(elem => { processing(path.join(input, elem)) }); }) } processing(input)
Shell
UTF-8
1,320
2.8125
3
[]
no_license
export PATH=~/bin:$PATH [[ -s "/Users/zporter/.rvm/scripts/rvm" ]] && source "/Users/zporter/.rvm/scripts/rvm" # This loads RVM into a shell session. # display git info function parse_git_dirty { [[ $(git status 2> /dev/null | tail -n1) != "nothing to commit (working directory clean)" ]] && echo "*" } function parse_git_branch { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/ (\1$(parse_git_dirty))/" } export PS1='\u \[\033[1;32m\]\w\[\033[33m\]$(parse_git_branch)\[\033[0m\]$ ' # aliases alias b=bundle alias be='bundle exec' alias pg='pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start' alias pgkill='pg_ctl -D /usr/local/var/postgres stop -s -m fast' alias mongostart='sudo mongod run --config /usr/local/Cellar/mongodb/1.8.1-x86_64/mongod.conf' # bdsm bits export projects_path="$HOME/projects" [[ -s "/usr/local/bdsm/extensions/builtin/core/modules/shell/project/interactive" ]] && source "/usr/local/bdsm/extensions/builtin/core/modules/shell/project/interactive" [[ -s "/usr/local/bdsm/extensions/builtin/core/modules/shell/project/interactive" ]] && source "/usr/local/bdsm/extensions/builtin/core/modules/shell/project/interactive" # dev-update command alias refreshr='brew update && rvm get head && rvm reload && gem update --system && gem update'
Python
UTF-8
175
3.09375
3
[]
no_license
def calc(a,b): sum = a+b difference = a-b multiply = a*b divide = a / b calclist = [a+b, a-b, a*b, a/b] sum = 0 for i in list: sum += i
C++
UTF-8
862
3.609375
4
[]
no_license
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: bool isSameTree(TreeNode* r1, TreeNode* r2) { if(r2 == NULL) return true; if(r1 == NULL) return false; return r1->val == r2->val && isSameTree(r1->left, r2->left) && isSameTree(r1->right, r2->right); } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { bool result = false; if(pRoot1 != NULL && pRoot2 != NULL) { if(pRoot1->val == pRoot2->val) result = isSameTree(pRoot1, pRoot2); if(!result) result = HasSubtree(pRoot1->left, pRoot2); if(!result) result = HasSubtree(pRoot1->right, pRoot2); } return result; } };
Markdown
UTF-8
5,042
2.75
3
[]
no_license
--- description: "Simple Way to Make Speedy Usal (Sprouted beans)" title: "Simple Way to Make Speedy Usal (Sprouted beans)" slug: 2156-simple-way-to-make-speedy-usal-sprouted-beans date: 2020-09-04T21:07:27.089Z image: https://img-global.cpcdn.com/recipes/a38f15db8fb71457/751x532cq70/usal-sprouted-beans-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/a38f15db8fb71457/751x532cq70/usal-sprouted-beans-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/a38f15db8fb71457/751x532cq70/usal-sprouted-beans-recipe-main-photo.jpg author: Sue Berry ratingvalue: 5 reviewcount: 20330 recipeingredient: - "1 cup Moth beans" - "1 medium onion Finely chopped" - "1/2 tsp sugar" - "As per taste salt" - "2 tsp oil" - "1/4 tsp cumin seeds" - "1 green chilli or 14 tsp red chilli powder" - "1/4 tsp turmeric powder" - "For garnishing" - "1 Lemon juice" - "As required Coriander leaves" recipeinstructions: - "Wash and soak moth beans for 6-7 hours. Remove most of the water and keep in a warm space to sprout covered with a damp cloth. When the moth beans sprout it&#39;s ready to be cooked." - "Heat a pan, add oil. When oil is hot add cumin seeds, fry for 10 sec and add onion. Cook onions until soft add remaining spices and sprouts do 1/2 tbsp water. Cook with partially covered pan. On mid low heat." - "After 5 mins add sugar and mix well. Cook for 10 more min on low flame or till sprouts are cooked." - "Serve hot, garnished with chopped coriander and lemon juice." categories: - Recipe tags: - usal - sprouted - beans katakunci: usal sprouted beans nutrition: 221 calories recipecuisine: American preptime: "PT29M" cooktime: "PT30M" recipeyield: "3" recipecategory: Dinner --- ![Usal (Sprouted beans)](https://img-global.cpcdn.com/recipes/a38f15db8fb71457/751x532cq70/usal-sprouted-beans-recipe-main-photo.jpg) Hello everybody, it is me again, Dan, welcome to my recipe page. Today, we're going to prepare a distinctive dish, usal (sprouted beans). One of my favorites food recipes. This time, I will make it a little bit tasty. This is gonna smell and look delicious. Usal (Sprouted beans) is one of the most well liked of current trending meals in the world. It is appreciated by millions daily. It's easy, it's fast, it tastes yummy. They are fine and they look fantastic. Usal (Sprouted beans) is something that I've loved my entire life. Matki chi Usal is a yummy and healthy Maharashtrian dish. It is made of sprouted moth Beans. In this video, I have shown how to make Matki Usal at home very. Usal can be made with sprouted beans or dried beans or even lentils. To begin with this recipe, we have to first prepare a few components. You can cook usal (sprouted beans) using 11 ingredients and 4 steps. Here is how you cook it. <!--inarticleads1--> ##### The ingredients needed to make Usal (Sprouted beans): 1. Make ready 1 cup Moth beans 1. Get 1 medium onion (Finely chopped) 1. Make ready 1/2 tsp sugar 1. Take As per taste salt 1. Prepare 2 tsp oil 1. Take 1/4 tsp cumin seeds 1. Make ready 1 green chilli or 1/4 tsp red chilli powder 1. Take 1/4 tsp turmeric powder 1. Take For garnishing: 1. Take 1 Lemon juice 1. Prepare As required Coriander leaves Easy-to-make and highly nutritious, Misal-Usal is considered as one of the most popular street food in Maharashtra. An &#34;usal&#34; is a typical Maharashtrian dish made from beans (sprouted moong beans, black-eyed peas, lentils…). It is not a curry but more like a dry stir-fry dish. Recipe for Moth Beans Sprouts curry. <!--inarticleads2--> ##### Instructions to make Usal (Sprouted beans): 1. Wash and soak moth beans for 6-7 hours. Remove most of the water and keep in a warm space to sprout covered with a damp cloth. When the moth beans sprout it&#39;s ready to be cooked. 1. Heat a pan, add oil. When oil is hot add cumin seeds, fry for 10 sec and add onion. Cook onions until soft add remaining spices and sprouts do 1/2 tbsp water. Cook with partially covered pan. On mid low heat. 1. After 5 mins add sugar and mix well. Cook for 10 more min on low flame or till sprouts are cooked. 1. Serve hot, garnished with chopped coriander and lemon juice. It is not a curry but more like a dry stir-fry dish. Recipe for Moth Beans Sprouts curry. The other is a Maharashtian style usal - made using these sprouted Moth beans, some spice powders from your pantry and a curry base of. Traditional they make usal with sprouted moth/matki beans. however, you could use any kind of legumes/sprouted legumes like green gram bean, black gram/kala chana, moong/mung beans. Using moong sprouts for usal is also not uncommon so I decided to go ahead and do just that. So that is going to wrap it up for this special food usal (sprouted beans) recipe. Thanks so much for your time. I am confident you will make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to save this page in your browser, and share it to your family, colleague and friends. Thank you for reading. Go on get cooking!
SQL
UTF-8
14,128
3.265625
3
[]
no_license
MySql: a12Bo873 delimiter $$ drop procedure if exists SP_GetMarketFreight; create procedure SP_GetMarketFreight( par_Extension bit ) begin if par_Extension = 1 then select row_number() over (order by th.Pickup asc ) as Id, th.Id as TruckStopId, SF_EscapeString( th.OriginCity ) as OriginCity, UPPER( th.OriginState ) as OriginState, StartCc.Latitude as OriginLatitude, StartCc.Longitude as OriginLongitude, SF_EscapeString( th.DestinationCity ) as DestinationCity, UPPER( th.DestinationState ) as DestinationState, FinishCc.Latitude as DestinationLatitude, FinishCc.Longitude as DestinationLongitude, th.Pickup as PickupDate, NULL as LastDeliveryDate, IFNULL( th.Rate, th.Miles * 2.5 ) as Rate, IF( th.Rate is not null, 1, 0 ) as IsRateOriginal from TruckstopHistorical as th inner join VW_CityCoords as StartCc on StartCc.City = TRIM(UPPER(th.OriginCity)) and StartCc.State = TRIM(UPPER(th.OriginState)) inner join VW_CityCoords as FinishCc on FinishCc.City = TRIM(UPPER(th.DestinationCity)) and FinishCc.State = TRIM(UPPER(th.DestinationState)) where th.OriginState = "TX" and th.DestinationState = "TX" and (th.Rate is not null or th.Miles is not null); else select row_number() over (order by th.Pickup asc ) as Id, th.Id as TruckStopId, SF_EscapeString( th.OriginCity ) as OriginCity, UPPER( th.OriginState ) as OriginState, StartCc.Latitude as OriginLatitude, StartCc.Longitude as OriginLongitude, SF_EscapeString( th.DestinationCity ) as DestinationCity, UPPER( th.DestinationState ) as DestinationState, FinishCc.Latitude as DestinationLatitude, FinishCc.Longitude as DestinationLongitude, th.Pickup as PickupDate, NULL as LastDeliveryDate, th.Rate as Rate from TruckstopHistorical as th inner join VW_CityCoords as StartCc on StartCc.City = TRIM(UPPER(th.OriginCity)) and StartCc.State = TRIM(UPPER(th.OriginState)) inner join VW_CityCoords as FinishCc on FinishCc.City = TRIM(UPPER(th.DestinationCity)) and FinishCc.State = TRIM(UPPER(th.DestinationState)) where th.Trlr = "V" and th.Rate is not null and th.OriginState = "TX" and th.DestinationState = "TX"; end if; end $$ delimiter ; delimiter $$ drop procedure if exists SP_GetMarketFreight_Ext; create procedure SP_GetMarketFreight_Ext() begin select row_number() over (order by th.Pickup asc ) as Id, th.Id as TruckStopId, SF_EscapeString( th.OriginCity ) as OriginCity, UPPER( th.OriginState ) as OriginState, StartCc.Latitude as OriginLatitude, StartCc.Longitude as OriginLongitude, SF_EscapeString( th.DestinationCity ) as DestinationCity, UPPER( th.DestinationState ) as DestinationState, FinishCc.Latitude as DestinationLatitude, FinishCc.Longitude as DestinationLongitude, th.Pickup as PickupDate, NULL as LastDeliveryDate, IFNULL( th.Rate, th.Miles * 2.5 ) as Rate from TruckstopHistorical as th inner join VW_CityCoords as StartCc on StartCc.City = TRIM(UPPER(th.OriginCity)) and StartCc.State = TRIM(UPPER(th.OriginState)) inner join VW_CityCoords as FinishCc on FinishCc.City = TRIM(UPPER(th.DestinationCity)) and FinishCc.State = TRIM(UPPER(th.DestinationState)) where th.OriginState = "TX" and th.DestinationState = "TX" and (th.Rate is not null or th.Miles is not null ) end $$ delimiter ; -- call SP_GetMarketFreight(); -- call SP_FillBackhaulsSummary(); delimiter $$ drop procedure SP_DistributeDates $$ create procedure SP_DistributeDates( par_FirstDay date, par_LastDay date, par_DayCount int, par_Hour time ) begin declare IntervalDayCount int; declare Cnt int; declare DayNumber int; declare TheDay date; if par_DayCount <= 0 or par_DayCount is null then SIGNAL SQLSTATE '22012' SET MESSAGE_TEXT = 'Wrong par_DayCount'; end if; if par_FirstDay > par_LastDay then SIGNAL SQLSTATE '22012' SET MESSAGE_TEXT = 'Wrong Date Interval'; end if; set IntervalDayCount = datediff( par_LastDay, par_FirstDay ) + 1; create temporary table if not exists TT_Days ( TheDateTime datetime not null ); delete from TT_Days; set Cnt = 0; while Cnt < par_DayCount do set DayNumber = floor( rand() * IntervalDayCount ); set TheDay = date_add( par_FirstDay, interval DayNumber DAY ); insert into TT_Days ( TheDateTime ) value ( ADDTIME( CONVERT(TheDay, datetime), par_Hour ) ); set Cnt = Cnt + 1; end while; end $$ delimiter ; -- call SP_DistributeDates( '2020-07-20', '2020-07-29', 3, '09:00:00' ); delimiter $$ drop procedure if exists SP_Test; create procedure SP_Test( par_FirstDay date, par_LastDay date ) begin DECLARE finished INTEGER DEFAULT 0; declare cur_BackhaulSumm cursor for select BackhaulSummaryId, DedLoadsToFill from TT_BackhaulsSummary; DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1; if finished > 0 then set finished = 1; end if; end $$ delimiter ; delimiter $$ drop procedure if exists SP_FillBackhaulsSummary; create procedure SP_FillBackhaulsSummary() begin drop temporary table if exists TT_BackhaulsSummary; create temporary table TT_BackhaulsSummary ( BackhaulSummaryId int not null, OriginCity varchar(64) not null, OriginState char(2) not null, OriginType char(8) not null, OriginLatitude double null, OriginLongitude double null, OriginWslr int null, DestinationCity varchar(64) not null, DestinationState char(2) not null, DestinationType char(8) not null, DestinationLatitude double null, DestinationLongitude double null, DestinationWslr int null, TotalLoadsToFill int null, DedLoadsToFill int null, TruckType char(8) null ); insert into TT_BackhaulsSummary with WslrToGeo as ( select Wslr_Zip.Wslr as Wslr, Zips.Latitude as Latitude, Zips.Longitude as Longitude from Wslr_Zip inner join Zips on Wslr_Zip.Zip = Zips.Zip ) select bd.Id as BackhaulSummaryId, bd.OriginCity as OriginCity, bd.OriginState as OriginState, bd.OriginType as OriginType, OriginGeo.Latitude as OriginLatitude, OriginGeo.Longitude as OriginLongitude, OriginGeo.Wslr as OriginWslr, bd.DestinationCity as DestinationCity, bd.DestinationState as DestinationState, bd.DestinationType as DestinationType, DestGeo.Latitude as DestinationLatitude, DestGeo.Longitude as DestinationLongitude, DestGeo.Wslr as DestinationWslr, bd.TotalLoadsToFill as TotalLoadsToFill, bd.DedicatedLoadsToFill as DedLoadsToFill, tt.LaneType as TruckType from BackhaulData as bd left outer join WslrToGeo as OriginGeo on bd.OriginWslr = OriginGeo.Wslr left outer join WslrToGeo as DestGeo on bd.DestinationWslr = DestGeo.Wslr left outer join LaneTractorTypes as tt on bd.Lane = concat( tt.Origin, "_", tt.Dest ) order by bd.Id asc; end $$ delimiter ; delimiter $$ drop procedure if exists SP_ModelBackhauls; create procedure SP_ModelBackhauls( par_FirstDay date, par_LastDay date ) begin declare LocalId int; declare LoadsCount int; declare IntervalDayCount int; declare DaysPerInterval double; declare DaysPerIntervalInt int; DECLARE finished INTEGER DEFAULT 0; declare MorningHour time default '09:00:00'; declare HorizonInDays int default 12; declare cur_BackhaulSumm cursor for select BackhaulSummaryId, DedLoadsToFill from TT_BackhaulsSummary order by BackhaulSummaryId asc; DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1; drop temporary table if exists TT_Backhauls; create temporary table TT_Backhauls ( Id int not null AUTO_INCREMENT primary key, BackhaulSummaryId int not null, OriginCity varchar(64) not null, OriginState char(2) not null, OriginType char(8) not null, OriginLatitude double null, OriginLongitude double null, OriginWslr int null, DestinationCity varchar(64) not null, DestinationState char(2) not null, DestinationType char(8) not null, DestinationLatitude double null, DestinationLongitude double null, DestinationWslr int null, EarlyStart datetime not null, LateFinish datetime not null, TruckType char(8) null ); if par_FirstDay > par_LastDay then SIGNAL SQLSTATE '22012' SET MESSAGE_TEXT = 'Wrong Date Interval'; end if; set IntervalDayCount = datediff( par_LastDay, par_FirstDay ) + 1; call SP_FillBackhaulsSummary(); open cur_BackhaulSumm; lbl: loop fetch cur_BackhaulSumm into LocalId, LoadsCount; IF finished = 1 THEN LEAVE lbl; END IF; set DaysPerInterval = convert(IntervalDayCount, double) * (convert(LoadsCount, double) / 365.0); if DaysPerInterval >= 1.0 then set DaysPerIntervalInt = round(DaysPerInterval); else if rand() < DaysPerInterval then set DaysPerIntervalInt = 1; else set DaysPerIntervalInt = 0; end if; end if; if DaysPerIntervalInt > 0 then call SP_DistributeDates( par_FirstDay, par_LastDay, DaysPerIntervalInt, MorningHour ); insert into TT_Backhauls( BackhaulSummaryId, OriginCity, OriginState, OriginType, OriginLatitude, OriginLongitude, OriginWslr, DestinationCity, DestinationState, DestinationType, DestinationLatitude, DestinationLongitude, DestinationWslr, EarlyStart, LateFinish, TruckType ) select bs.BackhaulSummaryId, SF_EscapeString( bs.OriginCity ) as OriginCity, UPPER( bs.OriginState ) as OriginState, bs.OriginType, bs.OriginLatitude, bs.OriginLongitude, bs.OriginWslr, SF_EscapeString( bs.DestinationCity ) as DestinationCity, UPPER( bs.DestinationState ) as DestinationState, bs.DestinationType, bs.DestinationLatitude, bs.DestinationLongitude, bs.DestinationWslr, TT_Days.TheDateTime as EarlyStart, date_add( TT_Days.TheDateTime, interval HorizonInDays day ) as LateFinish, bs.TruckType from TT_BackhaulsSummary as bs cross join TT_Days where bs.BackhaulSummaryId = LocalId; end if; end loop lbl; close cur_BackhaulSumm; select * from TT_Backhauls where OriginState = 'TX' and DestinationState = 'TX' and OriginLatitude is not null and OriginLongitude is not null and DestinationLatitude is not null and DestinationLongitude is not null order by BackhaulSummaryId asc, EarlyStart asc; end $$ delimiter ; -- call SP_ModelBackhauls( '2020-07-01', '2020-07-10' ); mysql --user=root --password=a12Bo873 -D Dto -e "call SP_ModelBackhauls( '2020-06-30', '2020-06-30' );" > _backhauls_.csv mysql --user=root --password=a12Bo873 -D Dto -e "call SP_GetMarketFreight( 1 );" > _market_.csv drop view VW_CityCoords; create view VW_CityCoords as with SelectedLocations as ( select City, State, min(Id) as MinId from Zips group by City, State ) select TRIM(UPPER(Zips.City)) as City, TRIM(UPPER(Zips.State)) as State, Zips.Latitude, Zips.Longitude from Zips inner join SelectedLocations as sl on sl.MinId = Zips.Id; ------------- select Id from TruckstopHistorical inner join VW_CityCoords on UPPER(VW_CityCoords.City) = UPPER(TruckstopHistorical.OriginCity) limit 3; if " GRAND PRAIRIE" delimiter $$ drop function if exists SF_EscapeString; create function SF_EscapeString( par_String varchar(16000) ) returns varchar(16000) DETERMINISTIC begin declare EscapedString varchar(16000); set EscapedString = REGEXP_REPLACE( par_String, "(^[^0-9a-zA-Z_]+|[^0-9a-zA-Z_]+$)", "" ); set EscapedString = REGEXP_REPLACE( EscapedString, "[^0-9a-zA-Z_]", "_" ); set EscapedString = UPPER( EscapedString ); return EscapedString; end $$ delimiter ;
Ruby
UTF-8
712
3.59375
4
[]
no_license
# frozen_string_literal: true require 'pry' def hash(string, array_length) total = 0 # Hashes take advantage of prime numbers to avoid collision. prime_number = 31 # Reduce the time taken if the length is greater than 100 min_length = [string.length - 1, 100].min (0..min_length).each do |index| position = string[index].ord - 96 total = (total * prime_number + position) % array_length end total end # Handling collisions # Separate chaining; store multiple key value pairs in the same position by nesting arrays. # Linear Probing; store one piece of data at each position, # if collision happens, you forward the data to the next position puts hash('pink', 10) # binding.pry
Python
UTF-8
496
2.875
3
[]
no_license
for _ in range(int(input())): a,b,c,d=map(int,input().split()) flag=0 if a==c and b==d: print("Yes") continue elif a>c and b>d: print("No") continue else: while True: if d-c>0: d-=c else: c-=d if c==a and d==b: flag=1 break if c<a or d<b: break if flag: print("Yes") else: print("No")
PHP
UTF-8
761
2.921875
3
[]
no_license
<?php namespace App\Service; class DataUtilService { /** * @param string $data * @param string|null $from_encoding * * @return false|string|string[]|null */ public static function convertToUTF8(string $data, ?string $from_encoding = null) { if ($from_encoding !== null) { return mb_convert_encoding($data, "UTF-8", $from_encoding); } return mb_convert_encoding($data, "UTF-8"); } /** * @param $pdfFilename * @param $htmlFilename * * @return string|null */ public static function convertPDFToHTML($pdfFilename, $htmlFilename) { return shell_exec('pdftohtml -enc UTF-8 -noframes ' . $pdfFilename . ' ' . $htmlFilename); } }
PHP
UTF-8
6,724
3.046875
3
[]
no_license
<?php /** * This is the Facebook User Class * * Managing Facebook Session and Facebook User profile Info * * @author David Raleche * * Time: 1:51 PM */ use Facebook\FacebookSession; use Facebook\FacebookJavaScriptLoginHelper; use Facebook\FacebookCanvasLoginHelper; use Facebook\FacebookRequest; use Facebook\GraphUser; use Facebook\FacebookRequestException; class FacebookUser { private $userId = null; private $session = null; private $accessToken = null; private $appId = null; private $secret = null; private $originId = 2; /** * Constructor */ public function __construct($appId, $secret, $originId = 2) { $this->originId = $originId; $this->appId = $appId; $this->secret = $secret; try { //Initialize Facebook Session FacebookSession::setDefaultApplication($this->appId, $this->secret); $this->initializeFacebookSessionBasedOnOriginId(); $this->throwExceptionIfAccessTokenNotValid(); } catch (\Exception $e) { $this->secret = null; //protect from the logs err("Class FacebookUser [__construct]: Exception : {$e->getMessage()} Object: ".print_r($this,1)); $this->resetAllObjectParameters(); } } /** * Get Facebook User information * * @param string $facebookUserProfileFields * @return object or null * */ public function getProfile($facebookUserProfileFields) { try { if ( ! ($this->session instanceof FacebookSession)) { err("Class FacebookUser [getProfile()]: No FacebookSession instance"); return null; } $request = new FacebookRequest($this->session, 'GET', "/{$this->userId}?{$facebookUserProfileFields}"); $user = $request->execute()->getGraphObject(GraphUser::className()); return $user; } catch (FacebookRequestException $e) { err("Class FacebookUser [getProfile()]: Request Exception: {$e->getMessage()}") ; } catch (\Exception $e) { err("Class FacebookUser [getProfile()]: User Profile Exception: {$e->getMessage()}"); } return null; } /** * getter Long Lived Token * * Set long Live Token */ public function getFBLongLivedToken() { try { // Set URL for GET GRAPH API CALL $url = "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token" ."&client_id=".$this->appId ."&client_secret=".$this->secret ."&fb_exchange_token=".$this->accessToken; // Execute Graph APi Call $responseFBLiveToken = file_get_contents($url); if($responseFBLiveToken === false) throw new Exception('FAILING file_get_contents '.$url); // Verify Response Headers if(strpos($http_response_header[0],' 200 ') === false) { throw new Exception('Access LONG LIVE Token Not Valid '.$url.' ' .print_r($http_response_header,1) .print_r( $url )); } // Parse Response from Facebook to get [access_token] & [expires] values $arrayResponse = array(); parse_str( $responseFBLiveToken, $arrayResponse); // SET FB ACCESS TOKEN $this->accessToken = $arrayResponse['access_token']; } catch (Exception $e) { err("FAILURE getFBLongLivedToken ".$e); throw new Exception('getFBLongLivedToken '.$e); } } /** * getter Session * * @return session */ public function getSession() { return $this->session; } /** * isValidSession * * @return boolean */ public function isValidSession() { if($this->session === null){ return false; }else{ return true; } } /** * getter userId * * @return userId */ public function getUserId() { return $this->userId; } /** * getter accessToken * * @return accessToken */ public function getAccessToken() { return $this->accessToken; } /** * throwExceptionIfAccessTokenNotValid * * @return void */ public function throwExceptionIfAccessTokenNotValid() { if(!isset($this->accessToken)) throw new Exception('Access Token is NOT SET Facebook Canvas originId :'.$this->originId); $url = "https://graph.facebook.com/me?access_token="; $headers = @get_headers($url.$this->accessToken); if(strpos($headers[0],' 200 ') === false) { throw new Exception('Access Token Not Valid '.$url.$this->accessToken.' '.print_r($headers,1) ); } } /** * resetObject * * @return boolean */ public function resetAllObjectParameters(){ $this->userId = null; $this->accessToken = null; $this->session = null; $this->appId = null; $this->secret = null; $this->originId = null; } /** * setAccessTokenFromCookies * * @return boolean */ public function setAccessTokenFromCookies(){ //If no accessToken - Retrieve from Cookies (if cookies exist) if(!isset($this->accessToken) && isset($_COOKIE['FB_accessToken'])){ $this->accessToken = $_COOKIE['FB_accessToken']; } else { $this->accessToken = null; } } /** * initializeObjectBasedOnOriginId * * @return boolean */ public function initializeFacebookSessionBasedOnOriginId(){ // coming from Facebook Canvas == 3 if ($this->originId === 3) { $facebookHelper = new FacebookCanvasLoginHelper($this->appId, $this->secret); $this->session = $facebookHelper->getSession(); $this->userId = $facebookHelper->getUserId(); if ($this->session instanceof FacebookSession) { $this->accessToken = $this->session->getToken(); } else throw new Exception('No instanceof FacebookSession '.print_r($this->session,1).' originId : '.$this->originId); } else { //coming high5casino.net PlayReal $this->session = FacebookSession::newAppSession(); $this->userId = (new FacebookJavaScriptLoginHelper())->getUserId(); $this->setAccessTokenFromCookies(); } } }
Markdown
UTF-8
4,117
2.625
3
[]
no_license
--- layout: post title: Snowplow Ruby Tracker 0.1.0 released title-short: Snowplow Ruby Tracker 0.1.0 tags: [snowplow, analytics, python, django, tracker] author: Fred category: Releases --- We are happy to announce the release of the new [Snowplow Ruby Tracker] [repo]. This is a Ruby gem designed to send Snowplow events to a Snowplow collector from a Ruby or Rails environment. This post will cover installing and setting up the Tracker, and provide some basic information about its features: 1. [How to install the tracker](/blog/2014/04/23/snowplow-ruby-tracker-0.1.0-released/#install) 2. [How to use the tracker](/blog/2014/04/23/snowplow-ruby-tracker-0.1.0-released/#usage) 3. [Features](/blog/2014/04/23/snowplow-ruby-tracker-0.1.0-released/#roadmap) 4. [Getting help](/blog/2014/04/23/snowplow-ruby-tracker-0.1.0-released/#help) <!--more--> <div class="html"> <h2><a name="install">1. How to install the tracker</a></h2> </div> The Snowplow Ruby Tracker is published to [RubyGems] [rubygems], the Ruby community's gem hosting service. This makes it easy to install the Tracker locally, or add it as a dependency into your own Ruby app. To install the Tracker locally: {% highlight bash %} $ gem install snowplow-tracker {% endhighlight %} To add the Snowplow Ruby Tracker as a dependency to your own Ruby gem, edit your gemfile and add: {% highlight ruby %} gem 'snowplow-tracker' {% endhighlight %} The Snowplow Ruby Tracker is compatible with Ruby versions 1.9.3, 2.0.0, and 2.1.0. The [setup page] [setup] has more information on the Tracker's own dependencies. <div class="html"> <h2><a name="usage">2. How to use the tracker</a></h2> </div> Require the Snowplow Tracker like this: {% highlight ruby %} require 'snowplow-tracker' {% endhighlight %} Initialize a Tracker like this: {% highlight ruby %} tracker = SnowplowTracker::Tracker.new('d3rkrsqld9gmqf.cloudfront.net', 'cf', '') {% endhighlight %} Set some additional information: {% highlight ruby %} tracker.set_user_id('a73e94') tracker.set_platform('mob') tracker.set_lang('en') {% endhighlight %} And fire some events: {% highlight ruby %} tracker.track_page_view("www.example.com", "example page", "www.referrer.com") tracker.track_struct_event("shop", "add-to-basket", None, "pcs", 2, 1369330909) tracker.track_ecommerce_transaction({ 'order_id' => '12345', 'total_value' => 35, 'affiliation' => 'my_company', 'tax_value' => 0, 'shipping' => 0, 'city' => 'Phoenix', 'state' => 'Arizona', 'country' => 'USA', 'currency' => 'GBP' }, [ { 'sku' => 'pbz0026', 'price' => 20, 'quantity' => 1 }, { 'sku' => 'pbz0038', 'price' => 15, 'quantity' => 1, 'name' => 'crystals', 'category' => 'magic' } ]) {% endhighlight %} For in-depth usage information on the Snowplow Ruby Tracker, see the [wiki page] [wiki]. <div class="html"> <h2><a name="usage">3. Features</a></h2> </div> The functionality and architecture of the Snowplow Ruby Tracker is very similar to that of the Snowplow Python Tracker. It has support for the same Snowplow events, and custom contexts can be attached to every event. The [contracts] [contracts] library for Ruby provides type checking. We have written a test suite using [RSpec] [rspec] and [webmock] [webmock]. <div class="html"> <h2><a name="help">4. Getting help</a></h2> </div> Since this is the first release of the Ruby Tracker, we're keen to hear people's opinions. If you have an idea for a new feature or want help getting things set up, please [get in touch] [talk-to-us]. And [raise an issue] [issues] if you spot any bugs! [contracts]: https://rubygems.org/gems/contracts [rspec]: https://rubygems.org/gems/rspec [webmock]: https://rubygems.org/gems/webmock [rubygems]: http://rubygems.org/gems/snowplow-tracker [repo]: https://github.com/snowplow/snowplow-ruby-tracker [wiki]: https://github.com/snowplow/snowplow/wiki/Ruby-Tracker [setup]: https://github.com/snowplow/snowplow/wiki/Ruby-tracker-setup [talk-to-us]: https://github.com/snowplow/snowplow/wiki/Talk-to-us [issues]: https://github.com/snowplow/snowplow-ruby-tracker/issues
Java
UTF-8
1,299
2.171875
2
[]
no_license
package view.controller; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDialog; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.layout.StackPane; import java.net.URL; import java.util.ResourceBundle; /** * @ClassName * @Description * @Author LGH * @Date 2020/7/14 19:08 * @Version 1.0 **/ public class Controller_dialog implements Initializable { @FXML private JFXButton centerButton; @FXML private JFXButton topButton; @FXML private JFXButton rightButton; @FXML private JFXButton bottomButton; @FXML private JFXButton leftButton; @FXML private JFXButton acceptButton; @FXML private JFXButton alertButton; @FXML private StackPane root; @FXML private JFXDialog dialog; @Override public void initialize(URL url, ResourceBundle resourceBundle) { root.getChildren().remove(dialog); centerButton.setStyle("-fx-background-color: #FF4040;-fx-text-fill: white"); centerButton.setOnAction(actionEvent -> { System.out.println("点击了"); dialog.setTransitionType(JFXDialog.DialogTransition.CENTER); dialog.show(root); }); acceptButton.setOnAction(action -> dialog.close()); } }
Shell
UTF-8
7,660
3.703125
4
[]
no_license
#!/bin/sh # Dmitry Troshenkov (troshenkov.d@gmail.com) # # This special script for making the git for a web projects on the Cloudinux when used CageFS and WHM/cPanel as a web hosting platform. # ################################ # sudo yum install git # # OR # # sudo yum groupinstall "Development Tools" # sudo yum install zlib-devel perl-ExtUtils-MakeMaker asciidoc xmlto openssl-devel # # cd ~ && wget -O git.zip https://github.com/git/git/archive/master.zip # unzip git.zip && cd git-master # # make configure # ./configure --prefix=/usr/local/cpanel/3rdparty/ # ./configure --prefix=/usr/local # make all doc # sudo make install install-doc install-html ################################### # GIT_USER=git GIT_SERVER=git.artmebius.com GIT_IGNORE='.gitignore_global' # Checking for the Git instalation ck_git() { if hash git 2>/dev/null; then git --version; else echo 'The Git should be installed'; exit 0; fi } # Checking for the GCC compiller instalation ck_gcc() { if hash gcc 2>/dev/null; then echo gcc: $(gcc -dumpversion)' '$(gcc -dumpmachine) else echo 'The gcc compiler should be installed' exit 0; fi } # Checking for the Git user existing if id -u ${GIT_USER} >/dev/null 2>&1 ; then echo The Git user ${GIT_USER} exists else echo The Git user ${GIT_USER} does not exist! exit 0 fi # Checking for input argument as a cPanel account name if [ $# -lt 1 ]; then echo Requires account name as an argument; exit 0; fi ACC=$1 # Checking for running as root this script if [ "$(id -u)" != "0" ]; then echo "This script must be run as root" 1>&2 ; exit 0 ; fi # Checking for an account name existing if [ ! -d /home/${ACC} ]; then echo Account ${ACC} not exists; exit 0; fi # Checking for the git existing in the account http folder if [ -d /home/${ACC}/public_html/.git ]; then echo The Git folder in the ${ACC} account already exists; exit 0; fi # Checking for the GitoLite existing if [ -d /home/${GIT_USER}/repositories/gitolite-admin.git/ ]; then GIT_REPOS=/home/${GIT_USER}/repositories _GitoLite=1 if [ ! -d ${GIT_REPOS}/${ACC}.git ]; then echo The bare Git for ${ACC} does not exists. Create it from Gitolite first; exit 0; else # If bare Git for account exists, check for size and detecting an empty or not empty it if [ `du --max-depth=0 ${GIT_REPOS}/${ACC}.git | awk '{ print $1 }'` -ge 100 ] ; then echo Git Bare ${GIT_REPOS}/${ACC}.git is not empty exit 0 # else echo ${GIT_REPOS}/${ACC}.git ok! fi fi echo GitoLite detected. echo Directory for Git repositories ${GIT_REPOS} else # If GitoLite is not exists GIT_REPOS=/home/${GIT_USER} _GitoLite=0 if [ ! -d ${GIT_REPOS} ]; then echo ${GIT_REPOS} directory not exists; exit 0; fi if [ -d ${GIT_REPOS}/${ACC}.git ]; then echo The Git repository ${ACC}.git already exists; exit 0; fi echo Directory for Git repositories ${GIT_REPOS} fi # Checking for the CloudLinux if [ -f /etc/cagefs/cagefs.mp ] ; then echo -e '++++++++++++++++++++++ When using the Cloudinux and CageFS checkout this settings or run: which git >> /etc/cagefs/cagefs.mp cagefsctl --remount-all cagefsctl --disable ${GIT_USER} ++++++++++++++++++++++' fi ck_git && ck_gcc # Add Git ignore file to configuration if [ -f /home/${GIT_USER}/${GIT_IGNORE} ] ; then git config --global core.excludesfile /home/${GIT_USER}/${GIT_IGNORE}; echo Using git ignore file /home/${GIT_USER}/${GIT_IGNORE} else echo The ${GIT_IGNORE} file no exist in the /home/${GIT_USER} exit 0 fi # If you have a punycode domain name, you get readable name for project _PING=$(echo ping -c 1 `ls -1 /home/${ACC}/access-logs/ | grep ^[^\.]` | grep PING | tr -d \(\) | awk '{ print $2 }') # Git initialisation cd /home/${ACC}/public_html git init git add . git commit -m "Initial Commit" -q #git status # A project name put to description in the account if [ $_PING ] ; then echo ${_PING} > .git/description else echo Unknown > .git/description fi # Creating .htaccess file echo -e "Order Deny,Allow\nDeny from all" > .git/.htaccess # if GitoLite does not exist, do create bare if [ ${_GitoLite} -eq 0 ] ; then mkdir -p ${GIT_REPOS}/${ACC}.git cd ${GIT_REPOS}/${ACC}.git git init --bare else cd ${GIT_REPOS}/${ACC}.git fi # A project name put to description in the bare if [ $_PING ] ; then echo ${_PING} > description else echo Unknown > description fi chown -R ${GIT_USER}.${GIT_USER} ../${ACC}.git/.[*\^.]* cd /home/${ACC}/public_html/ if [ ${_GitoLite} -eq 0 ] ; then git remote add hub ${GIT_REPOS}/${ACC}.git else git remote add hub ${GIT_USER}@${GIT_SERVER}:${ACC} fi git remote show hub git push hub master chown -R ${ACC}.${ACC} .git/.[*\^.]* PC=post-commit PU=post-update PR=pre-receive echo Creating post-update hook in the ${GIT_REPOS}/${ACC}.git/hooks # cd ${GIT_REPOS}/${ACC}.git/hooks cat << EOF > ${PU}.sh #!/bin/sh echo "******************************" echo "*** Deploying Website LIVE ***" echo "******************************" cd /home/$ACC/public_html || exit unset GIT_DIR git pull hub master git submodule init git submodule update git update-server-info git gc chown -R ${ACC}.${ACC} .[*\^.]* chown root.root .git/hooks/${PC} chmod 4777 .git/hooks/${PC} EOF cat << EOF > $PU.c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(){ setuid(0); system("sh hooks/${PU}.sh"); return 0; } EOF gcc ${PU}.c -o ${PU} && chown root.root ${PU} && chmod 4777 ${PU} chown ${GIT_USER}.${GIT_USER} ${PU}.sh rm ${PU}.c echo Creating post-commit hook in the /home/${ACC}/public_html/.git/hooks/ # cd /home/${ACC}/public_html/.git/hooks/ || exit cat << EOF > ${PC}.sh #!/bin/sh echo "******************************" echo "*** Pushing changes to Hub ***" echo "*** [Lives ${PC} hook] ***" echo "******************************" git push --set-upstream hub master git push hub git gc chown -R git.git ${GIT_REPOS}/${ACC}.git/.[*\^.]* chown root.root ${GIT_REPOS}/${ACC}.git/hooks/${PU} chown root.root ${GIT_REPOS}/${ACC}.git/hooks/${PP} chown root.root ${GIT_REPOS}/${ACC}.git/hooks/${PR} chmod 4777 ${GIT_REPOS}/${ACC}.git/hooks/${PU} chmod 4777 ${GIT_REPOS}/${ACC}.git/hooks/${PP} chmod 4777 ${GIT_REPOS}/${ACC}.git/hooks/${PR} EOF cat << EOF > ${PC}.c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(){ setuid(0); system("sh .git/hooks/${PC}.sh"); return 0; } EOF gcc ${PC}.c -o ${PC} && chown root.root ${PC} && chmod 4777 ${PC} chown ${ACC}.${ACC} ${PC}.sh rm ${PC}.c echo Creating pre-push hook in the ${GIT_REPOS}/$ACC.git/hooks # cd ${GIT_REPOS}/$ACC.git/hooks cat << EOF > ${PR}.sh #!/bin/sh echo "********************************************" echo "*** Pre-recive before pushing to the Hub ***" echo "********************************************" cd /home/$ACC/public_html/ || exit unset GIT_DIR #git push -u hub master #git pull --set-upstream hub master #git pull hub master #git submodule init #git submodule update #git update-server-info git add . git commit -m "Commiting a Live changes before push to the Hub" -q git gc LOCAL=\$(git rev-parse @) REMOTE=\$(git rev-parse @{u}) BASE=\$(git merge-base @ @{u}) echo L - \$LOCAL echo R - \$REMOTE echo B - \$BASE if [[ \$LOCAL = \$REMOTE ]]; then echo "Up-to-date" elif [[ \$LOCAL = \$BASE ]]; then echo "Need to pull" elif [[ \$REMOTE = \$BASE ]]; then echo "Need to push" else echo "Diverged" fi EOF cat << EOF > $PR.c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(){ setuid(0); system("sh hooks/${PR}.sh"); return 0; } EOF gcc ${PR}.c -o ${PR} && chown root.root ${PR} && chmod 4777 ${PR} chown ${GIT_USER}.${GIT_USER} ${PR}.sh rm ${PR}.c echo Done exit 0
Java
UTF-8
360
1.632813
2
[]
no_license
package com.tinder.presenters; import com.tinder.model.GlobalConfig; import rx.functions.Func1; final /* synthetic */ class ak implements Func1 { /* renamed from: a */ static final Func1 f55207a = new ak(); private ak() { } public Object call(Object obj) { return Boolean.valueOf(((GlobalConfig) obj).canEditSchools()); } }
Markdown
UTF-8
2,271
3.6875
4
[ "MIT" ]
permissive
# perlin-numpy I wrote two articles on my blog about this project, the [first one](https://pvigier.github.io/2018/06/13/perlin-noise-numpy.html) is about the generation of 2D noise while the [second one](https://pvigier.github.io/2018/11/02/3d-perlin-noise-numpy.html) is about the generation of 3D noise, feel free to read them! ## Description A fast and simple perlin noise generator using numpy. ### 2D noise The function `generate_perlin_noise_2d` generates a 2D texture of perlin noise. Its parameters are: * `shape`: shape of the generated array (tuple of 2 ints) * `res`: number of periods of noise to generate along each axis (tuple of 2 ints) Note: `shape` must be a multiple of `res` The function `generate_fractal_noise_2d` combines several octaves of 2D perlin noise to make 2D fractal noise. Its parameters are: * `shape`: shape of the generated array (tuple of 2 ints) * `res`: number of periods of noise to generate along each axis (tuple of 2 ints) * `octaves`: number of octaves in the noise (int) * `persistence`: scaling factor between two octaves (float) Note: `shape` must be a multiple of `2^(octaves-1)*res` ### 3D noise The function `generate_perlin_noise_3d` generates a 3D texture of perlin noise. Its parameters are: * `shape`: shape of the generated array (tuple of 3 ints) * `res`: number of periods of noise to generate along each axis (tuple of 3 ints) Note: `shape` must be a multiple of `res` The function `generate_fractal_noise_2d` combines several octaves of 3D perlin noise to make 3D fractal noise. Its parameters are: * `shape`: shape of the generated array (tuple of 3 ints) * `res`: number of periods of noise to generate along each axis (tuple of 3 ints) * `octaves`: number of octaves in the noise (int) * `persistence`: scaling factor between two octaves (float) Note: `shape` must be a multiple of `2^(octaves-1)*res` ## Gallery ![2D Perlin noise](https://github.com/pvigier/perlin-numpy/raw/master/examples/perlin2d.png) ![2D fractal noise](https://github.com/pvigier/perlin-numpy/raw/master/examples/fractal2d.png) ![3D Perlin noise](https://github.com/pvigier/perlin-numpy/raw/master/examples/perlin3d.gif) ![3D fractal noise](https://github.com/pvigier/perlin-numpy/raw/master/examples/fractal3d.gif)
Markdown
UTF-8
3,087
2.828125
3
[]
no_license
| Algorithm | Application | Complexity (Time) | Complexity (Space) | Source (Python) | Source (Java) | |:--------:|:--------:|:--------:|:--------:|:--------:|:--------:| | [Bubble Sort](https://www.youtube.com/watch?v=gfjIKgAjiB8) | already sorted (short) list | best: O(N) </br> average: O(n<sup>2</sup>) </br> worst: O(n<sup>2</sup>) | O(1) | [bubble_sort](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/bubble_sort.ipynb) | | | [Insertion Sort](https://www.youtube.com/watch?v=IH_xi5SNniM&t=18s) | almost sorted (short) list | best: O(N) </br> average: O(n<sup>2</sup>) </br> worst: O(n<sup>2</sup>) | O(1) | [insertion_sort](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/insertion_sort.ipynb)| | | [Selection Sort](https://www.youtube.com/watch?v=_MoTnAW6fs8&t=5s)| almost sorted (short) list | best: O(n<sup>2</sup>) </br> average: O(n<sup>2</sup>) </br> worst: O(n<sup>2</sup>) | O(1) | [selection_sort](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/selection_sort.ipynb) | | | [Quick Sort](https://www.youtube.com/watch?v=KThbTw5E23w) | fast and uses less memory | best: O(nlog(n)) </br> average: O(nlog(n)) </br> worst: O(n<sup>2</sup>) | O(n) | [quick_sort](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/quick_sort.ipynb) | | | [Heap Sort](https://www.youtube.com/watch?v=WDm8a9GvQyU)| find min or max | best: O(1)-max,min </br> average: O(nlog(n)) </br> worst: O(nlog(n)) | O(1)-inplace | [heap_sort](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/heap_sort.ipynb) | | | [Merge Sort](https://www.youtube.com/watch?v=DWZXj8WaHgA&list=PLVNY1HnUlO25sSWDr7CzVvkOF3bUgkiQQ&index=6)| divide and conquer | best: O(nlog(n)) </br> average: (nlog(n)) </br> worst: O(nlog(n))| O(n) |[merge_sort](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/merge_sort.ipynb) | | | [Breadth First Search](https://www.youtube.com/watch?v=0v3293kcjTI&list=PLVNY1HnUlO25sSWDr7CzVvkOF3bUgkiQQ&index=18)| finding the shortest path | O(V+E) | O(V) | [bfs](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/bfs.ipynb) | | | [Depth First Search](https://www.youtube.com/watch?v=-rcHMKIBo1E&list=PLVNY1HnUlO25sSWDr7CzVvkOF3bUgkiQQ&index=17)| finding connected component (in graph) | O(V+E)| O(V) | [dfs](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/dfs.ipynb)| | | Binary Search | | | | [binary_search](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/binary_search.ipynb) | | | lru | | | | [least_recently_used](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/least_recently_used.ipynb) | | | dijkstra | | | | [dijkstra](https://github.com/juyoung228/Evolving_Basic/blob/master/Algorithm/Source%20Code/Python/dijkstra.ipynb) | | | best first search | | | | | | | optimal search | | | | | |
Java
ISO-8859-1
2,310
3.140625
3
[]
no_license
package kailaBird; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; public class Wall { final private int WIDTH = 48; final private int GAP = 150; private Random rnd = new Random(); private int x = 500; private int y = rnd.nextInt((600) - GAP) + GAP; private int speed = 6; private int HEIGHT = Game.HEIGHT - y; private BufferedImage wallImg = null; /* * Wall-konstruktori: * lataa seinn kuva */ public Wall() { // lataa seinkuva try { wallImg = ImageIO.read(new File("res/wall.png")); } catch(IOException e) { e.printStackTrace(); } } /* * Piirt seinn alaosan ja ylosan suhteessa alaseinn korkeuteen vakiona pysyvn GAP-muuttujan eli aukon koon huomioon ottaen * */ public void render(Graphics g){ // alaosa g.drawImage(wallImg, x, y, null); // ylaosa g.drawImage(wallImg, x, ( -Game.HEIGHT ) + ( y - GAP), null); } /* * Tick-metodi: * sein liikkuu x-akselilla vasemmalle speed-muuttujan arvon mukaan * Tarkastetaan, onko parametrina annettu Bird-olion ja Wall-olioiden riviivat pllekkin * Jos riviivat ovat pllekkin, lintu kuolee ja sein kuolee (kutsutaan olioiden die-metodia) * Kun sein on liikkunut vasemmalle kokonaan nkyvn alueen ulkopuolelle, siirretn se oikealle puolelle ja alustetaan uudet satunnaiset arvot */ public void tick(Bird b){ x -= speed; // seinien riviivat Rectangle wallBounds = new Rectangle(x, y, WIDTH, HEIGHT); Rectangle wallBoundsTop = new Rectangle(x, 0, WIDTH, Game.HEIGHT - ( HEIGHT + GAP)); // trmys if (wallBounds.intersects(b.getBounds()) || wallBoundsTop.intersects(b.getBounds())){ b.die(); this.die(); } if (x <= 0 - WIDTH){ x = Game.WIDTH; y = rnd.nextInt((600) - GAP) + GAP; HEIGHT = Game.HEIGHT - y; } } /* * Asettaa seinn liikkumisnopeus 0, sein pyshtyy * */ public void die() { this.speed = 0; } /* * Antaa seinn sijainnin x-akselilla * */ public int getX() { return this.x; } }
C++
UTF-8
1,855
2.671875
3
[]
no_license
#pragma once #include "glad/glad.h" #include "Vector.h" #include "Matrix.h" #include "OBJ_Loader.h" #include <vector> #include <string> class Model { public: Model(); Model(Vector<3> const& position); ~Model(); void update(float delta_time); virtual void render() const; Matrix4 const get_model_matrix() const; protected: void load_buffer_data(std::vector<float> const&, std::vector<float> const&, std::vector<int> const&); void load_texture(std::string file_name); void load_VAO(); void load_vertices_VBO(std::vector<float> const& vertices); void load_textures_VBO(std::vector<float> const& texture_coords); void load_indices_VBO(std::vector<int> const& indices); unsigned int VAO; unsigned int VBOvertices, VBOtextures, VBOindices; unsigned int textureID; unsigned int indices_count {}; private: Model(std::vector<float> vertices, std::vector<float> texture_coords, std::vector<int> indices, objl::Material material); std::string file_name {}; Vector<3> position {}; Vector<3> scale {1, 1, 1}; Vector<3> rotation {}; std::vector<float> vertices = { // front -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, // back -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5 }; std::vector<float> texture_coords = { // front 0, 0, 1, 0, 1, 1, 0, 1, // back 0, 0, 1, 0, 1, 1, 0, 1 }; std::vector<int> indices = { 0, 1, 3, 3, 1, 2, 1, 5, 2, 2, 5, 6, 5, 4, 6, 6, 4, 7, 4, 0, 7, 7, 0, 3, 3, 2, 7, 7, 2, 6, 4, 5, 0, 0, 5, 1 }; friend class Loader; };
Go
UTF-8
616
3.15625
3
[]
no_license
package main func sumRootToLeaf(root *TreeNode) int { var arr []int res := []int{0} if root != nil { dfs1022(root, &arr, res) } return res[0] } func dfs1022(root *TreeNode, arr *[]int, sum []int) { *arr = append(*arr, root.Val) if root.Left == nil && root.Right == nil { sum[0] += getSum1022(*arr) return } if root.Left != nil { dfs1022(root.Left, arr, sum) } if root.Right != nil { dfs1022(root.Right, arr, sum) } *arr = (*arr)[:len(*arr)-1] } func getSum1022(arr []int) int { res := 0 temp := 1 for i := len(arr) - 1; i >= 0; i-- { res += temp * arr[i] temp <<= 1 } return res }
Markdown
UTF-8
1,053
2.890625
3
[]
no_license
# SVM-Iris-Seed-DataSets 2nd Assignment, Functional Data Analysis: Support Vector Machine Computer Exercises Harold A. Hernández Roig ### Iris Data Set We deal with the classical Iris database due to R.A. Fisher. The data set contains 3 classes of 50 instances each, where each class refers to a type of iris plant. The aim of this report is to predict the class of an iris data in terms of some of the following variables: 1. sepal length in cm 2. sepal width in cm 3. petal length in cm 4. petal width in cm 5. class: Setosa, Versicolour and Virginica ### Seeds Data Set We deal with the problem of classifying three different varieties of wheat (Kama, Rosa and Canadian), from Seeds Data Set (check: <http://archive.ics.uci.edu/ml/datasets/seeds>). There are several continuous covariates that correspond to measurements of geometrical properties of kernels from the seeds in study. These are: 1. area A, 2. perimeter P, 3. compactness $C = 4*\pi*A/P^2$, 4. length of kernel, 5. width of kernel, 6. asymmetry coefficient 7. length of kernel groove.
Java
UTF-8
5,078
3.09375
3
[]
no_license
package com.creditsuisse.shopping; import static org.junit.Assert.*; import org.junit.Test; import com.creditsuisse.shopping.exception.FreeLimeRequiredException; import com.creditsuisse.shopping.exception.InvalidItemException; import com.creditsuisse.shopping.exception.FreeMelonRequiredException; public class ShoppingBasketTest { @Test public void givenBasketWithOneAppleTotalCostReturnedShouldBe35p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Apple"}; assertEquals(35, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithTwoAppleTotalCostReturnedShouldBe70p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Apple","Apple"}; assertEquals(70, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithTwoApplesAndOneBananaTotalCostReturnedShouldBe90p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Apple","Banana","Apple"}; assertEquals(90, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithTwoApplesTwoMelonsAndOneBananaTotalCostReturnedShouldBe140p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Apple","Banana","Apple","Melon","Melon"}; assertEquals(140, getTotalCostOfBasket(itemsInBasket)); } @Test (expected=InvalidItemException.class) public void givenBasketListWithInvalidInputAnInvalidItemExceptionShouldBeThrown() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Apple","Banana","Apple","invalidItem"}; getTotalCostOfBasket(itemsInBasket); } @Test (expected=FreeMelonRequiredException.class) public void givenBasketWithThreeMelonsAnInvalidNumberOfMelonExceptionShouldBeThrown() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Melon","Melon","Melon"}; getTotalCostOfBasket(itemsInBasket); } @Test (expected=FreeMelonRequiredException.class) public void givenBasketWithOneMelonsAnInvalidNumberOfMelonExceptionShouldBeThrown() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Melon"}; getTotalCostOfBasket(itemsInBasket); } @Test public void givenBasketWithFourMelonsAnInvalidNumberOfMelonTotalCostReturnedShouldBe100p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Melon","Melon","Melon","Melon"}; assertEquals(100, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenEmptyBasketTotalCostReturnedShouldBe0p() throws FreeMelonRequiredException, InvalidItemException, FreeLimeRequiredException { String itemsInBasket[] = {}; assertEquals(0, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithThreeLimesTotalCostReturnedShouldBe30p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Lime","Lime","Lime"}; assertEquals(30, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithSixLimesTotalCostReturnedShouldBe60p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Lime","Lime","Lime","Lime","Lime","Lime"}; assertEquals(60, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithSevenLimesTotalCostReturnedShouldBe75p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Lime","Lime","Lime","Lime","Lime","Lime","Lime"}; assertEquals(75, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWithOneLimeTotalCostReturnedShouldBe15p() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Lime"}; assertEquals(15, getTotalCostOfBasket(itemsInBasket)); } @Test (expected=FreeLimeRequiredException.class) public void givenBasketWithTwoLimesAnAdditionalLimeRequiredExceptionShouldBeThrown() throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { String itemsInBasket[] = {"Lime","Lime"}; assertEquals(15, getTotalCostOfBasket(itemsInBasket)); } @Test public void givenBasketWith4Limes2Melons2Bananas2ApplesTotalCostReturnedShould205p() throws FreeMelonRequiredException, InvalidItemException, FreeLimeRequiredException { String itemsInBasket[] = {"Lime","Lime","Lime","Lime","Melon","Melon","Banana","Banana","Apple","Apple"}; assertEquals(205, getTotalCostOfBasket(itemsInBasket)); } private int getTotalCostOfBasket(String[] itemsInBasket) throws InvalidItemException, FreeMelonRequiredException, FreeLimeRequiredException { ShoppingBasket shoppingBasket = new ShoppingBasket(itemsInBasket); return shoppingBasket.totalCost(); } }
Python
UTF-8
1,080
3.15625
3
[]
no_license
import sqlite3 con = sqlite3.connect("first.db") # create cursor object c = con.cursor() # v1 # create table if it doesen't exist try: c.execute("""CREATE TABLE person(name TEXT, telefon TEXT)""") except: pass #========================================================================= # v2 # # create table if it doesen't exist # c.execute("""CREATE TABLE IF NOT EXISTS person(name TEXT, telefon TEXT)""") # c.execute("""INSERT INTO person (name, telefon) VALUES ('Janie', 2154635414143);""") # con.commit() # c.close() # con.close() #============================================================================= name_in_python = "Claudia" tel_i_python = "215465365464" names = ["Kat", "Peter", "Hans"] tels = ["46346161", "189813693", "34111184368"] c = sqlite3.connect("first.db") c = con.cursor() c.execute(""" INSERT INTO person(name, telefon) VALUES (?, ?); """, (name_in_python, tel_i_python)) con.commit() for i in range(3): c.execute(""" INSERT INTO person(name, telefon) VALUES (?, ?); """, (names[i], tels[i])) con.commit() c.close() con.close()
Java
UTF-8
1,265
2.328125
2
[ "MIT" ]
permissive
package com.librarymanagment.springbootlibrary.model; import javax.persistence.*; @Entity @Table(name="date_info") public class DateInformation { public DateInformation(){} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Long getBook_id() { return book_id; } public void setBook_id(Long book_id) { this.book_id = book_id; } public Integer getStudent_id() { return student_id; } public void setStudent_id(Integer student_id) { this.student_id = student_id; } public String getBorrowDate() { return borrowDate; } public void setBorrowDate(String borrowDate) { this.borrowDate = borrowDate; } public String getDueDate() { return dueDate; } public void setDueDate(String dueDate) { this.dueDate = dueDate; } @Id @GeneratedValue(strategy= GenerationType.AUTO) @Column(name="id") private Integer id; @Column(name="ISBN") private Long book_id; @Column(name="student_id") private Integer student_id; @Column(name="borrowDate") private String borrowDate; @Column(name="dueDate") private String dueDate; }
JavaScript
UTF-8
673
3.1875
3
[]
no_license
import recursiveLinearSearch from "../recursiveLinearSearch"; describe("recursiveLinearSearch", () => { it("should search number in an array", () => { const array = [1, 4, 3, 5, 7, 1]; expect(recursiveLinearSearch(array, 8)).toEqual(null); expect(recursiveLinearSearch(array, 7)).toEqual(4); expect(recursiveLinearSearch(array, 1)).toEqual(0); }); it("should search string in an array", () => { const array = ["John", "Paul", "George", "Ringo"]; expect(recursiveLinearSearch(array, "Pete")).toEqual(null); expect(recursiveLinearSearch(array, "John")).toEqual(0); expect(recursiveLinearSearch(array, "Ringo")).toEqual(3); }); });
Python
UTF-8
1,449
2.9375
3
[]
no_license
__author__ = 'Daniel' import sqlite3, csv def ReadValue(pEntity, pTime, pSource = 0, pDataBaseName = '/web-interface/simplealgotrade.db'): # Returns the most recent value for the Entity pEntity before pTime # Test case: No results returned # pTime: The number of seconds since 1900 Jan 1, 00:00:00 # pInstrument: The string matching the instrument stored in the database table try: db = sqlite3.connect(pDataBaseName) db.row_factory = sqlite3.Row cursor = db.cursor() # SELECT Entity, Time, Value FROM priceobservation WHERE Entity = 'EURUSD' AND Time = (SELECT MAX(Time) FROM priceobservation WHERE Time < 3630000000 AND Entity = 'EURUSD') sqlquery = ''' SELECT Entity, Time, Value FROM TimeSeriesData WHERE Entity = ? AND Time = (SELECT MAX(Time) FROM TimeSeriesData WHERE Time < ? AND Entity = ?) ''' sqlparameters = [pEntity, pTime, pEntity] cursor.execute(sqlquery, sqlparameters) returnValue = 0 for row in cursor: returnValue = row['Value'] continue return returnValue # Exception needs to be programmed. db.close() except: print("Exception when reading value from database.") #for row in cursor: # row['name'] returns the name column in the query, row['email'] returns email column. # print('{0} : {1}, {2}'.format(row['name'], row['email'], row['phone']))
C
UTF-8
203
2.75
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[40]; int i,l,lines=1; scanf("%s",&a); for(i=0;a[i]!='\0';i++) { if(a[i]=='.') { lines++; } } printf("%d",lines); getch(); }
Markdown
UTF-8
3,135
3.9375
4
[]
no_license
--- title: 算法练习08 用栈实现队列 top: false date: 2019-08-05 21:09:40 updated: 2019-08-05 21:09:42 tags: - LeetCode - 栈 - 队列 categories: 算法 --- 用栈实现队列 <!-- more --> ## 题目 在组内面试反馈的邮件中看到了用栈实现队列这样一道题目,觉得自己如果面试遇到这个题目还是有点懵的,所以特地上网上找了一下,在Leetcode上找到了这道题目[LeetCode 232 用栈实现队列](https://leetcode-cn.com/problems/implement-queue-using-stacks/)。 题目是这样的:使用栈实现队列的下列操作: - `push(x)` -- 将一个元素放入队列的尾部。 - `pop()` -- 从队列首部移除元素。 - `peek()` -- 返回队列首部的元素。 - `empty()` -- 返回队列是否为空。 注意:只能使用标准的栈操作,也就是只有`push to top`,`peek/pop from top`, `size`和`is empty`操作。 实例: ```JS const queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false ``` ## 分析 之所以对这道题目有点懵,是因为自己对栈和队列的特点不太了解 1. 栈是先进后出的,队列是先进先出的 2. 标准的栈只有`push`/`pop`/`size`几个方法 因为JavaScript中的数组实际上比队列和栈是更加灵活的,要用栈来模拟队列,实际上可以用数组先模拟栈,然后在模拟队列。也可以直接使用数组来模拟队列,但是只使用数组的`push`和`pop`方法。 关键是栈和队列的操作顺序如何实现,我的思路是使用了两个栈(数组)来模拟,一个主栈一个辅栈,当移除的时候,栈移除的是栈底的元素,而队列要移除的是队首的元素,所以将主栈的元素都添加到辅栈中,然后再`pop`辅栈栈底的元素,就是队列要移除的队首的元素。实际上和我们玩过的汉诺塔的操作过程。 添加的时候可以直接添加,但是要注意辅栈中是否有元素,如果有的话需要先将辅栈的元素移动会主栈,在进行添加。 ## 实现 ```JS function MyQueue() { // 主栈 this.queue1 = []; // 辅栈 this.queue2 = []; } MyQueue.prototype.push = function (x) { while (this.queue2.length !== 0) { this.queue1.push(this.queue2.pop()) } this.queue1.push(x); }; MyQueue.prototype.pop = function () { if (this.empty()) { return; } while (this.queue1.length !== 0) { this.queue2.push(this.queue1.pop()) } return this.queue2.pop(); }; MyQueue.prototype.peek = function () { if (this.empty()) { return; } while (this.queue1.length !== 0) { this.queue2.push(this.queue1.pop()) } const temp = this.queue2.pop(); this.queue2.push(temp); return temp; }; MyQueue.prototype.empty = function () { return this.queue1.length === 0 && this.queue2.length === 0 }; ``` ## 参考 - [LeetCode 232 用栈实现队列@leetcode](https://leetcode-cn.com/problems/implement-queue-using-stacks/) - [《剑指offer》— JavaScript(5)用两个栈实现队列@简书](https://www.jianshu.com/p/9e99dbdbaf5e)
C#
UTF-8
777
2.515625
3
[ "MIT" ]
permissive
using System; using System.Globalization; using System.Runtime.Serialization; namespace MyParcelApi.Net.Models { [DataContract] public class DateTimeStartEnd { [DataMember(Name = "date", EmitDefaultValue = false)] public string DateRaw { get; set; } public DateTime Date { get => DateTime.ParseExact(DateRaw, "yyyy-MM-dd HH:mm:ss.ffffff", CultureInfo.InvariantCulture); set => DateRaw = value.ToString("yyyy-MM-dd HH:mm:ss.ffffff"); } [DataMember(Name = "timezone_type", EmitDefaultValue = false)] public int TimezoneType { get; set; } [DataMember(Name = "timezone", EmitDefaultValue = false)] public string Timezone { get; set; } } }
Java
UTF-8
3,374
2.46875
2
[]
no_license
package uy.edu.fing.mina.fsa.logics.quineMcCluskey; /* Copyright (c) 2009 the authors listed at the following URL, and/or the authors of referenced articles or incorporated external code: http://en.literateprograms.org/Quine-McCluskey_algorithm_(Java)?action=history&offset=20090311182700 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. Retrieved from: http://en.literateprograms.org/Quine-McCluskey_algorithm_(Java)?oldid=16251 */ /* * modified by Javier Baliosian, Aug 2009 * */ import java.util.Arrays; public class Term { public TfTerm[] varVals; public Term(TfTerm[] varVals) { this.varVals = varVals; } public Term combine(Term term) { int diffVarNum = -1; // The position where they differ for (int i = 0; i < varVals.length; i++) { if (this.varVals[i].b != term.varVals[i].b) { if (diffVarNum == -1) { diffVarNum = i; } else { // They're different in at least two places return null; } } } if (diffVarNum == -1) { // They're identical return null; } TfTerm[] resultVars = varVals.clone(); resultVars[diffVarNum] = new TfTerm(varVals[diffVarNum].tf,TfTerm.DontCare.b); return new Term(resultVars); } public int countValues(byte value) { int result = 0; for (int i = 0; i < varVals.length; i++) { if (varVals[i].b == value) { result++; } } return result; } public boolean equals(Object o) { if (o == this) { return true; } else if (o == null || !getClass().equals(o.getClass())) { return false; } else { Term rhs = (Term) o; return Arrays.equals(this.varVals, rhs.varVals); } } public int getNumVars() { return varVals.length; } public int hashCode() { byte[] ba = new byte[varVals.length]; for (int i = 0; i < varVals.length; i++) { ba[i] = varVals[i].b; } return ba.hashCode(); } boolean implies(Term term) { for (int i = 0; i < varVals.length; i++) { if (this.varVals[i].b != TfTerm.DontCare.b && this.varVals[i].b != term.varVals[i].b) { return false; } } return true; } public String toString() { String result = "{"; for(int i=0; i<varVals.length; i++) { if (varVals[i].b == TfTerm.DontCare.b) result += "X"; else result += varVals[i]; result += " "; } result += "}"; return result; } }
C++
UTF-8
615
2.734375
3
[ "MIT" ]
permissive
#include <vector> using namespace std; class Solution { public: int distributeCookies(vector<int> &cookies, int k) { int N = cookies.size(), mask = (1 << N) - 1; vector<int> dp(1 << N, INT_MAX), count(1 << N); dp[0] = 0; for (int i = 0; i < 1 << N; ++i) { for (int j = 0; j < N; ++j) { if ((i >> j) & 1) count[i] += cookies[j]; } } for (int i = 0; i < k; ++i) { for (int j = mask; j >= 0; --j) { int submask = (~j & mask); for (int m = submask; m > 0; m = submask & (m - 1)) dp[j | m] = min(dp[j | m], max(dp[j], count[m])); } } return dp[mask]; } };
C#
UTF-8
1,287
2.65625
3
[]
no_license
using System.Diagnostics; using System.IO; using System.Text; namespace AppRunner.Utilities { public static class Shell { public static Executable RunCommandAsync(string fileName, string args, DataReceivedEventHandler eventhandler = null, ExecutionCompletedHandler completedHandler = null) { var executable = new Executable(fileName); executable.ExecutionCompleted += completedHandler; executable.RunAsync(args, eventHandler : eventhandler); return executable; } public static string RunCommand(string fileName, string args) { var executable = new Executable(fileName); return executable.Run(args); } //public static void CompileAndRun(string root, string solutionName, string executableName, string commandLineArgs) //{ // var tempPath = Path.GetTempPath() + @"\test-build"; // var solution = new Solution(root, solutionName); // var buildResults = solution.Build(tempPath); // if (buildResults.Success) // { // var executable = new Executable(tempPath + @"\" + executableName); // executable.Run(commandLineArgs); // } //} } }
Java
UTF-8
836
1.875
2
[]
no_license
package com.amap.api.mapcore.util; /* compiled from: SiteInfoBean */ public class O00o0 { private String O000000o; private String O00000Oo; private int O00000o; private String O00000o0; private String O00000oO; public O00o0(String str, String str2, String str3, int i, String str4) { this.O000000o = str; this.O00000Oo = str2; this.O00000o0 = str3; this.O00000o = i; this.O00000oO = str4; } public String O000000o() { return this.O000000o; } public String O00000Oo() { return this.O00000Oo; } public int O00000o() { return this.O00000o; } public String O00000o0() { return this.O00000o0; } public String O00000oO() { return this.O00000oO; } }