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
|
---|---|---|---|---|---|---|---|
TypeScript
|
UTF-8
| 9,115 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import { EventEmitter } from "@angular/core";
import { EntityBase } from "./entity-base";
import { Element } from "./element";
import { ElementCell } from "./element-cell";
import { RatingMode } from "./resource-pool";
import { UserElementField } from "./user-element-field";
export enum ElementFieldDataType {
// A field that holds string value.
// Use StringValue property to set its value on ElementItem level.
String = 1,
// A field that holds decimal value.
// Use DecimalValue property to set its value on ElementItem level.
Decimal = 4,
// A field that holds another defined Element object within the resource pool.
// Use SelectedElementItem property to set its value on ElementItem level.
Element = 6,
}
export class ElementField extends EntityBase {
// Server-side
Id: number = 0;
Element: Element;
Name: string = "";
get DataType(): ElementFieldDataType {
return this.fields.dataType;
}
set DataType(value: ElementFieldDataType) {
if (this.fields.dataType !== value) {
this.fields.dataType = value;
if (this.initialized) {
// a. UseFixedValue must be "true" for String & Element types
if (value === ElementFieldDataType.String
|| value === ElementFieldDataType.Element) {
this.UseFixedValue = true;
}
// b. IndexEnabled must be "false" for String & Element types
if (value === ElementFieldDataType.String
|| ElementFieldDataType.Element) {
this.IndexEnabled = false;
}
// Event
this.dataTypeChanged$.emit(this);
}
}
}
SelectedElement: Element;
UseFixedValue = false;
get IndexEnabled(): boolean {
return this.fields.indexEnabled;
}
set IndexEnabled(value: boolean) {
if (this.fields.indexEnabled !== value) {
this.fields.indexEnabled = value;
if (this.initialized) {
this.indexEnabledChanged$.emit(this);
// Update related
this.ElementCellSet.forEach(cell => {
cell.setIncome();
});
}
}
}
SortOrder: number = 0;
IndexRatingTotal: number = 0;
IndexRatingCount: number = 0;
ElementCellSet: ElementCell[];
UserElementFieldSet: UserElementField[];
// Client-side
get DataTypeText(): string {
let text = ElementFieldDataType[this.DataType];
if (this.DataType === ElementFieldDataType.Element) {
text += ` (${this.SelectedElement.Name})`;
}
return text;
}
otherUsersIndexRatingTotal = 0;
otherUsersIndexRatingCount = 0;
dataTypeChanged$ = new EventEmitter<ElementField>();
indexEnabledChanged$ = new EventEmitter<ElementField>();
indexRatingUpdated$ = new EventEmitter<number>();
private fields: {
currentUserIndexRating: number,
dataType: ElementFieldDataType,
income: number,
indexEnabled: boolean,
indexRating: number,
indexRatingPercentage: number,
numericValue: number,
} = {
currentUserIndexRating: 0,
dataType: ElementFieldDataType.String,
income: 0,
indexEnabled: false,
indexRating: 0,
indexRatingPercentage: 0,
numericValue: 0,
};
currentUserIndexRating() {
return this.fields.currentUserIndexRating;
}
income() {
return this.fields.income;
}
indexRating() {
return this.fields.indexRating;
}
indexRatingAverage() { // a.k.a allUsersIndexRating
return this.indexRatingCount() === 0 ?
0 :
this.indexRatingTotal() / this.indexRatingCount();
}
indexRatingCount() {
return this.otherUsersIndexRatingCount + 1; // There is always default value, increase count by 1
}
indexRatingPercentage() {
return this.fields.indexRatingPercentage;
}
indexRatingTotal() {
return this.otherUsersIndexRatingTotal + this.currentUserIndexRating();
}
initialize(): boolean {
if (!super.initialize()) return false;
// Cells
this.ElementCellSet.forEach(cell => {
cell.initialize();
});
// Other users'
this.otherUsersIndexRatingTotal = this.IndexRatingTotal;
this.otherUsersIndexRatingCount = this.IndexRatingCount;
// Exclude current user's
if (this.UserElementFieldSet[0]) {
this.otherUsersIndexRatingTotal -= this.UserElementFieldSet[0].Rating;
this.otherUsersIndexRatingCount -= 1;
}
// User fields
this.UserElementFieldSet.forEach(userField => {
userField.initialize();
});
// Initial values
this.setCurrentUserIndexRating();
// Event handlers
this.Element.ResourcePool.ratingModeUpdated.subscribe(() => {
this.setIndexRating();
});
return true;
}
numericValue() {
return this.fields.numericValue;
}
rejectChanges(): void {
const element = this.Element;
// Related cells
const elementCellSet = this.ElementCellSet.slice();
elementCellSet.forEach(elementCell => {
elementCell.rejectChanges();
});
// Related user element fields
if (this.UserElementFieldSet[0]) {
this.UserElementFieldSet[0].entityAspect.rejectChanges();
}
this.entityAspect.rejectChanges();
// Update related
element.setIndexRating();
}
remove() {
const element = this.Element;
const elementCellSet = this.ElementCellSet.slice();
elementCellSet.forEach(elementCell => {
// User element cell
if (elementCell.UserElementCellSet[0]) {
elementCell.UserElementCellSet[0].entityAspect.setDeleted();
}
// Cell
elementCell.entityAspect.setDeleted();
});
// User element field
if (this.UserElementFieldSet[0]) {
this.UserElementFieldSet[0].entityAspect.setDeleted();
}
this.entityAspect.setDeleted();
// Update related
element.setIndexRating();
}
setCurrentUserIndexRating() {
const value = this.UserElementFieldSet[0]
? this.UserElementFieldSet[0].Rating
: this.IndexEnabled
? 50 // Default value for IndexEnabled
: 0; // Otherwise 0
if (this.fields.currentUserIndexRating !== value) {
this.fields.currentUserIndexRating = value;
// Update related
this.setIndexRating();
}
}
setIncome() {
const value = this.Element.ResourcePool.InitialValue * this.indexRatingPercentage();
if (this.fields.income !== value) {
this.fields.income = value;
// Update related
this.ElementCellSet.forEach(cell => {
cell.setIncome();
});
}
}
setIndexRating() {
let value = 0; // Default value
switch (this.Element.ResourcePool.RatingMode) {
case RatingMode.CurrentUser: { value = this.currentUserIndexRating(); break; }
case RatingMode.AllUsers: { value = this.indexRatingAverage(); break; }
}
if (this.fields.indexRating !== value) {
this.fields.indexRating = value;
// Update related
//this.indexRatingPercentage(); - No need to call this one since element is going to update it anyway! / coni2k - 05 Nov. '17
this.Element.ResourcePool.mainElement().setIndexRating();
this.indexRatingUpdated$.emit(this.fields.indexRating);
}
}
setIndexRatingPercentage() {
const elementIndexRating = this.Element.ResourcePool.mainElement().indexRating();
const value = elementIndexRating === 0 ? 0 : this.indexRating() / elementIndexRating;
if (this.fields.indexRatingPercentage !== value) {
this.fields.indexRatingPercentage = value;
// Update related
this.setIncome();
}
}
setNumericValue() {
var value = 0;
this.ElementCellSet.forEach(cell => {
value += cell.numericValue();
});
if (this.fields.numericValue !== value) {
this.fields.numericValue = value;
// Update related
this.ElementCellSet.forEach(cell => {
cell.setNumericValuePercentage();
});
}
}
}
|
Java
|
UTF-8
| 1,114 | 3.40625 | 3 |
[] |
no_license
|
package strings;
public class SubstringUsingKMP {
public boolean Kmp(char[] str,char[] pattern){
int[] patternSuffixEqualsPrefix = getPattenSuffixEqualsPrefix(pattern);
int i=0;
int j=0;
while(i<str.length && j<pattern.length){
if(str[i]==pattern[j]){
i++;
j++;
}
else{
if(j!=0){
j=patternSuffixEqualsPrefix[j-1];
}else{
i++;
}
}
}
if(j==pattern.length)
return true;
return false;
}
private int[] getPattenSuffixEqualsPrefix(char[] pattern) {
int[] sp = new int[pattern.length];
int index = 0;
sp[0] = 0;
for(int i=1;i<pattern.length;){
if(pattern[i]==pattern[index]){
sp[i] = index+1;
index++;
i++;
}
else{
if(index!=0){
index = sp[index-1];
}else{
sp[i]=0;
i++;
}
}
}
return sp;
}
public static void main(String[] args) {
String str = "aaaabaaeaaaabaadaaaabaaa";
String pattern = "aaaabaaa";
SubstringUsingKMP kmp = new SubstringUsingKMP();
System.out.println(kmp.Kmp(str.toCharArray(), pattern.toCharArray()));
}
}
|
JavaScript
|
UTF-8
| 1,976 | 2.6875 | 3 |
[] |
no_license
|
//MODULES
import {useState} from "react";
import { logIn } from "../../services/blogService";
import PropTypes from "prop-types";
//COMPONENTS
import InputForm from "../InputForm/InputForm.component";
import Button from "../Button/Button.component";
import "./LogInForm.style.css";
const LogInForm = ({ setUser, setMessage }) =>{
const [userCredentials, setUserCredentials] = useState({
username: "",
password: ""
});
const handleChange = ({ target }) => {
setUserCredentials(prevState=>{
return{
...prevState,
[target.name]: target.value
}
})
};
const handleLogInClick = async (e) =>{
e.preventDefault();
try {
const data = await logIn(userCredentials);
if (!data.error){
setUserCredentials(prevState=>{
return{
...prevState,
username: "",
password:""
};
});
window.localStorage.setItem("loggedBlogUser", JSON.stringify(data));
setUser(data);
}
} catch (error) {
setMessage(prevState=>{
return{
...prevState,
isBad: true,
text: "Username or Password incorrect."
}
});
setInterval(()=>{
setMessage(prevState=>{
return{
...prevState,
text:""
}
});
}, 5000);
}
};
return (
<form onSubmit={handleLogInClick}>
<InputForm
handleChange={handleChange}
value={userCredentials.username}
type="text"
name="username"
label="username"
required
/>
<InputForm
handleChange={handleChange}
value={userCredentials.password}
type="password"
name="password"
label="password"
required
/>
<Button id="log-in">
Log In
</Button>
</form>
);
}
LogInForm.propTypes ={
setUser: PropTypes.func.isRequired,
setMessage: PropTypes.func.isRequired
};
export default LogInForm;
|
Java
|
UTF-8
| 1,709 | 3.921875 | 4 |
[] |
no_license
|
import java.util.*;
public class CarroMain {
public static void main(String[] args) throws Exception {
Carro[] carros = new Carro[2];
carros[0] = new Carro("CHEVROLET");
carros[1] = new Carro("MAZDA");
System.out.println("Informacion del objeto ubicado en 0 : " + carros[0].getMarca());
System.out.println(carros[0]); //estoy ingresando un obteto Carro, y este tiene implementado el étodo tostring que maneja sysout
for (int i = 0; i < carros.length; i++){
System.out.println("Indice: " + i + " Valor: " + carros[i].getMarca());
}
System.out.println("---------------arraylist------------");
ArrayList<Carro> carrosLista = new ArrayList<>();
carrosLista.add(new Carro("Nissan"));
carrosLista.add(new Carro("Ferrari"));
System.out.println(carrosLista.size());
System.out.println(carrosLista.get(0));
System.out.println("---------------conjuntos------------");
Set<Carro> carrosConjunto = new HashSet<>();
carrosConjunto.add(new Carro("pichirilo rojo"));
carrosConjunto.add(new Carro("Toyota"));
carrosConjunto.add(new Carro("BMW"));
System.out.println("TAmaño del conjunto: " + carrosConjunto.size());
for (Carro carro : carrosConjunto) {
System.out.println(carro.getMarca());
}
System.out.println("---------------mapas------------");
Map<String, Carro> carrosMap = new HashMap<>();
carrosMap.put("uno", new Carro("KIA"));
carrosMap.put("dos", new Carro("MAZDA"));
System.out.println(carrosMap.size());
System.out.println(carrosMap.get("uno"));
}
}
|
Markdown
|
UTF-8
| 4,836 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
---
published: true
hidden: false
title: Đàn bà khôn và 9 vũ khí mê hoặc khiến chồng yêu đến mê mẩn
tags: styling react styled-components
twitter_large: true
image: dan-ba-khon.jpg
custom_excerpt: Đàn bà muốn giữ đàn ông không chỉ hơn thua nhau ở nhan sắc mà còn là khôn ngoan biết đâu là vũ khí khiến chồng yêu đến mê mẩn một đời…
---
**Nhân hậu**
Đàn bà hơn nhau ở lòng dạ trong hay đục. Đàn bà có đẹp sắc nước hương trời mà tâm hồn héo úa thì vẫn chỉ là vô dụng trong mắt đàn ông. Đàn bà nhan sắc bình thường nhưng tâm sáng lại là của báu với chồng. Người đẹp thì sẽ có kẻ đẹp hơn, nhưng lương thiện nhân hậu thì không phải ai cũng giữ gìn được. Hãy là một người phụ nữ nổi bật với một trái tim nhân hậu, luôn biết thấu hiểu và cảm thông, trước sau đều hiểu lý lẽ. Có như thế thì dù có thua chân dài ngực khủng thì vẫn chiếm được vị trí số 1 trong lòng đàn ông đến suốt đời.
**Tài năng**
Phụ nữ đẹp thu hút ánh nhìn chốc lát của đàn ông. Nhưng phụ nữ tài năng sẽ khiến đàn ông nhìn hoài không chán. Phụ nữ nên biết đâu là điểm mạnh của mình để theo đuổi. Đàn ông luôn khó lòng rời mắt khỏi người phụ nữ theo đuổi đam mê của mình. Chính sự trau dồi tài năng và nỗ lực hoàn thiện mình luôn khiến đàn ông vừa thương vừa nể trọng phụ nữ. Không những thế, tài năng là bệ phóng cho thành công. Phụ nữ càng thành công càng dễ tìm kiếm người đàn ông xứng với mình.
**Tự tin**
Phụ nữ xinh đẹp nhất chính là khi tự tin. Và phụ nữ xấu xí nhất chính là khi không thể khiến mình tự tin. Đàn bà không nhất thiết phải xinh đẹp hơn người mới có thể giữ chân được đàn ông. Chỉ cần tự tin là chính mình, luôn cười tươi đầy rực rỡ thì đàn ông nào lại không say đắm cho được. Quan trọng không phải là ai thấy bạn xinh đẹp, mà bạn phải thấy bạn xinh đẹp trước đã. Tự tin sẽ khiến phụ nữ xinh đẹp hơn, nhớ nhé!
**Hiểu biết**
Đàn ông luôn khó chối từ phụ nữ thông minh và có hiểu biết. Đơn giản vì đó là những kiểu phụ nữ luôn biết rõ mình là ai, đang ở đâu và muốn làm gì. Phụ nữ đôi khi không cần quá giỏi giang hay tinh ranh, chỉ cần đủ hiểu biết để khiến đàn ông thấy nể trọng, thấy thú vị là đủ. Cũng từ những hiểu biết của mình, phụ nữ dễ dàng có tiếng nói và vị thế với xã hội hơn. Do đó, đã là phụ nữ thì đừng nghĩ không phải nỗ lực, mà là luôn phải cố gắng, mỗi ngày đều phải hoàn thiện mình thật tốt.
**Tự lập**
Phụ nữ quyến rũ luôn biết cô ấy muốn gì và làm thế nào để có thứ mình muốn. Cô ấy không trông mong vào ai khác, chỉ dựa vào bản thân mình. Phụ nữ khôn ngoan luôn hiểu, sa phải đợi chờ người khác bỏ tiền ra mua thứ họ muốn? Thích gì thì tự mua, muốn gì phải tự cố gắng, độc lập sẽ có lúc mỏi mệt nhưng đó sẽ là kiêu hãnh của đàn bà. Đàn ông nể phụ nữ độc lập và càng muốn chinh phục những cô nàng khó chiều này. Đơn giản vì đàn ông cũng hiểu, phụ nữ có độc lập có biết tôn trọng mình thì mới đủ sức yêu thương và bảo bọc người khác.
**Nụ cười**
Với phụ nữ, dù là ai thì luôn nổi bật nhất khi có nụ cười. Nụ cười của phụ nữ không chỉ thể hiện niềm vui mà còn mang đến sức sống cho mọi người xung quanh. Do đó, hãy luôn giữ gìn nụ cười thật xinh đẹp và rực rỡ nhất nhé, vì bạn sẽ không biết có ai đang say đắm nụ cười của mình đâu!
**Luôn biết yêu thương mình**
Phụ nữ quyến rũ nhất chính là khi biết yêu thương mình. Đơn giản vì phụ nữ biết trân trọng mình sẽ dành những gì tốt đẹp nhất cho bản thân. Từ những bộ cánh đẹp đẽ, đến việc chăm sóc da mặt, vóc dáng…tất thảy đều giúp họ xinh đẹp hơn. Đàn ông khi nhìn vào không chỉ ấn tượng bởi sắc đẹp mà họ biết ngay được rằng đây là người biết yêu thương mình. Mà phụ nữ biết trân trọng mình thì luôn khiến đàn ông muốn chinh phục, say mê khó rời.
|
JavaScript
|
UTF-8
| 866 | 4.375 | 4 |
[] |
no_license
|
class BankAccount{
constructor(balance){
/**
* this keyword is used to create variable inside the table of the object.
* This method is much like python.
*/
this.balance = balance;
}
deposit(value){
this.balance = this.balance + value;
console.log(`depositing value ${value}`);
}
withdraw(value){
if (this.balance >= value) {
this.balance = this.balance - value;
console.log(`withdrawing value ${value}`);
}
else{
console.log("insufficient balance");
}
}
statement(){
console.log(`balance = ${this.balance}`);
}
}
var ba = new BankAccount(5000);
console.log(ba);
ba.statement();
ba.deposit(100);
ba.statement();
ba.withdraw(50);
ba.statement();
/*
output:
BankAccount { balance: 5000 }
balance = 5000
depositing value 100
balance = 5100
withdrawing value 50
balance = 5050
*/
|
Java
|
UTF-8
| 1,034 | 1.875 | 2 |
[] |
no_license
|
package com.tinshine.blog.dao.tBlog;
import com.tinshine.blog.entity.BlogEntity;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface IBlogDao {
boolean addArticle(@Param("title") String title, @Param("summary") String summary,
@Param("releaseDate") String releaseDate, @Param("content") String content,
@Param("clickCnt") int clickCnt, @Param("replyCnt") int replyCnt,
@Param("type") int type, @Param("keyword") String keyword);
List<BlogEntity> listBlogs();
BlogEntity getBlogById(@Param("id") int id);
boolean updateArticle(@Param("title") String title, @Param("content") String content, @Param("summary") String summary,
@Param("updateDate") String updateDate, @Param("id") int id, @Param("keyword") String keyword);
boolean deleteBlogById(@Param("id") int id);
boolean onClick(@Param("id") int id);
List<String> listTags();
List<BlogEntity> listByTag(String tag);
}
|
C
|
UTF-8
| 1,078 | 4.28125 | 4 |
[
"MIT"
] |
permissive
|
// Given the root of a binary tree, flatten the tree into a "linked list":
// The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
// The "linked list" should be in the same order as a pre-order traversal of the binary tree.
void flatten(struct TreeNode* root)
{
// if root != null
if(root)
{
// initialize a variable of type TreeNode to root->right
struct TreeNode* flat_tree = root->right;
// perform recursive Depth First Search for left & right subtree
flatten(root->left);
flatten(root->right);
// Flatten by assigning root->right = root->left
root->right = root->left;
root->left = NULL;
// traverse the right subtree of root
while(root->right)
{
root = root->right;
}
// flat_tree = initial root->right
root->right = flat_tree;
}
}
|
Java
|
UTF-8
| 2,429 | 2.046875 | 2 |
[] |
no_license
|
package com.xdl.jjg.web.service;
import com.jjg.member.model.domain.EsGrowthWeightConfigDO;
import com.jjg.member.model.dto.EsGrowthWeightConfigDTO;
import com.jjg.member.model.dto.EsGrowthWeightConfigListDTO;
import com.xdl.jjg.response.service.DubboPageResult;
import com.xdl.jjg.response.service.DubboResult;
/**
* <p>
* 成长值权重配置服务类
* </p>
*
* @author LINS 1220316142@qq.com
* @since 2019-08-08 11:06:56
*/
public interface IEsGrowthWeightConfigService {
/**
* 插入数据
* @auther: lins 1220316142@qq.com
* @date: 2019/05/31 16:39:30
* @param growthWeightConfigDTO DTO
* @return: com.shopx.common.model.result.DubboResult<EsGrowthWeightConfigDO>
*/
DubboResult insertGrowthWeightConfig(EsGrowthWeightConfigListDTO growthWeightConfigDTO);
/**
* 根据条件更新更新数据
* @auther: lins 1220316142@qq.com
* @date: 2019/05/31 16:40:10
* @param growthWeightConfigDTO DTO
* @param id 主键id
* @return: com.shopx.common.model.result.DubboResult<EsGrowthWeightConfigDO>
*/
DubboResult updateGrowthWeightConfig(EsGrowthWeightConfigDTO growthWeightConfigDTO, Long id);
/**
* 根据id获取数据
* @auther: lins 1220316142@qq.com
* @date: 2019/05/31 16:37:16
* @param id 主键id
* @return: com.shopx.common.model.result.DubboResult<EsGrowthWeightConfigDO>
*/
DubboResult<EsGrowthWeightConfigDO> getGrowthWeightConfig(Long id);
/**
* 根据数据类型获取成长值权重
* @auther: lins 1220316142@qq.com
* @date: 2019/05/31 16:37:16
* @param type 主键id
* @return: com.shopx.common.model.result.DubboResult<EsGrowthWeightConfigDO>
*/
DubboResult<EsGrowthWeightConfigDO> getGrowthWeightConfigWeight(Integer type);
/**
* 根据查询条件查询列表
* @auther: lins 1220316142@qq.com
* @date: 2019/06/03 13:42:53
* @return: com.shopx.common.model.result.DubboPageResult<EsGrowthWeightConfigDO>
*/
DubboPageResult<EsGrowthWeightConfigDO> getGrowthWeightConfigList();
/**
* 根据主键删除数据
* @auther: lins 1220316142@qq.com
* @date: 2019/05/31 16:40:44
* @param id 主键id
* @return: com.shopx.common.model.result.DubboResult<EsGrowthWeightConfigDO>
*/
DubboResult deleteGrowthWeightConfig(Long id);
}
|
C
|
UTF-8
| 417 | 3.9375 | 4 |
[] |
no_license
|
// prints the conversion table from fahrenheit to celcius
#include <stdio.h>
main(){
float fahr, celcius;
float lower, upper, step;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
printf("%s\t%s", "Fahrenheit", "Celcius\n");
while(fahr <= upper){
celcius = (5.0 / 9.0) * (fahr - 32.0);
printf("%10.0f\t%7.2f\n", fahr, celcius);
fahr = fahr + step;
}
}
|
Markdown
|
UTF-8
| 13,786 | 2.53125 | 3 |
[] |
no_license
|
Live transcoding (including video transcoding and audio transcoding) refers to the process where the original stream pushed from the live streaming site is converted into streams of different codecs, resolutions, and bitrates in the cloud before being pushed to viewers. This meets playback needs in varying network environments on different devices. This document describes how to create, modify, bind, unbind, and delete a transcoding template in the console.
**You can create a transcoding template in two ways:**
- Create a transcoding template in the CSS console. For detailed directions, please see [Creating standard transcoding template](#C_trans), [Creating top speed codec transcoding template](#C_topspeed), and [Creating pure audio transcoding template](#C_audio).
- Create a transcoding template for live channels with APIs. For specific parameters and samples, please see [CreateLiveTranscodeTemplate](https://intl.cloud.tencent.com/document/product/267/30790).
## Notes
- CSS supports standard transcoding, top speed codec transcoding, and pure audio transcoding. Please read the billing overview before using the service.
- Standard transcoding: [standard transcoding pay-as-you-go billing mode](https://intl.cloud.tencent.com/document/product/267/2818#lvb-transcoding).
- Top speed codec transcoding: [top speed codec transcoding pay-as-you-go billing mode](https://intl.cloud.tencent.com/document/product/267/2818#top-speed-codec-transcoding).
- Compared with **standard transcoding**, **top speed codec transcoding** provides higher image quality at a lower bitrate. Top speed codec transcoding comes with features including intelligent scene recognition, dynamic encoding, and three-level (CTU/line/frame) precise bitrate control model, enabling your live streaming platform to provide higher-definition streaming services at lower bitrates (30% less on average), which effectively reduces your bandwidth costs. This service is widely used in live games, live fashion shows, and other live events.
- After creating a template, you can bind it to a playback domain name. The binding will take effect in 5–10 minutes.
- After creating the template, you can add `_transcoding template name` after the `StreamName` of a live stream to generate a transcoding stream address. If values of the height and width or the short and long sides of the screen are entered, the resolution of the pushed video should follow the entered values as much as possible to avoid image distortion.
- After a transcoding template is bound, the configured settings will be displayed in the template. You can also use this template to view and [unbind](#untie) granular settings created through APIs.
- You can bind one playback domain name to **multiple transcoding templates** or bind one transcoding template to **multiple playback domain names**.
<span id="create"></span>
## Creating Transcoding Template
<span id="C_trans"></span>
### Creating standard transcoding template
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Click **Create Transcoding Template**, select **Standard Transcoding** as the transcoding type, and configure as follows.
- Basic settings include template name, video bitrate, video resolution, and more. For more information, please see [Basic Configuration Description for Standard Transcoding](#C_trans_normal).
- Advanced settings (optional): click **Advanced Configuration** to configure advanced settings. For more information, please see [Advanced Configuration Description for Standard Transcoding](#C_trans_high).
3. After completing the configuration, click **Save**.

<table id="C_trans_normal">
<tr><th width="20%">Basic Settings for Standard Transcoding</th><th>Required</th><th>Description</th></tr>
<tr>
<td>Transcoding Type</td>
<td>Yes</td>
<td>You can select <b>standard transcoding</b>, top speed codec transcoding, or pure audio transcoding.</td>
</tr><tr>
<td>Template Name</td>
<td>Yes</td>
<td>Live transcoding template name, which can contain only letters and alphanumeric combinations. Please enter 1–10 characters.</td>
</tr><tr>
<td>Template Description</td>
<td>No</td>
<td>Live transcoding template description, which can contain only letters, digits, underscores (_), and hyphens (-).</td>
</tr><tr>
<td>Recommended Parameter</td>
<td>No</td>
<td>Three types of templates are supported: <b>Smooth, SD, and HD</b>. After you select a template, the system will automatically enter the recommended video bitrate and video height. You can also modify them manually.</td>
</tr><tr>
<td>Video Bitrate<br>(in Kbps)</td>
<td>Yes</td>
<td>Average output bitrate. Value range: 100–8000 Kbps.<ul style="margin:0">
<li>A value below 1,000 Kbps must be a multiple of 100.</li>
<li>A value above 1,000 Kbps must be a multiple of 500.</li></ul>
</td>
</tr><tr>
<td>Video resolution</td>
<td>Yes</td>
<td>Default setting: **Set by height**.<li>You should enter the height. You can also switch to **Set the short side length** and then enter the length of the short side of the screen. <li>Value range: 0–3000 px. The value should be a multiple of 2 and the other side of the screen will be scaled proportionally.</td>
</tr></table>
<table id="C_trans_high">
<tr><th width="20%">Advanced Settings for Standard Transcoding</th><th>Required</th><th>Description</th></tr>
<tr>
<td>Codec</td>
<td>No</td>
<td>Default setting: original bitrate. You can also select H.264 or H.265 as the codec. </td>
</tr><tr>
<td>Video Frame Rate</td>
<td>No</td>
<td>Value range: 0–60 fps. If this parameter is left empty, the default value 0 fps will be used.</td>
</tr><tr>
<td>Keyframe Interval/GOP<br>(in seconds)</td>
<td>No</td>
<td>Value range: 2–6 seconds. The larger the GOP, the higher the delay. If this parameter is not set, the system default value will be used.</td>
</tr><tr>
<td>Parameter Limit</td>
<td>No</td>
<td>This is disabled by default and can be enabled manually.<br>After the parameter limit is enabled, the original parameter of the input live stream will be the output if the entered parameter is higher than the original parameter. This prevents image quality issues where a low resolution video stream is forced to play back in a higher resolution.</td>
</tr></table>
<span id="C_topspeed"></span>
### Creating top speed codec transcoding template
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Click **Create Transcoding Template**, select **Top Speed Codec Transcoding** as the transcoding type, and configure as follows.
- Basic settings include template name, video bitrate, video resolution, and more. For more information, please see [Basic Configuration Description for Top Speed Codec Transcoding](#C_topspeed_normal).
- Advanced settings (optional): click **Advanced Configuration** to configure advanced settings. For more information, please see [Advanced Configuration Description for Top Speed Codec Transcoding](#C_topspeed_high).
3. Click **Save**.

<table id="C_topspeed_normal">
<tr><th width="20%">Basic Settings for Top Speed Codec Transcoding</th><th>Required</th><th>Description</th>
</tr><tr>
<td>Transcoding Type</td>
<td>Yes</td>
<td>You can select standard transcoding, <b>top speed codec transcoding</b>, or pure audio transcoding.</td>
</tr><tr>
<td>Template Name</td>
<td>Yes</td>
<td>CSS transcoding template name, which can contain only letters and alphanumeric combinations. Please enter 3–10 characters.</td>
</tr><tr>
<td>Template Description</td>
<td>No</td>
<td>CSS transcoding template description, which can contain only letters, digits, underscores (_), and hyphens (-).</td>
</tr><tr>
<td>Recommended Parameter</td>
<td>No</td>
<td>Three types of templates are supported: <b>Smooth, SD, and HD</b>. After you select a template, the system will automatically enter the recommended video bitrate and video height. You can also modify them manually.</td>
</tr><tr>
<td>Video Bitrate<br>(in Kbps)</td>
<td>Yes</td>
<td>Average output bitrate. Value range: 100–8000 Kbps. <li>A value below 1,000 Kbps must be a multiple of 100.</li><li>A value above 1,000 Kbps must be a multiple of 500.</li></td>
</tr><tr>
<td>Video Resolution</td>
<td>Yes</td>
<td>Default setting: **Set by height**.<li>You should enter the height. You can also switch to **Set the short side length** and then enter the length of the short side of the screen. </li><li>Value range: 0–3000 px. The value should be a multiple of 2 and the other side of the screen will be scaled proportionally.</li></td>
</tr>
</table>
<table id="C_topspeed_high">
<tr><th width="20%">Advanced Settings for Top Speed Codec Transcoding</th><th>Required</th><th>Description</th>
</tr><tr>
<td>Codec</td>
<td>No</td>
<td>Default setting: original bitrate. You can also select H.264 or H.265 as the codec. </td>
</tr><tr>
<td>Video Frame Rate</td>
<td>No</td>
<td>Value range: 0–60 fps. If this parameter is left empty, the default value 0 fps will be used.</td>
</tr><tr>
<td>Keyframe Interval/GOP<br>(in seconds)</td>
<td>No</td>
<td>Value range: 2–6 seconds. The larger the GOP, the higher the delay. If this parameter is not set, the system default value will be used.</td>
</tr><tr>
<td>Parameter Limit</td>
<td>No</td>
<td>This is disabled by default and can be enabled manually.<br>After the parameter limit is enabled, the original parameter of the input live stream will be the output if the entered parameter is higher than the original parameter. This prevents image quality issues where a low resolution video stream is forced to play back in a higher resolution.</td>
</tr></table>
<span id="C_audio"></span>
### Creating pure audio transcoding template
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Click **Create Transcoding Template**, select **Pure Audio Transcoding** as the transcoding type, configure [settings](#C_audio_normal), and then click **Save**.

<table id="C_audio_normal">
<tr><th width="20%">Basic Settings for Pure Audio Transcoding</th><th>Required</th><th>Description</th>
</tr><tr>
<td>Transcoding Type</td>
<td>Yes</td>
<td>You can select standard transcoding, top speed codec transcoding, or <strong>pure audio transcoding</strong>.</td>
</tr><tr>
<td>Template Name</td>
<td>Yes</td>
<td>Live transcoding template name, which can contain only letters and alphanumeric combinations. Please enter 3–10 characters.</td>
</tr><tr>
<td>Template Description</td>
<td>No</td>
<td>Live transcoding template description, which can contain only letters, digits, underscores (_), and hyphens (-).</td>
</tr>
</table>
<span id="related"></span>
## Binding Domain Name
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Enter the domain name binding page in either of the following ways:
- **Directly bind a domain name**: click **Bind Domain Name** in the top-left corner.

- **Bind a domain name after creating the transcoding template**: after the [template is created](#create), click **Bind Domain Name** in the pop-up.

3. Select a **transcoding template** and a **playback domain name** in the domain name binding window and then click **OK**.

>?You can click **Add** to bind multiple playback domain names to this template.
<span id="untie"></span>
## Unbinding
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Select domain names bound to the transcoding template and click **Unbind**.

3. Confirm whether to unbind the domain name and click **OK** to unbind it.

<span id="modify"></span>
## Modifying Template
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Select the target transcoding template and click **Edit** on the right to modify the template information.
3. Click **Save**.

<span id="delect"></span>
## Deleting Template
>! If the template has been bound to a domain name, you need to [unbind](#untie) the template before deleting it.
1. Log in to the CSS console and select **Feature Configuration** > **[Live Transcoding](https://console.cloud.tencent.com/live/config/transcode)**.
2. Select a template which is not bound to any playback domain name and click **Delete**.

3. Confirm whether to delete the selected transcoding template and click **OK** to delete it.

## Relevant Operations
For more information on **binding**/**unbinding** a domain name to/from a transcoding template, please see [Transcoding Configuration](https://intl.cloud.tencent.com/document/product/267/31062).
|
C#
|
UTF-8
| 1,343 | 3.375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppObs
{
class Program
{
static void Main(string[] args)
{
//the observable collection
var collection = new ObservableCollection<string>();
using (var observable = new NotifiableCollectionObservable(collection))
using (var observer = observable.Subscribe(new ConsoleStringObserver()))
{
collection.Add("ciao");
collection.Add("hahahah");
collection.Insert(0, "new first line");
collection.RemoveAt(0);
Console.WriteLine("Press RETURN to EXIT");
Console.ReadLine();
}
}
private static void OnCollectionChanged(object sender,NotifyCollectionChangedEventArgs e)
{
var collection = sender as ObservableCollection<string>;
if (e.NewStartingIndex >= 0) //adding new items
Console.WriteLine("-> {0} {1}", e.Action,collection[e.NewStartingIndex]);
else //removing items
Console.WriteLine("-> {0} at {1}", e.Action, e.OldStartingIndex);
}
}
}
|
Java
|
UTF-8
| 2,631 | 2.796875 | 3 |
[] |
no_license
|
/******************************************************/
/*Auteur: Hendrick Samuel & Khamana Benedict */
/*Groupe: 2203 */
/*Application: Inpres Harbour */
/*Date de creation: 25/03/2020 */
/******************************************************/
package HarbourGlobal;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyLogger
{
private DateFormat _formatDate = new SimpleDateFormat("dd/MM/YYYY - HH:mm:ss");
private String _fileDest;
public MyLogger()
{
this("logs");
}
public MyLogger(String text)
{
String sep = System.getProperty("file.separator");
String rep = System.getProperty("user.dir");
String fichier = rep+sep+text;
_fileDest = fichier;
}
public String Now()
{
Date date = new Date();
return _formatDate.format(date);
}
public void Write (String ligne){
try {
FileWriter f = new FileWriter(_fileDest, true);
BufferedWriter bf = new BufferedWriter(f);
bf.write("["+ this.Now() + "] : " + ligne);
System.out.println("["+ this.Now() + "] : " + ligne);
bf.newLine();
bf.close();
} catch (IOException e){
System.out.println("Erreur: " + e.getMessage());
}
}
public void Write (String entete, String info)
{
Write(entete + "> " + info);
}
public String ReadAll()
{
try
{
String all = "";
BufferedReader fin = new BufferedReader(new FileReader(_fileDest));
String line;
while ( (line=fin.readLine()) != null)
{
all += line + System.getProperty("line.separator");
//System.out.println(line);
}
return all;
}
catch (FileNotFoundException e)
{
System.out.println("Erreur: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("Erreur: " + e.getMessage());
}
return "";
}
}
|
JavaScript
|
UTF-8
| 389 | 2.53125 | 3 |
[] |
no_license
|
$(document).ready(function(){
$('form').on('submit', function(){
var add = $('form input');
var newRecipe = {name: add.val()};
$.ajax({
type: 'POST',
url: '/admin',
data: newRecipe,
success: function(data){
location.reload();
}
});
return false;
});
});
|
Java
|
UTF-8
| 5,709 | 1.898438 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: shulie@shulie.io
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.shulie.tro.web.app.service.perfomanceanaly.impl;
import com.google.common.collect.Lists;
import com.pamirs.tro.common.util.DateUtils;
import io.shulie.tro.web.app.convert.performace.PressureMachineStatisticsRespConvert;
import io.shulie.tro.web.app.request.perfomanceanaly.PressureMachineStatisticsRequest;
import io.shulie.tro.web.app.response.perfomanceanaly.PressureMachineStatisticsResponse;
import io.shulie.tro.web.app.response.perfomanceanaly.TypeValueDateVo;
import io.shulie.tro.web.app.service.perfomanceanaly.PressureMachineStatisticsService;
import io.shulie.tro.web.data.dao.perfomanceanaly.PressureMachineStatisticsDao;
import io.shulie.tro.web.data.param.perfomanceanaly.PressureMachineStatisticsInsertParam;
import io.shulie.tro.web.data.param.perfomanceanaly.PressureMachineStatisticsQueryParam;
import io.shulie.tro.web.data.result.perfomanceanaly.PressureMachineStatisticsResult;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Author: mubai
* @Date: 2020-11-13 11:36
* @Description:
*/
@Service
public class PressureMachineStatisticsServiceImpl implements PressureMachineStatisticsService {
@Autowired
private PressureMachineStatisticsDao pressureMachineStatisticsDao;
@Override
public void statistics() {
PressureMachineStatisticsResult statistics = getStatistics();
PressureMachineStatisticsInsertParam insertParam = new PressureMachineStatisticsInsertParam();
BeanUtils.copyProperties(statistics, insertParam);
pressureMachineStatisticsDao.insert(insertParam);
}
@Override
public void insert(PressureMachineStatisticsInsertParam param) {
pressureMachineStatisticsDao.insert(param);
}
@Override
public PressureMachineStatisticsResponse getNewlyStatistics() {
PressureMachineStatisticsResult newlyStatistics = pressureMachineStatisticsDao.getNewlyStatistics();
return PressureMachineStatisticsRespConvert.INSTANCE.of(newlyStatistics);
}
@Override
public List<TypeValueDateVo> queryByExample(PressureMachineStatisticsRequest request) {
PressureMachineStatisticsQueryParam param = new PressureMachineStatisticsQueryParam();
BeanUtils.copyProperties(request, param);
List<PressureMachineStatisticsResult> list = pressureMachineStatisticsDao.queryByExample(param);
//将数据进行采样,取200个点
list = pointSample(list);
return assembleData(list);
}
List<PressureMachineStatisticsResult> pointSample(List<PressureMachineStatisticsResult> source) {
List<PressureMachineStatisticsResult> results = new ArrayList<>();
int step = 0;
if (source != null && source.size() > 100) {
step = source.size() / 100;
for (int i = 0; i + step < source.size(); i++) {
i = i + step;
results.add(source.get(i));
}
results.add(source.get(source.size() - 1));
} else {
results = source;
}
return results;
}
private List<TypeValueDateVo> assembleData(List<PressureMachineStatisticsResult> list) {
List<TypeValueDateVo> resultList = new ArrayList<>();
if (CollectionUtils.isEmpty(list)) {
return Lists.newArrayList();
}
for (PressureMachineStatisticsResult result : list) {
String time = result.getGmtCreate().substring(0, 19);
time = time.replaceAll("T", " ");
TypeValueDateVo totalVo = new TypeValueDateVo();
totalVo.setType("总数");
totalVo.setValue(result.getMachineTotal());
totalVo.setDate(time);
TypeValueDateVo pressuredVo = new TypeValueDateVo();
pressuredVo.setDate(time);
pressuredVo.setValue(result.getMachinePressured());
pressuredVo.setType("压测中");
TypeValueDateVo freeVo = new TypeValueDateVo();
freeVo.setDate(time);
freeVo.setValue(result.getMachineFree());
freeVo.setType("空闲");
TypeValueDateVo offlineVo = new TypeValueDateVo();
offlineVo.setType("离线");
offlineVo.setDate(time);
offlineVo.setValue(result.getMachineOffline());
resultList.add(totalVo);
resultList.add(pressuredVo);
resultList.add(freeVo);
resultList.add(offlineVo);
}
return resultList;
}
@Override
public PressureMachineStatisticsResult getStatistics() {
//获取压力机
return pressureMachineStatisticsDao.statistics();
}
@Override
public void clearRubbishData() {
Date previousNDay = DateUtils.getPreviousNDay(91);
pressureMachineStatisticsDao.clearRubbishData(DateUtils.dateToString(previousNDay, DateUtils.FORMATE_YMDHMS));
}
}
|
Python
|
UTF-8
| 5,266 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
import instantiate
import pddl
class RelaxedAtom(object):
def __init__(self, name):
self.name = name
def __cmp__(self, other):
return cmp(self.name, other.name)
def __repr__(self):
return "<RelaxedAtom %r>" % self.name
def __str__(self):
return str(self.name)
class RelaxedAction(object):
def __init__(self, name, preconditions, effects, cost):
self.name = name
self.preconditions = preconditions
self.effects = effects
self.cost = cost
def dump(self):
print "ACTION %s (cost %d):" % (self.name, self.cost)
print "PRE:"
for fact in self.preconditions:
print " %s" % fact
print "EFF:"
for fact in self.effects:
print " %s" % fact
class RelaxedTask(object):
def __init__(self, atoms, init, goals, actions):
self.atoms = atoms
self.init = init
self.goals = goals
self.actions = actions
def convert_to_canonical_form(self):
# Transforms the relaxed task into an equivalent one such that:
# * Each relaxed plan begins with action "@@init-action".
# * Each non-redundant relaxed plan ends with action "@@goal-action".
# * There is exactly one initial fact, "@@init".
# * There is exactly one goal fact, "@@goal".
# * Each action has at least one precondition.
init_fact = RelaxedAtom("@@init")
old_init = list(self.init)
self.atoms.append(init_fact)
self.init = [init_fact]
init_action = RelaxedAction(
name="@@init-action",
preconditions=[init_fact],
effects=old_init,
cost=0)
self.actions.append(init_action)
goal_fact = RelaxedAtom("@@goal")
old_goals = list(self.goals)
self.atoms.append(goal_fact)
self.goals = [goal_fact]
self.actions.append(RelaxedAction(
name="@@goal-action",
preconditions=old_goals,
effects=[goal_fact],
cost=0))
artificial_precondition = None
for action in self.actions:
if not action.preconditions:
if not artificial_precondition:
artificial_precondition = RelaxedAtom("@@precond")
self.atoms.append(artificial_precondition)
init_action.effects.append(artificial_precondition)
action.preconditions.append(artificial_precondition)
def dump(self):
print "ATOMS:"
for fact in self.atoms:
print " %s" % fact
print
print "INIT:"
for fact in self.init:
print " %s" % fact
print
print "GOAL:"
for fact in self.goals:
print " %s" % fact
for action in self.actions:
print
action.dump()
def build_relaxed_action(action, symtable):
def fail():
raise SystemExit("not a STRIPS action: %s" % action.name)
preconditions = []
effects = []
for literal in action.precondition:
if literal.negated:
fail()
preconditions.append(symtable[literal])
for conditions, effect_literal in action.add_effects:
if conditions:
fail()
effects.append(symtable[effect_literal])
for conditions, effect_literal in action.del_effects:
if conditions:
fail()
return RelaxedAction(action.name, sorted(preconditions), sorted(effects), 1)
def collect_init_facts(init, symtable):
facts = []
for atom in init:
fact = symtable.get(atom)
if fact:
facts.append(fact)
return sorted(facts)
def collect_goal_facts(goal, symtable):
def fail():
raise SystemExit("not a STRIPS goal: %s" % goal)
facts = []
def recurse(condition):
if isinstance(condition, pddl.Conjunction):
for part in condition.parts:
recurse(part)
elif isinstance(condition, pddl.Literal):
if condition.negated:
fail()
fact = symtable.get(condition)
if fact:
facts.append(fact)
elif not isinstance(condition, pddl.Truth):
fail()
recurse(goal)
return sorted(facts)
def build_relaxed_task(task):
relaxed_reachable, fluent_atoms, actions, axioms = instantiate.explore(task)
if not relaxed_reachable:
raise SystemExit("goal is not relaxed reachable")
if axioms:
raise SystemExit("axioms not supported")
symtable = dict((atom, RelaxedAtom(str(atom))) for atom in fluent_atoms)
relaxed_atoms = sorted(symtable.values())
relaxed_actions = [build_relaxed_action(action, symtable)
for action in actions]
relaxed_init = collect_init_facts(task.init, symtable)
relaxed_goal = collect_goal_facts(task.goal, symtable)
return RelaxedTask(relaxed_atoms, relaxed_init, relaxed_goal,
relaxed_actions)
if __name__ == "__main__":
task = pddl.open()
relaxed_task = build_relaxed_task(task)
relaxed_task.convert_to_canonical_form()
relaxed_task.dump()
|
Markdown
|
UTF-8
| 10,424 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
---
Name: "Helpers"
weight: 6
aliases:
- /docs/helpers
- /es/docs/helpers
---
# Helpers
{{<note>}}
Este documento solo aplica cuando se usa [github.com/gobuffalo/buffalo/render](https://github.com/gobuffalo/buffalo/tree/main/render).
Consulta [github.com/gobuffalo/plush](https://github.com/gobuffalo/plush) para más detalles sobre el paquete de plantillas.
{{</note>}}
## Helpers incorporados
Una lista completa de todas las funciones de helpers para [`github.com/gobuffalo/plush`](https://godoc.org/github.com/gobuffalo/plush) se puede encontrar en [`github.com/gobuffalo/helpers`](https://godoc.org/github.com/gobuffalo/helpers).
## Helpers de rutas
Buffalo generará los helpers de rutas para todas las rutas que agregas a la aplicación. La forma mas fácil de ver cuáles son todos los helpers de ruta generados y a qué apuntan, es ejecutar `buffalo routes`. Esto imprimirá una lista como esta:
```text
$ buffalo routes
METHOD | HOST | PATH | ALIASES | NAME | HANDLER
------ | ---- | ---- | ------- | ---- | -------
GET | http://127.0.0.1:3000 | / | | rootPath | github.com/gobuffalo/coke/actions.HomeHandler
GET | http://127.0.0.1:3000 | /about | | aboutPath | github.com/gobuffalo/coke/actions.AboutHandler
GET | http://127.0.0.1:3000 | /drinks | | drinksPath | github.com/gobuffalo/coke/actions.DrinksResource.List
POST | http://127.0.0.1:3000 | /drinks | | drinksPath | github.com/gobuffalo/coke/actions.DrinksResource.Create
GET | http://127.0.0.1:3000 | /drinks/new | | newDrinksPath | github.com/gobuffalo/coke/actions.DrinksResource.New
GET | http://127.0.0.1:3000 | /drinks/{drink_id} | | drinkPath | github.com/gobuffalo/coke/actions.DrinksResource.Show
PUT | http://127.0.0.1:3000 | /drinks/{drink_id} | | drinkPath | github.com/gobuffalo/coke/actions.DrinksResource.Update
DELETE | http://127.0.0.1:3000 | /drinks/{drink_id} | | drinkPath | github.com/gobuffalo/coke/actions.DrinksResource.Destroy
GET | http://127.0.0.1:3000 | /drinks/{drink_id}/edit | | editDrinkPath | github.com/gobuffalo/coke/actions.DrinksResource.Edit
GET | http://127.0.0.1:3000 | /api/v1/users | | apiV1UsersPath | github.com/gobuffalo/coke/actions.UsersResource.List
POST | http://127.0.0.1:3000 | /api/v1/users | | apiV1UsersPath | github.com/gobuffalo/coke/actions.UsersResource.Create
GET | http://127.0.0.1:3000 | /api/v1/users/new | | newApiV1UsersPath | github.com/gobuffalo/coke/actions.UsersResource.New
GET | http://127.0.0.1:3000 | /api/v1/users/{user_id} | | apiV1UserPath | github.com/gobuffalo/coke/actions.UsersResource.Show
PUT | http://127.0.0.1:3000 | /api/v1/users/{user_id} | | apiV1UserPath | github.com/gobuffalo/coke/actions.UsersResource.Update
DELETE | http://127.0.0.1:3000 | /api/v1/users/{user_id} | | apiV1UserPath | github.com/gobuffalo/coke/actions.UsersResource.Destroy
GET | http://127.0.0.1:3000 | /api/v1/users/{user_id}/edit | | editApiV1UserPath | github.com/gobuffalo/coke/actions.UsersResource.Edit
```
Bajando por esta lista podemos ver la ruta en la columna *NAME* `rootPath`, la cual se representa en la columna *PATH* `/` o la ruta raíz del servidor y como bonus, con todos estos podemos incliso ver exactamente que controlador en la columna *HANDLER* se está ejecutando para esta combinación *METHOD* + *PATH*.
A continuación tenemos un estándar `app.GET("/about", AboutHandler)` que genera `aboutPath`.
Entonces usamos un recurso `app.Resource("/drinks", DrinksResource{})`, el cual genera una ruta para cada una de nuestras acciones estándar, y para cada una de ellas, un helper para usarlo en las plantillas. Los que toman un parametro se pueden usar asi `<%= drinkPath({drink_id: drink.ID}) %>`. Todos los helpers toman un `map[string]interface{}` que se usa para rellenar los parámetros.
Finalmente, cuando usamos un grupo podemos ver que esto cambia los helpers generados. Aquí está el enrutamiento para esas últimas rutas:
```go
api := app.Group("/api/v1")
api.Resource("/users", UsersResource{})
```
**Nota** que los helpers se generan para que coincidan con las rutas generadas. Es posible sobreescribir los nombres de las rutas en `App.Routes`, pero se conseja encarecidamente que encuentres un camino diferente a tu objetivo. Slack siempre está abierto a estas conversaciones.
### Helper PathFor
El helper [`github.com/gobuffalo/helpers/paths#PathFor`](https://godoc.org/github.com/gobuffalo/helpers/paths#PathFor) toma una `interface{}`, or a `slice` de ellas, e intenta convertirlo en una ruta de URL al estilo `/foos/{id}`.
Reglas:
* Si es `cadena` se devuelve tal cual
* Si es de tipo [`github.com/gobuffalo/helpers/paths#Pathable`](https://godoc.org/github.com/gobuffalo/helpers/paths#Pathable), se retornará el método `ToPath`.
* Si es un `slice` o de un `array`, cada elemento se pasa por el helper y luego se une.
* Si des de tipo [`github.com/gobuffalo/helpers/paths#Paramable`](https://godoc.org/github.com/gobuffalo/helpers/paths#Paramable) se usa el método `ToParam` para rellenar el espacio `{id}`.
* Si es `<T>.Slug`, el slug se utiliza para rellenar el espacio `{id}` de la URL.
* Si es `<T>.ID` el ID se utiliza para rellenar el espacio `{id}` de la URL.
### LinkTo Helpers
### LinkTo
El helper [`tags#LinkTo`](https://godoc.org/github.com/gobuffalo/helpers/tags#LinkTo) crea una etiqueta HTML <a> usando [`tags`](https://godoc.org/github.com/gobuffalo/tags) para crear la etiqueta con las [`tags#Options`](https://godoc.org/github.com/gobuffalo/tags#Options) dadas, y usando [`paths#PathFor`](https://godoc.org/github.com/gobuffalo/helpers/paths#PathFor) para establecer el atributo `href`.
Si se le da un bloque, se interrumpirá y se añadirá dentro de la etiqueta `<a>`.
#### Ejemplo 1:
```html
<%= linkTo([user, widget], {class: "btn"}) %>
<a class="btn" href="/users/id/widget/slug"></a>
```
#### Ejemplo 2:
```html
<%= linkTo("foo", {class: "btn"}) %>
<a class="btn" href="/foo"></a>
```
#### Ejemplo 3:
```html
<%= linkTo(user, {class: "btn"}) { %>
Click Me!
<% } %>
<a class="btn" href="/users/id">Click Me!</a>
```
### RemoteLinkTo
El helper [`tags#RemoteLinkTo`](https://godoc.org/github.com/gobuffalo/helpers/tags#RemoteLinkTo) proporciona la misma funcionalidad que [`tags#LinkTo`](https://godoc.org/github.com/gobuffalo/helpers/tags#LinkTo) pero agrega el atributo `data-remote` para ser usado con [https://www.npmjs.com/package/rails-ujs](https://www.npmjs.com/package/rails-ujs) el cual se incluye en la configuración por defecto de Webpack.
#### Ejemplo 1:
```html
<%= remoteLinkTo([user, widget], {class: "btn"}) %>
<a class="btn" data-remote="true" href="/users/id/widget/slug"></a>
```
#### Ejemplo 2:
```html
<%= remoteLinkTo("foo", {class: "btn"}) %>
<a class="btn" data-remote="true" href="/foo"></a>
```
#### Ejemplo 3:
```html
<%= remoteLinkTo(user, {class: "btn"}) { %>
Click Me!
<% } %>
<a class="btn" data-remote="true" href="/users/id">Click Me!</a>
```
## Helpers de contenido
Plush viene con dos helpers complementarios que te permiten crear fragmentos dinámicos de HTML y reutilizarlos despues en la plantilla.
### Helpers `contentFor` y `contentOf`
El helper `contentFor` toma un bloque de HTML y lo mantiene usando el nombre dado. Este bloque se puede usar en cualquier parte del archivo de plantilla, aun cuando el contenido definido en un bloque `contentFor` es una plantilla cedida y se expande dentro de un bloque `contentOf` una plantilla con llamada `yield`. La plantilla por defecto `templates/application.html` llama `yield` así:
Tomemos el siguiente ejemplo: supongamos que tenemos una plantilla `templates/application.html` que especifica completamente todo en `<head>` y el contenido mas externo dentro de `<body>`. Esta plantilla cede a otras subplantillas, como `templates/users/show.html`, para llenar `<body>`. Sin embargo, si queremos agregar o sobrescribir algo en el `<head>` desde una subplantilla, necesitaremos usar `contentFor`. En este ejemplo, agregaremos una manera de que las subplantillas agreguen un trozo extra de CSS al `<head>` de `application.plush.html`.
```html
<!-- aplication.plush.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Site</title>
<%= stylesheetTag("application.css") %>
<%= contentOf("extraStyle") %>
</head>
<body>
<div class="container">
<%= partial("flash.html") %>
<%= yield %>
</div>
</body>
</html>
```
Resulta que a nuestra plantilla `users/index.html` le vendría bien usar un poco de estilo para toda la página en vez de agregar un monton de atributos `style` a diferentes elementos, así que se define un bloque de CSS que no aparece dentro de la plantilla:
```html
<!-- users/index.html -->
<div class="page-header">
<h1>Users</h1>
</div>
<table class="table table-striped">
<thead>
<th>Username</th> <th>Password</th> <th>Email</th> <th>Admin?</th> <th> </th>
</thead>
<tbody>
<%= for (user) in users { %>
<!-- … -->
<% } %>
</tbody>
</table>
<% contentFor("extraStyle") { %>
<style>
.online {
color: limegreen;
background: black;
}
.offline {
color: lightgray;
background: darkgray;
}
</style>
<% } %>
```
El estilo para las clases `.outline` y `.offline` aparecen entonces al final de la etiqueta `<head>` en `/users`. En otras paginas no se agrega nada.
Por supuesto, si prefieres hacer un procesamiento extenso de lo que va en un trozo que va en una página web, es posible que desees hacer tu procesamiento en el código de Go en vez de en las plantillas. En ese caso, llama, digamos, `c.Set("moonPhase", mp)`, donde `c` es `buffalo.Context` en una función de una accion como en `actions/users.go`, y `mp` es alguna cadena u objeto. Luego en tus plantillas, haz referencia `<%= moonPhase %>` para mostrar tu fase de la luna calculada por expertos.
|
Python
|
UTF-8
| 317 | 2.640625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
req= urllib2.Request('http://www.baidu.com')
try:
urllib2.urlopen(req)
except urllib2.URLError,e:
if hasattr(e,"code"):
print(e.code)
except urllib2.URLError,e:
if hasattr(e,"reason"):
print(e.reason)
else:
print("OK")
|
Markdown
|
UTF-8
| 1,397 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
# web-crawler
A web crawler that seeks for urls. Currently it doesn't serve any purpose apart from collecting different urls it finds across the web.
## Getting Started
### Prerequisites
- Python >= 3
- pipenv
OR
- Docker Compose
### Installing
Navigate to the project root and run the following command:
```bash
ROOT_URL=insert_root_url_here docker-compose up --build --scale web-crawler=2
```
This starts the web-crawler-scheduler and two web-crawlers. The scale number can be anything, but keep in mind to not overload the target server.
OR
Open two seperate terminals and navigate to both _web-crawler-scheduler_ and _web-crawler_ directories, where in both run first the following command:
```bash
pipenv install
```
and then in the _web-crawler-scheduler_ directory run
```bash
pipenv run python main.py insert_root_url_here
```
and in the _web-crawler_ directory run
```bash
pipenv run python main.py
```
**All urls that the crawler finds will be stored into _/web-crawler-scheduler/data/data.txt_**
### Disclaimer
Please notice that this project was created just to practise network programming with Python. If you choose to test this app, be sure to not overload the servers you are targeting. Don't start too many crawlers at once and don't remove the `time.sleep(1)` that slows down the loop in `WebCrawler.py` file. I'm not liable for any misuse of this application.
|
JavaScript
|
UTF-8
| 826 | 3.765625 | 4 |
[] |
no_license
|
/*
pascal triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
*/
function pascal(n) {
if (n === 1) {
console.log(['1']);
} else if (n === 2) {
console.log([[1], [1, 1]]);
} else {
const ans = [[1], [1, 1]];
for (let i = 2; i <= n; i++) {
// lines
const newLine = [];
for (let j = 0; j < i; j++) {
// inLine
// if (j===0) 1 else if (j===i-1) 1 :
const newNum = ans[i][j] + ans[i][j + 1];
newLine.push(newNum);
}
ans.push(newLine);
}
console.log(ans);
}
}
/* return the kth largest element */
function largest(array, k) {
let max = array[0];
for (let i = 0; i < array.length; i++) {
if (array[i] > ans) {
ans = array[i];
}
return ans;
}
}
|
Java
|
UHC
| 6,518 | 1.90625 | 2 |
[] |
no_license
|
/***************************************************************************************************
* ϸ : .java
* :
* ۼ :
* ۼ :
***************************************************************************************************/
/***************************************************************************************************
* :
* :
* :
* :
***************************************************************************************************/
package chosun.ciis.ss.sls.brsup.ds;
import java.sql.*;
import java.util.*;
import somo.framework.db.*;
import somo.framework.util.*;
import chosun.ciis.ss.sls.brsup.dm.*;
import chosun.ciis.ss.sls.brsup.rec.*;
/**
*
*/
public class SS_L_VACT_STAT_INITDataSet extends somo.framework.db.BaseDataSet implements java.io.Serializable{
public ArrayList teamlist = new ArrayList();
public ArrayList arealist = new ArrayList();
public ArrayList partlist = new ArrayList();
public ArrayList curmedicd = new ArrayList();
public ArrayList curbankcd = new ArrayList();
public String errcode;
public String errmsg;
public SS_L_VACT_STAT_INITDataSet(){}
public SS_L_VACT_STAT_INITDataSet(String errcode, String errmsg){
this.errcode = errcode;
this.errmsg = errmsg;
}
public void setErrcode(String errcode){
this.errcode = errcode;
}
public void setErrmsg(String errmsg){
this.errmsg = errmsg;
}
public String getErrcode(){
return this.errcode;
}
public String getErrmsg(){
return this.errmsg;
}
public void getValues(CallableStatement cstmt) throws SQLException{
this.errcode = Util.checkString(cstmt.getString(1));
this.errmsg = Util.checkString(cstmt.getString(2));
if(!"".equals(this.errcode)){
return;
}
ResultSet rset0 = (ResultSet) cstmt.getObject(5);
while(rset0.next()){
SS_L_VACT_STAT_INITTEAMLISTRecord rec = new SS_L_VACT_STAT_INITTEAMLISTRecord();
rec.dept_cd = Util.checkString(rset0.getString("dept_cd"));
rec.dept_nm = Util.checkString(rset0.getString("dept_nm"));
this.teamlist.add(rec);
}
ResultSet rset1 = (ResultSet) cstmt.getObject(6);
while(rset1.next()){
SS_L_VACT_STAT_INITPARTLISTRecord rec = new SS_L_VACT_STAT_INITPARTLISTRecord();
rec.dept_cd = Util.checkString(rset1.getString("dept_cd"));
rec.dept_nm = Util.checkString(rset1.getString("dept_nm"));
rec.supr_dept_cd = Util.checkString(rset1.getString("supr_dept_cd"));
this.partlist.add(rec);
}
ResultSet rset2 = (ResultSet) cstmt.getObject(7);
while(rset2.next()){
SS_L_VACT_STAT_INITAREALISTRecord rec = new SS_L_VACT_STAT_INITAREALISTRecord();
rec.area_cd = Util.checkString(rset2.getString("area_cd"));
rec.area_nm = Util.checkString(rset2.getString("area_nm"));
rec.dept_cd = Util.checkString(rset2.getString("dept_cd"));
rec.supr_dept_cd = Util.checkString(rset2.getString("supr_dept_cd"));
this.arealist.add(rec);
}
ResultSet rset3 = (ResultSet) cstmt.getObject(8);
while(rset3.next()){
SS_L_VACT_STAT_INITCURMEDICDRecord rec = new SS_L_VACT_STAT_INITCURMEDICDRecord();
rec.cicodeval = Util.checkString(rset3.getString("cicodeval"));
rec.cicdnm = Util.checkString(rset3.getString("cicdnm"));
rec.ciymgbcd = Util.checkString(rset3.getString("ciymgbcd"));
rec.cicdgb = Util.checkString(rset3.getString("cicdgb"));
rec.cicdynm = Util.checkString(rset3.getString("cicdynm"));
this.curmedicd.add(rec);
}
ResultSet rset4 = (ResultSet) cstmt.getObject(9);
while(rset4.next()){
SS_L_VACT_STAT_INITCURBANKCDRecord rec = new SS_L_VACT_STAT_INITCURBANKCDRecord();
rec.cicodeval = Util.checkString(rset4.getString("cicodeval"));
rec.cicdnm = Util.checkString(rset4.getString("cicdnm"));
this.curbankcd.add(rec);
}
}
}/*----------------------------------------------------------------------------------------------------
Web Tier DataSet ü ڵ ۼ Ͻʽÿ.
<%
SS_L_VACT_STAT_INITDataSet ds = (SS_L_VACT_STAT_INITDataSet)request.getAttribute("ds");
%>
Web Tier Record ü ڵ ۼ Ͻʽÿ.
<%
for(int i=0; i<ds.teamlist.size(); i++){
SS_L_VACT_STAT_INITTEAMLISTRecord teamlistRec = (SS_L_VACT_STAT_INITTEAMLISTRecord)ds.teamlist.get(i);%>
HTML ڵ....
<%}%>
<%
for(int i=0; i<ds.partlist.size(); i++){
SS_L_VACT_STAT_INITPARTLISTRecord partlistRec = (SS_L_VACT_STAT_INITPARTLISTRecord)ds.partlist.get(i);%>
HTML ڵ....
<%}%>
<%
for(int i=0; i<ds.arealist.size(); i++){
SS_L_VACT_STAT_INITAREALISTRecord arealistRec = (SS_L_VACT_STAT_INITAREALISTRecord)ds.arealist.get(i);%>
HTML ڵ....
<%}%>
<%
for(int i=0; i<ds.curmedicd.size(); i++){
SS_L_VACT_STAT_INITCURMEDICDRecord curmedicdRec = (SS_L_VACT_STAT_INITCURMEDICDRecord)ds.curmedicd.get(i);%>
HTML ڵ....
<%}%>
<%
for(int i=0; i<ds.curbankcd.size(); i++){
SS_L_VACT_STAT_INITCURBANKCDRecord curbankcdRec = (SS_L_VACT_STAT_INITCURBANKCDRecord)ds.curbankcd.get(i);%>
HTML ڵ....
<%}%>
----------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------
Web Tier DataSet ü <%= %> ۼ Ͻʽÿ.
<%= ds.getErrcode()%>
<%= ds.getErrmsg()%>
<%= ds.getTeamlist()%>
<%= ds.getPartlist()%>
<%= ds.getArealist()%>
<%= ds.getCurmedicd()%>
<%= ds.getCurbankcd()%>
----------------------------------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------------------------------
Web Tier Record ü <%= %> ۼ Ͻʽÿ.
<%= teamlistRec.dept_cd%>
<%= teamlistRec.dept_nm%>
<%= partlistRec.dept_cd%>
<%= partlistRec.dept_nm%>
<%= partlistRec.supr_dept_cd%>
<%= arealistRec.area_cd%>
<%= arealistRec.area_nm%>
<%= arealistRec.dept_cd%>
<%= arealistRec.supr_dept_cd%>
<%= curmedicdRec.cicodeval%>
<%= curmedicdRec.cicdnm%>
<%= curmedicdRec.ciymgbcd%>
<%= curmedicdRec.cicdgb%>
<%= curmedicdRec.cicdynm%>
<%= curbankcdRec.cicodeval%>
<%= curbankcdRec.cicdnm%>
----------------------------------------------------------------------------------------------------*/
/* ۼð : Wed Sep 30 14:19:28 KST 2015 */
|
Swift
|
UTF-8
| 3,779 | 2.703125 | 3 |
[] |
no_license
|
//
// AppDelegate.swift
// Clok
//
// Created by Secret Asian Man Dev on 23/12/20.
// Copyright © 2020 Secret Asian Man 3. All rights reserved.
//
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
var notificationCentre: NotificationCentre? = .none
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
/** Docs: https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate
Documentation explicitly instructs developers to assign `UNUserNotificationCenterDelegate` at app start up, which is what I'm doing here.
I have no idea if this is the right way to do it, but keeping a reference to the thing in my `AppDelegate` seems like the right way to go.
*/
self.notificationCentre = NotificationCentre()
return true
}
}
final class NotificationCentre: NSObject, UNUserNotificationCenterDelegate {
/// assign itself as the delegate, per instructions in
/// https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate
override init() {
super.init()
let center = UNUserNotificationCenter.current()
center.delegate = self
center.setNotificationCategories([
UNNotificationCategory(
identifier: NotificationConstants.RunningCategory,
actions: [
UNNotificationAction(
identifier: NotificationConstants.Identifier.stop.rawValue,
title: "Stop"
)
],
intentIdentifiers: [] /// no intents to declare
)
])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
/// display the alert, even when the app is in the foreground
completionHandler(.list)
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
// pull out the buried userInfo dictionary
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
print("Custom data received: \(customData)")
}
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
#if DEBUG
print("User Swiped")
#endif
case NotificationConstants.Identifier.stop.rawValue:
#if DEBUG
print("Stop requested")
#endif
/// execute stop request in the background
let token = try! getKey().token
let running = WidgetManager.running
guard running != .noEntry else { break }
/// since app is in the background, completion is handled in `urlSession(_:downloadTask:didFinishDownloadingTo:)`
TimeEntry.stop(id: running.id, with: token, downloadDelegate: DownloadDelegate()) { _ in }
default:
break
}
// you must call the completion handler when you're done
completionHandler()
}
}
final class DownloadDelegate: NSObject, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
#if DEBUG
print("finished")
#endif
}
}
|
JavaScript
|
UTF-8
| 549 | 2.890625 | 3 |
[] |
no_license
|
const Post = require("./post");
class Poll extends Post {
constructor({ options, title, author, text }) {
super({ title, author, text });
this.options = options;
this.votes = { A: 0, B: 0, C: 0, D: 0 };
}
vote(optionLetter) {
this.votes[optionLetter]++;
}
}
class Options {
// Users can add at least 2 and at most 4 options.
constructor(A, B, C = null, D = null) {
this.A = A;
this.B = B;
this.C = C;
this.D = D;
}
}
module.exports = { Poll, Options };
|
Ruby
|
UTF-8
| 725 | 3.5 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
op1 =
[
" _ ∩ おっ\n",
" ( ゜∀゜)彡 \n",
" ( | \n",
" | | \n",
" し ⌒ J \n"
]
op2 =
[
" _ \n",
" ( ゜∀゜) ぱい \n",
" ( ⊂彡 \n",
" | | \n",
" し ⌒ J \n"
]
class Op
@array = []
def initialize(ar = [])
@array = ar
end
def say_op
system("clear")
@array.map! {|v| print v ; v = " " + v }
sleep 0.5
end
end
o1 = Op.new(op1)
o2 = Op.new(op2)
Signal.trap(:INT){
exit(0)
}
while (true)
o1.say_op
o2.say_op
end
|
Markdown
|
UTF-8
| 1,937 | 3.4375 | 3 |
[] |
no_license
|
##simple string
```ruby
puts "ln -s file1 file2"
```
#####string concatenation
```ruby
command = "ln"
options = "-s"
arguments = "file1 file2"
puts command + options + arguments
#=> command + options + arguments
```
####splate operator
```ruby
command = ["ln"]
options = ["-s"]
arguments = ["file1", "file2"]
command + options + arguments
#=> ["ln", "-s", "file1", "file2"]
puts *(command + options + arguments)
#=>n
#=>-s
#=>file1
#=>file2
```
* advanced usage:
```ruby
puts **{x:100,y:200}
#=>{:x=>100, :y=>200}
puts *{x:100,y:200}
#=> x
#=> 100
#=> y
#=> 200
puts *[x:100,y:200]
#=>{:x=>100, :y=>200}
puts *["ln", "-s", "file1", "file2"]
#=>n
#=>-s
#=>file1
#=>file2
```
```ruby
#usage:
def say(what, *people)
people.each{|person| puts "#{person}: #{what}"}
end
say "Hello!", "Alice", "Bob", "Carl"
# Alice: Hello!
# Bob: Hello!
# Carl: Hello!
people = ["Rudy", "Sarah", "Thomas"]
say "Howdy!", *people
# Rudy: Howdy!
# Sarah: Howdy!
# Thomas: Howdy!
```
* [more usage](http://blog.honeybadger.io/ruby-splat-array-manipulation-destructuring/)
//TODO: blog later
####convert words array into array
With %W, we precede an array with %W, and then surround it with any delimiters we choose. Inside, we put the elements of the array. Each whitespace-delimited token becomes a string array element
```ruby
%W[file1 file2]
#=> ["file1", "file2"]
```
* usage
```ruby
width = 960
height = 600
recording_options = %W[-f x11grab -s #{width}x#{height} -i 0:0+800,300 -r 30]
recording_options
# => ["-f", "x11grab", "-s", "960x600", "-i", "0:0+800,300", "-r", "30"]
misc_options = %W[-sameq -threads 6]
output_options = %W[screencast.mp4]
ffmpeg_flags =
recording_options +
misc_options +
output_options
#=> ["-f", "x11grab", "-s", "960x600", "-i", "0:0+800,300", "-r", "30", "-sameq", "-threads", "6", "screencast.mp4"]
system "ffmpeg", *ffmpeg_flags
```
|
Shell
|
UTF-8
| 1,364 | 3.9375 | 4 |
[] |
no_license
|
#!/bin/bash
#set -x
usage () {
echo "Usage: $0 SERVICE_NAME LOG_FILE"
}
if [ "$#" -ne 2 ];then
usage;
exit 1;
fi;
#if [ ! -f "$1" ];then
# echo "SERVICE_NAME $1 is not existent"
# usage;
# exit 1;
#fi;
if [ ! -f "$2" ];then
echo "LOG_FILE $2 is not existent"
usage;
exit 1;
fi;
SERVICE_DIR=$(dirname "$1")
SERVICE_NAME=$(basename "$1")
LOG_FILE=$2
LOG_FILE_BAK=${LOG_FILE}"."$(date +"%Y%m%d_%H%M%S")
IFS=$'\n'
RETVAL=0
items=""
pids=""
length=0
init () {
IFS_old=$IFS
IFS=$'\x0A'
items=(`ps -ef | grep "[0-9]\+:[0-9]\+:[0-9]\+ \S*$SERVICE_NAME\b"`)
IFS=$IFS_old
length=${#items[@]}
if [ "$length" -gt 0 ];then
for ((i=0; i<$length; i++))
do
pids[$i]=`echo ${items[$i]} | awk '{print $2}'`
echo ${items[$i]}
echo ${pids[$i]}
done
fi;
mv $LOG_FILE $LOG_FILE_BAK
RETVAL=$?
if [ $RETVAL -eq 0 ];then
echo "Mv $LOG_FILE $LOG_FILE_BAK Succeed";
else
echo "Mv $LOG_FILE $LOG_FILE_BAK Fail";
fi;
if [ "${#items}" -le 0 ];then
echo "$SERVICE_NAME doesn't run"
return 1;
fi;
for p in ${pids[@]}; do
kill -USR1 $p
RETVAL=$?
if [ $RETVAL -eq 0 ];then
echo "Truncate $LOG_FILE of Process $p Succeed";
else
echo "Truncate $LOG_FILE of Process $p Fail";
fi;
done
return $RETVAL;
}
init;
RETVAL=$?
exit $RETVAL;
|
Python
|
UTF-8
| 7,754 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import numpy as np
import os
import cv2
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from scipy.misc import imresize
def print_training_params_to_file(init_locals):
"""save param log file"""
del init_locals['self']
with open(os.path.join(init_locals['save_log_path'], 'Training_Parameters.txt'), 'w') as f:
f.write('Training Parameters:\n\n')
for key, value in init_locals.items():
f.write('* %s: %s\n' % (key, value))
def heat_maps_to_landmarks(maps, image_size=256, num_landmarks=68):
"""find landmarks from heatmaps (arg max on each map)"""
landmarks = np.zeros((num_landmarks,2)).astype('float32')
for m_ind in range(num_landmarks):
landmarks[m_ind, :] = np.unravel_index(maps[:, :, m_ind].argmax(), (image_size, image_size))
return landmarks
def heat_maps_to_landmarks_alloc_once(maps, landmarks, image_size=256, num_landmarks=68):
"""find landmarks from heatmaps (arg max on each map) with pre-allocation"""
for m_ind in range(num_landmarks):
landmarks[m_ind, :] = np.unravel_index(maps[:, :, m_ind].argmax(), (image_size, image_size))
def batch_heat_maps_to_landmarks_alloc_once(batch_maps, batch_landmarks, batch_size, image_size=256, num_landmarks=68):
"""find landmarks from heatmaps (arg max on each map) - for multiple images"""
for i in range(batch_size):
heat_maps_to_landmarks_alloc_once(
maps=batch_maps[i, :, :, :], landmarks=batch_landmarks[i, :, :], image_size=image_size,
num_landmarks=num_landmarks)
def normalize_map(map_in):
map_min = map_in.min()
return (map_in - map_min) / (map_in.max() - map_min)
def map_to_rgb(map_gray):
cmap = plt.get_cmap('jet')
rgba_map_image = cmap(map_gray)
map_rgb = np.delete(rgba_map_image, 3, 2) * 255
return map_rgb
def create_img_with_landmarks(image, landmarks, image_size=256, num_landmarks=68, scale=255, circle_size=2):
"""add landmarks to a face image"""
image = image.reshape(image_size, image_size, -1)
if scale is 0:
image = 127.5 * (image + 1)
elif scale is 1:
image *= 255
landmarks = landmarks.reshape(num_landmarks, 2)
landmarks = np.clip(landmarks, 0, image_size-1)
for (y, x) in landmarks.astype('int'):
cv2.circle(image, (x, y), circle_size, (255, 0, 0), -1)
return image
def heat_maps_to_image(maps, landmarks=None, image_size=256, num_landmarks=68):
"""create one image from multiple heatmaps"""
if landmarks is None:
landmarks = heat_maps_to_landmarks(maps, image_size=image_size, num_landmarks=num_landmarks)
x, y = np.mgrid[0:image_size, 0:image_size]
pixel_dist = np.sqrt(
np.square(np.expand_dims(x, 2) - landmarks[:, 0]) + np.square(np.expand_dims(y, 2) - landmarks[:, 1]))
nn_landmark = np.argmin(pixel_dist, 2)
map_image = maps[x, y, nn_landmark]
map_image = (map_image-map_image.min())/(map_image.max()-map_image.min()) # normalize for visualization
return map_image
def merge_images_landmarks_maps_gt(images, maps, maps_gt, landmarks=None, image_size=256, num_landmarks=68,
num_samples=9, scale=255, circle_size=2, fast=False):
"""create image for log - containing input face images, predicted heatmaps and GT heatmaps (if exists)"""
images = images[:num_samples]
if maps.shape[1] is not image_size:
images = zoom(images, (1, 0.25, 0.25, 1))
image_size /= 4
image_size=int(image_size)
if maps_gt is not None:
if maps_gt.shape[1] is not image_size:
maps_gt = zoom(maps_gt, (1, 0.25, 0.25, 1))
cmap = plt.get_cmap('jet')
row = int(np.sqrt(num_samples))
if maps_gt is None:
merged = np.zeros([row * image_size, row * image_size * 2, 3])
else:
merged = np.zeros([row * image_size, row * image_size * 3, 3])
for idx, img in enumerate(images):
i = idx // row
j = idx % row
if landmarks is None:
img_landmarks = heat_maps_to_landmarks(maps[idx, :, :, :], image_size=image_size,
num_landmarks=num_landmarks)
else:
img_landmarks = landmarks[idx]
if fast:
map_image = np.amax(maps[idx, :, :, :], 2)
map_image = (map_image - map_image.min()) / (map_image.max() - map_image.min())
else:
map_image = heat_maps_to_image(maps[idx, :, :, :], img_landmarks, image_size=image_size,
num_landmarks=num_landmarks)
rgba_map_image = cmap(map_image)
map_image = np.delete(rgba_map_image, 3, 2) * 255
img = create_img_with_landmarks(img, img_landmarks, image_size, num_landmarks, scale=scale,
circle_size=circle_size)
if maps_gt is not None:
if fast:
map_gt_image = np.amax(maps_gt[idx, :, :, :], 2)
map_gt_image = (map_gt_image - map_gt_image.min()) / (map_gt_image.max() - map_gt_image.min())
else:
map_gt_image = heat_maps_to_image(maps_gt[idx, :, :, :], image_size=image_size,
num_landmarks=num_landmarks)
rgba_map_gt_image = cmap(map_gt_image)
map_gt_image = np.delete(rgba_map_gt_image, 3, 2) * 255
merged[i * image_size:(i + 1) * image_size, (j * 3) * image_size:(j * 3 + 1) * image_size, :] = img
merged[i * image_size:(i + 1) * image_size, (j * 3 + 1) * image_size:(j * 3 + 2) * image_size,
:] = map_image
merged[i * image_size:(i + 1) * image_size, (j * 3 + 2) * image_size:(j * 3 + 3) * image_size,
:] = map_gt_image
else:
merged[i * image_size:(i + 1) * image_size, (j * 2) * image_size:(j * 2 + 1) * image_size, :] = img
merged[i * image_size:(i + 1) * image_size, (j * 2 + 1) * image_size:(j * 2 + 2) * image_size,:] = map_image
return merged
def map_comapre_channels(images, maps1, maps2, image_size=64, num_landmarks=68, scale=255):
"""create image for log - present one face image, along with all its heatmaps (one for each landmark)"""
map1 = maps1[0]
if maps2 is not None:
map2 = maps2[0]
image = images[0]
if image.shape[0] is not image_size:
image = zoom(image, (0.25, 0.25, 1))
if scale is 1:
image *= 255
elif scale is 0:
image = 127.5 * (image + 1)
row = np.ceil(np.sqrt(num_landmarks)).astype(np.int64)
if maps2 is not None:
merged = np.zeros([row * image_size, row * image_size * 2, 3])
else:
merged = np.zeros([row * image_size, row * image_size, 3])
for idx in range(num_landmarks):
i = idx // row
j = idx % row
channel_map = map_to_rgb(normalize_map(map1[:, :, idx]))
if maps2 is not None:
channel_map2 = map_to_rgb(normalize_map(map2[:, :, idx]))
merged[i * image_size:(i + 1) * image_size, (j * 2) * image_size:(j * 2 + 1) * image_size, :] =\
channel_map
merged[i * image_size:(i + 1) * image_size, (j * 2 + 1) * image_size:(j * 2 + 2) * image_size, :] =\
channel_map2
else:
merged[i * image_size:(i + 1) * image_size, j * image_size:(j + 1) * image_size, :] = channel_map
i = (idx + 1) // row
j = (idx + 1) % row
if maps2 is not None:
merged[i * image_size:(i + 1) * image_size, (j * 2) * image_size:(j * 2 + 1) * image_size, :] = image
else:
merged[i * image_size:(i + 1) * image_size, j * image_size:(j + 1) * image_size, :] = image
return merged
|
Java
|
UTF-8
| 746 | 2.875 | 3 |
[] |
no_license
|
package com.song.newsreader.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by Administrator on 2016/2/27.
*/
public class SortHashMap {
public static void main(String[] args){
sortMap();
}
public static void sortMap(){
ArrayList<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(4);
list.add(2);
list.add(5);
System.out.println(list);
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer lhs, Integer rhs) {
return rhs - lhs;
}
});
System.out.println(list);
}
}
|
Java
|
UTF-8
| 1,668 | 2.09375 | 2 |
[] |
no_license
|
package com.zhp.bos.service.impl.auth;
import java.util.List;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhp.bos.dao.auth.MenuDao;
import com.zhp.bos.entity.auth.Menu;
import com.zhp.bos.service.intf.auth.IMenuService;
@Service
@Transactional
public class MenuServiceImpl implements IMenuService {
@Autowired
private MenuDao menuDao;
@Override
public List<Menu> ajaxListHasSonMenus() {
return menuDao.ajaxListHasSonMenus();
}
@Override
public void save(Menu model) {
menuDao.save(model);
}
@Override
public Page<Menu> pageQuery(PageRequest pageRequest) {
Page<Menu> pages = menuDao.findAll(pageRequest);
List<Menu> content = pages.getContent();
if (content != null && content.size() != 0) {
for (Menu menu : content) {
// Hibernate.initialize(menu.getMenu());
init(menu);
}
}
return pages;
}
@Override
public List<Menu> ajaxList() {
return menuDao.findAll();
}
public void init(Menu menu) {
if (menu != null) {
Hibernate.initialize(menu.getMenu());
init(menu.getMenu());
}
}
@Override
public List<Menu> findMenuByRoleId(String roleId) {
return menuDao.findMenuByRoleId(roleId);
}
@Override
public List<Menu> menuList(Integer userId) {
List<Menu> menuList = menuDao.menuList(userId);
if (menuList != null && menuList.size() != 0) {
for (Menu menu : menuList) {
init(menu);
}
}
return menuList;
}
}
|
C#
|
UTF-8
| 343 | 2.53125 | 3 |
[] |
no_license
|
using System;
namespace CodeSharper.Core.Common.NameMatchers
{
public class EqualityNameMatcher : INameMatcher
{
/// <summary>
/// Matches the specified collection.
/// </summary>
public Boolean Match(String expected, String actual)
{
return expected == actual;
}
}
}
|
Markdown
|
UTF-8
| 25,558 | 2.921875 | 3 |
[] |
no_license
|
# Create Basic VUE-APP
Instruksi Project Dari nol
# Vue CLI
[========]
- Pertama kita install vue CLI
````bash
# install with npm
npm i -g @vue/cli @vue/cli-service-global
# install with yarn
yarn global add @vue/cli @vue/cli-service-global
````
Sekarang Vue CLI telah terinsal secara global, kita bisa menggunakan command vue dimana saja.
- Kita akan menggunakan `vue create` untuk memulai project baru.
```bash
vue create vue-app
```
Akan muncul tampilan seperti ini, terdapat beberapa opsi untuk hal ini kita pilih `Manual select features`
```bash
Vue CLI v4.5.11
? Please pick a preset:
Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
> Manually select features
```
Untuk sementara kita hanya centang `Choose Vue version`
```
Vue CLI v4.5.11
? Please pick a preset: Manually select features
? Check the features needed for your project:
>(*) Choose Vue version
( ) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
( ) Router
( ) Vuex
( ) CSS Pre-processors
( ) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
```
Disini kita akan menggunakan yang versi 2.x
```
Vue CLI v4.5.11
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
> 2.x
3.x (Preview)
```
Silahkan anda pilih letak config untuk Babel, ESlint, dll berada. Kalau saya lebih suka saya taruh di package.json
```
? Where do you prefer placing config for Babel, ESLint, etc.?
In dedicated config files
> In package.json
```
Setelah semua instalasi selesai, kita bisa berpindah ke direktori project yang sudah dibuat dan run project dengan perintah seperti dibawah ini:
```
cd vue-app
npm run serve
# or
yarn serve
```
Pada titik ini kita sudah selesai mempersiapkan semua yang dibutuhkan untuk membangun Vue aplikasi. jangan lupa tambahkan plugin Vetur untuk formatter dan highlight pada text editor anda dan juga install ekstensi Vue Devtools untuk memberi informasi tentang *components* - *state, method, data,* dll ketika anda *running* vue pada browser anda.
# Getting Started
Selamat kita sudah me-setting Vue boilerplate app. di projek ini terdapat `public` folder yang didalamnya terdapat `index.html`, dan `src` folder dengan `main.js` sebagai titik awal js. Disini juga kita diperkenalkan pula dengan `.vue` file, dengan komponen `HelloWorld.vue` dan `App.vue`.
## Titik Awal
Pada `main.js` disini membawa Vue dan *redering* App ke app div pada `index.html`. File ini tidak butuh diubah.
```javascript
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: function (h) { return h(App) },
}).$mount('#app')
```
## Anatomi Vue
Ketika kita akan membuat suatu file `.vue`, selalu terdapat 3 tag yang pasti yaitu:
- `<template>`
- `<script>`
- `<style>`
```vue
<template></template>
<script>
export default {
name: 'nama-komponen',
}
</script>
<style scoped></style>
```
Setiap data logic pada setiap komponen akan berada pada tag `<script>`, seperti kita tahu `<style>` hanya digunakan untuk CSS, kita juga bisa gunakan `scoped` untuk mengaplikasikan style tersebut tidak secara global.
Karena tujuan dari pembelajaran kali ini adalah tentang fungsionalitas, bukan soal *styling*, saya akan menambahkan secara cepat `Skeleton` framework CSS pada `public/index.html` file untuk lebih memudahkan dalam *styling*.
```vue
<!DOCTYPE html>
<html lang="">
<head>
<!-- .... isi header -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
</head>
<body>
<!-- .... isi body -->
</body>
</html>
```
Putar musik lo-fi 🎧 dan mulai memasak 👨🍳.
# Creating a Component
Buat file dengan nama `MahasiswaTable.vue` du `src/components`. Kita akan membuat tabel dengan beberapa data statik seperti dibawah ini.
```vue
<template>
<div id="mhs-table">
<table class="u-full-width">
<thead>
<tr>
<th>Nama</th>
<th>No Induk Mahasiswa</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jonatan Teofilus</td>
<td>6876879890</td>
<td>jonatan.teofilus@gmail.com</td>
</tr>
<tr>
<td>Dwayne Johnson</td>
<td>0978769767</td>
<td>dwayne150@gmail.com</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: 'mahasiswa-table',
}
</script>
<style scoped>
</style>
```
Di Vue, import nama file akan menjadi PascalCase, seperti `MahasiswaTable` tapi ketika komponen tersebut digunakan pada `<template>`, akan berubah menjadi kebab-case, `<mahasiswa-table>`. Hal ini supaya kita bisa mengenali konvensi untuk masing-masing javascript dan HTML.
Kita export `mahasiswaTable` dan import ke `App.vue`. Pada waktu me-import, kita bisa menggunakan `@` sebagai referensi `src` folder. App.vue mengenali dan komponen tersebut bisa digunakan melalui `components` property. Jadi semua komponen yang dibutuhkan dalam satu `.vue` harus ditambahkan disana.
```vue
<template>
<div id="app">
<div class="container">
<h1>Mahasiswa</h1>
<mahasiswa-table/>
</div>
</div>
</template>
<script>
import MahasiswaTable from '@/components/MahasiswaTable.vue'
export default {
name: 'App',
components: {
MahasiswaTable
}
}
</script>
<style scoped>
</style>
```
Akan tampil seperti ini:
####gambar review
Supaya data pada tabel menjadi dinamis, kita akan ubah menjadi array object. Jadi mari kita tambah method `data()` dan return array mahasiswa. kita juga menambahkan ID untuk setiap item agar membuatnya untuk dan teridentifikasi.
Sekarang kita memiliki data tersebut pada `App.vue`, tapi kita harus bawa data tersebut ke `MahasiswaTable`. Kita bisa melakukan hal itu dengan *passing* date sebagai properti. Sebuah atribut dengan *colon* `:` untuk mengirim data pada. `:` juga merupakan *shorthand* dari `v-bind`. Dalam kasus ini kita akan membawa array datamahasiswa.
```vue
<mahasiswa-table :datamahasiswa="datamahasiswa"/>
<!-- atau -->
<mahasiswa-table v-bind:datamahasiswa="datamahasiswa"/>
```
Saat ini pada sisi `MahasiswaTable`, kita ingin mengambil data tersebut, jadi kita harus membuat `props` attribute dengan nama `datamahasiswa`.
## Loops
Sekarang kita telah mendapatkan data tersebut, kita butuh mengulang data dan menampilkanya ke DOM. Kita bisa lakukan ini dengan menggunakan `v-for` attribute. Sekarang kita telah mendapatkan `datamahasiswa` di `MahasiswaTable` kita tampilkan per baris.
```vue
<template>
<div id="mhs-table">
<table class="u-full-width">
<thead>
<tr>
<th>Nama</th>
<th>No Induk Mahasiswa</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr v-for="mahasiswa in datamahasiswa" :key="mahasiswa.id">
<td>{{ mahasiswa.nama }}</td>
<td>{{ mahasiswa.npm }}</td>
<td>{{ mahasiswa.email }}</td>
</tr>
</tbody>
</table>
</div>
</template>
```
# Form
Kita sekarang membuat form tambah mahasiswa.
Buat `MahasiswaForm.vue` dan atur field nama, npm, email dan juga `button` submit. Juga buat data object mahasiswa dengan nama, npm dan juga email.
```vue
<template>
<form>
<div class="row">
<label for="inputNama">Nama Mahasiswa</label>
<input class="u-full-width" type="text" placeholder="Nama Mahasisiwa" id="inputNama">
<label for="inputNpm">Nomer Induk Mahasiswa</label>
<input class="u-full-width" type="text" placeholder="Nomor Induk Mahasiswa" id="inputNpm">
<label for="inputNama">Email Mahasiswa</label>
<input class="u-full-width" type="email" placeholder="Email Mahasisiwa" id="inputEmail">
<button class="button-primary">Add Mahasiswa</button>
</div>
</form>
</template>
<script>
export default {
data() {
return {
mahasiswa:{
nama:'',
npm:'',
email:''
}
}
},
}
</script>
<style scoped>
form {
margin-bottom: 2rem;
}
</style>
```
Kita juga menambahkan beberapa baris code pada `App.vue`
```vue
<template>
<div id="app">
<div class="container">
<h1>Mahasiswa</h1>
<mahasiswa-form/>
<mahasiswa-table :datamahasiswa="datamahasiswa"/>
</div>
</div>
</template>
<script>
import MahasiswaTable from '@/components/MahasiswaTable.vue'
import MahasiswaForm from '@/components/mahasiswaForm.vue'
export default {
name: 'App',
components: {
MahasiswaTable,
MahasiswaForm
},
data() {
//...
},
}
</script>
<style scoped>
</style>
```
Sekarang gimana caranya mendapatkan data dan mengirimkannya ke Vue component state. Untuk itu kita gunakan `v-model`. `v-model` suatu *sytactic sugar* built-in Vue untuk mengubah input value ketika ada event `onchange`.
```vue
<template>
<form>
<div class="row">
<label for="inputNama">Nama Mahasiswa</label>
<input v-model="mahasiswa.nama" class="u-full-width" type="text" placeholder="Nama Mahasisiwa" id="inputNama">
<label for="inputNpm">Nomer Induk Mahasiswa</label>
<input v-model="mahasiswa.npm" class="u-full-width" type="text" placeholder="Nomor Induk Mahasiswa" id="inputNpm">
<label for="inputNama">Email Mahasiswa</label>
<input v-model="mahasiswa.email" class="u-full-width" type="email" placeholder="Email Mahasisiwa" id="inputEmail">
<button class="button-primary">Add Mahasiswa</button>
</div>
</form>
</template>
```
Sekarang kita bisa tambahkan ini, kita bisa lihati di Vue DevTools ketika *state* pada komponen berubah.
Kita tinggal submit lalu update ke parent `(App)` state dengan object mahasiswa baru.
# Event listeners
Untuk submit form kita tambahkan atribut `v-on:submit` atau kita bisa gunakan `@submit` untuk shorthand pada tag `<form>`. ini sama dengan event `@click/v-on:click`. Event submit juga memiliki `prevent` yang difungsikan untuk mematikan method GET/POST yang secara default sudah disediakan oleh form.
Mari kita tambah script ini ke form, dan juga buat method submitMahasiswa.
```vue
<form @submit.prevent="submitMahasiswa"></form>
```
# Methods
Saat ini kita membuat method pertama pada component. Dibawah `data()`, kita bisa buat object `methods`, dimana akan menampung semua custom method yang kita buat. mari kita buat `submitMahasiswa` disana.
```vue
<script>
export default {
data() {
return {
mahasiswa:{
nama:'',
npm:'',
email:''
}
}
},
methods: {
submitMahasiswa() {
console.log("test submited")
}
},
}
</script>
```
# Emitting events
Sekarang kita coba submit form, kita akan melihat message log di console, lalubagaimana caranya kita mengirimkan data ke parent `App` sekarang? tentunya kita bisa melakukan hal tersebut dengan `$emit`
Emit mengirim nama event dan data ke parent component, seperti ini:
```javascript
this.$emit('nama-emit-event', dataPass)
```
pada case kita, kita akan buat event dengan nama `add:mahasiswa` dan membawa data `this.mahasiswa`
```javascript
submitMahasiswa() {
this.$emit("add:mahasiswa",this.mahasiswa)
}
```
Ketika sudah ditambahakan, klik untuk add form lalu ke Vue DevTools. kita akan lihat notifikasi untuk event baru, dan akan memberi tahu kuta tentang nama, source, dan payload, dimana pada kasus ini object terbuat.
## Menerima Event dari child component
hal pertama yang harus dilakukan adalah membuat supaya `mahasiswa-form` untuk me-handle event yang di-emmit untuk memanggil ke method baru. contoh seperti ini:
```vue
<component @name-of-emitted-event="methodToCallOnceEmitted"></component>
```
Mari kita tambah ke App.vue.
```vue
<mahasiswa-form @add:mahasiswa="addMahasiswa"/>
```
Kita hanya perlu membuat method `addMahasiswa` di `App.vue`, dimana memodifikasi array `datamahasiswa` dengan menambah item baru kedalamnya.
kode dibawah adalah untuk mendapatkan `id` mahasiswa baru berdasarkan nomer item array. Pada database sebenarnya, `id` sudah tergenerate secara unik atau *auto increment*.
```javascript
addMahasiswa(mahasiswa) {
const lastId = this.datamahasiswa.length > 0? this.datamahasiswa[this.datamahasiswa.length - 1].id: 0 ;
const id = lastId + 1;
// Using spread untuk will clone your object.
const newMahasiswa = { ...mahasiswa, id };
// spread untuk mengulang
this.datamahasiswa = [...this.datamahasiswa, newMahasiswa];
}
```
sekarang dengan ini, kita sudah bisa add mahasiswa baru. Nggak sampai disini karena ini hanya front end dan tidak terkoneksi dengan database.
# Form Validation
Kebutuhan validasi adalah sebagai berikut:
- Menampilkan success message jika semua terkirim.
- Menampilkan error message jika terdapat input yang salah atau kosong.
- Highlight pada input yang tidak valid.
- Bersihkan semua input setelah form telah tersubmit dengan baik.
- Fokus pada item pertama jika sukses.
## Computed properties
Di Vue, kita bisa menggunakan **computed properties**, dimana suatu fungsi secara otomatis melakukan penghitungan/menjalankan ketika sesuatu berubah. Disini saya coba untuk membuat *basic check* validasi untuk memastikan field tidak kosong untuk semua input field.
```javascript
computed: {
invalidNama() {
return this.mahasiswa.nama === ''
},
invalidNpm() {
return this.mahasiswa.npm === ''
},
invalidEmail() {
return this.mahasiswa.email === ''
},
},
```
Kita juga membutuhkan `submitting` *state* untuk mengecek apakah form sudah tersubmit, `error` *state* jika sesuatu salah dan `success` *state* jika form input benar.
```javascript
data() {
return {
submitting: false,
error: false,
success: false,
mahasiswa:{
nama:'',
npm:'',
email:''
}
}
},
```
Fungsi submit pertama akan mereset ulang state baik itu succes atau error yang telah terseting, mulai submit, setelah itu cek semua method `computed` dan jika terdapat return *true*, maka error state akan diset. Jika tida kita bisa submit, dan mengatur state sukses dan semua state kembali seperti semula.
```javascript
methods: {
submitMahasiswa() {
// set state menjadi tersubmit
this.submitting = true
// bersihkan terlebih dahulu state error & success
this.clearStatus()
// panggil setiap computed fungsi untuk validasi
if (this.invalidNama || this.invalidNpm || this.invalidEmail) {
this.error = true
return
}
// emit ke parent
this.$emit("add:mahasiswa",this.mahasiswa)
// kosongkan kembali obj mahasiswa
this.clearMahasiswa()
// set sukses
this.error = false
this.success = true
// set status submit jadi false
this.submitting = false
},
clearStatus() {
this.success = false
this.error = false
},
clearMahasiswa(){
this.mahasiswa = {
nama:'',
npm:'',
email:''
}
}
},
```
Saya juga tambahkan bebarapa baris CSS untuk kondisi success state dan error state.
```css
<style scoped>
form {
margin-bottom: 2rem;
}
[class*='-message'] {
font-weight: 500;
}
.error-message {
color: #d33c40;
}
.success-message {
color: #32a95d;
}
input.has-error {
border: 1.5px solid #d33c40;;
}
</style>
```
Akhirnya kita telah mengatur form. Jika form tersubmit dan satu dari antara computed preoperty tidak valid, kita akan set class `has-error` pada input. Gunakan `:class=` untuk memastikan bahwa class akan diterapkan melalui Javascript. Kita juga pastikan pesan success dan error tertampil di atas form.
```vue
<form @submit.prevent="submitMahasiswa">
<div class="row">
<label for="inputNama">Nama Mahasiswa</label>
<input v-model="mahasiswa.nama" class="u-full-width" :class="{ 'has-error': submitting && invalidNama }" type="text" placeholder="Nama Mahasisiwa" id="inputNama">
<label for="inputNpm">Nomer Induk Mahasiswa</label>
<input v-model="mahasiswa.npm" class="u-full-width" :class="{ 'has-error': submitting && invalidNpm }" type="text" placeholder="Nomor Induk Mahasiswa" id="inputNpm">
<label for="inputNama">Email Mahasiswa</label>
<input v-model="mahasiswa.email" class="u-full-width" :class="{ 'has-error': submitting && invalidEmail }" type="email" placeholder="Email Mahasisiwa" id="inputEmail">
<p v-if="error && submitting" class="error-message">
❗Isi file yang dibutuhkan
</p>
<p v-if="success" class="success-message">✅ Sukses menambahkan mahasiswa.</p>
<button class="button-primary">Add Mahasiswa</button>
</div>
</form>
```
# Delete
Form sudah selesai, sekarang tinggal update dan delete. Hal pertama yang akan kita kerjakan yaitu menambahkan baris `aksi`, dan button untuk edit dan delete.
```vue
<template>
<div id="mhs-table">
<table class="u-full-width">
<thead>
<tr>
<th>Nama</th>
<th>No Induk Mahasiswa</th>
<th>Email</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<tr v-for="mahasiswa in datamahasiswa" :key="mahasiswa.id">
<td>{{ mahasiswa.nama }}</td>
<td>{{ mahasiswa.npm }}</td>
<td>{{ mahasiswa.email }}</td>
<td>
<button>edit</button>
<button>delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props:["datamahasiswa"],
}
</script>
<style scoped>
button {
margin:2px
}
</style>
```
kita akan emit dan membawa id untuk memanggil fungsi `deleteMahasiswa` yang nanti akan kita buat pada parent.
```vue
<button @click="$emit('delete:mahasiswa', mahasiswa.id)">Delete</button>
```
kembali ke `App.vue`, kita telah menambah event aksi on delete-mahasiswa pada `mahasiswa-table`, tambahakan fungsi untuk menghandler event tersebut.
```vue
<mahasiswa-table @delete:mahasiswa="deleteMahasiswa" :datamahasiswa="datamahasiswa"/>
```
dan kita lakukan filter array dengan menambahkan method `deleteMahasiswa` dan dengan logika seperti dibawah.
```javascript
deleteMahasiswa(id){
this.datamahasiswa = this.datamahasiswa.filter(mahasiswa => mahasiswa.id !== id)
}
```
Sekarang kita bisa hapus item. mari kita buat pesan untuk memberi info data mahasiswa kosong jika array `datamahasiswa` kosong.
```vue
<div id="mhs-table">
<p v-if="datamahasiswa < 1"> data mahasiswa kosong</p>
<table v-else class="u-full-width">
...
</table>
</div>
```
Kita telah selesai menghapus item mahasiswa.
# Edit item
Edit data seding lebih *tricky* dibandingkan dengan delete. Hal pertama yang dilakukan yaitu kita tambah event `edit:mahasiswa` dan kita juga buatkan method untuk menghadle event tersebut dengan nama `editMahasiswa` sama seperti delete.
```vue
<mahasiswa-table
@delete:mahasiswa="deleteMahasiswa"
@edit:mahasiswa="editMahasiswa"
:datamahasiswa="datamahasiswa"/>
```
dan pada method `editMahasiswa`, kita akan ambil data dari array berdasarkan id lalu kita update.
```javascript
editMahasiswa(id, updatemahasiswa){
this.datamahasiswa = this.datamahasiswa.map(mahasiswa => mahasiswa.id == id ? updatemahasiswa : mahasiswa);
}
```
Cukup mudah.
Sekarang kembali ke `MahasiswaTable.vue`, kita ingin buat "edit mode" enable ketika button terklik.
```vue
<button @click="editMode(mahasiswa.id)">Edit</button>
```
kita akan membuat editing state dan akan get dan set id pada row yang sedang pada posisi edited ketika `editMode` enabled. `MahasiswaTable` memiliki local method `editMahasiswa` yang memiliki fungsi untuk emit `edit:mahasiswa` di App jika semua value field tidak kosong, proses kedua yaitu kita reset edit state.
```javascript
data() {
return {
editing: null,
}
},
methods: {
editMode(id) {
this.editing = id
},
editMahasiswa(mahasiswa) {
if (mahasiswa.nama === '' || mahasiswa.email === '' || mahasiswa.npm === '') return
this.$emit('edit:mahasiswa', mahasiswa.id, mahasiswa)
this.editing = null
}
}
```
untuk membuat editable, kita akan cek data `editing === mahasiswa.id` kalau sama pada baris tersebut, maka input akan ditampilkan. kita juga tambahkan button `cancel` untuk mebatalkan edit dan set `editing` menjadi null.
```vue
<tr v-for="mahasiswa in datamahasiswa" :key="mahasiswa.id">
<td v-if="editing === mahasiswa.id">
<input type="text" v-model="mahasiswa.nama" placeholder="Nama Mahasiswa"/>
</td>
<td v-else>{{ mahasiswa.nama }}</td>
<td v-if="editing === mahasiswa.id">
<input type="text" v-model="mahasiswa.npm" placeholder="Nomor Induk Mahasiswa"/>
</td>
<td v-else>{{ mahasiswa.npm }}</td>
<td v-if="editing === mahasiswa.id">
<input type="email" v-model="mahasiswa.email" placeholder="Email Mahasiswa"/>
</td>
<td v-else>{{ mahasiswa.email }}</td>
<td v-if="editing === mahasiswa.id">
<button class="button-primary" @click="editMahasiswa(mahasiswa)">Save</button>
<button @click="editing = null">Cancel</button>
</td>
<td v-else>
<button @click="editMode(mahasiswa.id)">Edit</button>
<button @click="$emit('delete:mahasiswa',mahasiswa.id)">delete</button>
</td>
</tr>
```
edit telah berhasil, tetapi masih ada masalah yaitu ketika `cancel` data tidak kembali seperti sebelum teredit. Maka dari itu kita butuh caching data mahasiswa sebelu diedit.
```javascript
editMode(mahasiswa) {
this.cachemahasiswa = {...mahasiswa}
this.editing = mahasiswa.id
},
cancelEdit(mahasiswa){
Object.assign(mahasiswa, this.cachemahasiswa)
this.editing = null
}
```
saat ini kita telah selesai CRUD data mock, namun ketika dir real produksi app akan membuat API call ke back end database. kita akan coba buat.
# Asynchronous REST API
kita akan mengubah data mock dengan real API dan kita akan buat POST, PUT, dan DELETE request. Disini sudah tersedia APInya kita tinggal panggil.
Method asynchronous dengan `async/await` dan menggunakan `try/catch` blok seperti contoh dibawah ini.
sebenarnya untuk `Fetch API` sendiri sudah banyak opsi library node yang terkenal dan bisa digunakan seperti `Axios` dll. Namun disini saya hanya menggunakan `Fetch`, fetch merupakan bawaan dari javascript untuk async fetch API dan alasan lain yaitu karena tidak perlu menginstall depedensi dan tujuan sampel.
```javascript
async asynchronousMethod() {
try {
const response = await fetch('url')
const data = await response.json()
// do something with `data`
} catch (error) {
// do something with `error`
}
}
```
## Lifecycle methods
Ketika GET request, kita akan menghapus semua data array mahasiswa yang kita punya, lalu mengganti data tersebut dengan get dari API. Kita panggil GET pada saat vue `mounted` lifecycle method.
kenapa pada saat `mounted`?. Mounted dijalankan ketika component semua sudah terisi ke DOM. ini adalah cara yang biasa dilakukan ketika ingin menampilkan data dari API.
```javascript
export default {
name: 'App',
components: {
MahasiswaTable,
MahasiswaForm
},
data() {
...
},
mounted() {
this.getMahasiswa()
},
methods: {
...
}
}
```
### GET
Mengambil data.
```javascript
async getMahasiswa(){
try {
const response = await fetch('http://localhost:8008/api/mahasiswa/')
const data = await response.json()
console.log(data)
this.datamahasiswa = data.data
} catch (error) {
console.error(error)
}
}
```
### POST
```javascript
async addMahasiswa(mahasiswa) {
try {
const response = await fetch('http://localhost:8008/api/mahasiswa/', {
method: 'POST',
body: JSON.stringify(mahasiswa),
headers: { 'Content-type': 'application/json; charset=UTF-8' },
})
const dataresponse = await response.json()
this.datamahasiswa = [...this.datamahasiswa, dataresponse.data]
} catch (error) {
console.error(error)
}
}
```
### PUT
```javascript
async editMahasiswa(id, updatedMahasiswa) {
try {
const response = await fetch(
`http://localhost:8008/api/mahasiswa/${id}`,
{
method: 'PUT',
body: JSON.stringify(updatedMahasiswa),
headers: { 'Content-type': 'application/json; charset=UTF-8' },
}
);
const dataresponse = await response.json();
this.datamahasiswa = this.datamahasiswa.map((mahasiswa) =>
mahasiswa.id === id ? dataresponse.data : mahasiswa
);
} catch (error) {
console.error(error);
}
}
```
### DELETE
```javascript
async deleteEmployee(id) {
try {
await fetch(`http://localhost:8008/api/mahasiswa/${id}`, {
method: "DELETE"
});
this.datamahasiswa = this.datamahasiswa.filter(mahasiswa => mahasiswa.id !== id);
} catch (error) {
console.error(error);
}
}
```
Dan violaa ✨✨ aplikasi selesai.
|
Markdown
|
UTF-8
| 3,416 | 2.609375 | 3 |
[
"CC-BY-4.0",
"MIT",
"CC-BY-3.0"
] |
permissive
|
<properties
pageTitle="Skalowanie usługi sieci web | Microsoft Azure"
description="Dowiedz się, jak skalowanie usługi sieci web przez zwiększanie współbieżności oraz dodawania nowych punktów końcowych."
services="machine-learning"
documentationCenter=""
authors="neerajkh"
manager="srikants"
editor="cgronlun"
keywords="Azure maszynowego uczenia, usług sieci web, operationalization skalowania, punktu końcowego współbieżności"
/>
<tags
ms.service="machine-learning"
ms.devlang="NA"
ms.workload="data-services"
ms.tgt_pltfrm="na"
ms.topic="article"
ms.date="10/05/2016"
ms.author="neerajkh"/>
# <a name="scaling-a-web-service"></a>Skalowanie usługi sieci Web
>[AZURE.NOTE] W tym temacie opisano techniki dotyczące usługi sieci Web uczenia maszynowego klasyczny.
Domyślnie każdy opublikowanych usługi sieci Web jest skonfigurowana do obsługi 20 równoczesne żądania i można możliwie jak 200 równoczesne żądania. Gdy portalu klasyczny Azure umożliwia ta wartość, Azure maszynowego uczenia automatycznie optymalizuje to ustawienie, aby zapewnić najlepszą wydajność usługi sieci web i portalu wartość jest ignorowana.
Jeśli plan nawiązać połączenie z interfejsu API z obciążeniem wyższymi niż określona wartość maksymalna liczba wywołania 200 będzie obsługiwać, należy utworzyć wiele punktów końcowych na tej samej usługi sieci Web. Następnie można losowo rozłożenie usługi obciążenia w każdy z nich.
## <a name="add-new-endpoints-for-same-web-service"></a>Dodaj nowe punkty końcowe w tym samym usługi sieci web
Skalowanie usługi sieci Web jest typowych zadań. Przyczyny przeskalować mają obsługuje więcej niż 200 równoczesne żądania, zwiększyć dostępność za pośrednictwem wiele punktów końcowych lub podać osobnych punkty końcowe usługi sieci web. Skala można zwiększyć, dodając dodatkowe punkty końcowe usługi sieci Web za pomocą [portal Azure klasyczny](https://manage.windowsazure.com/) lub z portalu [Usługi sieci Web uczenia Azure](https://services.azureml.net/) .
Aby uzyskać więcej informacji na temat dodawania nowych punktów końcowych zobacz [Tworzenie punktów końcowych](machine-learning-create-endpoint.md).
Należy pamiętać, używanym zestawienia współbieżności duży może być niekorzystne, jeśli nie dzwonisz interfejsu API o wysokim częstotliwości. Jeśli umieszczenie małą obciążenia na interfejs API skonfigurowane dla wysokie obciążenie może zostać wyświetlony z sporadycznie limity czasu i/lub tych najwyższych wartościach opóźnienia.
Synchroniczne interfejsy API zwykle są używane w sytuacjach, gdzie potrzeby krótki czas oczekiwania. W tym polu Opóźnienie oznacza czasu potrzebnego na interfejsu API do wykonania jedno żądanie, a nie stanowią opóźnień w sieci. Załóżmy, że masz interfejsem API z opóźnienie 50 ms. Aby w pełni wykorzystać pojemność ograniczenia poziomu Wysoki i Max wywołania = 20; trzeba zadzwonić ten interfejs API 20 * 1000 / 50 = 400 times na sekundę. Rozszerzanie to dodatkowo, Max wywołania 200 umożliwia nawiązywanie połączenia razy 4000 interfejsu API na sekundę, przy założeniu opóźnienie 50 ms.
<!--Image references-->
[1]: ./media/machine-learning-scaling-webservice/machlearn-1.png
[2]: ./media/machine-learning-scaling-webservice/machlearn-2.png
|
Java
|
UTF-8
| 1,035 | 2.15625 | 2 |
[] |
no_license
|
package com.phonebookbackend.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import javax.validation.constraints.Email;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Document("users")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
@Id
private String id;
@Field("username")
private String username;
@Field("password")
private String password;
@Field("email")
@Email
private String email;
@DBRef
private Set<Role> roles = new HashSet<>();
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
}
|
Markdown
|
UTF-8
| 4,624 | 2.828125 | 3 |
[] |
no_license
|
初识机器学习
1. 机器学习的概述
2. 机器学习的现状分析
3. 机器学习的核心思想
4. 机器学习的框架与选型..
一. 机器学习的概述
1) 概述:
机器学习是用数据或以往的经验, 并以此来优化程序的性能标准. (用现有已知的数据, 预测未来可能发展的情况)
Machine learning is programming computers to optimize a performance critertion using example data or past experience.
2) 机器学习的发展史:
1950s-1960s: 研究火热(1957年感知机算法)
1960s-1970s: 逐渐冷清
1970s-1980s: 复兴
1986-新时期(Hinton 提出 BP 神经网络)
1990s 神经网络逐渐冷清
2012 - 深度学习成为风口(AlexNet的影响)
3) 机器学习(ML)与人工智能(AI) 的关系
详见图: 机器学习与人工智能关系图.jpg
4) 机器学习的一般功能
a. 分类: 识别图像中人脸的性别是男是女
b. 聚类: 发掘喜欢类型的女朋友
c. 回归: 预测一下股市价格
5) 分类与回归的区别
1. 分类的类别是离散的, 回归的输出是连续的
例如: 性别分类的结果只能是{男, 女}集合中的一个; 而回归输出的值可能是一定范围的任意数字, 例如股票的价格。
6) 机器学习的应用
a. 自然语言处理, 数据挖掘, 生物信息识别(如人脸识别), 计算机视觉等... ==> NLP
二. 机器学习的现状分析
a. 应用领域十分广泛: 如DNA测序, 证券分析
b. 国家战略: 多次出现在政府工作报告中
c. 人才缺乏: 新兴发展领域, 门槛相对较高, 人才缺口巨大
三. 机器学习的核心思想***
1) 机器学习的方法
a. 统计机器学习(课程的主要内容)
b. BP 神经网络
c. 深度学习
2) 机器学习的种类
a. 监督学习:
学习一个模型, 使模型能够对任意给定输入做出相应的预测; 学习的数据形式是(X, Y)组合.
b. 无监督学习(也有介于两者的半监督学习)
学习一个模型, 使用的数据是没有被标记过的, 自己默默地学习隐含特性, 寻找模型与规律. 输入数据形式只有X. 例如类聚.
c. 强化学习
在没有指示的情况下, 算法自己评估预测结果的好坏. 从而使得计算机在没有学习过的问题上, 依然具有很好的泛化能力.
3) 由此总结出机器学习的思想:
本质思想: 使用现有的数据, 训练出一个模型, 然后再用这样一个模型去拟合其他数据, 给未知的数据做出一个预测.
人类学习的过程--老师教数学题, 学生举一反三, 考试成绩是学习效果的校验
4) 更深入一点的数学原理:
a. 在数学上找到衡量预测结果与实际结果偏差之间的一个函数
b. 通过反复(迭代)的训练模型, 学习特征, 使偏差极小化
c. 衡量预测偏差的函数称为: 损失函数(loss function)
d. 机器学习是一个求解最优化问题的过程
5) 训练模型应避免的两种情况
a. 过拟合: 模型训练过渡, 假设过于严格
判别图片是否是一片树叶: 模型认为树叶一定包含锯齿
b. 欠拟合: 模型有待继续训练, 拟合能力不强
特征点不够全面, 只有部分特点被使用, 训练模型不能够被泛化 ==> 把癞蛤蟆当成了千里马
判别图片是否是一片树叶: 模型认为只要是绿色的就是树叶
四. 机器学习的框架与选型..
1) 机器学习常用编程语言
a. Python
b. C++
c. Scala
2) 机器学习常用框架
a. 统计学习: Spark(ML/MLlib) FlinkML scikit-learn Mahout
b. 深度学习: TF(TensorFlow), Caffe, Keras ==> (x OnSpark & SparkNet)
3) 使用Spark的好处
a. 技术栈统一: 便于整合Spark四个模块
b. 机器学习模型的训练是迭代过程, 基于内存的计算效率更高
c. 天然的分布式: 弥补单机算力不足, 具备弹性扩容能力
d. 原型即产品: Spark可直接试用在生产环境
e. 支持主流深度学习框架运行在Spark上
f. 自带矩阵计算和机器学习库, 算法全面
4) 机器学习项目选型要点
a. 充分考虑生产环境与业务场景
b. 尽量选择文档更详细, 资料更完备, 社区更活跃的开源项目
c. 考虑研发团队情况, 力求技术栈精简统一, 避免冗杂
------本章小结------
本章主要内容:
1. 机器学习的概括 2. 机器学习的现状分析
3. 机器学习的核心思想 4. 机器学习框架与选型
|
C++
|
UTF-8
| 3,397 | 3.3125 | 3 |
[] |
no_license
|
/**
* @file player.h
* header de clase Player
* */
#ifndef __PLAYER_H__
#define __PLAYER_H__
#include "lib/utilities.h"
#include "lib/edge.h"
#include "lib/vertex.h"
#include "lib/thread.h"
#include "lib/mutex.h"
#include <map>
#include <vector>
/**
* Clase abstracta padre de Pacman y Ghost. Esta clase contiene el id del jugador, la orientación que tiene en el arco, su velocidad, la posición en el arco, una referencia al arco, un booleano para saber si esta vivo o no, y una referencia a un mutex (el cual evitará superposiciones entre los jugadores).
* La clase básicamente tiene métodos setters y getters, pero además un método keyPressed() que recibe la tecla presionada y efectúa el movimiento, que si es un giro, lo implementa facilmente, pero si la acción es la de moverse, entonces utiliza un método abstracto move(), el que será redefinido por cada uno de sus descendientes.
* */
class Player{
private:
int _idPlayer; ///< id del jugador
tPlayerOrientation _orientation;///< orientacion de jugador
int _speed;///< velocidad de jugador
unsigned short _position; ///< posicion relativa dentro de la arista 0 a 63
const Edge* _tunnel; ///< arista en la que se encuentra
bool _alive;///< flag para saber si esta vivo
int _edgeID;///< id del arco que contiene
inline void setOrientation(const tPlayerOrientation & orientation){
_orientation = orientation;
}
Mutex & _key;
protected:
virtual void move(){};
void lockPlayers(){
_key.lock();
}
void unlockPlayers(){
_key.unlock();
}
public:
///
static const unsigned short steps;
///
static const unsigned short ratio;
///constructor con parametros
Player(const int &idPlayer, const Edge * tunnel, int initPosition, tPlayerOrientation orientation, Mutex & key);
///destructor
virtual ~Player(){};
///devuelve id de jugador al que esta detectando
inline int getPlayerId() const {return _idPlayer;}
///devuelve posicion
inline unsigned short getPosition() const { return _position; }
///setea la posicion del jugador
inline void setPosition(unsigned short position){ _position = position; }
///jugador toco tecla
void keyPressed(const tKeyType &key);
///cambia velocidad
inline void setSpeed (const int &speed) {
_speed = speed;
}
///devuelve la velocidad
inline int getSpeed () const{
return _speed;
}
///devuelve la arista en la que se encuentra
inline const Edge * getEdge() const{return _tunnel;}
///setea una nueva arista para que se posicione el jugador
void setEdge(const Edge* edge);
///devuelve el id del arco actual donde se encuentra el jugador
inline int getEdgeID() const{
return _edgeID;
}
///devuelve la direccion del jugador segun el tipo de arco
inline tPlayerOrientation getDirection() const{
return _orientation;
}
///termina la ejecucion del thread para ese jugador
void endGame();
///devuelve si el jugador esta vivo o no
inline bool isAlive() const{
return _alive;
}
///setea la variable alive
inline void setAlive(bool alive){
_alive = alive;
}
///devuelve la orientacion del jugador
tOrientation getOrientation();
};
/// Lista de Jugadores
typedef std::vector< Player* > PlayerList;
#endif /* __PLAYER_H__ */
|
Java
|
UTF-8
| 1,883 | 2.203125 | 2 |
[] |
no_license
|
package org.tq.Utility;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.tq.EsignGenie.BaseClass;
public class EmailSent extends BaseClass
{
public static void emailSentAfterSuccessfullTestCaseExecution() throws Exception
{
System.out.println("==========Email Started==========");
EmailAttachment attachment=new EmailAttachment();
//attachment.setPath("E:\\Hybrid framwork\\EsignGenie\\ExtentReports\\EsignGenie"+Helper.getcurrentDateTime()+".html");
attachment.setPath("C:\\Users\\shivu\\git\\EsignGenie\\EsignGenie\\ExtentReports\\EsignGenie"+Helper.getcurrentDateTime()+".html");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Test Report");
attachment.setName("Test Execution Report");
MultiPartEmail email= new MultiPartEmail();
//Email email = new SimpleEmail();
//email.setHostName("smtp.googlemail.com");
email.setHostName("mail.esigngenie.com");
email.setSmtpPort(465);
//email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator("sjain@esigngenie.com", "$j@!nbpB>8F"));
email.setSSLOnConnect(true);
email.setFrom("sjain@esigngenie.com");
email.setSubject("Test Execution Report Mail");
email.setMsg("Dear Sir,\n\nTest case has been executed successfully. Please find attached Test Report with this mail. \n\nNote- This mail has been sent automatically after the execution of all test cases through Selenium. Please open a test execution report in Google Chrome or Mozilla Firefox Browser for better GUI.\n\nThanks & Regards\nShivam Jain");
// email.addTo("dsingh@accountsight.com");
// email.addTo("mbist@accountsight.com");
email.addTo("sjain@accountsight.com");
email.addCc("sjain@esigngenie.com");
email.attach(attachment);
email.send();
System.out.println("==========Email Ended==========");
}
}
|
C++
|
UTF-8
| 846 | 2.96875 | 3 |
[] |
no_license
|
#ifndef METALH
#define METALH
#include "material.h"
#include "randomize.h"
class metal : public material {
public:
vec3 albedo;
float fuzz;
public:
metal(const vec3& a) : albedo(a) { fuzz = 0; };
metal(const vec3& a, float f) : albedo(a) { if (f < 1) fuzz = f; else fuzz = 1; };
virtual bool scatter(const ray& r_in, const hit_record& rec, vec3& attenuation, ray& scattered) const {
randomize* randomize_gen = &randomize::get_instance();
vec3 reflected = reflect(r_in.direction().unit_vector(), rec.normal);
scattered = ray(rec.p, reflected + fuzz*randomize_gen->random_in_unit_sphere());
attenuation = albedo;
return scattered.direction().dot(rec.normal) > 0;
}
private:
vec3 reflect(const vec3& v, const vec3& n) const {
return v - 2 * v.dot(n) * n;
}
};
#endif
|
Java
|
UTF-8
| 1,337 | 2.96875 | 3 |
[] |
no_license
|
package com.ustglobal.springcore1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import com.ustglobal.springcore1.config.PetConfigurationClass;
import com.ustglobal.springcore1.di.Animal;
import com.ustglobal.springcore1.di.Hello;
import com.ustglobal.springcore1.di.Pet;
public class AnnotationApp {
public static void main(String[] args) {
/*
* ApplicationContext context = new
* AnnotationConfigApplicationContext(ConfigurationClass.class);
*/
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(PetConfigurationClass.class);
Hello hello = context.getBean(Hello.class);
System.out.println(hello.getMsg());
Hello hello1 = context.getBean(Hello.class);
System.out.println(hello);
System.out.println(hello1);
/* which behaves like a singletone object */
System.out.println("*********************************");
/*
* Animal animal = context.getBean(Animal.class); animal.makeSound();
*/
System.out.println("************************************");
Pet pet = context.getBean(Pet.class);
System.out.println(pet.getName());
pet.getAnimal().makeSound();
context.close();
}
}
|
C++
|
UTF-8
| 6,235 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
/// ComputeSingleGeneQuery.hpp
/// Shaun Harker
/// 2018-05-14
/// MIT LICENSE
#include "ComputeSingleGeneQuery.h"
namespace ComputeSingleGeneQuery_detail_ {
inline bool isPowerOfTwo(uint64_t x) { return x && (!(x & (x - 1)));}
inline bool HammingDistanceOne(uint64_t x, uint64_t y) {return isPowerOfTwo(x ^ y);}
}
inline ComputeSingleGeneQuery::
ComputeSingleGeneQuery(Network network, std::string const& gene, std::function<char(uint64_t)> labeller) {
using namespace ComputeSingleGeneQuery_detail_;
self.network = network;
self.gene = gene;
self.parametergraph = ParameterGraph(self.network);
self.D = self.parametergraph.dimension();
//self.names = [ self.network.name(i) for i in range(0, self.D)]
// Initialize multi-radix indexing scheme:
// equivalent python code:
// self.indexing_place_bases = [self.parametergraph.logicsize(i) for i in range(0,self.D)] + [self.parametergraph.ordersize(i) for i in range(0,self.D)]
// self.indexing_place_values = functools.reduce ( lambda x, y : x + [x[-1]*y], self.indexing_place_bases[:-1], [1])
self.indexing_place_bases.resize(2*self.D);
self.indexing_place_values.resize(2*self.D);
uint64_t value = 1;
for ( uint64_t d = 0; d < self.D; ++ d) {
auto base = self.parametergraph.logicsize(d);
self.indexing_place_bases[d]=base;
self.indexing_place_values[d]=value;
value *= base;
}
for ( uint64_t d = 0; d < self.D; ++ d) {
auto base = self.parametergraph.ordersize(d);
self.indexing_place_bases[d+self.D]=base;
self.indexing_place_values[d+self.D]=value;
value *= base;
}
// "gene_index" gives the integer index used in the representation
self.gene_index = self.network.index(self.gene);
// num_gene_param is the size of the factor graph associated with "gene"
self.num_gene_param = self.indexing_place_bases[self.gene_index];
// num_reduced_param is the product of the sizes of all remaining factor graphs, and reorderings of all genes (including "gene")
self.num_reduced_param = self.parametergraph.size() / self.num_gene_param;
// Create factor graph
// TODO: The following algorithm for creating a factor graph takes O(NM^2) time, where N is length of hexcodes and M is size of factorgraph.
// An O(NM) algorithm is possible (based on looping through codewords and trying out each promotion, using a hash table)
// Implement this.
self.hexcodes = self.parametergraph.factorgraph(self.gene_index);
self.labeller = labeller;
// List of contiguous integers for vertices
uint64_t n = self.hexcodes.size();
self.vertices.resize(n);
for ( uint64_t i = 0; i < n; ++ i ) self.vertices[i] = i;
// Set of edges
for ( auto gpi1 : self.vertices ) {
auto x = stoull(self.hexcodes[gpi1], 0, 16 );
for ( auto gpi2 : self.vertices ) {
auto y = stoull(self.hexcodes[gpi2], 0, 16 );
if ( x < y && HammingDistanceOne(x,y)) {
self.edges.push_back({gpi1, gpi2});
}
}
}
// Add leaf node by convention (we match on edges, not nodes, so edge to leaf will have label to match last node)
self.vertices.push_back(n);
self.edges.push_back({n-1,n});
}
inline uint64_t ComputeSingleGeneQuery::
full_parameter_index(uint64_t rpi, uint64_t gpi) const {
return rpi % self.indexing_place_values[self.gene_index] + gpi * self.indexing_place_values[self.gene_index] +
(rpi / self.indexing_place_values[self.gene_index]) * self.indexing_place_values[self.gene_index+1];
};
/// reduced_parameter_index
/// Return (reduced_parameter_index, gene_parameter_index)
inline std::pair<uint64_t,uint64_t> ComputeSingleGeneQuery::
reduced_parameter_index(uint64_t pi) const {
return {pi % self.indexing_place_values[self.gene_index] +
(pi / self.indexing_place_values[self.gene_index+1]) * self.indexing_place_values[self.gene_index],
(pi / self.indexing_place_values[self.gene_index]) % self.indexing_place_bases[self.gene_index] };
};
/// operator ()
/// The query returns a graph which contains the poset of gene parameter indices
/// corresponding to adjusting the parameter by changing the logic parameter associated
/// with the gene being queried. The vertices are labelled according to the function
/// labeller which accepts full parameter indices.
/// The graph is as follows:
/// * The vertices of the graph are named according to Gene Parameter Index (gpi).
/// * There is a directed edge p -> q iff p < q and the associated logic parameters are adjacent.
/// * The graph is labelled (graph.matching_label) with the output of `labeller`
/// In addition the following extra structures are provided:
/// * `graph.num_inputs` is the number of network edges which are inputs to the gene associated with the query
/// * `graph.num_outputs`is the number of network edges which are outputs to the gene associated with the query
/// * `graph.essential` is a boolean-valued function which determines if each vertex corresponds to an essential parameter node
inline NFA ComputeSingleGeneQuery::
operator () (uint64_t reduced_parameter_index) const {
NFA result;
for ( auto v : self.vertices ) {
auto i = result.add_vertex();
result.add_edge(i,i,' '); // self epsilon edge
}
for ( auto e : self.edges ) {
auto u = e.first;
auto v = e.second;
auto parameter_index = full_parameter_index(reduced_parameter_index,u);
auto label = self.labeller(parameter_index);
result.add_edge(u,v,label);
}
result.set_initial(0);
result.set_final(self.vertices.size()-1);
return result;
}
/// number_of_gene_parameters
/// Return number of gene parameters associated with query object
/// This is the size of the logic factor graph associated with the selected gene
inline uint64_t ComputeSingleGeneQuery::
number_of_gene_parameters(void) const {
return self.num_gene_param;
}
/// number_of_reduced_parameters
/// Return number of reduced parameters associated with query object
/// This is the size of the parameter graph divided by the size of the
/// logic factor graph associated with the selected gene
inline uint64_t ComputeSingleGeneQuery::
number_of_reduced_parameters(void) const {
return self.num_reduced_param;
}
|
PHP
|
UTF-8
| 1,472 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace App\Controllers;
class AuthController extends BaseController
{
public function login()
{
if ($this->request->getMethod() == 'post'){
$rules = [
'username' => 'required',
'password' => 'required'
];
$validate = $this->validate($rules);
if($validate){
return view('Admin/index');
}
else{
return redirect()->back()->withInput()->with('validation', $this->validator);
}
}
return view('auth/login');
}
public function register(){
if ($this->request->getMethod() === 'post') {
$rules = [
'first_name' => [
'label' => 'First Name',
'rules' => 'required'
],
'last_name' => [
'label' => 'Last Name',
'rules' => 'required'
],
'username' => [
'label' => 'Username',
'rules' => 'required'
],
'email' => [
'label' => 'E-Mail',
'rules' => 'required'
],
'password' => [
'label' => 'Password',
'rules' => 'required'
],
'cpassword' => [
'label' => 'Password Confirmation',
'rules' => 'required'
]
];
$validate = $this->validate($rules);
if($validate){
return view ('Admin/index');
}
else
return redirect()->back()->withInput()->with('validation', $this->validator);
}
return view('auth/register');
}
}
|
Java
|
UTF-8
| 808 | 2.5625 | 3 |
[] |
no_license
|
package ca.uqam.mgl7460.a2011.hospitalizer.domain;
import static org.junit.Assert.*;
import org.junit.Test;
public class AddressTest {
@Test
public void testGetCivicNumber() {
String expectedCivicNumber = "123";
String expectedStreet = "Sainte-Catherine";
String expectedCity = "Montreal";
String expectedProvince = "QC";
String expectedPostalCode = "H0H 0H0";
Address address = new Address(expectedCivicNumber, expectedStreet, expectedCity, expectedProvince, expectedPostalCode);
assertEquals(expectedCivicNumber, address.getCivicNumber());
assertEquals(expectedStreet, address.getStreet());
assertEquals(expectedCity, address.getCity());
assertEquals(expectedProvince, address.getProvince());
assertEquals(expectedPostalCode, address.getPostalCode());
}
}
|
C#
|
UTF-8
| 8,766 | 3.421875 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
namespace JetBlack.MessageBus.Common
{
/// <summary>
/// This class is an adjunct to System.BitConverter. It's purpose is to provide
/// platform independent methods to transform types into byte arrays and back.
/// </summary>
public static class PortableBitConverter
{
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
/// <summary>
/// Convert a signed long to a date time.
/// </summary>
/// <param name="timestamp">The timestamp as a long in milliseconds since 1970-01-01.</param>
/// <returns>The date time corresponing to the milliseconds since 1970-01-01</returns>
public static DateTime Int64ToDate(this long timestamp)
{
return Epoch.AddMilliseconds(timestamp);
}
/// <summary>
/// Converts a date time to a long as the number of milliseconds since 1970-01-01.
/// </summary>
/// <param name="date">The date to convert.</param>
/// <returns>A long value which is the number of milliseconds since 1970-01-01.</returns>
public static long DateToInt64(this DateTime date)
{
var diff = date - Epoch;
return (long)Math.Floor(diff.TotalMilliseconds);
}
/// <summary>
/// Converts a byte array to a date time.
/// </summary>
/// <param name="buf">The byte array containing the date time</param>
/// <param name="offset">An offset into the byte stream</param>
/// <returns>The decoded date time value.</returns>
public static DateTime ToDateTime(this byte[] buf, int offset = 0)
{
var timestamp = ToInt64(buf, offset);
return Int64ToDate(timestamp);
}
/// <summary>
/// Converts a date time into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the date time.</returns>
public static byte[] GetBytes(this DateTime value)
{
var timestamp = DateToInt64(value);
return GetBytes(timestamp);
}
/// <summary>
/// Converts a byte array into a short.
/// </summary>
/// <param name="buf">The byte array.</param>
/// <param name="offset">A start offset into the byte array.</param>
/// <returns>A decoded short value.</returns>
public static short ToInt16(this byte[] buf, int offset = 0)
{
return (short)((buf[offset] << 8) + (buf[offset + 1] << 0));
}
/// <summary>
/// Converts a byte array into a signed int.
/// </summary>
/// <param name="buf">The byte array.</param>
/// <param name="offset">A start offset into the byte array.</param>
/// <returns>A decoded signed int value.</returns>
public static int ToInt32(this byte[] buf, int offset = 0)
{
return
(buf[offset] << 24) +
(buf[offset + 1] << 16) +
(buf[offset + 2] << 8) +
(buf[offset + 3] << 0);
}
/// <summary>
/// Converts a byte array into a signed long.
/// </summary>
/// <param name="buf">The byte array.</param>
/// <param name="offset">A start offset into the byte array.</param>
/// <returns>A decoded signed long value.</returns>
public static long ToInt64(this byte[] buf, int offset = 0)
{
return (((long)buf[offset] << 56) +
((long)(buf[offset + 1] & 255) << 48) +
((long)(buf[offset + 2] & 255) << 40) +
((long)(buf[offset + 3] & 255) << 32) +
((long)(buf[offset + 4] & 255) << 24) +
((buf[offset + 5] & 255) << 16) +
((buf[offset + 6] & 255) << 8) +
((buf[offset + 7] & 255) << 0));
}
/// <summary>
/// Converts a byte array into a float.
/// </summary>
/// <param name="buf">The byte array.</param>
/// <param name="offset">A start offset into the byte array.</param>
/// <returns>A decoded float value.</returns>
public static float ToFloat(this byte[] buf, int offset = 0)
{
byte[] byteArray = { buf[offset + 3], buf[offset + 2], buf[offset + 1], buf[offset] };
return BitConverter.ToSingle(byteArray, offset);
}
/// <summary>
/// Converts a byte array into a double.
/// </summary>
/// <param name="buf">The byte array.</param>
/// <param name="offset">A start offset into the byte array.</param>
/// <returns>A decoded double value.</returns>
public static double ToDouble(this byte[] buf, int offset = 0)
{
var value = ToInt64(buf, offset);
return BitConverter.Int64BitsToDouble(value);
}
/// <summary>
/// Converts a byte array into a char.
/// </summary>
/// <param name="buf">The byte array.</param>
/// <param name="offset">A start offset into the byte array.</param>
/// <returns>A decoded char value.</returns>
public static char ToChar(this byte[] buf, int offset = 0)
{
return (char)((buf[offset] << 8) + (buf[offset + 1] << 0));
}
/// <summary>
/// Converts a char into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the char.</returns>
public static byte[] GetBytes(this char value)
{
return new[]
{
(byte) ((value >> 8) & 0xFF),
(byte) ((value >> 0) & 0xFF)
};
}
/// <summary>
/// Converts a signed int into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the signed int.</returns>
public static byte[] GetBytes(this int value)
{
return new[]
{
(byte) ((value >> 24) & 0xFF),
(byte) ((value >> 16) & 0xFF),
(byte) ((value >> 8) & 0xFF),
(byte) ((value >> 0) & 0xFF)
};
}
/// <summary>
/// Converts a signed long into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the signed long.</returns>
public static byte[] GetBytes(this long value)
{
return new[]
{
(byte) ((value >> 56) & 0xFF),
(byte) ((value >> 48) & 0xFF),
(byte) ((value >> 40) & 0xFF),
(byte) ((value >> 32) & 0xFF),
(byte) ((value >> 24) & 0xFF),
(byte) ((value >> 16) & 0xFF),
(byte) ((value >> 8) & 0xFF),
(byte) ((value >> 0) & 0xFF)
};
}
/// <summary>
/// Converts a signed short into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the signed short.</returns>
public static byte[] GetBytes(this short value)
{
return new[]
{
(byte) ((value >> 8) & 0xFF),
(byte) ((value >> 0) & 0xFF)
};
}
/// <summary>
/// Converts a float into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the float.</returns>
public static byte[] GetBytes(this float value)
{
var byteArray = BitConverter.GetBytes(value);
Array.Reverse(byteArray);
return byteArray;
}
/// <summary>
/// Converts a double into a byte stream.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>A stream of bytes representing the double.</returns>
public static byte[] GetBytes(this double value)
{
var byteArray = BitConverter.GetBytes(value);
Array.Reverse(byteArray);
return byteArray;
}
}
}
|
C++
|
UTF-8
| 1,608 | 2.546875 | 3 |
[
"BSL-1.0"
] |
permissive
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
@copyright 2016 J.T. Lapreste
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_TOINTS_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_TOINTS_HPP_INCLUDED
#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
/*!
@ingroup group-arithmetic
Function object implementing toints capabilities
Convert to integer by saturated truncation.
@par semantic:
For any given value @c x of type @c T:
@code
as_integer_t<T> r = toints(x);
@endcode
The code is similar to:
@code
as_integer_t<T> r = static_cast<as_integer_t<T> >(saturate<as_integer_t<T> >(x))
@endcode
@par Notes:
- The @ref Inf, @ref Minf and @ref Nan values are treated properly and go respectively to
@ref Valmax, @ref Valmin and @ref Zero of the destination integral type.
- All values superior (resp.) less than @ref Valmax (resp. @ref Valmin) of the return type
are saturated accordingly.
- If you do not care about invalid values or overflows, toint is faster.
@par Alias
@c ifix, @c itrunc
@see toint
**/
const boost::dispatch::functor<tag::toints_> toints = {};
} }
#endif
#include <boost/simd/function/scalar/toints.hpp>
#include <boost/simd/function/simd/toints.hpp>
#endif
|
C#
|
UTF-8
| 2,390 | 2.53125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
using System;
using System.Collections;
using System.Collections.Generic;
using PCRE.Internal;
namespace PCRE.Dfa
{
public sealed class PcreDfaMatchResult : IReadOnlyList<PcreDfaMatch>
{
private readonly uint[] _oVector;
private readonly int _resultCode;
private readonly PcreDfaMatch[] _matches;
internal string Subject { get; }
internal PcreDfaMatchResult(string subject, ref Native.match_result result, uint[] oVector)
{
// Real match
Subject = subject;
_oVector = oVector;
_resultCode = result.result_code;
if (_resultCode > 0)
_matches = new PcreDfaMatch[_resultCode];
else if (_resultCode == 0)
_matches = new PcreDfaMatch[_oVector.Length / 2];
else
_matches = Array.Empty<PcreDfaMatch>();
}
private PcreDfaMatch GetMatch(int index)
{
if (index < 0 || index >= Count)
return null;
var match = _matches[index];
if (match == null)
_matches[index] = match = CreateMatch(index);
return match;
}
private PcreDfaMatch CreateMatch(int index)
{
index *= 2;
if (index >= _oVector.Length)
return null;
var startOffset = (int)_oVector[index];
var endOffset = (int)_oVector[index + 1];
return new PcreDfaMatch(Subject, startOffset, endOffset);
}
private IEnumerable<PcreDfaMatch> GetMatches()
{
for (var i = 0; i < Count; ++i)
yield return GetMatch(i);
}
public IEnumerator<PcreDfaMatch> GetEnumerator() => GetMatches().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public PcreDfaMatch this[int index] => GetMatch(index);
public int Count => _matches.Length;
public bool Success => _resultCode >= 0;
public int Index => LongestMatch?.Index ?? -1;
public PcreDfaMatch LongestMatch => GetMatch(0);
public PcreDfaMatch ShortestMatch => GetMatch(Count - 1);
public override string ToString()
{
var match = LongestMatch;
return match != null ? match.Value : string.Empty;
}
}
}
|
C++
|
UTF-8
| 854 | 2.5625 | 3 |
[] |
no_license
|
#include "system.h"
namespace mathmod
{
System::System(Area *area)
{
m_Area = area;
}
void System::addCondition(Point3f p)
{
if(m_Area->isInitial(p))
{
m_L0.push_back(p);
}
else
{
m_Lg.push_back(p);
}
}
void System::addObservation(Point3f p)
{
Position position = m_Area->position(p);
if(position == LEFT || position == RIGHT)
{
m_U0.push_back(p);
}
else if(position == DOWN)
{
m_Ug.push_back(p);
}
}
void System::setGreensFunction(Function f)
{
m_G = f;
}
void System::setStateFunction(Function f)
{
m_Y = f;
}
void System::setExternalDynamicPerturbationsFunction(Function f)
{
m_U = f;
}
}
|
C++
|
UTF-8
| 475 | 2.578125 | 3 |
[] |
no_license
|
#ifndef MATERIASOURCE_HPP
# define MATERIASOURCE_HPP
#include <string>
#include <iostream>
#include "IMateriaSource.hpp"
#include "AMateria.hpp"
class MateriaSource: public IMateriaSource
{
int amount;
AMateria *source[4];
public:
MateriaSource();
~MateriaSource();
MateriaSource(const MateriaSource& copy);
MateriaSource& operator=(const MateriaSource& op);
void learnMateria(AMateria* m);
AMateria* createMateria(std::string const & type);
};
#endif
|
Java
|
UTF-8
| 809 | 2.171875 | 2 |
[] |
no_license
|
package com.swift.hello.spring.boot.bootstrap;
import com.swift.hello.spring.boot.annotation.EnableHello;
import com.swift.hello.spring.boot.service.UserService;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@EnableHello
public class EnableInterfaceBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableInterfaceBootstrap.class).web(WebApplicationType.NONE).run(args);
String hello = context.getBean("initConfig", String.class);
System.out.println("hello: " + hello);
context.close();
}
}
|
Go
|
UTF-8
| 1,824 | 3.28125 | 3 |
[] |
no_license
|
package main
import (
"encoding/json"
"fmt"
)
/**
golang 的json用法https://blog.csdn.net/wade3015/article/details/88401969
*/
type Stu struct {
Name string `json:"name"`
Age int
HIgh bool
Sex string `json:"sex"`
Class *Class `json:"class"`
}
type Class struct {
Name string
Grade int
}
type Server struct {
ServerName string `json:"serverName,string"`
ServerIP string `json:"serverIP,omitempty"`
}
type Serverslice struct {
Servers []Server `json:"servers"`
}
type Request struct {
Data []interface{} `json:"data"`
Errmsg string `json:"errmsg"`
Errno int `json:"errno"`
}
type Response struct {
Errmsg string `json:"errmsg"`
Data []interface{} `json:"data"`
Errno int `json:"errno"`
}
func main() {
JsonToMapDemo()
//beJson()
}
//json转化成结构体和map
func simpJson() {
}
//转换成json
func beJson() {
//实例化一个数据结构,用于生成json字符串
stu := Stu{
Name: "张三",
Age: 18,
HIgh: true,
Sex: "男",
}
//指针变量
cla := new(Class)
cla.Name = "1班"
cla.Grade = 3
stu.Class = cla
//Marshal失败时err!=nil
jsonStu, err := json.Marshal(stu)
if err != nil {
fmt.Println("生成json字符串错误")
}
//jsonStu是[]byte类型,转化成string类型便于查看
beJ := string(jsonStu)
fmt.Println(beJ)
return
var s Serverslice
s.Servers = append(s.Servers, Server{ServerName: "Guangzhou_Base", ServerIP: "127.0.0.1"})
s.Servers = append(s.Servers, Server{ServerName: "Beijing_Base", ServerIP: "127.0.02"})
s.Servers = append(s.Servers, Server{ServerName: "Beijing_Base1", ServerIP: "192.0.02"})
//s.Servers = append(s.Servers, stu)
//fmt.Printf("%+v",stu)
b, err := json.Marshal(s)
if err != nil {
fmt.Println("JSON ERR:", err)
}
j := string(b)
fmt.Println(j)
}
|
C++
|
UTF-8
| 578 | 3.375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
struct some_key
{
int a = 0;
double b = 0;
std::string c;
std::vector<int> d;
bool operator<(some_key const& rhs) const
{
return std::tie(a,b,c,d)<std::tie(rhs.a,rhs.b,rhs.c,rhs.d);
}
};
int main()
{
some_key key1;
some_key key2;
key2.a=1;
std::map<some_key, std::string> m;
m[key1] = "hi";
m[key2] = "goodbye";
std::cout<<m[key1]<<std::endl;
}
|
Markdown
|
UTF-8
| 3,541 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# Run on Kubernetes
## Run directly
Note: If you want to customize the configuration, you are required to link Firebase. See the
[firebase documentation](../advanced/firebase.md) on how to do that.
Note that you shouldn't be running more than 1 replica.
```yml
kind: Namespace
apiVersion: v1
metadata:
name: cimonitor
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: cimonitor-server
namespace: cimonitor
labels:
app: cimonitor-server
spec:
replicas: 1
selector:
matchLabels:
app: cimonitor-server
template:
metadata:
labels:
app: cimonitor-server
spec:
containers:
- image: cimonitor/server:latest
name: cimonitor-server-container
imagePullPolicy: Always
resources:
requests:
memory: "16Mi"
cpu: "10m"
limits:
memory: "256Mi"
cpu: "500m"
ports:
- containerPort: 9999
env:
- name: APP_ENV
value: production
---
apiVersion: v1
kind: Service
metadata:
name: cimonitor-server-service
namespace: cimonitor
spec:
type: ClusterIP
ports:
- port: 80
targetPort: 9999
selector:
app: cimonitor-server
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: cimonitor-server-ingress
namespace: cimonitor
annotations:
kubernetes.io/tls-acme: "true"
kubernetes.io/ingress.class: "nginx"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
cert-manager.io/acme-challenge-type: http01
spec:
tls:
- secretName: cimonitor-server-tls
hosts:
- YOUR_HOST_ADDRESS
rules:
- host: YOUR_HOST_ADDRESS
http:
paths:
- path: /
backend:
serviceName: cimonitor-server-service
servicePort: 80
```
## With firebase config
Create a firebase secret, containing your firebase service account private key json:
```
export FIREBASE_PRIVATE_KEY=$(cat/YOUR-FIREBASE-ACCOUNT-PRIVATE-KEY-FILE.json)
kubectl create secret generic firebase-private-key \
--namespace cimonitor \
--from-file=firebase-private-key.json=$FIREBASE_PRIVATE_KEY
```
Use the top example, except replace the deployment:
```yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: cimonitor-server
namespace: cimonitor
labels:
app: cimonitor-server
spec:
replicas: 1
selector:
matchLabels:
app: cimonitor-server
template:
metadata:
labels:
app: cimonitor-server
spec:
volumes:
- name: firebase-private-key
secret:
secretName: firebase-private-key
containers:
- image: cimonitor/server:latest
name: cimonitor-server-container
imagePullPolicy: Always
resources:
requests:
memory: "16Mi"
cpu: "10m"
limits:
memory: "256Mi"
cpu: "500m"
ports:
- containerPort: 9999
env:
- name: FIREBASE_PRIVATE_KEY_FILE
value: "/etc/firebase-secrets/firebase-private-key.json"
- name: FIREBASE_URL
value: "https://YOUR_UNIQUE_FIREBASE_SLUG.firebaseio.com/"
- name: STORAGE
value: "firebase"
- name: APP_ENV
value: production
volumeMounts:
- name: firebase-private-key
readOnly: true
mountPath: "/etc/firebase-secrets"
```
|
C++
|
UTF-8
| 3,492 | 2.59375 | 3 |
[] |
no_license
|
#include "audioplayer.h"
#include <string.h>
#include <stdio.h>
void AudioPlayer::pad_added_handler (GstElement * src, GstPad * srcPad, AudioPlayer *player) {
GstPad *sinkPad = gst_element_get_static_pad(player->convert, "sink");
gst_pad_link(srcPad, sinkPad);
}
AudioPlayer::AudioPlayer(){
strCurrentTime = (char*)malloc(16);
strDuration = (char*)malloc(16);
}
void AudioPlayer::init(char *url){
source = gst_element_factory_make("uridecodebin", "source");
convert = gst_element_factory_make("audioconvert", "convert");
sink = gst_element_factory_make("autoaudiosink", "sink");
pipeline = gst_pipeline_new("pipeline");
gst_bin_add_many(GST_BIN(pipeline), source, convert, sink, NULL);
gst_element_link(convert, sink);
g_object_set(source, "uri", url, NULL);
g_signal_connect(source, "pad-added", G_CALLBACK(AudioPlayer::pad_added_handler), this);
gst_element_set_state(pipeline, GST_STATE_PLAYING);
bus = gst_element_get_bus(pipeline);
GstMessage *msg;
//loop until state change to PLAY
while (1) {
msg = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE, static_cast<GstMessageType>(GST_MESSAGE_ERROR | GST_MESSAGE_STATE_CHANGED));
if (msg != NULL) {
if (msg->type == GST_MESSAGE_ERROR) {
g_print("load err\n");
break;
}
else if (msg->type == GST_MESSAGE_STATE_CHANGED) {
GstState newState;
gst_message_parse_state_changed(msg, NULL, &newState, NULL);
if (newState == GST_STATE_PLAYING) {
gint64 duration;
gst_element_query_duration(pipeline, GST_FORMAT_TIME, &duration);
char fullDurationTime[16];
sprintf(fullDurationTime, "%"GST_TIME_FORMAT, GST_TIME_ARGS(duration));
strncpy(strDuration, fullDurationTime+2, 5);
strDuration[5] = 0;
ready = true;
break;
}
}
}
}
//loop until reach End of Sound
char fullCurrentTime[16];
while (1) {
msg = gst_bus_timed_pop_filtered(bus, GST_SECOND, static_cast<GstMessageType>(GST_MESSAGE_EOS));
if (msg){
if (msg->type == GST_MESSAGE_EOS) {
finished = true;
// g_print("end of sound\n");
break;
}
}
else {
gint64 current = -1;
gst_element_query_position(pipeline, GST_FORMAT_TIME, ¤t);
sprintf(fullCurrentTime, "%"GST_TIME_FORMAT, GST_TIME_ARGS(current));
strncpy(strCurrentTime, fullCurrentTime+2, 5);
strCurrentTime[5] = 0;
}
}
}
void AudioPlayer::play(){
gst_element_set_state(pipeline, GST_STATE_PLAYING);
}
void AudioPlayer::pause(){
gst_element_set_state(pipeline, GST_STATE_PAUSED);
}
char* AudioPlayer::getDuration(){
return strDuration;
}
char* AudioPlayer::getCurrentTime(){
return strCurrentTime;
}
bool AudioPlayer::isReady(){
return ready;
}
bool AudioPlayer::isFinished() {
return finished;
}
// int main(int argc, char *argv[]) {
// AudioPlayer player(argc, argv);
// player.init("https://av.voanews.com/clips/VLE/2019/12/02/df3285f5-19bf-452a-a0bb-22103c2ac0e7_hq.mp3");
// return 0;
// }
|
C#
|
UTF-8
| 2,022 | 3.84375 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Practice.InterviewBit.Problems.ProblemSet.Level7.DynamicProgramming
{
/// <summary>
/// Jump Game Array
/// https://www.interviewbit.com/problems/jump-game-array/
/// </summary>
public class JumpGameArray
{
/*
Given an array of non-negative integers, A, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Input Format:
The first and the only argument of input will be an integer array A.
Output Format:
Return an integer, representing the answer as described in the problem statement.
=> 0 : If you cannot reach the last index.
=> 1 : If you can reach the last index.
Constraints:
1 <= len(A) <= 1e6
0 <= A[i] <= 30
Examples:
Input 1:
A = [2,3,1,1,4]
Output 1:
1
Explanation 1:
Index 0 -> Index 2 -> Index 3 -> Index 4 -> Index 5
Input 2:
A = [3,2,1,0,4]
Output 2:
0
Explanation 2:
There is no possible path to reach the last index.
*/
public int Solve(List<int> nums)
{
if (nums == null || nums.Count <= 2)
{
return 1;
}
var prev = nums.Count - 2;
var needed = 1;
while (prev >= 0)
{
if (nums[prev] >= needed)
{
if (prev == 0)
{
return 1;
}
prev--;
needed = 1;
}
else
{
prev--;
needed++;
}
}
return 0;
}
}
}
|
Java
|
UTF-8
| 1,655 | 2.8125 | 3 |
[] |
no_license
|
package com.windsor.node.plugin.common;
/**
* Implementation of {@link ITranformer}.
*
* @param <IN>
* type to be transformed from
* @param <OUT>
* type to be tranformed into
*/
public abstract class AbstractTransformer<IN, OUT> implements ITransformer<IN, OUT> {
@SuppressWarnings("unchecked")
@Override
public Object transform(final Object input) {
return typedTransform((IN) input);
}
/**
* Transforms a {@link String} into an upper-case {@link String}.
*
*/
static class UpperCaseTransformer extends AbstractTransformer<String, String> {
@Override
public String typedTransform(final String in) {
return in == null ? null : in.toUpperCase();
}
}
public static final UpperCaseTransformer UPPER_CASE_TRANSFORMER = new UpperCaseTransformer();
/**
* Transforms a {@link String} into a {@link String} of no more than maxLength.
*
*/
public static class LengthTransformer extends AbstractTransformer<String, String> {
private final int maxLength;
public LengthTransformer(final int maxLength) {
this.maxLength = maxLength;
}
@Override
public String typedTransform(final String in) {
return in == null ? null : (in.length() > maxLength ? in.substring(0,
maxLength) : in);
}
}
/**
* Adds a suffix to a {@link String}.
*
*/
public static class SuffixAppenderTransformer extends
AbstractTransformer<String, String> {
private final String suffix;
public SuffixAppenderTransformer(final String suffix) {
this.suffix = suffix;
}
@Override
public String typedTransform(final String in) {
return in == null ? null : in + suffix;
}
}
}
|
Python
|
UTF-8
| 1,296 | 2.609375 | 3 |
[] |
no_license
|
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import time
mnist=tf.keras.datasets.mnist
(train_x,train_y),(test_x,test_y)=mnist.load_data()
X_train,X_test=tf.cast(train_x,dtype=tf.float32)/255.0,tf.cast(test_x,dtype=tf.float32)/255.0
y_train,y_test=tf.cast(train_y,dtype=tf.int32),tf.cast(test_y,dtype=tf.int32)
X_train=train_x.reshape(60000,28,28,1)
X_test=test_x.reshape(10000,28,28,1)
model=tf.keras.Sequential([
#unit1
tf.keras.layers.Conv2D(16,kernel_size=(3,3),padding='same',activation=tf.nn.relu,input_shape=(28,28,1)),
tf.keras.layers.MaxPool2D(pool_size=(2,2)),
#unit2
tf.keras.layers.Conv2D(32,kernel_size=(3,3),padding='same',activation=tf.nn.relu),
tf.keras.layers.MaxPool2D(pool_size=(2,2)),
#unit3
tf.keras.layers.Flatten(),
#unit4
tf.keras.layers.Dense(128,activation='relu'),
tf.keras.layers.Dense(10,activation='softmax')
])
#model.summary()
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['sparse_categorical_accuracy'])
start = time.perf_counter()
model.fit(X_train,y_train,batch_size=64,epochs=5,validation_split=0.2)
end = time.perf_counter()
print("模型训练时间: ",end-start)
print("模型评估结果为:")
model.evaluate(X_test, y_test, verbose=2)
|
Swift
|
UTF-8
| 1,055 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
//
// CollectionCellViewModel.swift
// Papr
//
// Created by Joan Disho on 05.09.18.
// Copyright © 2018 Joan Disho. All rights reserved.
//
import Foundation
import RxSwift
protocol CollectionCellViewModelInput {}
protocol CollectionCellViewModelOutput {
var photoCollection: Observable<PhotoCollection> { get }
}
protocol CollectionCellViewModelType {
var input: CollectionCellViewModelInput { get }
var output: CollectionCellViewModelOutput { get }
}
class CollectionCellViewModel: CollectionCellViewModelType,
CollectionCellViewModelInput,
CollectionCellViewModelOutput {
// MARK: Input & Output
var input: CollectionCellViewModelInput { return self }
var output: CollectionCellViewModelOutput { return self }
// MARK: Input
// MARK: Output
let photoCollection: Observable<PhotoCollection>
// MARK: Private
// MARK: Init
init(photoCollection: PhotoCollection) {
self.photoCollection = Observable.just(photoCollection)
}
}
|
C++
|
UTF-8
| 2,892 | 3.5625 | 4 |
[] |
no_license
|
#include "Quaternion.h"
inline Quaternion::Quaternion(float _pitch, float _yaw, float _roll) :pitch(_pitch), yaw(_yaw), roll(_roll) {}
Quaternion Quaternion::operator+(const Quaternion& other) const
{
return{ pitch + other.pitch, yaw + other.yaw,roll + other.roll };
}
Quaternion Quaternion::operator-(const Quaternion& other) const
{
return{ pitch - other.pitch, yaw - other.yaw,roll - other.roll };
}
Quaternion Quaternion::operator*(float s) const
{
return{ pitch * s, yaw * s,roll * s };
}
Quaternion Quaternion::operator/(float s) const
{
return{ pitch / s, yaw / s ,roll / s };
}
Quaternion& Quaternion::operator+=(const Quaternion& other)
{
pitch += other.pitch;
yaw += other.yaw;
roll += other.roll;
return *this;
}
Quaternion& Quaternion::operator-=(const Quaternion& other)
{
pitch -= other.pitch;
yaw -= other.yaw;
roll -= other.roll;
return *this;
}
Quaternion& Quaternion::operator*=(float s)
{
pitch *= s;
yaw *= s;
roll *= s;
return *this;
}
Quaternion& Quaternion::operator/=(float s)
{
pitch /= s;
yaw /= s;
roll /= s;
return *this;
}
bool Quaternion::operator==(const Quaternion& other)
{
return ((int)pitch == (int)other.pitch && (int)yaw == (int)other.yaw && (int)roll == (int)other.roll);
}
bool Quaternion::operator!=(const Quaternion& other)
{
return ((int)pitch != (int)other.pitch || (int)yaw != (int)other.yaw || (int)roll != (int)other.roll);
}
bool Quaternion::operator>=(const Quaternion& other)
{
return ((int)pitch >= (int)other.pitch && (int)yaw >= (int)other.yaw && (int)roll >= (int)other.roll);
}
bool Quaternion::operator<=(const Quaternion& other)
{
return ((int)pitch <= (int)other.pitch && (int)yaw <= (int)other.yaw && (int)roll <= (int)other.roll);
}
bool Quaternion::operator<(const Quaternion& other)
{
return ((int)pitch < (int)other.pitch || (int)yaw < (int)other.yaw || (int)roll < (int)other.roll);
}
bool Quaternion::operator>(const Quaternion& other)
{
return ((int)pitch > (int)other.pitch || (int)yaw > (int)other.yaw || (int)roll > (int)other.roll);
}
inline float Quaternion::LengthSq() const
{
return pitch * pitch + yaw * yaw + roll * roll;
}
inline float Quaternion::Length() const
{
return sqrt(LengthSq());
}
inline float Quaternion::dot(const Quaternion& other) const
{
return pitch * other.pitch + yaw * other.yaw + roll * other.roll;
}
inline float Quaternion::distanceFrom(const Quaternion& other) const
{
Quaternion v;
v.pitch = pitch - other.pitch;
v.yaw = yaw - other.yaw;
v.roll = roll - other.roll;
return v.Length();
}
inline Quaternion Quaternion::Normalized() const
{
return { pitch / Length(), yaw / Length(), roll / Length() };
}
inline Quaternion Quaternion::Lerp(const Quaternion& destination, float t)
{
pitch = pitch + (destination.pitch - pitch) * t;
yaw = yaw + (destination.yaw - yaw) * t;
roll = roll + (destination.roll - roll) * t;
return *this;
}
|
Java
|
UTF-8
| 40,498 | 1.734375 | 2 |
[
"IJG"
] |
permissive
|
package com.cartracker.mobile.android.util;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.cartracker.mobile.android.R;
import com.cartracker.mobile.android.config.VariableKeeper;
import com.cartracker.mobile.android.data.CarTrackerApplication;
import com.cartracker.mobile.android.data.beans.UsbCameraDevice;
import com.cartracker.mobile.android.ui.base.BaseActivity;
import com.cartracker.mobile.android.util.handler.InterfaceGen;
import com.cartracker.mobile.android.util.handler.InterfaceGen.PermissionFileHandlerListener;
import com.cartracker.mobile.android.util.handler.InterfaceGen.RecordThreadStatusListener;
import com.cartracker.mobile.android.util.handler.InterfaceGen.RootResultListener;
import com.cartracker.mobile.android.util.handler.InterfaceGen.ShellExeListener;
import com.googlecode.javacv.cpp.opencv_core;
import java.io.*;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.googlecode.javacv.cpp.opencv_core.IPL_DEPTH_8U;
import static com.googlecode.javacv.cpp.opencv_core.IplImage;
/**
* Created by jw362j on 9/19/2014.
*/
public class SystemUtil {
public static void log(String msg) {
if (VariableKeeper.logMode) {
Log.d("bigdog", msg);
}
}
public static void MyToast(final String msg) {
new Thread(new Runnable() {
@Override
public void run() {
CarTrackerApplication.getTrackerAppContext().getHandler().post(new Runnable() {
@Override
public void run() {
Toast.makeText(VariableKeeper.getmCurrentActivity(), msg, 0).show();
}
});
}
}).start();
}
public static void recycleBitmap(Bitmap img) {
if (img != null && !img.isRecycled()) {
img.recycle();
}
}
/**
* 调用系统浏览器
*
* @param url
*/
public static void runBrowser(String url) {
if (VariableKeeper.getmCurrentActivity() != null) {
// Uri uri = Uri.parse(url);
Uri uri = Uri.parse("http://shouji.baidu.com/s?wd=android%20root%B9%A4%BE%DF%26data_type=app");
Intent intent = new Intent();
intent.setAction(intent.ACTION_VIEW);
intent.setData(uri);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (VariableKeeper.getmCurrentActivity() != null)
VariableKeeper.getmCurrentActivity().startActivity(intent);
}
}
//在当前activity上显示对话框 仅仅只做提示用户用 不能处理任何逻辑
/*public static void dialogJust4TipsShow(final String title, final String msg) {
if (VariableKeeper.getmCurrentActivity() != null) {
VariableKeeper.getmCurrentActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(VariableKeeper.getmCurrentActivity());
builder.setTitle(title).setMessage(msg).setPositiveButton(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialog = null;
}
});
dialog = builder.create();
dialog.show();
}
});
}
}*/
//在当前activity上显示对话框 仅仅只做提示用户用 不能处理任何逻辑
private static Dialog dialog = null;
public static void dialogJust4TipsShow(final String title, final String msg) {
if (VariableKeeper.getmCurrentActivity() != null) {
VariableKeeper.getmCurrentActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
View view_title = View.inflate(VariableKeeper.getmCurrentActivity(), R.layout.emergency_help_menu_setting_title, null);
View view_body = View.inflate(VariableKeeper.getmCurrentActivity(), R.layout.dialog_body_tips, null);
TextView id_tv_tips_msg = (TextView) view_body.findViewById(R.id.id_tv_tips_msg);
Button id_btn_tips_body = (Button) view_body.findViewById(R.id.id_btn_tips_body);
TextView id_tv_tips_title = (TextView) view_title.findViewById(R.id.id_tv_tips_title);
id_tv_tips_title.setText(title);
id_tv_tips_msg.setText(msg);
TextView menu_emergency_help_settings_send_frequence_title_close = (TextView) view_title.findViewById(R.id.menu_emergency_help_settings_send_frequence_title_close);
menu_emergency_help_settings_send_frequence_title_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (dialog != null) {
dialog.dismiss();
}
}
});
id_btn_tips_body.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(VariableKeeper.getmCurrentActivity());
builder.setCustomTitle(view_title).setView(view_body);
dialog = builder.create();
dialog.show();
}
});
}
}
public static void LowerVersionWarning() {
SystemUtil.dialogJust4TipsShow(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.dialog_tips_title),
VariableKeeper.getmCurrentActivity().getResources().getString(R.string.desktop_sdk_too_low_msg_1) +
VariableKeeper.Version_RELEASE +
VariableKeeper.getmCurrentActivity().getResources().getString(R.string.desktop_sdk_too_low_msg_2)
);
}
public static void getRootStatus(RootResultListener rootResultListener) {
Process process = null;
OutputStream out = null;
int value = -1;
try {
process = Runtime.getRuntime().exec("su");
out = process.getOutputStream();
out.write("exit\n".getBytes()); //Linux命令,注意加上换行符
out.flush();
process.waitFor();
value = process.exitValue(); //value = 0则有root权限;不等于0,则未取得root权限
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rootResultListener != null) rootResultListener.onRootResult(value, null);
if (value == 0) {
VariableKeeper.isRooted = true;
} else {
VariableKeeper.isRooted = false;
}
try {
if (out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void logOnFile(String string) {
if (!VariableKeeper.logMode) {
return;
}
try {
String sdFilePath = VariableKeeper.system_file_save_BaseDir + File.separator + VariableKeeper.LogFolderName + File.separator;
String fileName = sdFilePath + "log" + ".txt";
File filePath = new File(sdFilePath);
if (!filePath.exists()) {
filePath.mkdir();
}
File file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else if (file.length() > 100 * 1000) {
try {
file.delete();
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
String a = "\r\n" + string;
FileOutputStream fos;
fos = new FileOutputStream(file, true);
fos.write(a.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean isAvaiableSpace(int sizeMb) {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
String sdcard = Environment.getExternalStorageDirectory().getPath();
StatFs statFs = new StatFs(sdcard);
long blockSize = statFs.getBlockSize();
long blocks = statFs.getAvailableBlocks();
long availableSpare = (blocks * blockSize) / (1024 * 1024);
// Log.v("wt","availableSpare = " + availableSpare);
if (sizeMb > availableSpare) {
return false;
} else {
return true;
}
}
return false;
}
public static String convertDateToString(Date dateTime) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
return df.format(dateTime);
}
public static Date convertStrToDate(String strDate) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = format.parse(strDate, pos);
return strtodate;
}
public static Date LongToDate(long date) {
Date result = null;
new Date(date);
return result;
}
public static IplImage processImage(byte[] data) {
int width = VariableKeeper.APP_CONSTANT.IMG_WIDTH;
int height=VariableKeeper.APP_CONSTANT.IMG_HEIGHT;
int f = 4;// SUBSAMPLING_FACTOR;
// First, downsample our image and convert it into a grayscale IplImage
IplImage grayImage = IplImage.create(width / f, height / f, IPL_DEPTH_8U, 1);
int imageWidth = grayImage.width();
int imageHeight = grayImage.height();
int dataStride = f * width;
int imageStride = grayImage.widthStep();
ByteBuffer imageBuffer = grayImage.getByteBuffer();
for (int y = 0; y < imageHeight; y++) {
int dataLine = y * dataStride;
int imageLine = y * imageStride;
for (int x = 0; x < imageWidth; x++) {
imageBuffer.put(imageLine + x, data[dataLine + f * x]);
}
}
return grayImage;
}
public static Bitmap createImage(byte[] imgData) {
Bitmap img = null;
try {
img = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
// BitmapFactory.Options options=new BitmapFactory.Options();
// options.inSampleSize = 2;
// img = BitmapFactory.decodeByteArray(imgData, 0,
// imgData.length,options);
} catch (Exception e) {
recycleBitmap(img);
img = null;
// System.gc();
SystemUtil.log(e.getMessage());
} catch (OutOfMemoryError e) {
recycleBitmap(img);
img = null;
// System.gc();
SystemUtil.log(e.getMessage());
}
return img;
}
/**
* 将bitmap转化为byte[]
*/
public static byte[] Bitmap2Bytes(Bitmap bm, int quality) {
byte[] imgByteArray = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, quality, bos);
imgByteArray = bos.toByteArray();
// Log.v("kxy", "--- compressed image size: " + imgByteArray.length +
// ", quality: " + quality);
closeQuietly(bos);
return imgByteArray;
}
public static Bitmap getImageFromAssetsFile(String filename) {
Bitmap image = null;
AssetManager am = VariableKeeper.context.getResources().getAssets();
try {
InputStream is = am.open(filename);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);//此时不解码并分配存储空间只是计算出长度和宽度并存放在options变量中
options.inSampleSize = computeSampleSize(options, -1, 128 * 128);
options.inJustDecodeBounds = false;
image = BitmapFactory.decodeStream(is, null, options);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
private static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
public static void reNamaeFile(String source, String dest) {
File f = new File(source);
if (f.exists()) {
File dest_file = new File(dest);
f.renameTo(dest_file);
}
}
private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 :
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) &&
(minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
public static void closeInputStream(InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e("error", "close failed");
e.printStackTrace();
}
}
}
public static boolean fitApiLevel(int level) {
try {
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion >= level) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
//此处应该将设备信息概况收集起来
/* for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}*/
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = formatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".txt";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = VariableKeeper.system_file_save_BaseDir + VariableKeeper.LogFolderName;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
log("an error occured while writing file..." + e.getMessage());
}
return null;
}
/**
* 查看SD卡的剩余空间
*
* @return
*/
public static long getSDFreeSize() {
//取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
//获取单个数据块的大小(Byte)
long blockSize = sf.getBlockSize();
//空闲的数据块的数量
long freeBlocks = sf.getAvailableBlocks();
//返回SD卡空闲大小
// freeBlocks * blockSize; //单位Byte
// (freeBlocks * blockSize)/1024; //单位KB
long free_size = (freeBlocks * blockSize) / 1024 / 1024;//单位MB
VariableKeeper.sdCard_CurrentFreeSize = free_size;
return free_size;
}
/**
* 查看SD卡总容量
*
* @return
*/
public static long getSDAllSize() {
//取得SD卡文件路径
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
//获取单个数据块的大小(Byte)
long blockSize = sf.getBlockSize();
//获取所有数据块数
long allBlocks = sf.getBlockCount();
//返回SD卡大小
//return allBlocks * blockSize; //单位Byte
//return (allBlocks * blockSize)/1024; //单位KB
return (allBlocks * blockSize) / 1024 / 1024; //单位MB
}
public static boolean isFileExistInSDRoot(String filename) {
boolean isexist = false;
if (new File(VariableKeeper.sdCard_mountRootPath + filename).exists()) isexist = true;
return isexist;
}
/**
* 执行 shell 脚本命令
*/
public static void exe(String cmd, ShellExeListener shellListener) {
/* 获取执行工具 */
Process process = null;
/* 存放脚本执行结果 */
List<String> list = new ArrayList<String>();
try {
/* 获取运行时环境 */
Runtime runtime = Runtime.getRuntime();
/* 执行脚本 */
process = runtime.exec(cmd);
/* 获取脚本结果的输入流 */
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
/* 逐行读取脚本执行结果 */
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if (shellListener != null) shellListener.onExec(list);
}
/**
* 检测 /data/data/com.cartracker.mobile.android/files/目录下是否有指定的文件
*/
public static boolean varifyFile(Context context, String fileName) {
boolean exist = false;
/* 查看文件是否存在, 如果不存在就会走异常中的代码 */
// context.openFileInput(fileName);
String[] filelists = context.fileList();
if (filelists != null && filelists.length > 0) {
for (String s : filelists) {
if (s != null && s.contains(fileName)) {
exist = true;//如果文件已经存在 那么就忽略拷贝操作 说明用户以前已经拷贝过此文件了
break;
}
}
}
return exist;
}
/**
* 将文件从assets目录中拷贝到app安装目录的files目录下
*/
public static void copyFromAssets2Data(Context context, String source,
String destination) throws IOException {
/* 获取assets目录下文件的输入流 */
InputStream is = context.getAssets().open(source);
/* 获取文件大小 */
int size = is.available();
/* 创建文件的缓冲区 */
byte[] buffer = new byte[size];
/* 将文件读取到缓冲区中 */
is.read(buffer);
/* 关闭输入流 */
is.close();
/* 打开app安装目录文件的输出流 */
FileOutputStream output = context.openFileOutput(destination, Context.MODE_PRIVATE);
/* 将文件从缓冲区中写出到内存中 */
output.write(buffer);
/* 关闭输出流 */
output.close();
}
/**
* 将文件从assets目录中拷贝到系统任意目录下,前提是有root权限
*/
public static void copyFromAssets2AnyDir(Context context, String source,
String destination, PermissionFileHandlerListener permissionFileHandlerListener) {
SystemUtil.log("copyFromAssets2AnyDir,source:" + source + ",destination:" + destination);
try {
/* 获取assets目录下文件的输入流 */
InputStream inStream = context.getAssets().open(source);
int byteread = 0;
FileOutputStream fs_out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
fs_out.write(buffer, 0, byteread);
}
fs_out.flush();
inStream.close();
if (permissionFileHandlerListener != null) permissionFileHandlerListener.onPermission(true, null);
} catch (Exception e) {
if (permissionFileHandlerListener != null)
permissionFileHandlerListener.onPermission(false, e.getMessage());
}
}
public static void giveThree6(final String filePath) {
String cmd_changeMode = "";
if (VariableKeeper.isUsingBusyBox) {
cmd_changeMode = VariableKeeper.app_path + VariableKeeper.busybox_cmd_name + " chmod 0666 " + filePath;
} else {
cmd_changeMode = "chmod 0666 " + filePath;
}
SystemUtil.exe(cmd_changeMode, new ShellExeListener() {
@Override
public void onExec(List<String> execResult) {
SystemUtil.log("give the file :" + filePath + ",results are:" + execResult);
}
});
}
//探测文件是否有666权限
public static boolean isThree6(List<String> results) {
boolean res = false;
for (String t : results) {
if (t.contains(VariableKeeper.three6_permisssion_string)) {
res = true;
break;
}
}
return res;
}
//如果设备没有666权限 则给予666权限 即文件权限控制在这里 只要外接usb设备挂接上来并且手机有root 那么所挂接的设备就会自动具备0666权限
public static void verifyDevice(final UsbCameraDevice ucd_tmp) {
String cmd_tmp = "";
if (VariableKeeper.isUsingBusyBox) {
cmd_tmp = VariableKeeper.app_path + VariableKeeper.busybox_cmd_name + " ls -l " + ucd_tmp.getDeviceName();
} else {
cmd_tmp = "ls -l " + ucd_tmp.getDeviceName();
}
//所有挂载上的设备 自动将权限改为0666
SystemUtil.exe(cmd_tmp, new ShellExeListener() {
@Override
public void onExec(List<String> execResult) {
boolean is666 = SystemUtil.isThree6(execResult);
SystemUtil.MyToast(ucd_tmp.getDeviceName() + " is:" + is666);
if (!is666) {
//赋予文件666权限
SystemUtil.giveThree6(ucd_tmp.getDeviceName());
}
}
});
//修改成功后将设备列表按照venderid和productid拼成串后存入sp 方便下次对比以发现是否有新设备接入系统
String old_devices = VariableKeeper.mSp.getString(VariableKeeper.three6_permission_device_sp_name, "");
String new_device_infor = ucd_tmp.getVendorId() + ":" + ucd_tmp.getProductId();
if (!"".equals(old_devices)) {
//判断旧的记录中是否有此设备的记录值
if (!old_devices.contains(new_device_infor)) {
old_devices = old_devices + ",";
new_device_infor = old_devices + new_device_infor;
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.three6_permission_device_sp_name, new_device_infor);
editor.commit();
}
} else {
SharedPreferences.Editor editor = VariableKeeper.mSp.edit();
editor.putString(VariableKeeper.three6_permission_device_sp_name, new_device_infor);
editor.commit();
}
}
public static byte[] toByteArray(InputStream input) throws Exception {
if (input == null) {
return null;
}
ByteArrayOutputStream output = null;
byte[] result = null;
try {
output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 100];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
result = output.toByteArray();
} finally {
closeQuietly(input);
closeQuietly(output);
}
return result;
}
public static void closeQuietly(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeQuietly(OutputStream os) {
try {
if (os != null) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static opencv_core.IplImage getIp1ImageFromBitmap(Bitmap mBitmap) {
opencv_core.IplImage grabbedImage = opencv_core.IplImage.create(mBitmap.getWidth(), mBitmap.getHeight(), IPL_DEPTH_8U, 4);
mBitmap.copyPixelsToBuffer(grabbedImage.getByteBuffer());
return grabbedImage;
}
public static void MyGC() {
if ((VariableKeeper.system_lastGC_ExecuteTime - System.currentTimeMillis()) > VariableKeeper.APP_CONSTANT.system_lastGC_DeltaTime) {
VariableKeeper.system_lastGC_ExecuteTime = System.currentTimeMillis();
SystemUtil.log("gc is running....");
System.gc();
}
}
public static Bitmap convertFileToBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 设置为ture只获取图片大小
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
// 返回为空
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
// 缩放
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int) scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
public static void recordStatusMonitor() {
//每2个时间脉冲检测一次刻录线程是否在工作
int flag = 0;
if (VariableKeeper.videoCaptures != null) {
for (int i = 0; i < VariableKeeper.APP_CONSTANT.size_num_cam; i++) {
if (VariableKeeper.videoCaptures[i] != null) {
if (VariableKeeper.videoCaptures[i].isStarted()) {
flag = 1;
}
for (RecordThreadStatusListener listener : VariableKeeper.threadStatusListeners) {
if (listener != null) {
listener.onStatus(i, flag, null);
}
}
flag = 0;
} else {
for (RecordThreadStatusListener listener : VariableKeeper.threadStatusListeners) {
if (listener != null) {
listener.onStatus(i, flag, null);
}
}
}
}
} else {
for (int i = 0; i < VariableKeeper.APP_CONSTANT.size_num_cam; i++) {
for (RecordThreadStatusListener listener : VariableKeeper.threadStatusListeners) {
if (listener != null) {
listener.onStatus(i, flag, null);
}
}
}
}
}
public static boolean phoneNumberCheck(String phone) {
return true;
}
public static void sendSms(String cellphoneNumber, String smsContent) {
SmsManager smsManager = SmsManager.getDefault();
String sms_content = VariableKeeper.getmCurrentActivity().getResources().getString(R.string.emergency_sms_test_text);
if (!"".equals(cellphoneNumber) && cellphoneNumber != null && phoneNumberCheck(cellphoneNumber)) {
if (sms_content.length() > 70) {
List<String> contents = smsManager.divideMessage(sms_content);
for (String sms : contents) {
smsManager.sendTextMessage(cellphoneNumber, null, sms, null, null);
}
} else {
smsManager.sendTextMessage(cellphoneNumber, null, sms_content, null, null);
}
SystemUtil.MyToast(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.emergency_sms_test_sucess));
} else {
SystemUtil.MyToast(VariableKeeper.getmCurrentActivity().getResources().getString(R.string.emergency_sms_no_phonenumber_text));
}
}
//判断设备是否具备通话能力即是手机还是平板电脑
public static boolean isTabletDevice() {
TelephonyManager telephony = (TelephonyManager) VariableKeeper.context.getSystemService(Context.TELEPHONY_SERVICE);
int type = telephony.getPhoneType();
boolean result = false;
if (type == TelephonyManager.PHONE_TYPE_NONE) {
result = false;
} else {
result = true;
}
return result;
}
public static void setDensity(BaseActivity activity) {
if (VariableKeeper.density != 0 || activity == null) {
return;
}
DisplayMetrics metric = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
VariableKeeper.density = metric.density; // 屏幕密度(0.75 / 1.0 / 1.5)
// Log.v("kxy", "-------------------------------screen width: " + metric.widthPixels + ", screen height: " + metric.heightPixels);
VariableKeeper.screenResolution = metric.widthPixels * metric.heightPixels;
VariableKeeper.screenWidth = metric.widthPixels;
VariableKeeper.screenHeight = metric.heightPixels;
VariableKeeper.screen = "" + metric.widthPixels + "*" + metric.heightPixels;
}
//如果是手机 则判断sim卡的状态即是否有sim卡
public static boolean isSimCardAvaiable(){
boolean haveSim = false;
TelephonyManager tm = (TelephonyManager)VariableKeeper.context.getSystemService(Context.TELEPHONY_SERVICE);//取得相关系统服务
StringBuffer sb = new StringBuffer();
switch(tm.getSimState()){ //getSimState()取得sim的状态 有下面6中状态
case TelephonyManager.SIM_STATE_ABSENT :sb.append("无卡");break;
case TelephonyManager.SIM_STATE_UNKNOWN :sb.append("未知状态");break;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED :sb.append("需要NetworkPIN解锁");break;
case TelephonyManager.SIM_STATE_PIN_REQUIRED :sb.append("需要PIN解锁");break;
case TelephonyManager.SIM_STATE_PUK_REQUIRED :sb.append("需要PUK解锁");break;
case TelephonyManager.SIM_STATE_READY :sb.append("良好");haveSim = true;break;
}
if(tm.getSimSerialNumber()!=null){
sb.append("@" + tm.getSimSerialNumber().toString());
}else{
sb.append("@无法取得SIM卡号");
}
if(tm.getSimOperator().equals("")){
sb.append("@无法取得供货商代码");
}else{
sb.append("@" + tm.getSimOperator().toString());
}
if(tm.getSimOperatorName().equals("")){
sb.append("@无法取得供货商");
}else{
sb.append("@" + tm.getSimOperatorName().toString());
}
if(tm.getSimCountryIso().equals("")){
sb.append("@无法取得国籍");
}else{
sb.append("@" + tm.getSimCountryIso().toString());
}
if (tm.getNetworkOperator().equals("")) {
sb.append("@无法取得网络运营商");
} else {
sb.append("@" + tm.getNetworkOperator());
}
if (tm.getNetworkOperatorName().equals("")) {
sb.append("@无法取得网络运营商名称");
} else {
sb.append("@" + tm.getNetworkOperatorName());
}
if (tm.getNetworkType() == 0) {
sb.append("@无法取得网络类型");
} else {
sb.append("@" + tm.getNetworkType());
}
log("sim 卡的状态:"+sb.toString());
return haveSim;
}
public static long getDirSize(File file) {
// freeBlocks * blockSize; //单位Byte
// (freeBlocks * blockSize)/1024; //单位KB
// long free_size = (freeBlocks * blockSize) / 1024 / 1024;//单位MB
//判断文件是否存在
if (file.exists()) {
//如果是目录则递归计算其内容的总大小
if (file.isDirectory()) {
File[] children = file.listFiles();
long size = 0;
for (File f : children)
size += getDirSize(f);
return size;
} else {//如果是文件则直接返回其大小,以“兆”为单位
long size = file.length();
return size;
}
} else {
log("文件或者文件夹不存在,请检查路径是否正确!");
return 0;
}
}
//探测dev下所有的视频设备 将权限更新为0666
public static void DevScanner() {
if (!VariableKeeper.isRooted) {
SystemUtil.log("设备未root 拒绝扫描dev目录");
return;
}
if ( VariableKeeper.isVideoDirScannable = false) {
SystemUtil.log("上次扫描dev目录后后无新设备到来 本次不扫描...");
return;
}
//只能是成root后的设备才能运行以下代码
//==================监视/dev/video*=================
String cmd_video_all = " ls /dev/";
SystemUtil.exe(cmd_video_all, new InterfaceGen.ShellExeListener() {
@Override
public void onExec(List<String> execResult) {
//更新VariableKeeper.SystemGlobalUsbVideoDevices中的设备列表
// SystemUtil.log("execResult size:"+execResult.size()+","+execResult);
List<UsbCameraDevice> usbCameraDevices = new ArrayList<UsbCameraDevice>();
for (String vid : execResult) {
if (vid.contains("video")) {
usbCameraDevices.add(new UsbCameraDevice(0, "", 0, 0, "/dev/" + vid, 0));
//将所有的video设备都变成666的权限
List<String> commnandList = new ArrayList<String>();
commnandList.add("chmod 0666 " + "/dev/" + vid);
ShellUtils.CommandResult result = ShellUtils.execCommand(commnandList, true);
SystemUtil.MyToast("/dev/" + vid + " is 666 already!");
}
}
if (usbCameraDevices.size() > 0) {
VariableKeeper.SystemGlobalVideoDevices = null;
VariableKeeper.SystemGlobalVideoDevices = new UsbCameraDevice[usbCameraDevices.size()];//此处数组的长度不可确定 所有需要动态确定
for (int i = 0; i < VariableKeeper.SystemGlobalVideoDevices.length; i++) {
VariableKeeper.SystemGlobalVideoDevices[i] = usbCameraDevices.get(i);
}
}
}
});
VariableKeeper.isVideoDirScannable = false;
//==================监视/dev/video*=================
}
public static void save2Cach(String path, byte[] image_jpg) {
if ("".equals(path) || path == null) {
return;
}
if (image_jpg == null || image_jpg.length <= 0) {
return;
}
File f = new File(path);
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
bos.write(image_jpg, 0, image_jpg.length);
bos.flush();
bos.close();
image_jpg = null;
} catch (FileNotFoundException e) {
SystemUtil.log(e.getMessage());
} catch (IOException e) {
log(e.getMessage());
}
}
public static boolean[] Int2BolArray(int x) {
if (x<0||x>15) {
return null;
}
boolean[] exsits = new boolean[4];
String arr_tmp = Integer.toBinaryString(x);
if (!"".equals(arr_tmp)&&arr_tmp!= null) {
if (arr_tmp.length() != 4 && arr_tmp.length()>0) {
//此时在位数的最左端补0
int i = 4- arr_tmp.length();
for (int j = 0;j< i ; j++){
arr_tmp = "0"+arr_tmp;
}
}
SystemUtil.log("camera int:"+arr_tmp);
for (int i = 0;i<arr_tmp.length();i++) {
if("1".equals( (arr_tmp.charAt(i)+"") ) ){
exsits[i] = true;
}else {
exsits[i] = false;
}
}
}
return exsits;
}
public static void logArray(boolean [] objs) {
if (objs == null) {
return;
}
if (objs.length == 0) {
return;
}
String result = "";
for (Object o:objs) {
result+= (o.toString()+",");
}
log(result);
}
}
|
Python
|
UTF-8
| 409 | 3.53125 | 4 |
[] |
no_license
|
print(""" ******************************
Girilen Sayıların Toplamını Hesaplama
Çıkmak için "q" Basınız...
******************************
""")
toplam = 0
sayi = input("Değer Giriniz: ")
while True:
if (sayi=="q"):
print("Hoşçakalın")
break
sayi = int(sayi)
toplam = toplam + sayi
sayi = input("Değer Giriniz: ")
print("Girdiğiniz sayıların toplamı:",toplam)
|
Markdown
|
UTF-8
| 6,468 | 2.8125 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
# auro-counter
`<auro-counter>` is a [HTML custom element](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) for the purpose of ...
## UI development browser support
For the most up to date information on [UI development browser support](https://auro.alaskaair.com/support/browsersSupport)
## Install
[](https://github.com/AlaskaAirlines/auro-counter/actions?query=workflow%3A%22test+and+publish%22)
[](https://www.npmjs.com/package/@alaskaairux/auro-counter)
[](https://www.apache.org/licenses/LICENSE-2.0)
```shell
$ npm i @alaskaairux/auro-counter
```
Installing as a direct, dev or peer dependency is up to the user installing the package. If you are unsure as to what type of dependency you should use, consider reading this [stack overflow](https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencies) answer.
### Design Token CSS Custom Property dependency
The use of any Auro custom element has a dependency on the [Auro Design Tokens](https://auro.alaskaair.com/getting-started/developers/design-tokens).
### CSS Custom Property fallbacks
[CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) are [not supported](https://auro.alaskaair.com/support/custom-properties) in older browsers. For this, fallback properties are pre-generated and included with the npm.
Any update to the Auro Design Tokens will be immediately reflected with browsers that support CSS custom properties, legacy browsers will require updated components with pre-generated fallback properties.
### Define dependency in project component
Defining the component dependency within each component that is using the `<auro-counter>` component.
```javascript
import "@alaskaairux/auro-counter";
```
**Reference component in HTML**
```html
<auro-counter></auro-counter>
```
## Install bundled assets from CDN
In cases where the project is not able to process JS assets, there are pre-processed assets available for use. Two bundles are available -- `auro-counter__bundled.js` for modern browsers and `auro-counter__bundled.es5.js` for legacy browsers (including IE11).
Since the legacy bundle includes many polyfills that are not needed by modern browsers, we recommend you load these bundles using [differential serving](https://philipwalton.com/articles/deploying-es2015-code-in-production-today/) so that the browser only loads the bundle it needs. To accomplish this, the script tag for the modern bundle should have `type="module"` and the script tag for the legacy bundle should have the `nomodule` attribute. See the example below.
**NOTE:** Be sure to replace `@latest` in the URL with the version of the asset you want. @latest is NOT aware of any MAJOR releases, use at your own risk.
```html
<link rel="stylesheet" href="https://unpkg.com/@alaskaairux/design-tokens@latest/dist/tokens/CSSCustomProperties.css" />
<link rel="stylesheet" href="https://unpkg.com/@alaskaairux/webcorestylesheets@latest/dist/bundled/essentials.css" />
<script src="https://unpkg.com/@alaskaairux/auro-counter@latest/dist/auro-counter__bundled.js" type="module"></script>
<script src="https://unpkg.com/@alaskaairux/auro-counter@latest/dist/auro-counter__bundled.es5.js" nomodule></script>
```
## auro-counter use cases
The `auro-counter` component renders a basic numerical counter which can be manually increased and decreased by clicking on + and - buttons. Optionally, the component also supports value changes using the keyboard arrow keys. Minimum and maximum values are also supported which can be used in combination to constrain upper and lower bounds.
## Optional Parameters
`auro-counter` supports multiple parameters to control interaction and constraints.
### Setting the values and constraints of the counter
* `currentValue` Start the counter at a given integer value; defaults to 0
* `minValue` Set the lower boundary as an integer value, null value has no lower boundary; defaults to null
* `maxValue` Set the upper boundary as an integer value, null value has no upper boundary; defaults to null
### Defining keyboard controls
Default web client behavior is to scroll the page content when pressing the keyboard arrow keys. Optionally, the `auro-counter` component can override the behavior and use those keys to control the counter.
* `udKeys` Short for "up down Keys". When included the up arrow key will increase the counter value by 1 and the down arrow key will decrease the value by 1.
* `lrKeys` Short for "left right Keys". When included the right arrow key will increase the counter value by 1 and the left arrow key will decrease the value by 1.
## API Code Examples
Default `auro-counter`
```html
<auro-counter></auro-counter>
```
`auro-counter` with all options in use
```html
<auro-counter
currentValue="0"
minValue="0"
maxValue="10"
udKeys
lrKeys>
</auro-counter>
```
## Development
In order to develop against this project, if you are not part of the core team, you will be required to fork the project prior to submitting a pull request.
Please be sure to review the [contribution guidelines](https://auro.alaskaair.com/getting-started/developers/contributing) for this project. Please make sure to **pay special attention** to the **conventional commits** section of the document.
### Start development environment
Once the project has been cloned to your local resource and you have installed all the dependencies you will need to open two different shell sessions. One is for the **npm tasks**, the second is to run the **server**.
```shell
// shell terminal one
$ npm run dev
// shell terminal two
$ npm run serve
```
Open [localhost:8000](http://localhost:8000/)
### Testing
Automated tests are required for every Auro component. See `.\test\auro-counter.test.js` for the tests for this component. Run `npm test` to run the tests and check code coverage. Tests must pass and meet a certain coverage threshold to commit. See [the testing documentation](https://auro.alaskaair.com/support/tests) for more details.
|
C#
|
UTF-8
| 774 | 2.5625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrackSystem {
class Filler {
public static void Fill (out Developer developer, out Tester tester, int sample) {
developer = new Developer (sample);
tester = new Tester (sample);
}
public static void Fill (out Developer developer, int sample) {
developer = new Developer (sample);
}
public static void Fill ( out Tester tester, int sample) {
tester = new Tester (sample);
}
public static void Fill (out Tasks task, int sample) {
task = new Tasks (sample);
}
}
}
|
Python
|
UTF-8
| 1,648 | 3.15625 | 3 |
[] |
no_license
|
import unittest
from pipe import Parallelepiped, select, where, concat
class TestPipes(unittest.TestCase):
def test_parallelepiped(self):
par0 = (range(100) | where(lambda x: x % 2 == 1)
| select(lambda x: x ** 2)
| select(lambda x: x - 1)
| where(lambda x: x < 50))
par1 = (range(100) | where(lambda x: x % 2 == 1)
| (Parallelepiped() | select(lambda x: x ** 2))
| select(lambda x: x - 1)
| where(lambda x: x < 50))
par2 = (range(100) | where(lambda x: x % 2 == 1)
| (Parallelepiped() | select(lambda x: x ** 2)
| select(lambda x: x - 1))
| where(lambda x: x < 50))
l0 = list(par0)
l1 = list(par1)
l2 = list(par2)
self.assertEqual(l0, l1)
self.assertEqual(l0, l2)
def test_right_or(self):
ror_piped = (range(100) | where(lambda x: x % 2 == 1)
| select(lambda x: x ** 2)
| select(lambda x: x - 1)
| where(lambda x: x < 50))
or_pipe = (where(lambda x: x % 2 == 1) | select(lambda x: x ** 2)
| select(lambda x: x - 1)
| where(lambda x: x < 50))
lror = list(ror_piped)
lor = list(range(100) | or_pipe)
self.assertEqual(lror, lor)
if __name__ == '__main__':
unittest.main()
|
Java
|
UTF-8
| 489 | 2.015625 | 2 |
[] |
no_license
|
package genlab.igraph.algos.readers;
import genlab.core.exec.IExecution;
import genlab.core.model.instance.IAlgoInstance;
import genlab.core.model.meta.basics.graphs.IGenlabGraph;
public class ReadLGLExec extends AbstractIGraphReaderExec {
public ReadLGLExec(IExecution exec, IAlgoInstance algoInst) {
super(exec, algoInst);
}
public ReadLGLExec() {
}
@Override
protected IGenlabGraph readGraph(String filename) {
return getLibrary().readGraphLGL(filename, exec);
}
}
|
Markdown
|
UTF-8
| 1,076 | 2.53125 | 3 |
[] |
no_license
|
---
title: 'DIY Devs: Helpful Guides for Learning How to Code'
customTitleTag: 'DIY Devs: Helpful Guides for Learning How to Code'
date: 2019-10-26 12:09:47
description: Hi there, I'm John, and I've put together a number of guides and posts to help you learn how to code and become a developer.
share_cover: /img/share-img/main-page-cover-image-plain-2.png
---
_Hi there, I'm John, and I've put together a number of guides and posts to help you learn how to code and become a developer._
Here is the list of guides I've written so far:
- [The Best Way to Learn JavaScript for Free](/learn-javascript/)
- ~~No Budget Coding Bootcamp~~ (coming very soon)
- ~~JavaScript Crash Course~~ (coming soon)
<!-- You can learn more about me on [my about page](/about/). -->
Subscribe to the <a href="/rss2.xml" target="_blank">RSS feed</a>, or [follow me on Twitter](https://twitter.com/JohnTurnerPGH), to find out when new guides and resources are released.
<!-- (you can use a service like [Blogtrottr](https://blogtrottr.com/) to get RSS updates delivered to you via email) -->
|
Markdown
|
UTF-8
| 8,742 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
import { Callout } from '../../components/Callout';
## Install using a docker image
The docker image is probably the simplest installation use case, since it includes all dependencies and works standalone.
There are two "flavors", [RoadRunner](https://roadrunner.dev/)-based and [openswoole](https://openswoole.com/)-based. [See more details](#runtime-variations)
<Callout type="info">
Shlink docker images are published both in [Docker hub](https://hub.docker.com/r/shlinkio/shlink) and [Github Container Registry](https://github.com/shlinkio/shlink/pkgs/container/shlink).
All examples use Docker hub images. In order to install images from Github Container Registry, use `ghcr.io/shlinkio/shlink` instead of `shlinkio/shlink`.
</Callout>
### Usage
The most basic way to run Shlink's docker image is by providing these mandatory env vars.
* `DEFAULT_DOMAIN`: The custom short domain used for this Shlink instance. For example **s.test**.
* `IS_HTTPS_ENABLED`: Either **true** or **false**.
* `GEOLITE_LICENSE_KEY`: Your GeoLite2 license key. [Learn more](/documentation/geolite-license-key/) about this.
To run Shlink on top of a local docker service, and using an internal SQLite database, do the following:
```bash
docker run \
--name my_shlink \
-p 8080:8080 \
-e DEFAULT_DOMAIN=s.test \
-e IS_HTTPS_ENABLED=true \
-e GEOLITE_LICENSE_KEY=kjh23ljkbndskj345 \
shlinkio/shlink:stable
```
#### Generate first API key
Once the Shlink container is running, you can interact with the [CLI entry point](/documentation/command-line-interface/entry-point) by running `shlink` with any of the supported commands.
One of the main reasons you would want to do that, is to generate your first API key. For example, if the container is called `my_shlink`, you can do it with:
```bash
docker exec -it my_shlink shlink api-key:generate
```
If you can't interact with the container's shell (for example, when running Shlink in [Google Cloud Run](https://cloud.google.com/run) or similar), or if you wish to provide an initial API key yourself, starting with Shlink 3.3.0, you can do so by providing the `INITIAL_API_KEY` env var with an API key of your choice.
```bash
docker run \
--name my_shlink \
[...] \
-e INITIAL_API_KEY=<super_secure_api_key> \
shlinkio/shlink:stable
```
#### Interact with Shlink's CLI on a running container.
Generating the first API key is not the only thing you can do with Shlink's CLI entry point inside the container's shell.
You can also list all tags:
```bash
docker exec -it my_shlink shlink tag:list
```
Or locate remaining visits:
```bash
docker exec -it my_shlink shlink visit:locate
```
All Shlink commands will work the same way.
You can also list all available commands by just running this:
```bash
docker exec -it my_shlink shlink
```
### Use an external DB
The image comes with a working SQLite database, but in production, it's strongly recommended using a distributed database.
It is possible to use a set of env vars to make this Shlink instance interact with an external MySQL, MariaDB, PostgreSQL or Microsoft SQL Server database.
* `DB_DRIVER`: **[Mandatory]**. Use the value **mysql**, **maria**, **postgres** or **mssql** to prevent the SQLite database to be used.
* `DB_NAME`: [Optional]. The database name to be used. Defaults to **shlink**.
* `DB_USER`: **[Mandatory]**. The username credential for the database server.
* `DB_PASSWORD`: **[Mandatory]**. The password credential for the database server.
* `DB_HOST`: **[Mandatory]**. The host name of the server running the database engine.
* `DB_PORT`: [Optional]. The port in which the database service is running.
* Default value is based on the value provided for `DB_DRIVER`:
* **mysql** or **maria** -> `3306`
* **postgres** -> `5432`
* **mssql** -> `1433`
> PostgreSQL is supported since v1.16.1 and Microsoft SQL server since v2.1.0. Do not try to use them with previous versions.
Taking this into account, you could run Shlink on a local docker service like this:
```bash
docker run \
--name my_shlink \
-p 8080:8080 \
-e DEFAULT_DOMAIN=s.test \
-e IS_HTTPS_ENABLED=true \
-e GEOLITE_LICENSE_KEY=kjh23ljkbndskj345 \
-e DB_DRIVER=mysql \
-e DB_USER=root \
-e DB_PASSWORD=123abc \
-e DB_HOST=something.rds.amazonaws.com \
shlinkio/shlink:stable
```
You could even link to a local database running on a different container:
```bash
docker run \
--name my_shlink \
-p 8080:8080 \
[...] \
-e DB_HOST=some_mysql_container \
--link some_mysql_container \
shlinkio/shlink:stable
```
> If you have considered using SQLite but sharing the database file with a volume, read [this issue](https://github.com/shlinkio/shlink-docker-image/issues/40) first.
### Other integrations
#### Use an external redis server
If you plan to run more than one Shlink instance, there are some resources that should be shared ([Multi instance considerations](/documentation/install-docker-image#multi-instance-considerations)).
One of those resources are the locks Shlink generates to prevent some operations to be run more than once in parallel. You can find more information [here](/documentation/advanced/using-redis/#shared-locks).
#### Integrations for real-time updates
Shlink supports sending real-time updates to some queueing systems, like [Mercure]((https://mercure.rocks/)), [RabbitMQ](https://www.rabbitmq.com/) or [Redis pub/sub](https://redis.io/docs/manual/pubsub/).
Check the [real-time updates](/documentation/advanced/real-time-updates) section to get more details on how to integrate with them.
### Supported env vars
A few env vars have been already used in previous examples, but this image supports others that can be used to customize its behavior.
See the full list of supported [Environment variables](/documentation/environment-variables).
### Multi-architecture
Starting on v2.3.0, Shlink's docker image is built for multiple architectures.
The only limitation is that images for architectures other than `amd64` will not have support for Microsoft SQL databases, since there are no official binaries.
### Multi-instance considerations
These are some considerations to take into account when running multiple Shlink instances.
* Some operations performed by Shlink should never be run more than once at the same time (like creating the database for the first time, or downloading the GeoLite2 database). For this reason, Shlink uses a locking system.
However, these locks are locally scoped to each Shlink instance by default.
You can (and should) make the locks to be shared by all Shlink instances by using a redis server/cluster. Just define the `REDIS_SERVERS` env var with the list of servers.
### Versions
Versioning on this docker image works as follows:
* `X.X.X`: when providing a specific version number, the image version will match the Shlink version it contains. For example, installing `shlinkio/shlink:2.9.1`, you will get an image containing Shlink v2.9.1.
* `stable`: always holds the latest stable tag. For example, if latest Shlink version is 3.0.0, installing `shlinkio/shlink:stable`, you will get an image containing shlink v3.0.0
* `latest`: always holds the latest contents, and it's considered unstable and not suitable for production.
#### Runtime variations
Before Shlink 3.6.0, you had to add `-roadrunner` to the tag you wanted to install in order to get an image using RoadRunner (for example, `shlinkio/shlink:stable-roadrunner` or `shlinkio/shlink:3.4.0-roadrunner`).
Starting with v3.6.0, you can add `-roadrunner` or `-openswoole` to the tag name to make sure you get an image using a specific runtime, otherwise, you will get the default one, which is unlikely, but open to change.
As of today, RoadRunner is the default runtime. Both runtimes are mostly compatible and should be possible to change from one image to the other transparently, so **it's ok to use docker tags with no suffix**.
#### Non-root
For historical reasons, Shlink docker image runs as root. If it's important for you to run it as non-root, add `-non-root` to the tag name, like `shlinkio/shlink:stable-non-root`.
These images have two considerations: they always run with the default runtime (RoadRunner as of today), and the `ENABLE_PERIODIC_VISIT_LOCATE` env var will be ignored, as it requires root privileges.
<Callout type="warning" title="Considerations">
* There are no versions older than 3.0.0 published in GitHub Container registry.
* RoadRunner-based images are only available since v3.3.0
* Default runtime has changed from openswoole to RoadRunner in v3.6.0
* `non-root` docker images are only available since v3.6.0
</Callout>
|
C#
|
UTF-8
| 2,430 | 2.796875 | 3 |
[] |
no_license
|
using System;
using System.Data;
namespace Banking.Repository.Repositories.AdoNET
{
public static class DataReaderExtensiones
{
public static short GetValueInt16(this IDataReader reader, int ordinal)
{
short value = 0;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetInt16(ordinal);
}
return value;
}
public static int GetValueInt32(this IDataReader reader, int ordinal)
{
var value = 0;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetInt32(ordinal);
}
return value;
}
public static decimal GetValueDecimal(this IDataReader reader, int ordinal)
{
decimal value = 0;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetDecimal(ordinal);
}
return value;
}
public static string GetValueString(this IDataReader reader, int ordinal)
{
var value = string.Empty;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetString(ordinal);
}
return value;
}
public static DateTime GetValueDateTime(this IDataReader reader, int ordinal)
{
var value = DateTime.MinValue;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetDateTime(ordinal);
}
return value;
}
public static Boolean GetValueBoolean(this IDataReader reader, int ordinal)
{
var value = false;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetBoolean(ordinal);
}
return value;
}
public static Guid GetValueGuid(this IDataReader reader, int ordinal)
{
Guid value = default(Guid);
if (!reader.IsDBNull(ordinal))
{
value = reader.GetGuid(ordinal);
}
return value;
}
public static byte GetValueByte(this IDataReader reader, int ordinal)
{
byte value = 0;
if (!reader.IsDBNull(ordinal))
{
value = reader.GetByte(ordinal);
}
return value;
}
}
}
|
Ruby
|
UTF-8
| 557 | 3.78125 | 4 |
[] |
no_license
|
# Look at Ruby's merge method. Notice that it has two versions. What is the difference between merge and merge!? Write a program that uses both and illustrate the differences.
action_movies = { first_blood: 1984, predator: 1987, alien: 1988 }
comedies = { kings_speech: 2011, just_go_with_it: 2012, father_of_the_bride: 2001 }
# #merge doesn't mutate the caller
all_movies = action_movies.merge(comedies)
p action_movies: action_movies, comedies: comedies
# unlike #merge!
action_movies.merge!(comedies)
p action_movie: action_movies, comedies: comedies
|
JavaScript
|
UTF-8
| 6,141 | 3.28125 | 3 |
[] |
no_license
|
var c1 = document.getElementById("choice1");
var c2 = document.getElementById("choice2");
var c3 = document.getElementById("choice3");
var c4 = document.getElementById("choice4");
var hat = document.getElementById("hat");
var shirt = document.getElementById("shirt");
var pants = document.getElementById("pants");
var shoes = document.getElementById("shoes");
var prev = document.getElementById("prev");
var next = document.getElementById("next");
var comboText = document.getElementById("comboText");
var hatcount = 0;
var shirtcount = 0;
var pantcount = 0;
var shoecount = 0;
next.addEventListener("click", function() {
if(c1.checked){
if(hatcount == 0){
hat.src = "imgs/gears/h2.png";
hatcount = 1;
} else if(hatcount == 1){
hat.src = "imgs/gears/h3.png";
hatcount = 2;
} else if(hatcount == 2){
hat.src = "imgs/gears/h1.png";
hatcount = 0;
}
} else if(c2.checked){
if(shirtcount == 0){
shirt.src = "imgs/gears/b2.png";
shirtcount = 1;
} else if(shirtcount == 1){
shirt.src = "imgs/gears/b3.png";
shirtcount = 2;
} else if(shirtcount == 2){
shirt.src = "imgs/gears/b1.png";
shirtcount = 0;
}
} else if(c3.checked){
if(pantcount == 0){
pants.src = "imgs/gears/l2.png";
pantcount = 1;
} else if(pantcount == 1){
pants.src = "imgs/gears/l3.png";
pantcount = 2;
} else if(pantcount == 2){
pants.src = "imgs/gears/l1.png";
pantcount = 0;
}
} else if(c4.checked){
if(shoecount == 0){
shoes.src = "imgs/gears/f2.png";
shoecount = 1;
} else if (shoecount == 1){
shoes.src = "imgs/gears/f3.png";
shoecount = 2;
} else if (shoecount == 2){
shoes.src = "imgs/gears/f1.png";
shoecount = 0;
}
} else{
alert("Choose an option.");
}
});
prev.addEventListener("click", function(){
if(c1.checked){
if(hatcount == 0){
hat.src = "imgs/gears/h3.png";
hatcount = 2;
} else if(hatcount == 1){
hat.src = "imgs/gears/h1.png";
hatcount = 0;
} else if(hatcount == 2){
hat.src = "imgs/gears/h2.png";
hatcount = 1;
}
} else if(c2.checked){
if (shirtcount == 0){
shirt.src = "imgs/gears/b3.png";
shirtcount = 2;
} else if(shirtcount == 1){
shirt.src = "imgs/gears/b1.png";
shirtcount = 0;
} else if(shirtcount == 2){
shirt.src = "imgs/gears/b2.png";
shirtcount = 1;
}
} else if(c3.checked){
if (pantcount == 0){
pants.src = "imgs/gears/l3.png";
pantcount = 2;
} else if(pantcount == 1){
pants.src = "imgs/gears/l1.png";
pantcount = 0;
} else if(pantcount == 2){
pants.src = "imgs/gears/l2.png";
pantcount = 1;
}
} else if(c4.checked){
if (shoecount == 0){
shoes.src = "imgs/gears/f3.png";
shoecount = 2;
} else if(shoecount == 1){
shoes.src = "imgs/gears/f1.png";
shoecount = 0;
} else if(shoecount == 2){
shoes.src = "imgs/gears/f2.png";
shoecount = 1;
}
} else{
alert("Choose an option.");
}
});
comboText.addEventListener("keyup", function(ev){
if(ev.keyCode == 13){
if(comboText.value == "combo1"){
hat.src = "imgs/gears/h1.png";
shirt.src = "imgs/gears/b1.png";
pants.src = "imgs/gears/l1.png";
shoes.src = "imgs/gears/f1.png";
hatcount = 0;
shirtcount = 0;
pantcount = 0;
shoecount = 0;
} else if(comboText.value == "combo2"){
hat.src = "imgs/gears/h2.png";
shirt.src = "imgs/gears/b2.png";
pants.src = "imgs/gears/l2.png";
shoes.src = "imgs/gears/f2.png";
hatcount = 1;
shirtcount = 1;
pantcount = 1;
shoecount = 1;
} else if(comboText.value == "combo3"){
hat.src = "imgs/gears/h3.png";
shirt.src = "imgs/gears/b3.png";
pants.src = "imgs/gears/l3.png";
shoes.src = "imgs/gears/f3.png";
hatcount = 2;
shirtcount = 2;
pantcount = 2;
shoecount = 2;
} else if(comboText.value == "random"){
hatcount = getRandomInt(0,3);
if (hatcount == 0){
hat.src = "imgs/gears/h1.png";
} else if (hatcount == 1){
hat.src = "imgs/gears/h2.png";
} else if (hatcount == 2){
hat.src = "imgs/gears/h3.png";
}
shirtcount = getRandomInt(0,3);
if (shirtcount == 0){
shirt.src = "imgs/gears/b1.png";
} else if (shirtcount == 1){
shirt.src = "imgs/gears/b2.png";
} else if (shirtcount == 2){
shirt.src = "imgs/gears/b3.png";
}
pantcount = getRandomInt(0,3);
if (pantcount == 0){
pants.src = "imgs/gears/l1.png";
} else if (pantcount == 1){
pants.src = "imgs/gears/l2.png";
} else if (pantcount == 2){
pants.src = "imgs/gears/l3.png";
}
shoecount = getRandomInt(0,3);
if (shoecount == 0){
shoes.src = "imgs/gears/f1.png";
} else if (shoecount == 1){
shoes.src = "imgs/gears/f2.png";
} else if (shoecount == 2){
shoes.src = "imgs/gears/f3.png";
}
}
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1) ) + min;
};
};
});
|
Java
|
UTF-8
| 21,128 | 2.078125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.senacrs.view;
import br.com.senacrs.Dao.UsuarioDao;
import br.com.senacrs.model.Usuario;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author 181810025
*/
public class FrmManterUsuarios extends javax.swing.JFrame {
public FrmManterUsuarios() {
initComponents();
setLocationRelativeTo(null);
DefaultTableModel modelo = (DefaultTableModel) tbPesquisar.getModel();
tbPesquisar.setRowSorter(new TableRowSorter(modelo));
readJTable();
}
public void readJTable() {
DefaultTableModel modelo = (DefaultTableModel) tbPesquisar.getModel();
modelo.setNumRows(0);
UsuarioDao udao = new UsuarioDao();
for (Usuario u : udao.read()) {
modelo.addRow(new Object[]{
u.getIdUsu(),
u.getNomeUsu(),
u.getLoginUsu(),
u.getSenhaUsu()
});
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane2 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
edCodigo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
edNomeUsu = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
edLoginUsu = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
edSenha = new javax.swing.JPasswordField();
btSalvar = new javax.swing.JButton();
btAlterar = new javax.swing.JButton();
btExcluir = new javax.swing.JButton();
edPesquisa = new javax.swing.JTextField();
btPesquisar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tbPesquisar = new javax.swing.JTable();
jPanel4 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setBackground(new java.awt.Color(0, 102, 51));
jPanel1.setBackground(new java.awt.Color(0, 102, 102));
jPanel1.setForeground(new java.awt.Color(0, 153, 153));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText(" CONTROLE DE USUÁRIOS");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(163, 163, 163)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jLabel1)
.addContainerGap(53, Short.MAX_VALUE))
);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setText("Código");
edCodigo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
edCodigoActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("Nome do Usuário");
edNomeUsu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
edNomeUsuActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setText("login do Usuário");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel5.setText("Senha");
edSenha.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
edSenhaActionPerformed(evt);
}
});
btSalvar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMG/iconfinder_save_101249.png"))); // NOI18N
btSalvar.setText("Slavar");
btSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSalvarActionPerformed(evt);
}
});
btAlterar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMG/iconfinder_administrator1_(edit)_16x16_9715.gif"))); // NOI18N
btAlterar.setText("Alterar");
btAlterar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btAlterarActionPerformed(evt);
}
});
btExcluir.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMG/iconfinder_trash_100984.png"))); // NOI18N
btExcluir.setText("Excluir");
btExcluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btExcluirActionPerformed(evt);
}
});
btPesquisar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btPesquisar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMG/iconfinder_search_4103.png"))); // NOI18N
btPesquisar.setText("Pesquisar");
btPesquisar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btPesquisarActionPerformed(evt);
}
});
tbPesquisar.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Código ", "Nome Usuário", "Login Usuário", "Senha"
}
));
tbPesquisar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbPesquisarMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tbPesquisar);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 14, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(10, 10, 10)
.addComponent(edCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(27, 27, 27)
.addComponent(edNomeUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(35, 35, 35)
.addComponent(edLoginUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(56, 56, 56)
.addComponent(edSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addComponent(btAlterar)
.addGap(54, 54, 54)
.addComponent(btExcluir)
.addGap(17, 17, 17)
.addComponent(edPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37)
.addComponent(btPesquisar))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 736, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 15, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(edCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(edNomeUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(edLoginUsu, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(edSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(btSalvar))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(btAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(btExcluir))
.addComponent(edPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(btPesquisar)))
.addGap(15, 15, 15)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Cadastro/Consulta", jPanel2);
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTabbedPane1.addTab("", jPanel4);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTabbedPane1)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(35, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void tbPesquisarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbPesquisarMouseClicked
if (tbPesquisar.getSelectedRow() != -1) {
edCodigo.setText(tbPesquisar.getValueAt(tbPesquisar.getSelectedRow(), 0).toString());
edNomeUsu.setText(tbPesquisar.getValueAt(tbPesquisar.getSelectedRow(), 1).toString());
edLoginUsu.setText(tbPesquisar.getValueAt(tbPesquisar.getSelectedRow(), 2).toString());
edSenha.setText(tbPesquisar.getValueAt(tbPesquisar.getSelectedRow(), 3).toString());
}
}//GEN-LAST:event_tbPesquisarMouseClicked
private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
readForDesc(edPesquisa.getText());
}//GEN-LAST:event_btPesquisarActionPerformed
private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
if (tbPesquisar.getSelectedRow() != -1) {
Usuario u = new Usuario();
UsuarioDao dao = new UsuarioDao();
u.setIdUsu((int) tbPesquisar.getValueAt(tbPesquisar.getSelectedRow(), 0));
dao.delete(u);
edCodigo.setText("");
edNomeUsu.setText("");
edLoginUsu.setText("");
edSenha.setText("");
readJTable();
} else {
JOptionPane.showMessageDialog(null, "Selecione um produto para excluir.");
}
}//GEN-LAST:event_btExcluirActionPerformed
private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
if (tbPesquisar.getSelectedRow() != -1) {
Usuario u = new Usuario();
UsuarioDao dao = new UsuarioDao();
u.setNomeUsu(edNomeUsu.getText());
u.setLoginUsu(edLoginUsu.getText());
u.setSenhaUsu(edSenha.getText());
u.setIdUsu((int) tbPesquisar.getValueAt(tbPesquisar.getSelectedRow(), 0));
dao.update(u);
edCodigo.setText("");
edNomeUsu.setText("");
edLoginUsu.setText("");
edSenha.setText("");
readJTable();
}
}//GEN-LAST:event_btAlterarActionPerformed
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
Usuario u = new Usuario();
UsuarioDao dao = new UsuarioDao();
u.setNomeUsu(edNomeUsu.getText());
u.setLoginUsu(edLoginUsu.getText());
u.setSenhaUsu(edSenha.getText());
dao.create(u);
edCodigo.setText("");
edNomeUsu.setText("");
edLoginUsu.setText("");
edSenha.setText("");
readJTable();
}//GEN-LAST:event_btSalvarActionPerformed
private void edSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edSenhaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_edSenhaActionPerformed
private void edNomeUsuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edNomeUsuActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_edNomeUsuActionPerformed
private void edCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edCodigoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_edCodigoActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmManterUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmManterUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmManterUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmManterUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmManterUsuarios().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btAlterar;
private javax.swing.JButton btExcluir;
private javax.swing.JButton btPesquisar;
private javax.swing.JButton btSalvar;
private javax.swing.JTextField edCodigo;
private javax.swing.JTextField edLoginUsu;
private javax.swing.JTextField edNomeUsu;
private javax.swing.JTextField edPesquisa;
private javax.swing.JPasswordField edSenha;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTabbedPane jTabbedPane2;
private javax.swing.JTable tbPesquisar;
// End of variables declaration//GEN-END:variables
private void readForDesc(String text) {
}
}
|
Python
|
UTF-8
| 546 | 3.671875 | 4 |
[] |
no_license
|
# Задача A-Шестнадцатеричные и двоичные
# Вычислите XOR от двух чисел.
# Логическая операция "исключающее или".
# FALSE XOR FALSE = FALSE
# FALSE XOR TRUE =TRUE
# TRUE XOR FALSE =TRUE
# TRUE XOR TRUE =FALSE
# Операция дает FALSE если операнды равны не зависимо от них. Еще одно название "Сложение по модулю 2"
x, y = input().split()
x = int(x, 16)
y = int(y, 16)
print(hex(x ^ y)[2:])
|
PHP
|
UTF-8
| 712 | 2.953125 | 3 |
[] |
no_license
|
<?php
require_once __DIR__ . "\AbstractController.php";
require_once __DIR__ . "\..\Models\Product.php";
class SearchController extends AbstractController
{
// This method searches for products in the database and adds them to an array
function search()
{
$searchTerm = $this->request->GET("searchTerm");
$query = "SELECT * FROM produkte WHERE LOWER(Name) LIKE '%$searchTerm%'";
$result = $this->database->query($query);
$products = array();
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
array_push($products,$row);
}
}
echo json_encode($products);
}
}
|
C++
|
UTF-8
| 371 | 2.640625 | 3 |
[] |
no_license
|
#include <cstdint>
#include <algorithm>
union Tstamp {
uint64_t value;
uint16_t shorts[4];
};
extern "C" {
std::uint64_t getEventTimestamp(void* pBody) {
uint16_t* pData = reinterpret_cast<uint16_t*>(pBody);
pData += 7; // traverse to the tstamp output
Tstamp tstamp;
std::copy(pData, pData+4, tstamp.shorts);
return tstamp.value;
}
}
|
Markdown
|
UTF-8
| 5,919 | 2.5625 | 3 |
[] |
permissive
|
Fuel REST Client (for Node.js) [](https://travis-ci.org/salesforce-marketingcloud/FuelSDK-Node-REST) [](https://greenkeeper.io/)
=============
**This repo used to be located at https://github.com/exacttarget/Fuel-Node-REST**
This library allows users access to the Salesforce Marketing Cloud REST API at a low level.
## Support
The Salesforce Marketing Cloud SDKs are community-supported projects. The SDK source code, samples, and documentation are publicly available on Github to use as-is or fork and modify for your needs. We invite everyone in the community to collaborate with us on Github and submit pull requests to help improve the source code and samples.
* Post questions on [StackExchange](https://salesforce.stackexchange.com/questions/tagged/marketing-cloud).
* Submit ideas and suggestions to the [Trailblazer Community](https://success.salesforce.com/ideaSearch?sort=2&filter=Marketing+Cloud).
* File issues and feature requests here on Github.
## Installation
```
npm install fuel-rest --save
yarn add fuel-rest
```
## Initialization
**new FuelRest(options)** - Initialization
* `options.auth`
* Required: yes
* Type: `Object` or [FuelAuth Instance][1]
* properties need to match [FuelAuth][1]
* `options.origin` or `options.restEndpoint`
* Required: no
* Type: `String`
* Default: https://www.exacttargetapis.com
* `options.headers`
* Required: no
* Type: `Object`
* set headers that apply to all REST requests (not auth requests)
* `options.globalReqOptions`
* Required: no
* Type: `Object`
* set configuration options that apply to all requests (auth + REST)
## API
* **apiRequest(options, callback)**
* `options` - [see request modules options][3]
* `options.auth` - will be passed into [getAccessToken][4] inside Fuel Auth
* `options.uri` - can either be a full url or a path that is appended to `options.origin` used at initialization ([url.resolve][2])
* `options.retry` - boolean value representing whether or not to retry request (and request new token) on 401 invalid token response. `default: false`
* `callback` - executed after task is completed.
* if no callback is passed, you'll need to use the promise interface
* **get | post | put | patch | delete(options, callback)**
* `options` - see apiRequest options
* `options.retry` - see above for description. `default: true`
* `callback` - see apiRequest options
* Request method will be overwritten by these methods. It will be set to same value as the name of the method used
## Setting up the client
```js
const FuelRest = require('fuel-rest');
const options = {
auth: {
// options you want passed when Fuel Auth is initialized
clientId: 'clientId',
clientSecret: 'clientSecret'
},
origin: 'https://alternate.rest.endpoint.com' // default --> https://www.exacttargetapis.com
};
const RestClient = new FuelRest(options);
```
## Examples
```js
const options = {
uri: '/platform/v1/endpoints',
headers: {}
// other request options
};
// CANNOT USE BOTH CALLBACKS AND PROMISES TOGETHER
RestClient.get(options, (err, response) => {
if (err) {
// error here
console.log(err);
}
// will be delivered with 200, 400, 401, 500, etc status codes
// response.body === payload from response
// response.res === full response from request client
console.log(response);
});
// or with promises
RestClient.get(options)
.then(response => {
// will be delivered with 200, 400, 401, 500, etc status codes
// response.body === payload from response
// response.res === full response from request client
console.log(response);
})
.catch(err => console.log(err));
```
## Contributors
* Alex Vernacchia (author) - [twitter](https://twitter.com/vernacchia), [github](https://github.com/vernak2539)
* Kelly Andrews - [twitter](https://twitter.com/kellyjandrews), [github](https://github.com/kellyjandrews)
* David Brainer-Banker - [twitter](https://twitter.com/TweetTypography), [github](https://github.com/tweettypography)
## Contributing
We welcome all contributions and issues! There's only one way to make this better, and that's by using it. If you would like to contribute, please checkout our [guidelines][5]!
## Supported Node Versions
We follow the [Node.js Release Schedule](https://github.com/nodejs/Release#release-schedule). When the current date is past the version's "Maintenance LTS End" it will no longer be supported by this library. A major release on this module will be published when this occurs.
## ChangeLog
* **See tags/release page for release notes after 0.7.2**
* **0.7.2** - 2014-10-16 - account for content-type header not being present on API response
* **0.7.1** - 2014-09-09 - removed unneeded "!!"
* **0.7.0** - 2014-08-29 (public release, 1st npm version)
* request retry on 401 invalid token response
* created helpers file for certain functions
* updated error delivering/throwing
* **0.6.0** - 2014-08-26 - added patch method
* **0.5.0** - 2014-08-26 - API overhaul (apiRequest + all http methods) - *breaking*
* **0.4.0** - 2014-08-25 - changed object initialization - *breaking*
* **0.3.0** - 2014-08-20
* added ability to use initialized fuel auth
* updated travis ci config
* added license
* **0.2.0** - 2014-08-09 - removed event emitter - *breaking*
* **0.1.0** - 2014-08-07
* initial module
* initial unit tests
[1]: https://github.com/salesforcefuel/FuelSDK-Node-Auth/wiki/Initialization
[2]: http://nodejs.org/api/url.html#url_url_resolve_from_to
[3]: https://github.com/mikeal/request#requestoptions-callback
[4]: https://github.com/salesforcefuel/FuelSDK-Node-Auth/wiki/getAccessToken
[5]: https://github.com/salesforcefuel/FuelSDK-Node-REST/wiki/Contributing
|
PHP
|
UTF-8
| 7,202 | 2.59375 | 3 |
[] |
no_license
|
<?php
session_start();
require_once "config.php";
if(!isset($_SESSION['username'])) {
header("Location: index.php"); //Redirect the user
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$foodname = $_POST["name"];
$username = $_SESSION['username'];
$rating = $_POST["rating"];
$review = $_POST["review"];
if(isset($_POST["submit"])){
$sql = "INSERT INTO `rating_02` (`serial`, `username`, `foodname`, `rating`, `review`) VALUES (NULL, '$username', '$foodname', '$rating', '$review')" ;
if (mysqli_query($conn, $sql))
{
echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Success!</strong> New Rate Added successfully!
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>';
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
?>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Rating!</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha384-SI27wrMjH3ZZ89r4o+fGIJtnzkAnFs3E4qz9DIYioCQ5l9Rd/7UAa8DHcaL8jkWt" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.css">
</head>
<body>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="welcome.php">Street30</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="welcome.php">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="chat.php">Chat with admin</a>
</li>
<li class="nav-item">
<a class="nav-link" href="user_review.php">View Reviews and Ratings by users</a>
</li>
<li class="nav-item">
<a class="nav-link" href="logout.php">Logout</a>
</li>
</ul>
<div class="navbar-collapse collapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#"> <img src="https://img.icons8.com/metro/26/000000/guest-male.png"> <?php echo "Welcome ". $_SESSION['username']?></a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<form action="" method="post">
<div>
<h3>Pizza</h3>
</div>
<div>
<input type="hidden" name="name" value="Pizza">
</div>
<div class="rateyo" id= "rating"
data-rateyo-rating="4"
data-rateyo-num-stars="5"
data-rateyo-score="3">
</div>
<span class='result'>0</span>
<input type="hidden" name="rating">
</div>
<div class="form-group" style="padding:12px;>
<label for="comment">Please write a review:</label>
<textarea class="form-control" name="review"></textarea>
</div>
<div><input type="submit" name="submit"> </div>
</form>
</div>
</div>
<!-- -------------------------------------------------------->
<br>
<br>
<div class="container">
<div class="row">
<form action="" method="post">
<div>
<h3>Burger</h3>
</div>
<div>
<input type="hidden" name="name" value="Burger">
</div>
<div class="rateyo" id= "rating"
data-rateyo-rating="4"
data-rateyo-num-stars="5"
data-rateyo-score="3">
</div>
<span class='result'>0</span>
<input type="hidden" name="rating">
</div>
<div class="form-group">
<label for="comment">Please write a review:</label>
<textarea class="form-control" name="review"></textarea>
</div>
<div><input type="submit" name="submit"> </div>
</form>
</div>
</div>
<!-- -------------------------------------------------------->
<br>
<br>
<div class="container">
<div class="row">
<form action="" method="post">
<div>
<h3>Fries</h3>
</div>
<div>
<input type="hidden" name="name" value="Fries">
</div>
<div class="rateyo" id= "rating"
data-rateyo-rating="4"
data-rateyo-num-stars="5"
data-rateyo-score="3">
</div>
<span class='result'>0</span>
<input type="hidden" name="rating">
</div>
<div class="form-group">
<label for="comment">Please write a review:</label>
<textarea class="form-control" name="review"></textarea>
</div>
<div><input type="submit" name="submit"> </div>
</form>
</div>
</div>
<!-- -------------------------------------------------------->
<br>
<br>
<div class="container">
<div class="row">
<form action="" method="post">
<div>
<h3>Sandwich</h3>
</div>
<div>
<input type="hidden" name="name" value="Sandwich">
</div>
<div class="rateyo" id= "rating"
data-rateyo-rating="4"
data-rateyo-num-stars="5"
data-rateyo-score="3">
</div>
<span class='result'>0</span>
<input type="hidden" name="rating">
</div>
<div class="form-group">
<label for="comment">Please write a review:</label>
<textarea class="form-control" name="review"></textarea>
</div>
<div><input type="submit" name="submit"> </div>
</form>
</div>
</div>
<!-- -------------------------------------------------------->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.js"></script>
<script>
$(function () {
$(".rateyo").rateYo().on("rateyo.change", function (e, data) {
var rating = data.rating;
$(this).parent().find('.score').text('score :'+ $(this).attr('data-rateyo-score'));
$(this).parent().find('.result').text('rating :'+ rating);
$(this).parent().find('input[name=rating]').val(rating); //add rating value to input field
});
});
</script>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/609834d7b1d5182476b73605/1f598srd4';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
|
Python
|
UTF-8
| 850 | 3.671875 | 4 |
[] |
no_license
|
'''
https://www.hackerrank.com/contests/juniper-2016/challenges/bus-1
Bus and Time
One day, when Meera was standing in a bus stop, she noticed that the bus always comes in every K minutes.
She also got the information that the bus takes exactly T minutes to travel from its first stop to the last stop.
The bus needs another T minutes to get back to the first stop. Here, we are ignoring the time to pick up the passengers and drop the passengers and also assuming that a new bus is always released from its first stop.
Now she wonders, what is the minimum number of buses the company must release every day.
Input Format
The first line contains two integers, K and T.
Output Format
Single integer representing the answer.
Sample Input
10 20
Sample Output
4
'''
import math
k,t = map(int, raw_input().split())
print int(math.ceil(t*2.0/k))
|
JavaScript
|
UTF-8
| 1,384 | 3 | 3 |
[] |
no_license
|
"use strict";
var byId = document.getElementById.bind(document);
var queryS = document.querySelector.bind(document);
var querySa = document.querySelectorAll.bind(document);
var parOne = byId("p1");
var parTwo = byId("p2");
var parThree = byId("p3");
var parFour = byId("p4");
var sp1 = byId("p1S1");
var sp2 = byId("p1S2");
var sp3 = byId("p1S3");
var sp4 = byId("p2S1");
var sp5 = byId("p2S2");
var sp6 = byId("p2S3");
var sp7 = byId("p3S1");
var sp8 = byId("p3S2");
var sp9 = byId("p3S3");
var sp10 = byId("p4S1");
var sp11 = byId("p4S2");
var sp12 = byId("p4S3");
var main = byId("secInp");
/* Lexical structure of JavaScript */
/*
Whitespace:
(\u0020) - space;
(\u0009) - tab
(\u000B) - vertical tab
(\u000C) - form feed
(\u00A0) - nonbreaking space
(\uFEFF) - byte order mark
Line terminators:
(\u000A) - line feed
(\u000D) - carriage return
(\u2028) - line separator
(\u2029) - paragraph separator
Unicode format controls characters
(\u200F) - RIGHT-TO-LEFT MARK
(\u200E) - LEFT-TO-RIGHT MARK
(\u200D) - ZERO WIDTH JOINER
(\u200C) - ZERO WIDTH NON-JOINER
*/
main.innerText = "Cafe" + "-" + "\u000A\u000D" + "Caf\u00e9" + "_-_" + "\u00e9" + "_-_" + "\u0301";
sp1.innerText= "Fuck";
// console.log(0xff)
// console.log(0xcafe911)
// console.log(6.02e23)
|
Java
|
UTF-8
| 4,738 | 2.25 | 2 |
[] |
no_license
|
package br.com.cerveja.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import br.com.cerveja.model.cerveja.Category;
import br.com.cerveja.model.cerveja.Style;
import br.com.cerveja.repository.cerveja.CategoriaRepository;
import br.com.cerveja.repository.cerveja.StyleRepository;
@RestController
@RequestMapping(value = "/service/style")
public class StylesCtrl {
@Autowired
private StyleRepository repo;
@Autowired
private CategoriaRepository catRepo;
@RequestMapping(method=RequestMethod.GET)
public ResponseEntity<?> getAll(@RequestParam(value="pg",defaultValue="0")Integer pg,
@RequestParam(value="qtd",defaultValue="10")Integer qtd,
@RequestParam(value="filterStyle",required=false,defaultValue="")String filterStyle,
@RequestParam(value="orderStyle",required=false)String orderStyle,
@RequestParam(value="categoria",required=false,defaultValue="")String filterCat,
@RequestParam(value="orderCategoria",required=false)String orderCat){
Pageable pageRequest = null;
List<Order> orders = new ArrayList<Sort.Order>();
if(orderStyle!=null)
orders.add(new Order(Direction.fromString(orderStyle), "name"));
if(orderCat!=null)
orders.add(new Order(Direction.fromString(orderCat), "category.name"));
if(orders.isEmpty())
pageRequest = new PageRequest(pg,qtd,new Sort("name"));
else
pageRequest = new PageRequest(pg,qtd,new Sort(orders));
Page<Style> pages =null;
if(filterCat == null && filterStyle==null)
pages = repo.findAll(pageRequest);
else
pages = repo.findByNameOrCategory(filterStyle, filterCat, pageRequest);
if(pages.getTotalElements()<=0)
return ResponseEntity.notFound().build();
return ResponseEntity.ok(pages);
}
@RequestMapping(value="/categoria",method=RequestMethod.GET)
public ResponseEntity<?> getCatAll(@RequestParam(value="pg",defaultValue="0")Integer pg,
@RequestParam(value="qtd",defaultValue="10")Integer qtd,Filter filter,SortParam sort){
Pageable pageRequest = null;
List<Order> orders = new ArrayList<Sort.Order>();
if (sort.getSortCategoria() != null)
orders.add(new Order(Direction.fromString(sort.getSortCategoria() ), "name"));
else
orders.add(new Order(Direction.ASC , "name"));
Page<Category> lista = catRepo.pesquisarCat(filter, pageRequest);
if (lista.getTotalElements() <= 0)
return ResponseEntity.notFound().build();
return ResponseEntity.ok(lista);
}
@RequestMapping(value="/{id}",method=RequestMethod.GET)
public ResponseEntity<?> getOne(@PathVariable("id") Long id){
Style style = repo.findOne(id);
if(style==null)
return ResponseEntity.notFound().build();
return ResponseEntity.ok(style);
}
@RequestMapping(value="/{id}",method=RequestMethod.PUT)
public ResponseEntity<?> update(@PathVariable("id") Long id,@Valid @RequestBody Style style,Errors erros){
try{
if(!erros.hasErrors()){
Style salvo = repo.save(style);
return ResponseEntity.ok(salvo);
}else{
return ResponseEntity.badRequest().body(erros.getAllErrors());
}
}catch(Exception e){
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(e.getMessage());
}
}
@RequestMapping(method=RequestMethod.POST)
public ResponseEntity<?> novo(@Valid @RequestBody Style style,Errors erros){
try{
if(!erros.hasErrors()){
Style salvo = repo.save(style);
return ResponseEntity.ok(salvo);
}else{
return ResponseEntity.badRequest().body(erros.getAllErrors());
}
}catch(Exception e){
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(e.getMessage());
}
}
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public ResponseEntity<?> delete(@PathVariable("id") Long id){
try{
repo.delete(id);
return ResponseEntity.ok().build();
}catch(Exception e){
return ResponseEntity.badRequest().build();
}
}
}
|
Java
|
UTF-8
| 1,255 | 2.46875 | 2 |
[] |
no_license
|
//package com.bigbird.learnkafka.springboot;
//
//import org.apache.kafka.clients.consumer.ConsumerRecord;
//import org.springframework.kafka.annotation.KafkaListener;
//import org.springframework.stereotype.Component;
//
//import java.util.List;
//import java.util.Optional;
//
///**
// * kafka消费者开启批量消费
// */
//@Component
//public class KafkaBatchConsumer {
//
// /**
// * 也可以指定containerFactory,即@KafkaListener(topics = "${spring.kafka.topic}", containerFactory="batchFactory")
// * 这里没有其它containerFactory实例,所以可以不用手动指定名称
// *
// * @param records
// */
// @KafkaListener(topics = "${spring.kafka.topic}")
// public void onMessage(List<ConsumerRecord<?, ?>> records) {
// System.out.println("接收到消息数量:" + records.size());
// for (ConsumerRecord record : records) {
// Optional<?> kafkaMessage = Optional.ofNullable(record.value());
// if (kafkaMessage.isPresent()) {
// Object message = record.value();
// String topic = record.topic();
// System.out.println("接收到topic: " + topic + " 的消息:" + message);
// }
// }
// }
//}
|
Java
|
UTF-8
| 1,102 | 2.125 | 2 |
[] |
no_license
|
package com.invoice.controller;
import com.invoice.entity.Department;
import com.invoice.entity.Submit;
import com.invoice.service.SubmitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;
@Controller
@RequestMapping("/submit")
public class SubmitController {
@Autowired
private SubmitService submitService;
@PostMapping("/add")
public String addSubmit(HttpSession session,Double sum, String reason){
Submit submit=new Submit();
Department department=(Department)session.getAttribute("department");
submit.setDepartment_id(department.getDepartment_id());
submit.setReason(reason);
submit.setSubmit_date(new Date());
submit.setSum(sum);
submitService.addSubmit(submit);
Integer sid=submit.getSubmit_id();
return "index";
}
}
|
Markdown
|
UTF-8
| 4,407 | 3.28125 | 3 |
[] |
no_license
|
# Final Project - Status Dashboard
Using the tools and techniques you learned in this class, design, prototype and test an interactive device.
Project Github page set up - May 3
Functional check-off - May 10
Final Project Presentations (video watch party) - May 12
Final Project Documentation due - May 19
## Team Members
- [Kae-Jer Cho kc2225](https://github.com/moonorblue/Interactive-Lab-Hub)
- [Cheng-Wei Hu ch956](https://github.com/HcwXd/Interactive-Lab-Hub)
- [Jeff Ming-Chun Lu ml2684](https://github.com/r06921039/Interactive-Lab-Hub)
## Project Description
Our project is a status dashboard that can connect with multiple devices from your friends. This device can be placed on the desk and you can set your own status for the moment right now, such as you're busy, you're available, or even like you have a short free time slot right now.
Besides status, our status dashboard also supports using Computer Vision to translate facial impressions to emojis. We will use the camera to detect the user's emotion and display the corresponding emoji on the screen of our device.
The status will sync with all your friends who also connected with your device, and you can chat with people with available status using the device just like you bump into them in a hallway and have a short small talk.
Special thanks to Angelica Kosasih (ak2725) for sharing the thoughts and inspiring me to have this idea at the beginning of the semester.
## Technical Implementation
### Update local status
To adjust the local status of the device, the users can press the button on the device to switch between three statuses: Free to talk, Free but don’t want to talk, Busy. As shown in figure (1). We used three different colors to indicate three different statuses: Free to talk (Green), Free but don’t want to talk (Blue), Busy (Red). After pressing the button, the user’s status dashboard will change color accordingly.
.png)
### Sync status across multiple devices
To connect different multiple devices, we used the similar structure we have learned and used in Lab 6. MQTT was used to send and sync states between different devices. Whenever a user presses the button to change the status, it will send the new status over MQTT under the specific topic `IDD/Illusinate/playerX_status`. The path here will be determined by which player is using the Raspberry Pi. As shown in figure (2).
.png)
### Facial impression translation
To translate the facial impressions to emojis, we utilized what we have learned and used in Lab5. We used Teachable Machine service to help us train a Computer Vision model that can identify whether a user's facial impression is indicating a good mood or not. By doing so, we can adjust the emoji on the user's status dashboard accordingly.
## Design
To make the device more usable, we use cardboards to let the user be able to put the device on their desk and adjust it to an angle that the user can easily see all the users’ statuses and press the button to update their own statuses.
Also, because our device is aiming to let the user be able to have a phone call with their available friends, we also designed the device the way that the user can put their phones on it, as shown in the video later.
.png)
## Project Video
[Demo Video](https://drive.google.com/file/d/1Fq6qUFNlfVv9uQ__QDI-Z0VBWKINB6cy/view)
## Reflection
In the process of the final project, we learned to integrate what we have learned in the previous labs and made something that we think can be valuable and useful for people.
The display technique we learned in lab 2 help us program the user interface of the status dashboard. In lab 4, we also learned about leveraging cardboard to increase the device's usability and make it more enjoyable to use, which also contributed to the status dashboard's final design. As we have mentioned above, in lab 5 we learned about how to use services like Teachable Machine to support Computer Vision functions like image recognition and classification, which enables us to add the features to translate facial impressions to emojis. Last but not least, in lab 6 we learned about MQTT and how to send and sync states between different devices. By adopting a similar structure, we make the status dashboard able to connect to multiple devices, and therefore, multiple people.
|
C
|
UTF-8
| 325 | 2.875 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<string.h>
void
rec_rev_util(char *str, char **s)
{
if(!*str)
return ;
char a = *str;
rec_rev_util(str+1, s);
**s = a;
*s = *s+1;
}
void
str_rev_rec(char *str)
{
rec_rev_util(str, &str);
}
main() {
char str[15] = "maruthi manohar";
printf("%s\n",str);
str_rev_rec(str);
printf("%s\n",str);
}
|
Java
|
ISO-8859-1
| 2,682 | 3.15625 | 3 |
[] |
no_license
|
import java.util.Scanner;
public class Vacaciones{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String nombre = "";
int clave = 0;
int antiguedad = 0;
System.out.println("*******************************************************");
System.out.println("*Bienvenido al sistema vacacional de Coca-Cola Company*");
System.out.println("*******************************************************");
System.out.println("");
System.out.println("");
nombre = in.nextLine();
System.out.println("Cul es el nombre del trabajador?: ");
nombre = in.nextLine();
System.out.println("");
System.out.println("Cuantos aos de servicio tiene el trabajador?: ");
antiguedad = in.nextInt();
System.out.println("");
System.out.println("Cul es la clave de su departamento?: ");
clave = in.nextInt();
System.out.println("");
if(clave == 1){
System.out.println("De acuerdo a tu clave perteneces al departamento de Atencin al Ciente");
if(antiguedad == 1){
System.out.println("El trabajador " + nombre + " tiene derecho a 6 das");
}else if(antiguedad >= 2 && antiguedad <=6){
System.out.println("El trabajador " + nombre + " tiene derecho a 14 das");
}else if(antiguedad >= 7){
System.out.println("El trabajador " + nombre + " tiene derecho a 21 das");
}
}else if(clave == 2){
System.out.println("De acuerdo a tu clave perteneces al departamento de Logistica");
if(antiguedad == 1){
System.out.println("El trabajador " + nombre + " tiene derecho a 7 das");
}if(antiguedad >= 2 && antiguedad <=6){
System.out.println("El trabajador " + nombre + " tiene derecho a 15 das");
}if(antiguedad >= 7){
System.out.println("El trabajador " + nombre + " tiene derecho a 22 das");
}
}else if(clave == 3){
System.out.println("De acuerdo a tu clave perteneces a la Gerencia");
if(antiguedad == 1){
System.out.println("El trabajador " + nombre + " tiene derecho a 10 das");
}if(antiguedad >= 2 && antiguedad <=6){
System.out.println("El trabajador " + nombre + " tiene derecho a 20 das");
}if(antiguedad >= 7){
System.out.println("El trabajador " + nombre + " tiene derecho a 30 das");
}
}else{
System.out.println("La clave de departamento no es valida");
}
System.out.println("Gracias por usar el sistema de vacaciones empresarial, \nDisfruta tus vacaciones.");
}
}
|
Java
|
UTF-8
| 1,074 | 2.328125 | 2 |
[] |
no_license
|
package org.mule.modules.baseannotations;
import org.mule.api.annotations.Configurable;
import org.mule.api.annotations.param.Default;
public class BaseConfig {
/**
* Base parameter
*/
@Configurable
@Default("BaseParam")
private String baseParameter;
/**
* Set greeting message
*
* @param baseParameter the greeting message
*/
public void setBaseParameter(String baseParameter) {
this.baseParameter = baseParameter;
}
/**
* Get greeting message
*/
public String getBaseParameter() {
return this.baseParameter;
}
/**
* Base parameter
*/
@Configurable
@Default("BaseParam")
private String baseParameter1;
/**
* Set greeting message
*
* @param baseParameter1 the greeting message
*/
public void setBaseParameter1(String baseParameter1) {
this.baseParameter1 = baseParameter1;
}
/**
* Get greeting message
*/
public String getBaseParameter1() {
return this.baseParameter1;
}
}
|
C++
|
UTF-8
| 1,399 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
////////////////////////////////////////////////////////////////////////////////
//! \file AboutDlg.cpp
//! \brief The AboutDlg class definition.
//! \author Chris Oldwood
#include "Common.hpp"
#include "AboutDlg.hpp"
#include <WCL/Path.hpp>
#include <WCL/VerInfoReader.hpp>
////////////////////////////////////////////////////////////////////////////////
//! Constructor.
AboutDlg::AboutDlg()
: CDialog(IDD_ABOUT)
{
DEFINE_CTRL_TABLE
CTRL(IDC_VERSION, &m_versionLabel)
CTRL(IDC_COPYRIGHT, &m_crightLabel)
CTRL(IDC_EMAIL, &m_emailLabel)
CTRL(IDC_WEBSITE, &m_webLabel)
END_CTRL_TABLE
// Set the URL label protocols.
m_emailLabel.Protocol(TXT("mailto:"));
m_webLabel.Protocol(TXT("http://"));
}
////////////////////////////////////////////////////////////////////////////////
//! Destructor.
AboutDlg::~AboutDlg()
{
}
////////////////////////////////////////////////////////////////////////////////
//! Handle dialog creation.
void AboutDlg::OnInitDialog()
{
// Extract details from the resources.
tstring filename = CPath::Application();
tstring version = WCL::VerInfoReader::GetStringValue(filename, WCL::VerInfoReader::PRODUCT_VERSION);
tstring copyright = WCL::VerInfoReader::GetStringValue(filename, WCL::VerInfoReader::LEGAL_COPYRIGHT);
#ifdef _DEBUG
version += TXT(" [Debug]");
#endif
// Update UI.
m_versionLabel.Text(version);
m_crightLabel.Text(copyright);
}
|
JavaScript
|
UTF-8
| 2,763 | 3.25 | 3 |
[] |
no_license
|
/**
* Индикатор JS скилла
* */
const indicatorArrow = document.querySelector('.js-indicator-arrow');
const checkboxContent = document.querySelector('.js-checkbox-content');
const checkboxMark = document.querySelectorAll('.js-checkbox-mark');
const indicatedSkills = ['vanillajs','gulp','angular','jquery'];
const oneIndicatorDivision = 180 / indicatedSkills.length;
const numberIndicatorElements = 1000 / indicatedSkills.length;
let startingPoint = 270;
let startKnowledgeCounter = 0;
function easeCounterChanged() {
const roundingDivision = Math.ceil(numberIndicatorElements);
$.easing.easeIn = (x, t, b, c, d) => {
return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
};
$('.js-knowledge-counter').each(function() {
$(this).prop('counter', 0 - roundingDivision).animate({
counter: $(this).text(),
}, {
duration: 470,
easing: 'easeIn',
step(val) {
$(this).text(Math.abs(Math.ceil(val)));
},
});
});
}
function addValueToIndicator(action, element) {
const levelLowerText = element.nextElementSibling.textContent.toLowerCase();
const knowledgeCounter = document.querySelector('.js-knowledge-counter');
indicatedSkills.forEach(item => {
if (levelLowerText === item) {
const roundingDivision = Math.ceil(numberIndicatorElements);
const renderKnowledgeCounter = action === 'add' ?
startKnowledgeCounter += roundingDivision :
startKnowledgeCounter -= roundingDivision;
const roundingAsInteger = (Math.round(parseInt(renderKnowledgeCounter, 10) / 10) * 10);
startingPoint = action === 'add' ? startingPoint += oneIndicatorDivision : startingPoint -= oneIndicatorDivision;
knowledgeCounter.innerHTML = typeof roundingAsInteger === 'number' ? roundingAsInteger : 0;
easeCounterChanged();
indicatorArrow.style.transform = `translateX(-50%) rotate(${startingPoint}deg)`;
}
});
}
function listenerChecked(e) {
const target = e.target;
const targetChecked = target.classList.contains('js-checkbox-mark');
const targetInputLabel = target.classList.contains('js-checkbox-label');
if (!targetChecked && !targetInputLabel) {
return;
}
const currentCheckbox = target.closest('.js-checkbox');
const currentDataset = currentCheckbox.dataset.skill;
checkboxMark.forEach(mark => {
if (currentDataset !== mark.nextElementSibling.textContent.toLowerCase()) {
return;
}
if (mark.classList.contains('is-checked')) {
addValueToIndicator('remove', mark);
return mark.classList.remove('is-checked');
}
addValueToIndicator('add', mark);
mark.classList.add('is-checked');
});
}
checkboxContent.addEventListener('click', listenerChecked);
checkboxContent.addEventListener('keydown', e => {
if (e.code === 'Space') {
listenerChecked(e);
}
});
|
Shell
|
UTF-8
| 275 | 2.984375 | 3 |
[] |
no_license
|
#!/bin/bash
declare -a folders=("go" "java" "python3" "nodejs8", "rust")
export AWS_PROFILE=default
export AWS_REGION=us-east-1
for i in `seq 1 11`;
do
for folder in "${folders[@]}"
do
cd $folder
pwd
sls deploy --region $AWS_REGION
cd ..
done
done
|
C#
|
UTF-8
| 3,031 | 3.203125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Image_Generator_project
{
class Program
{
private static string GLOBAL_FOLDER
{
get
{
string workingDirectory = Directory.GetCurrentDirectory();
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
return Path.GetFullPath(Path.Combine(projectDirectory, @"..\..\"));
}
}
private static string INPUT_FOLDER_BASE
{
get
{
return GLOBAL_FOLDER + @"input\";
}
}
private static string OUTPUT_FOLDER_BASE
{
get
{
return GLOBAL_FOLDER + @"output\";
}
}
private static Rectangle GetLargestRectangle(List<NotationObject> objects)
{
Rectangle rectangle = new Rectangle(0, 0, 0, 0);
foreach (NotationObject obj in objects)
{
if (obj.Rectangle.Width > rectangle.Width) rectangle.Width = obj.Rectangle.Width;
if (obj.Rectangle.Height > rectangle.Height) rectangle.Height = obj.Rectangle.Height;
}
return rectangle;
}
private static void CreateImages(List<NotationObject> objects, Rectangle rectangle)
{
for (int i = 0; i < objects.Count; i++)
{
string folder = OUTPUT_FOLDER_BASE + objects[i].Name;
string output = folder + "\\" + "image" + i.ToString() + ".jpg";
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
Bitmap bitmap = Drawer.CreateImage(objects[i], rectangle, 2);
bitmap.Save(output);
//Console.WriteLine("Completed: " + ((float)i / (float)objects.Count) * 100 + "%");
}
}
static void Main(string[] args)
{
List<string> folders = new List<string>();
List<NotationObject> notationObjects = new List<NotationObject>();
string[] directories = Directory.GetDirectories(INPUT_FOLDER_BASE);
for (int i = 0; i < directories.Length; i++)
{
//Get files per directory
string[] files = Directory.GetFiles(directories[i]);
for (int j = 0; j< files.Length; j++)
{
NotationObject obj = Parser.Read(files[j]);
notationObjects.Add(obj);
}
Console.WriteLine("Completed: " + ((float)i / (float)directories.Length) * 100 + "%");
}
Rectangle rectangle = GetLargestRectangle(notationObjects);
CreateImages(notationObjects, rectangle);
}
}
}
|
C#
|
UTF-8
| 532 | 2.546875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Common
{
/// <summary>
/// The Application Settings Manager
/// </summary>
public static class AppSettingsManager
{
/// <summary>
/// Gets the application setting value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public static string GetAppSettingValue(string key)
=> System.Configuration.ConfigurationManager.AppSettings[key];
}
}
|
Java
|
UTF-8
| 2,989 | 2.359375 | 2 |
[] |
no_license
|
package com.sixgod.teachPlan.service.impl;
import com.sixgod.teachPlan.Exception.EntityRepeatException;
import com.sixgod.teachPlan.entity.EducatePlan;
import com.sixgod.teachPlan.entity.Major;
import com.sixgod.teachPlan.repository.EducatePlanRepository;
import com.sixgod.teachPlan.service.EducatePlanService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import java.util.List;
@Service
public class EducatePlanServiceImpl implements EducatePlanService {
@Autowired
EducatePlanRepository educatePlanRepository;
@Override
public Page<EducatePlan> findAllByMajor(Long majorId, Pageable pageable) {
if(majorId == 0){
return educatePlanRepository.findAll(pageable);
}
else {
return educatePlanRepository.findAllByMajor(
Major.builder().id(majorId).build(), pageable);
}
}
@Override
public void add(EducatePlan educatePlan) {
if (educatePlanRepository.existsByTermNumberAndMajorId(
educatePlan.getTermNumber(),
educatePlan.getMajor().getId()
)) {
throw new EntityRepeatException("培养计划添加重复");
}
educatePlanRepository.save(educatePlan);
}
@Override
public void update(Long id, EducatePlan educatePlan) {
EducatePlan educatePlan1 = educatePlanRepository.findById(id).orElse(null);
if(educatePlan1 == null){
throw new EntityNotFoundException("培养计划id为:" + id + "不存在");
}
else{
educatePlan1.setCourseList(educatePlan.getCourseList());
educatePlan1.setMajor(educatePlan.getMajor());
educatePlan1.setTermNumber(educatePlan.getTermNumber());
educatePlanRepository.save(educatePlan1);
}
}
@Override
public void deleteById(Long id) {
EducatePlan educatePlan = educatePlanRepository.findById(id).orElse(null);
if(educatePlan == null){
throw new EntityNotFoundException("培养计划id为:" + id + "不存在");
}
else {
educatePlanRepository.deleteById(id);
}
}
@Override
public EducatePlan getOneEducatePlan() {
return EducatePlan.builder()
.termNumber(RandomUtils.nextInt())
.build();
}
@Override
public EducatePlan getOneSavedEducatePlan() {
return educatePlanRepository.save(getOneSavedEducatePlan());
}
@Override
public EducatePlan findById(Long id) {
return educatePlanRepository.findById(id).orElse(null);
}
@Override
public List<EducatePlan> getAllEducatePlan() {
return educatePlanRepository.findAll();
}
}
|
Java
|
UTF-8
| 3,156 | 2.46875 | 2 |
[
"MIT"
] |
permissive
|
package com.elmakers.mine.bukkit.heroes;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public class PlayerListener implements Listener {
private final HotbarController controller;
public PlayerListener(HotbarController controller) {
this.controller = controller;
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
controller.clearActiveSkillSelector(event.getPlayer());
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) {
final Player player = event.getPlayer();
// Unprepare skills when dropped
ItemStack droppedItem = event.getItemDrop().getItemStack();
controller.unprepareSkill(player, droppedItem);
// Catch lag-related glitches dropping items from GUIs
SkillSelector selector = controller.getActiveSkillSelector(player);
if (selector != null) {
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
Item itemEntity = event.getEntity();
ItemStack spawnedItem = itemEntity.getItemStack();
if (controller.isSkill(spawnedItem) || controller.isLegacySkill(spawnedItem)) {
event.setCancelled(true);
return;
}
}
@EventHandler
public void onPlayerEquip(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
PlayerInventory inventory = player.getInventory();
ItemStack next = inventory.getItem(event.getNewSlot());
boolean isSkill = controller.isSkill(next);
if (isSkill) {
controller.useSkill(player, next);
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event)
{
if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) return;
Player player = event.getPlayer();
PlayerInventory inventory = player.getInventory();
ItemStack itemInHand = inventory.getItemInMainHand();
boolean isSkill = controller.isSkill(itemInHand);
if (isSkill) {
controller.useSkill(player, itemInHand);
event.setCancelled(true);
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event)
{
ItemStack itemStack = event.getItemInHand();
if (controller.isSkill(itemStack) || controller.isLegacySkill(itemStack)) {
event.setCancelled(true);
return;
}
}
}
|
C#
|
UTF-8
| 4,098 | 2.625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UdpSever
{
#region 字段
// 定义节点
IPEndPoint ipEndPoint = null;
// 定义UDP发送和接收
UdpClient udpReceive = null;
UdpState udpReceiveState = null;
public event Action<Byte[], UdpState> eventTrigger;
// 异步状态同步
AutoResetEvent receiveDone = new AutoResetEvent(false);
static object syncUdp = new object();
Thread t;
#endregion
public void UdpSeverInit(int port)
{
// 本机节点
ipEndPoint = new IPEndPoint(IPAddress.Any, port);
// 实例化
udpReceive = new UdpClient(ipEndPoint);
// 分别实例化udpSendState、udpReceiveState
udpReceiveState = new UdpState();
udpReceiveState.udpClient = udpReceive;
udpReceiveState.ipEndPoint = ipEndPoint;
//监听UDP的线程
t = new Thread(Thread_Listener);
t.IsBackground = true;
t.Priority = ThreadPriority.AboveNormal;
t.Start();
}
/// <summary>
/// 监听链接
/// </summary>
public void Listener(int port)
{
UdpSeverInit(port);
}
/// <summary>
/// 监听链接的线程
/// </summary>
void Thread_Listener()
{
while (true)
{
lock (syncUdp)
{
try
{
// 调用接收回调函数
IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
receiveDone.WaitOne();
}
catch
{
receiveDone.Set();
}
}
}
}
/// <summary>
/// 接收回调函数
/// </summary>
/// <param name="iar"></param>
void ReceiveCallback(IAsyncResult iar)
{
try
{
UdpState udpState = iar.AsyncState as UdpState;
if (iar.IsCompleted)
{
Byte[] rBytes = udpState.udpClient.EndReceive(iar, ref udpState.remoteEP);
if (eventTrigger != null)
eventTrigger(rBytes, udpState);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
receiveDone.Set();
}
}
/// <summary>
/// 发送函数
/// </summary>
public void SendMsg(UdpState udpState, string content)
{
Byte[] sendBytes = Encoding.Default.GetBytes(content);
try
{
udpState.udpClient.Send(sendBytes, sendBytes.Length, udpState.remoteEP);
}
catch
{
}
}/// <summary>
/// 发送函数
/// </summary>
public static void SendMsgStr(UdpState udpState, string content)
{
//Byte[] sendBytes = Encoding.UTF8.GetBytes(content);
Byte[] sendBytes=Enumerable.Range(0, content.Length).Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(content.Substring(x, 2), 16))
.ToArray();
try
{
udpState.udpClient.Send(sendBytes, sendBytes.Length, udpState.remoteEP);
}
catch
{
}
}
/// <summary>
/// 停止监听
/// </summary>
public void StopListen()
{
try
{
if (udpReceive != null)
udpReceive.Close();
if (ipEndPoint != null)
ipEndPoint = null;
if (udpReceiveState != null)
udpReceiveState = null;
if (t != null && t.IsAlive)
{
t.Abort();
t = null;
}
}
catch (Exception)
{
}
}
}
public class UdpState
{
public UdpClient udpClient;
public IPEndPoint ipEndPoint;
public IPEndPoint remoteEP;
public byte[] buffer = new byte[1024];
public int counter = 0;
}
|
C++
|
UTF-8
| 727 | 3.25 | 3 |
[] |
no_license
|
//{5,4,1,4,3,5,1,2}
//output: 3,2
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int >a;
int n,pos=0,i=0;
int res=0,one=0,two=0;
cin>>n;
while(n--){
int x;
cin>>x;
a.push_back(x);
res^=x;
}
one=two=res;
while(res>0){
if(res&1)break;
res=res>>1;
pos++;
}
n=a.size();
while(n--){
//right shift to the position to find set bit
a[i]=a[i]>>pos;
//below creates two buckets and non repeating number gets seprated
if(a[i]&1)one^=a[i];
else two^=a[i];
i++;
}
cout<<one<<" "<<two;
return 0;
}
|
SQL
|
UTF-8
| 321 | 3.21875 | 3 |
[] |
no_license
|
create table Owner
(
owner_id NUMBER GENERATED ALWAYS AS IDENTITY,
owner_name VARCHAR2(40),
vehicle_id NUMBER(6) not null,
address VARCHAR2(40),
constraint owner_id_pk primary key (owner_id)
)
alter table Owner
add constraint owner_vehicle_id_fk foreign key (vehicle_id)
references Vehicles(vehicle_id);
|
C#
|
UTF-8
| 7,190 | 3.140625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
namespace LibrarySystem.Entities
{
/// <summary>
/// 枚举项在数据库中的值与在网页中的值的映射关系
/// </summary>
[Serializable]
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
[ComVisible(true)]
public class EnumMappingAttribute : Attribute
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="code"></param>
/// <param name="name"></param>
public EnumMappingAttribute(string code, string name)
{
DBCode = code;
DisplayName = name;
}
/// <summary>
/// 枚举编码(记入数据库)
/// </summary>
public string DBCode { get; private set; }
/// <summary>
/// 枚举显示值(程序显示)
/// </summary>
public string DisplayName { get; private set; }
}
/// <summary>
/// 枚举扩展方法(在使用过程要中要注意Enum.ToString()的问题,因为基本上用于映射的这个本身的字符串或者值都是没有用的)
/// </summary>
public static class EnumHelper
{
/// <summary>
/// 获取枚举定义中的数据库名称
/// </summary>
/// <param name="myEnum"></param>
/// <returns></returns>
public static string GetDBCode(this Enum myEnum)
{
Type type = myEnum.GetType();
FieldInfo info = type.GetField(myEnum.ToString());
EnumMappingAttribute ema = info.GetCustomAttributes(typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (ema != null)
return ema.DBCode;
else
return null;
}
/// <summary>
/// 获取枚举定义中的程序显示名称
/// </summary>
/// <param name="myEnum"></param>
/// <returns></returns>
public static string GetDisplayName(this Enum myEnum)
{
Type type = myEnum.GetType();
FieldInfo info = type.GetField(myEnum.ToString());
EnumMappingAttribute spa = info.GetCustomAttributes(typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (spa != null)
return spa.DisplayName;
else
return null;
}
/// <summary>
/// 根据枚举定义中的数据库名称来判断某个数据值是否与某枚举相等
/// </summary>
/// <param name="myEnum"></param>
/// <param name="dbCode"></param>
/// <returns></returns>
public static bool EqualByDBCode(this Enum myEnum, string dbCode)
{
Type type = myEnum.GetType();
FieldInfo info = type.GetField(myEnum.ToString());
EnumMappingAttribute ema = info.GetCustomAttributes(typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (ema != null)
{
if (ema.DBCode == dbCode)
return true;
else
return false;
}
else
return false;
}
/// <summary>
/// 根据枚举定义中的程序显示名称来判断某个显示值是否与某枚举相等
/// </summary>
/// <param name="myEnum"></param>
/// <param name="displayName"></param>
/// <returns></returns>
public static bool EqualByDisplayName(this Enum myEnum, string displayName)
{
Type type = myEnum.GetType();
FieldInfo info = type.GetField(myEnum.ToString());
EnumMappingAttribute ema = info.GetCustomAttributes(typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (ema != null)
{
if (ema.DisplayName == displayName)
return true;
else
return false;
}
else
return false;
}
/// <summary>
/// 把某个数据值翻译成对应的枚举项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str"></param>
/// <returns></returns>
public static T Parse2EnumByDBCode<T>(string str)
{
try
{
Type t = typeof(T);
foreach (var fi in t.GetFields(BindingFlags.Static | BindingFlags.Public))
{
EnumMappingAttribute spa = Attribute.GetCustomAttributes(fi, typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (spa != null && spa.DBCode == str)
{
return (T)Enum.Parse(typeof(T), fi.Name, true);
}
}
return default(T);
}
catch
{
return default(T);
}
}
/// <summary>
/// 把某个显示值翻译成对应的枚举项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str"></param>
/// <returns></returns>
public static T Parse2EnumByDisplayName<T>(string str)
{
try
{
Type t = typeof(T);
foreach (var fi in t.GetFields(BindingFlags.Static | BindingFlags.Public))
{
EnumMappingAttribute spa = Attribute.GetCustomAttributes(fi, typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (spa != null && spa.DisplayName == str)
{
return (T)Enum.Parse(typeof(T), fi.Name, true);
}
}
return default(T);
}
catch
{
return default(T);
}
}
/// <summary>
/// 获取某个枚举类型的映射集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static List<EnumMappingAttribute> GetMappingList<T>()
{
List<EnumMappingAttribute> list = new List<EnumMappingAttribute>();
try
{
Type t = typeof(T);
foreach (var fi in t.GetFields(BindingFlags.Static | BindingFlags.Public))
{
EnumMappingAttribute spa = Attribute.GetCustomAttributes(fi, typeof(EnumMappingAttribute), true)[0] as EnumMappingAttribute;
if (spa != null)
{
list.Add(spa);
}
}
}
catch
{
list.Clear();
}
return list;
}
}
}
|
Java
|
UTF-8
| 1,353 | 2.234375 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.view.ViewTreeObserver;
/**
* A CursorController instance can be used to control a cursor in the text.
* This class is based on the private inner interface CursorController in
* android.widget.TextView
* TODO(olilan): refactor and share with Android code if possible
*/
interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener {
/**
* Hide the cursor controller from screen.
*/
public void hide();
/**
* @return true if the CursorController is currently visible
*/
public boolean isShowing();
/**
* Called when the handle is about to start updating its position.
* @param handle
*/
public void beforeStartUpdatingPosition(HandleView handle);
/**
* Update the controller's position.
*/
public void updatePosition(HandleView handle, int x, int y);
/**
* Called when the view is detached from window. Perform house keeping task, such as
* stopping Runnable thread that would otherwise keep a reference on the context, thus
* preventing the activity to be recycled.
*/
public void onDetached();
}
|
PHP
|
UTF-8
| 1,813 | 2.65625 | 3 |
[] |
no_license
|
<?php
require ("core.php");
$BANK_TITLE = $_SESSION ["uname"];
$target_dir = "uploads/";
$target_file = $target_dir . $_SESSION ["uid"] . basename ( $_FILES ["fileToUpload"] ["name"] );
$uploadOk = 1;
$imageFileType = pathinfo ( $target_file, PATHINFO_EXTENSION );
// Check if image file is a actual image or fake image
$errorOutput = "";
if (isset ( $_POST ["submit"] )) {
if (file_exists ( $target_file )) {
$errorOutput .= "File already exists. ";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "csv") {
$errorOutput .= "Only .csv files are allowed. ";
$uploadOk = 0;
}
if ($uploadOk == 0) {
$errorOutput .= "Sorry, your file was not uploaded. ";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file ( $_FILES ["fileToUpload"] ["tmp_name"], $target_file )) {
$successOutput = "The file " . basename ( $_FILES ["fileToUpload"] ["name"] ) . " has been uploaded.";
exec ( "./c-fileparser/fileparser " . $target_file, $output );
unlink ( $target_file );
} else {
$errorOutput .= "Sorry, there was an error uploading your file."; //. print_r ( $_FILES );
}
}
}
include ("layout/header.php");
?>
If you wish to upload a batch file that performs one or multiple transactions you can upload such a file here.<br>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select a .csv file to upload: <input type="file" name="fileToUpload"
id="fileToUpload"> <input type="submit" value="Upload"
name="submit">
</form>
<br>
The .csv file must have this format:<br>
sourceID, targetID, TAN, Amount<br><br>
The user must exist, have enough money and the TAN must be correct!
<?php
include ("layout/errorSuccessBox.php");
include ("layout/footer.php");
?>
|
TypeScript
|
UTF-8
| 577 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
import { emitMeta } from './emit';
import { TEventMap, TUnsubscribeHandlers } from './types';
import { EMetaEvents } from './meta-events';
export const unsubscribe = <M extends TEventMap>(
eventMap: M
) => <E extends keyof M>(
event: E
): TUnsubscribeHandlers<M, E> => (
...handlers
) => {
if (event in eventMap) for (
const h of handlers.length > 0
? handlers
: eventMap[event].keys()
) // Emit meta-event (ignore promise)
emitMeta(EMetaEvents.UNSUBSCRIBE)(eventMap, event, h),
eventMap[event].delete(h);
};
export const off = unsubscribe;
|
Java
|
UTF-8
| 5,043 | 2.8125 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controladores;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author julio
*/
public class ComunicadorCliente {
private BufferedReader in;
private PrintWriter out;
private String serverAddress;
private Socket socket;
private String usuario;
private boolean estadoConexion;
private String respuestaServidor;
private static ComunicadorCliente INSTANCE = null;
/*
public ComunicadorCliente(String direccionServer, int puerto) throws IOException {
//usuario = usuario;
serverAddress = direccionServer;
socket = new Socket(direccionServer, 9001);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
estadoConexion=false;
}
*/
public void generarComunicacion(String direccionServer, int puerto)throws IOException{
serverAddress = direccionServer;
socket = new Socket(direccionServer, 9001);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
estadoConexion=false;
}
/*Patron de diseño Singleton*/
private synchronized static void createInstance() throws IOException{
if(INSTANCE == null){
INSTANCE = new ComunicadorCliente();
}
}
public static ComunicadorCliente getInstance() throws IOException{
createInstance();
return INSTANCE;
}
public void enviarMensaje(String mensaje){
//System.out.println("Este es el mensaje que se va a enviar:"+mensaje);
out.println(mensaje);
}
public String retornarRespuesta(){
return this.respuestaServidor;
}
public void run() throws IOException {
boolean flag=true;
while (flag) {
/*
Scanner entrada = new Scanner(System.in);
if(estadoConexion){
System.out.println("introduzca el mensaje");
}else{
System.out.println("introduzca sus credenciales");
}
enviarMensaje(entrada.nextLine());
*/
String line = in.readLine();
if (line.startsWith("CONECTAR_EMPLEADO")) {
line=line.replaceAll(" ", "");
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
} else if (line.startsWith("SOLICITAR_TICKETS")) {
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
} else if(line.startsWith("RESERVAR_TICKET")){
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
}else if(line.startsWith("ACTUALIZAR_TICKET")){
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
}else if(line.startsWith("LIBERAR_TICKET")){
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
}else if(line.startsWith("REPORTE_TICKET")){
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
}else if(line.startsWith("DESCONECTAR_EMPLEADO")){
System.out.println("Retorno del servidor:");
System.out.println(line + "\n");
this.respuestaServidor=line;
estadoConexion=false;
socket.close();
flag=false;
}else{
System.out.println("ERROR! No se ha reconocido la instrucción.");
}
}
if(!flag){
System.out.println("La conexión se ha cerrado!!!");
}
}
}
|
PHP
|
UTF-8
| 489 | 2.671875 | 3 |
[] |
no_license
|
<?php
require_once("compania.php");
class Alpha extends Compania {
var $codautorizacion;
function __construct ($nombre,$telefonoemergencia,$codautorizacion){
parent::__construct($nombre,$telefonoemergencia);
$this->codautorizacion = $codautorizacion;
}
function getCodAutorizacion (){
return $this->codautorizacion;
}
function setCodAutorizacion($codautorizacion){
$this->codautorizacion = $codautorizacion;
}
}
|
C#
|
UTF-8
| 11,389 | 2.546875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Shop_project.Utils;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Drawing.Printing;
namespace Shop_project.Forms
{
public partial class ConfirmOrder : Form
{
User user;
List<Product> cart;
SqlConnection conn;
bool isOrdered;
string address;
public ConfirmOrder(User user, List<Product> cart,SqlConnection connection)
{
this.conn = connection;
this.user = user;
this.cart = cart;
InitializeComponent();
}
private void confirmOrder_Load(object sender, EventArgs e)
{
isOrdered = false;
textBoxEmail.Text = user.email;
}
private void buttonAddOrder_Click(object sender, EventArgs e)
{
if (textBoxAddress.Text != string.Empty && textBoxEmail.Text != string.Empty)
{
try
{
if (textBoxComment.Text == string.Empty)
{
textBoxComment.Text = "-";
}
SqlCommand cmd;
SqlCommand updateCmd;
conn.Open();
foreach (Product product in cart)
{
Product p = new Product(product.id);
cmd = new SqlCommand("INSERT INTO Orders VALUES (@userId,@productId,@productName,@comment,@address,@price,@date,@state)", conn);
cmd.Parameters.Add("@userId", SqlDbType.Int).Value = user.id;
cmd.Parameters.Add("@productId", SqlDbType.Int).Value = product.id;
cmd.Parameters.Add("@productName", SqlDbType.NVarChar).Value = product.name;
cmd.Parameters.Add("@comment", SqlDbType.NVarChar).Value = textBoxComment.Text;
cmd.Parameters.Add("@address", SqlDbType.NVarChar).Value = textBoxAddress.Text;
cmd.Parameters.Add("@price", SqlDbType.Decimal).Value = product.price;
cmd.Parameters.Add("@date", SqlDbType.Date).Value = DateTime.Now.ToShortDateString();
cmd.Parameters.Add("@state", SqlDbType.Bit).Value = true;
cmd.ExecuteNonQuery();
if (p.quantity > 0)
{
updateCmd = new SqlCommand($"UPDATE Products SET popularity = popularity + 10, quantity = quantity - 1 WHERE Id = {product.id}", conn);
updateCmd.ExecuteNonQuery();
}
else
{
updateCmd = new SqlCommand($"UPDATE Products SET popularity = popularity + 10 WHERE Id = {product.id}", conn);
updateCmd.ExecuteNonQuery();
}
address = textBoxAddress.Text;
}
GC.Collect();
conn.Close();
isOrdered = true;
buttonAddOrder.Enabled = false;
labelMessage.Visible = true;
buttonSendMail.Enabled = true;
buttonToTXT.Enabled = true;
buttonPrint.Enabled = true;
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.DialogResult = DialogResult.Abort;
}
}
else
{
MessageBox.Show("Дополните данные формы","Info",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
//send order to admin
try
{
string body = "";
body += $"<b>Пользователь: {user.name} {user.lastName}</b><br/>";
body += $"<b>Номер телефона: {user.phoneNum}</b><br/>";
body += $"<b>Адрес: {address}</b><br/>";
body += $"<b>Дата: {DateTime.Now.ToShortDateString()}</b><br/><br/>";
body += $"<h1>\tТовары:</h1></br><ol>";
float sum = 0;
foreach (Product item in cart)
{
sum += item.price;
body += $"<li>{item.name} (id: {item.id}) - Цена: {item.price}</li>";
}
body += "</ol><br/><hr/>";
body += $"<b><i>Сумма заказа = {sum}</b></i>";
MailAddress from = new MailAddress("horoshihblag@gmail.com", "admin");
MailAddress to = new MailAddress("horoshihblag@gmail.com");
MailMessage mail = new MailMessage(from, to);
mail.Subject = $"Чек заказа {user.name}";
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential("horoshihblag@gmail.com", "horoshihblag123");
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception)
{
//nothing
}
}
private void buttonSendMail_Click(object sender, EventArgs e)
{
string body = "";
body += $"<b>Пользователь: {user.name} {user.lastName}</b><br/>";
body += $"<b>Номер телефона: {user.phoneNum}</b><br/>";
body += $"<b>Адрес: {address}</b><br/>";
body += $"<b>Дата: {DateTime.Now.ToShortDateString()}</b><br/>";
body += $"<b>Комментарий к заказу: {textBoxComment.Text}</b><br/><br/>";
body += $"<h1>\tТовары:</h1></br><ol>";
float sum = 0;
foreach (Product item in cart)
{
sum += item.price;
body += $"<li>{item.name} (id: {item.id}) - Цена: {item.price}</li>";
}
body += "</ol><br/><hr/>";
body += $"<b><i>Сумма заказа = {sum}</b></i>";
try
{
MailAddress from = new MailAddress("horoshihblag@gmail.com","Менеджер \"ХорошихБлаг\"");
MailAddress to = new MailAddress(textBoxEmail.Text);
MailMessage mail = new MailMessage(from, to);
mail.Subject = "Чек заказа \"ХорошихБлаг\"";
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential("horoshihblag@gmail.com", "horoshihblag123");
smtp.EnableSsl = true;
smtp.Send(mail);
MessageBox.Show($"Чек успешно оправлен на почту {textBoxEmail.Text}", "success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonToTXT_Click(object sender, EventArgs e)
{
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != string.Empty)
{
StreamWriter writer = new StreamWriter(saveFileDialog1.FileName);
writer.WriteLine($"Пользователь: {user.name} {user.lastName}");
writer.WriteLine($"Номер телефона: {user.phoneNum}");
writer.WriteLine($"Адрес: {address}");
writer.WriteLine($"Эл. почта: {textBoxEmail.Text}");
writer.WriteLine($"Дата: {DateTime.Now.ToShortDateString()}");
writer.WriteLine($"Комментарий к заказу: {textBoxComment.Text}");
writer.WriteLine();
writer.WriteLine($"\tТовары:");
int counter = 1;
float sum = 0;
foreach (Product item in cart)
{
sum += item.price;
writer.WriteLine($"{counter}. {item.name} (id: {item.id}) - Цена: {item.price}");
counter++;
}
writer.WriteLine("==============================");
writer.WriteLine($"Сумма заказа = {sum}");
writer.Close();
MessageBox.Show("Файл сохранён", "success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Вы не выбрали файл", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
string pageBody = "";// var for print function
private void buttonPrint_Click(object sender, EventArgs e)
{
pageBody += $"Пользователь: {user.name} {user.lastName}\n";
pageBody += $"Номер телефона: {user.phoneNum}\n";
pageBody += $"Адрес: {address}\n";
pageBody += $"Эл. почта: {textBoxEmail.Text}\n";
pageBody += $"Дата: {DateTime.Now.ToShortDateString()}\n";
pageBody += $"Комментарий к заказу: {textBoxComment.Text}\n\n";
pageBody += $"\tТовары:\n";
double sum = 0;
int counter = 1;
foreach (Product item in cart)
{
sum += item.price;
pageBody += $"{counter}. {item.name} (id: {item.id}) - Цена: {item.price}\n";
counter++;
}
pageBody += "==============================\n";
pageBody += $"Сумма заказа = {sum}";
try
{
PrintDocument doc = new PrintDocument();
doc.PrintPage += PrintPageHandler;
printPreviewDialog1.Document = doc;
printPreviewDialog1.ShowDialog();
printDialog1.Document = doc;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDialog1.Document.Print();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
pageBody = string.Empty;
}
void PrintPageHandler(object sender, PrintPageEventArgs e) // for printing handler
{
e.Graphics.DrawString(pageBody, new Font("Arial", 14), Brushes.Black, 0, 0);
}
private void ConfirmOrder_FormClosing(object sender, FormClosingEventArgs e)
{
if (isOrdered)
{
this.DialogResult = DialogResult.OK;
}
else
{
this.DialogResult = DialogResult.Cancel;
}
}
}
}
|
Markdown
|
UTF-8
| 1,563 | 3.5625 | 4 |
[
"MIT"
] |
permissive
|
Object.map.js
=============
`Array.map` for `Object` in JavaScript. Map both an object’s keys and values.
Usage
-----
By default, will allow calling `Object.map` (obviously, as a non-enumerable property).
If you're terrified about augmenting prototypes of natives zomg ruin on us all, just set the `shouldAugmentObjectPrototype` param to `false` on the last line. The enclosing IEFE will then return the `mapObject` function with the source object as its first parameter, so you can call it however you want.
```JavaScript
/**
*@param {Function|String} [valueMapper = pass-through] The function to map the value from the source's value. Will be passed the current value, the original key, and the mapped key. If a string, will be set to an accessor for that attribute.
*@param {Function|String} [keyMapper = pass-through] The function to map the key from the source's key. Will be passed the original key and the original value. If a string, will be set to an accessor for that attribute.
*@throws TypeError If one of the mapper is an illegal type.
*@returns {Object<String,String>}
*/
Object.map(valueMapper, keyMapper);
```
### Example
```JavaScript
var source = { a: 1, b: 2 };
function sum(x) { return x + x }
source.map(sum); // returns { a: 2, b: 4 }
source.map(undefined, sum); // returns { aa: 1, bb: 2 }
source.map(sum, sum); // returns { aa: 2, bb: 4 }
```
License
-------
**MIT**: Do whatever you want as long as you don't sue me nor prevent others to reuse this piece of software.
Also, credit is always appreciated ;)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.