language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 5,994 | 1.828125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*==============================================================================
Copyright (c) 2017 Rizky Kharisma (@ngengs)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================*/
package com.ngengs.skripsi.todongban.utils.notifications.handler;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.ngengs.skripsi.todongban.MainActivityPersonal;
import com.ngengs.skripsi.todongban.R;
import com.ngengs.skripsi.todongban.data.enumerations.Values;
import com.ngengs.skripsi.todongban.data.local.PeopleHelp;
import com.ngengs.skripsi.todongban.utils.GsonUtils;
import com.ngengs.skripsi.todongban.utils.notifications.NotificationBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class ResponsePeopleHelpNotificationHandler {
public static void handle(Context context, Map<String, String> payload) {
String helpId = payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_ID);
String name = payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_NAME);
int badge = Integer.parseInt(
payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_BADGE));
int userType = Integer.parseInt(
payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_USER_TYPE));
double distance = Double.parseDouble(
payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_DISTANCE));
boolean accept = Boolean.parseBoolean(
payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_ACCEPT));
PeopleHelp peopleHelp = new PeopleHelp(helpId, name, badge, userType, distance, accept);
SharedPreferences sharedPreferences = context.getSharedPreferences(
Values.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
if (ResponsePeopleHelpNotificationHandler.isCanRun(sharedPreferences)) {
ResponsePeopleHelpNotificationHandler.saveData(sharedPreferences, peopleHelp);
ResponsePeopleHelpNotificationHandler.sendNotification(context);
ResponsePeopleHelpNotificationHandler.sendBroadcast(context, peopleHelp);
}
}
public static void handleReject(Context context, Map<String, String> payload) {
String helpId = payload.get(Values.NOTIFICATION_DATA_PEOPLE_HELP_ID);
PeopleHelp peopleHelp = new PeopleHelp(helpId);
peopleHelp.setAccept(false);
SharedPreferences sharedPreferences = context.getSharedPreferences(
Values.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
if (ResponsePeopleHelpNotificationHandler.isCanRun(sharedPreferences)) {
ResponsePeopleHelpNotificationHandler.saveData(sharedPreferences, peopleHelp);
ResponsePeopleHelpNotificationHandler.sendNotification(context);
ResponsePeopleHelpNotificationHandler.sendBroadcast(context, peopleHelp);
}
}
private static void saveData(SharedPreferences sharedPreferences,
PeopleHelp data) {
Gson gson = GsonUtils.provideGson();
List<PeopleHelp> saveData = new ArrayList<>();
String oldData = sharedPreferences.getString(Values.SHARED_PREFERENCES_KEY_PEOPLE_HELP,
null);
if (!TextUtils.isEmpty(oldData)) {
PeopleHelp[] temp = gson.fromJson(oldData, PeopleHelp[].class);
saveData.addAll(Arrays.asList(temp));
}
boolean alreadyHave = false;
for (int i = 0; i < saveData.size(); i++) {
if (saveData.get(i).getId().equalsIgnoreCase(data.getId())) {
PeopleHelp newSavedData = saveData.get(i);
newSavedData.setAccept(data.isAccept());
saveData.set(i, newSavedData);
alreadyHave = true;
break;
}
}
if (!alreadyHave) saveData.add(data);
sharedPreferences.edit()
.putString(Values.SHARED_PREFERENCES_KEY_PEOPLE_HELP,
gson.toJson(saveData))
.apply();
}
private static void sendBroadcast(Context context, PeopleHelp peopleHelp) {
Intent intent = new Intent();
intent.setAction(MainActivityPersonal.ARGS_BROADCAST_FILTER);
intent.putExtra(MainActivityPersonal.ARGS_BROADCAST_DATA, peopleHelp);
context.sendBroadcast(intent);
}
private static void sendNotification(Context context) {
NotificationBuilder.sendNotification(context, Values.NOTIFICATION_ID_PEOPLE_HELP,
Values.NOTIFICATION_TAG_PEOPLE_HELP,
context.getString(R.string.appName),
context.getString(
R.string.notification_message_found_people_helper),
NotificationBuilder
.buildPendingIntentDefault(context),
null);
}
private static boolean isCanRun(SharedPreferences sharedPreferences) {
return sharedPreferences.getBoolean(Values.SHARED_PREFERENCES_KEY_IN_HELP_PROCESS,
false);
}
}
|
C
|
UTF-8
| 1,406 | 3.90625 | 4 |
[] |
no_license
|
//Tom Burright
//Stuxnet 2.0
#include <stdio.h>
int main(void)
{
//Task i: Declare and zeroize an int array with a dimension equal to the number of students + 1
int classAge[13] = { 0 }; //zeroize?
//Task ii: Set index 0 with the age* of the instructor
classAge[0] = 75;
//Task iii: Fill the elements of the array with the ages* of the students starting with index 1
//classAge[1] = 18;
//classAge[2] = 19;
//classAge[3] = 20;
//classAge[4] = 21;
//classAge[5] = 22;
//classAge[6] = 23;
//classAge[7] = 24;
//classAge[8] = 25;
//classAge[9] = 26;
//classAge[10] = 27;
//classAge[11] = 28;
//classAge[12] = 29;
//////////////NEW FOR LOOP! :D //////////////////
for (int y = 1; y < 13; y++)
{
classAge[y] = 17 + y;
}
/////////////////////////////////////////////////
//Task iv: Print the array
printf("Class ages-\n");
for (int i = 0; i < 13; i++) {
if (i == 0) {
printf("Teacher: %d \n", classAge[i]);
}
else {
printf("Student: %d \n", classAge[i]);
}
}
//Task 2 i: Declare and initialize a char array with your favorite saying
//Task 2 iii: Separate each word in the array with a new line character ('\n' or decimal value 10)
char faveQuote[40] = { "I\nlove\nyou\nlike\na\nfat\nkid\nloves\ncake." };
//task 2 ii: Ensure the last index is set to nul ('\0')
faveQuote[40] = '\0';
printf("\nMy favorite quote-\n");
printf("%s \n", faveQuote);
return 0;
}
|
C++
|
UTF-8
| 289 | 2.828125 | 3 |
[] |
no_license
|
//맞은 코드
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
for (int i = 0;i < N;i++)
cout << i + 1 << "\n";
}
//시간초과
/*
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
for (int i = 0;i < N;i++)
cout << i + 1 << endl;
}*/
|
PHP
|
UTF-8
| 3,856 | 2.734375 | 3 |
[] |
no_license
|
<?php
namespace xBeastMode\RainbowArmor\Task;
use pocketmine\item\Item;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\Player;
use pocketmine\scheduler\Task;
use xBeastMode\RainbowArmor\RainbowArmor;
class ArmorTickTask extends Task{
/** @var RainbowArmor */
protected $plugin;
/** @var Player */
protected $player;
/** @var array */
protected $options = [];
/** @var bool */
protected $increasing = false;
/** @var int */
protected $step = 0;
/** @var int */
protected $colorLen = 0;
/** @var array */
protected $generatedColors = [];
/**
*
* AcrobatTask constructor.
*
* @param RainbowArmor $rainbowArmor
* @param Player $player
* @param array $options
*
*/
public function __construct(RainbowArmor $rainbowArmor, Player $player, array $options){
$this->plugin = $rainbowArmor;
$this->player = $player;
$this->options = $options;
$this->generateColors();
}
/**
*
* @return void
*
*/
public function generateColors(): void{
$colors = (int) $this->options["color-amount"];
switch($this->options["type"]){
case "smooth":
$k = mt_rand(0xFF, 0xFFFFFF);
for($i = 0; $i <= $colors; ++$i){
$k = $k + 0xFF;
$this->generatedColors[] = $k;
}
break;
case "flash":
$k = mt_rand(0xFFFF, 0xFFFFFF);
for($i = 0; $i <= $colors; ++$i){
$k = $k + $i;
$this->generatedColors[] = $k;
}
break;
}
$this->colorLen = count($this->generatedColors) - 1;
}
/**
*
* @return int
*
*/
public function getNextColor(): int{
if($this->step >= $this->colorLen){
$this->increasing = false;
}elseif($this->step <= 0){
$this->increasing = true;
}
if($this->increasing){
$this->step++;
}else{
$this->step--;
}
return $this->generatedColors[$this->step];
}
/**
*
* @param int $currentTick
*
*/
public function onRun(int $currentTick){
if(!$this->player->isOnline() || !$this->plugin->hasRGBArmorEnabled($this->player)){
$this->getHandler()->cancel();
$this->player->getArmorInventory()->clearAll(true);
return;
}
$helmet = Item::get(Item::LEATHER_HELMET, 0, 1);
$chest = Item::get(Item::LEATHER_CHESTPLATE, 0, 1);
$legs = Item::get(Item::LEATHER_PANTS, 0, 1);
$feet = Item::get(Item::LEATHER_BOOTS, 0, 1);
$nbt = new CompoundTag("", []);
$nbt->setInt("customColor", $this->getNextColor());
$helmet->setCompoundTag($nbt);
$chest->setCompoundTag($nbt);
$legs->setCompoundTag($nbt);
$feet->setCompoundTag($nbt);
$this->player->getArmorInventory()->setContents([$helmet, $chest, $legs, $feet]);
}
}
|
Java
|
UTF-8
| 12,793 | 1.835938 | 2 |
[] |
no_license
|
package com.ambition.improve.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import com.ambition.product.base.WorkflowIdEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
*
* 类名:8D改进报告
* <p>amb</p>
* <p>厦门安必兴信息科技有限公司</p>
* <p>功能说明:</p>
* @author LPF
* @version 1.00 2016年9月29日 发布
*/
@Entity
@Table(name = "IMP_8D_REPORT")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
public class ImproveReport extends WorkflowIdEntity{
private static final long serialVersionUID = 1L;
public static final String ENTITY_LIST_CODE = "IMP_8D_REPORT";//实体_列表_编码
public static final String ENTITY_LIST_NAME = "8D改进报告";//实体_列表_名称
private String formNo;//表单编号
private String processSection; // 制程区段
private String model;//机种
private Date happenDate;//发生日期
private String sponsor;//发起人
private String productModel;//产品型号
private String customerName;//客户名称
private String hanppenArea;//发生区
private String productPhase;//产品阶段
private String problemBelong;//问题归属
private String lotNo;//lot no
private String problemSource;//问题来源
private String problemType;//问题类型
private String problemDegree;//问题严重度
private String problemPoint;//问题点
private String remark1;//问题点说明
private String unqualifiedRate;//不良率
private String productionEnterpriseGroup;//生产事业群
//D2
@Column(length=1000)
private String problemDescrible;//问题描述
private String dutyManD2;//D2负责人
private String dutyManD2Login;//D2负责人登录名
private String dutyManD2Manager;//D2负责人主管
private String dutyManD2ManagerLogin;//D2负责人主管登录名
private String deprtmentD2;//D2部门
private Date planDateD2;//D2预计完成时间
//D3
private Integer clientStore;//客户端库存
private Integer onOrder;//在途数量
private Integer innerStore;//内部成品仓库库存数量
private Integer innerOnOrder;//内部在线数量
private Integer rmaStore;//RMA库存数量
private Integer materialStore;//原材料仓
@Column(length=1000)
private String emergencyMeasures;//应急措施
//D4
private String dutyManD4;//D4负责人
private String dutyManD4Login;//D4负责人登录名
private String deprtmentD4;//D4部门
private Date planDateD4;//D4预计完成时间
private String method;//方法
private String reason;//原因分类
private String dutyDept;//责任部门
@Column(length=3000)
private String remarkD4;//D4意见
private String attachmentD4;//D4附件
//D5
@Column(length=3000)
private String remarkD5;//D5意见
private String attachmentD5;//D5附件
//D6
private String dutyManD6;//D6负责人
private String dutyManD6Login;//D6负责人登录名
private String deprtmentD6;//D6部门
private Date planDateD6;//D6预计完成时间
@Column(length=3000)
private String remarkD6;//D6意见
private String attachmentD6;//D6附件
//D7
@Column(length=3000)
private String remarkD7;//D7意见
private String attachmentD7;//D7附件aw
//D8
private Date confirmDate;//确认日期
private String closeState;//关闭状态
private String closeMan;//关闭确认人
private String closeManLogin;//关闭确认人登录名
private Date closeDate;//结案日期
@Column(length=3000)
private String remarkD8;//D8意见
private String attachmentD8;//D8附件
@OneToMany(mappedBy = "improveReport",cascade={CascadeType.ALL})
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@JsonIgnore
List<ImproveReportTeam> improveReportTeams;//建立团队
public String getFormNo() {
return formNo;
}
public void setFormNo(String formNo) {
this.formNo = formNo;
}
public Date getHappenDate() {
return happenDate;
}
public void setHappenDate(Date happenDate) {
this.happenDate = happenDate;
}
public String getSponsor() {
return sponsor;
}
public void setSponsor(String sponsor) {
this.sponsor = sponsor;
}
public String getProductModel() {
return productModel;
}
public void setProductModel(String productModel) {
this.productModel = productModel;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getHanppenArea() {
return hanppenArea;
}
public void setHanppenArea(String hanppenArea) {
this.hanppenArea = hanppenArea;
}
public String getProductPhase() {
return productPhase;
}
public void setProductPhase(String productPhase) {
this.productPhase = productPhase;
}
public String getProblemBelong() {
return problemBelong;
}
public void setProblemBelong(String problemBelong) {
this.problemBelong = problemBelong;
}
public String getLotNo() {
return lotNo;
}
public void setLotNo(String lotNo) {
this.lotNo = lotNo;
}
public String getProblemSource() {
return problemSource;
}
public void setProblemSource(String problemSource) {
this.problemSource = problemSource;
}
public String getProblemType() {
return problemType;
}
public void setProblemType(String problemType) {
this.problemType = problemType;
}
public String getProblemDegree() {
return problemDegree;
}
public void setProblemDegree(String problemDegree) {
this.problemDegree = problemDegree;
}
public String getProblemPoint() {
return problemPoint;
}
public void setProblemPoint(String problemPoint) {
this.problemPoint = problemPoint;
}
public String getUnqualifiedRate() {
return unqualifiedRate;
}
public void setUnqualifiedRate(String unqualifiedRate) {
this.unqualifiedRate = unqualifiedRate;
}
public String getProductionEnterpriseGroup() {
return productionEnterpriseGroup;
}
public void setProductionEnterpriseGroup(String productionEnterpriseGroup) {
this.productionEnterpriseGroup = productionEnterpriseGroup;
}
public String getProblemDescrible() {
return problemDescrible;
}
public void setProblemDescrible(String problemDescrible) {
this.problemDescrible = problemDescrible;
}
public String getDutyManD2() {
return dutyManD2;
}
public void setDutyManD2(String dutyManD2) {
this.dutyManD2 = dutyManD2;
}
public String getDutyManD2Login() {
return dutyManD2Login;
}
public void setDutyManD2Login(String dutyManD2Login) {
this.dutyManD2Login = dutyManD2Login;
}
public String getDeprtmentD2() {
return deprtmentD2;
}
public void setDeprtmentD2(String deprtmentD2) {
this.deprtmentD2 = deprtmentD2;
}
public Date getPlanDateD2() {
return planDateD2;
}
public void setPlanDateD2(Date planDateD2) {
this.planDateD2 = planDateD2;
}
public Integer getClientStore() {
return clientStore;
}
public void setClientStore(Integer clientStore) {
this.clientStore = clientStore;
}
public Integer getOnOrder() {
return onOrder;
}
public void setOnOrder(Integer onOrder) {
this.onOrder = onOrder;
}
public Integer getInnerStore() {
return innerStore;
}
public void setInnerStore(Integer innerStore) {
this.innerStore = innerStore;
}
public Integer getInnerOnOrder() {
return innerOnOrder;
}
public void setInnerOnOrder(Integer innerOnOrder) {
this.innerOnOrder = innerOnOrder;
}
public Integer getRmaStore() {
return rmaStore;
}
public void setRmaStore(Integer rmaStore) {
this.rmaStore = rmaStore;
}
public Integer getMaterialStore() {
return materialStore;
}
public void setMaterialStore(Integer materialStore) {
this.materialStore = materialStore;
}
public String getEmergencyMeasures() {
return emergencyMeasures;
}
public void setEmergencyMeasures(String emergencyMeasures) {
this.emergencyMeasures = emergencyMeasures;
}
public String getDutyManD4() {
return dutyManD4;
}
public void setDutyManD4(String dutyManD4) {
this.dutyManD4 = dutyManD4;
}
public String getDutyManD4Login() {
return dutyManD4Login;
}
public void setDutyManD4Login(String dutyManD4Login) {
this.dutyManD4Login = dutyManD4Login;
}
public String getDeprtmentD4() {
return deprtmentD4;
}
public void setDeprtmentD4(String deprtmentD4) {
this.deprtmentD4 = deprtmentD4;
}
public Date getPlanDateD4() {
return planDateD4;
}
public void setPlanDateD4(Date planDateD4) {
this.planDateD4 = planDateD4;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getDutyDept() {
return dutyDept;
}
public void setDutyDept(String dutyDept) {
this.dutyDept = dutyDept;
}
public String getRemarkD4() {
return remarkD4;
}
public void setRemarkD4(String remarkD4) {
this.remarkD4 = remarkD4;
}
public String getAttachmentD4() {
return attachmentD4;
}
public void setAttachmentD4(String attachmentD4) {
this.attachmentD4 = attachmentD4;
}
public String getRemarkD5() {
return remarkD5;
}
public void setRemarkD5(String remarkD5) {
this.remarkD5 = remarkD5;
}
public String getAttachmentD5() {
return attachmentD5;
}
public void setAttachmentD5(String attachmentD5) {
this.attachmentD5 = attachmentD5;
}
public String getDutyManD6() {
return dutyManD6;
}
public void setDutyManD6(String dutyManD6) {
this.dutyManD6 = dutyManD6;
}
public String getDutyManD6Login() {
return dutyManD6Login;
}
public void setDutyManD6Login(String dutyManD6Login) {
this.dutyManD6Login = dutyManD6Login;
}
public String getDeprtmentD6() {
return deprtmentD6;
}
public void setDeprtmentD6(String deprtmentD6) {
this.deprtmentD6 = deprtmentD6;
}
public Date getPlanDateD6() {
return planDateD6;
}
public void setPlanDateD6(Date planDateD6) {
this.planDateD6 = planDateD6;
}
public String getRemarkD6() {
return remarkD6;
}
public void setRemarkD6(String remarkD6) {
this.remarkD6 = remarkD6;
}
public String getAttachmentD6() {
return attachmentD6;
}
public void setAttachmentD6(String attachmentD6) {
this.attachmentD6 = attachmentD6;
}
public String getRemarkD7() {
return remarkD7;
}
public void setRemarkD7(String remarkD7) {
this.remarkD7 = remarkD7;
}
public String getAttachmentD7() {
return attachmentD7;
}
public void setAttachmentD7(String attachmentD7) {
this.attachmentD7 = attachmentD7;
}
public Date getConfirmDate() {
return confirmDate;
}
public void setConfirmDate(Date confirmDate) {
this.confirmDate = confirmDate;
}
public String getCloseState() {
return closeState;
}
public void setCloseState(String closeState) {
this.closeState = closeState;
}
public String getCloseMan() {
return closeMan;
}
public void setCloseMan(String closeMan) {
this.closeMan = closeMan;
}
public String getCloseManLogin() {
return closeManLogin;
}
public void setCloseManLogin(String closeManLogin) {
this.closeManLogin = closeManLogin;
}
public Date getCloseDate() {
return closeDate;
}
public void setCloseDate(Date closeDate) {
this.closeDate = closeDate;
}
public String getRemarkD8() {
return remarkD8;
}
public void setRemarkD8(String remarkD8) {
this.remarkD8 = remarkD8;
}
public String getAttachmentD8() {
return attachmentD8;
}
public void setAttachmentD8(String attachmentD8) {
this.attachmentD8 = attachmentD8;
}
public List<ImproveReportTeam> getImproveReportTeams() {
return improveReportTeams;
}
public void setImproveReportTeams(List<ImproveReportTeam> improveReportTeams) {
this.improveReportTeams = improveReportTeams;
}
public String getRemark1() {
return remark1;
}
public void setRemark1(String remark1) {
this.remark1 = remark1;
}
public String getDutyManD2Manager() {
return dutyManD2Manager;
}
public void setDutyManD2Manager(String dutyManD2Manager) {
this.dutyManD2Manager = dutyManD2Manager;
}
public String getDutyManD2ManagerLogin() {
return dutyManD2ManagerLogin;
}
public void setDutyManD2ManagerLogin(String dutyManD2ManagerLogin) {
this.dutyManD2ManagerLogin = dutyManD2ManagerLogin;
}
public String getProcessSection() {
return processSection;
}
public void setProcessSection(String processSection) {
this.processSection = processSection;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
|
Python
|
UTF-8
| 571 | 4.0625 | 4 |
[] |
no_license
|
"""
Given a number, return all its prime divisors in a list. Create a function
that takes a number as an argument and returns all its prime divisors.
* n = 27
* All divisors: `[3, 9, 27]`
* Finally, from that list of divisors, return the prime ones: `[3]`
### Examples
prime_divisors(27) ➞ [3]
prime_divisors(99) ➞ [3, 11]
prime_divisors(3457) ➞ [3457]
### Notes
N/A
"""
def prime_divisors(num):
divisors=[d for d in range(2,num//2+1) if num%d==0]
return [d for d in divisors if all(d%od!=0 for od in divisors if od!=d)]
|
Markdown
|
UTF-8
| 913 | 3 | 3 |
[] |
no_license
|
# [Personal Library](https://www.freecodecamp.org/learn/quality-assurance/quality-assurance-projects/personal-library)
[](https://repl.it/@Panda4817/personal-library)
A freecodecamp project for the quality assurance certificate. A library API implementation using NodeJS, ExpressJS server and MongoDB database for storage of books. It follows CRUD principles. You can add books, update them with new comments, delete a book and delete all books. I have also added a frontend to test out API responses and wrote all 10 functional tests using Chai and Mocha.
## Usage on local machine
- Add `NODE_ENV=test` to `.env`
- Add `DB=<your database connection variable>` to `.env`
- Add `PORT=8080` to `.env`
- run `npm install && npm start` to run all 10 functional tests and start node server
- Open `localhost:8080` on browser to see frontend
|
Markdown
|
UTF-8
| 1,289 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
# mapeo-migrate
Commandline tool for mapeo migrating databases from the older format to the
latest.
## Migrate from osm-p2p-db to kappa-osm
```
npm run migrate /path/to/datafile.mapeosinangoe output/
```
Where `datafile.mapeosinangoe` is an [osm-p2p-syncfile](https://github.com/digidem/osm-p2p-syncfile), and `output/` is the output directory.
Creates two directories:
* `old` which is the old database
* `output`, which contains `data` and `media` directory.
## Fix media paths
The migration script assumes [safe-fs-blob-store](https://github.com/noffle/safe-fs-blob-store) for media, and mapeo-migrate
doesn't add dir prefixes (e.g. media/fo/foo.jpg instead of media/foo.jpg)
To fix the media paths so they are supported by `@mapeo/core`, run:
```
./update_media_paths.sh output
```
## Test the migration
Run the tests to see if they're the same:
```
npm run test output/
```
Where `output/` is the same directory you specified before in the `npm run
migrate` script.
## Create osm-p2p-syncfile
Install `osm-p2p-syncfile` globally:
```
npm install -g osm-p2p-syncfile
```
Then to create the syncfile:
```
osm-p2p-syncfile init kappa.mapeodata output
```
Where `output/` is the same directory you created before with the `migrate`
script.
## License
MIT
|
Python
|
UTF-8
| 190 | 3.65625 | 4 |
[] |
no_license
|
def space():
statement = input("Irj be egy mondatot: ")
new_statement = ""
for letter in statement:
new_statement += letter + " "
print(new_statement)
space()
|
Markdown
|
UTF-8
| 1,499 | 3.296875 | 3 |
[] |
no_license
|
* `code` {string} 将被编译和运行的JavaScript代码
* `contextifiedSandbox` {Object} 一个被[上下文隔离化][contextified]过的对象,会在代码被编译和执行之后充当`global`对象
* `options`
* `filename` {string} 定义供脚本生成的堆栈跟踪信息所使用的文件名
* `lineOffset` {number} 定义脚本生成的堆栈跟踪信息所显示的行号偏移
* `columnOffset` {number} 定义脚本生成的堆栈跟踪信息所显示的列号偏移
* `displayErrors` {boolean} 当值为真的时候,假如在解析代码的时候发生错误[`Error`][],引起错误的行将会被加入堆栈跟踪信息
* `timeout` {number} 定义在被终止执行之前此code被允许执行的最大毫秒数。假如执行被终止,将会抛出一个错误[`Error`][]
`vm.runInContext()`在指定的`contextifiedSandbox`的上下文里执行vm.Script对象中被编译后的代码并返回其结果。被执行的代码无法获取本地作用域。`contextifiedSandbox`*必须*是事先被[`vm.createContext()`][][上下文隔离化][contextified]过的对象。
以下例子使用一个单独的, [上下文隔离化][contextified]过的对象来编译并运行几个不同的脚本:
```js
const util = require('util');
const vm = require('vm');
const sandbox = { globalVar: 1 };
vm.createContext(sandbox);
for (let i = 0; i < 10; ++i) {
vm.runInContext('globalVar *= 2;', sandbox);
}
console.log(util.inspect(sandbox));
// { globalVar: 1024 }
```
|
PHP
|
UTF-8
| 2,976 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace Webservices\StructType;
use \WsdlToPhp\PackageBase\AbstractStructBase;
/**
* This class stands for geoLocationDistanceSortedPostcodesRequestType StructType
* @subpackage Structs
* @author JCID <[email protected]>
*/
class GeoLocationDistanceSortedPostcodesRequestType extends AbstractStructBase
{
/**
* The postcodefrom
* @var string
*/
public $postcodefrom;
/**
* The postcodes
* @var \Webservices\ArrayType\StringArray
*/
public $postcodes;
/**
* Constructor method for geoLocationDistanceSortedPostcodesRequestType
* @uses GeoLocationDistanceSortedPostcodesRequestType::setPostcodefrom()
* @uses GeoLocationDistanceSortedPostcodesRequestType::setPostcodes()
* @param string $postcodefrom
* @param \Webservices\ArrayType\StringArray $postcodes
*/
public function __construct($postcodefrom = null, \Webservices\ArrayType\StringArray $postcodes = null)
{
$this
->setPostcodefrom($postcodefrom)
->setPostcodes($postcodes);
}
/**
* Get postcodefrom value
* @return string|null
*/
public function getPostcodefrom()
{
return $this->postcodefrom;
}
/**
* Set postcodefrom value
* @param string $postcodefrom
* @return \Webservices\StructType\GeoLocationDistanceSortedPostcodesRequestType
*/
public function setPostcodefrom($postcodefrom = null)
{
// validation for constraint: string
if (!is_null($postcodefrom) && !is_string($postcodefrom)) {
throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($postcodefrom)), __LINE__);
}
$this->postcodefrom = $postcodefrom;
return $this;
}
/**
* Get postcodes value
* @return \Webservices\ArrayType\StringArray|null
*/
public function getPostcodes()
{
return $this->postcodes;
}
/**
* Set postcodes value
* @param \Webservices\ArrayType\StringArray $postcodes
* @return \Webservices\StructType\GeoLocationDistanceSortedPostcodesRequestType
*/
public function setPostcodes(\Webservices\ArrayType\StringArray $postcodes = null)
{
$this->postcodes = $postcodes;
return $this;
}
/**
* Method called when an object has been exported with var_export() functions
* It allows to return an object instantiated with the values
* @see AbstractStructBase::__set_state()
* @uses AbstractStructBase::__set_state()
* @param array $array the exported values
* @return \Webservices\StructType\GeoLocationDistanceSortedPostcodesRequestType
*/
public static function __set_state(array $array)
{
return parent::__set_state($array);
}
/**
* Method returning the class name
* @return string __CLASS__
*/
public function __toString()
{
return __CLASS__;
}
}
|
Java
|
UTF-8
| 6,488 | 2.046875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.netcai.admin.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class BuyerReceipt implements Serializable{
/**
*/
private static final long serialVersionUID = -8261082704694840981L;
/**
* 自增ID
*/
private Long brId;
/**
* 买家ID
*/
private Long buyerId;
/**
* 收款日期
*/
private Date receiptDate;
/**
* 销售人员ID
*/
private Long saleId;
/**
* 配送人员ID
*/
private Long deliveryId;
/**
* 应收金额
*/
private BigDecimal ysAmt;
/**
* 实收金额
*/
private BigDecimal ssAmt;
/**
* 收款状态(1未收 2已收)
*/
private Byte skStatus;
/**
* 收款备注
*/
private String skReamk;
/**
* 收款时间
*/
private Date skTime;
/**
* 核实状态(1未核实 2已核实)
*/
private Byte hsStatus;
/**
* 核实人
*/
private Long hsUserId;
/**
* 核实时间
*/
private Date hsTime;
/**
* 入账状态(1未入账 2已入账)
*/
private Byte rzStatus;
/**
* 入账人
*/
private Long rzUserId;
/**
* 入账时间
*/
private Date rzTime;
public Long getBrId() {
return brId;
}
public void setBrId(Long brId) {
this.brId = brId;
}
public Long getBuyerId() {
return buyerId;
}
public void setBuyerId(Long buyerId) {
this.buyerId = buyerId;
}
public Date getReceiptDate() {
return receiptDate;
}
public void setReceiptDate(Date receiptDate) {
this.receiptDate = receiptDate;
}
public Long getSaleId() {
return saleId;
}
public void setSaleId(Long saleId) {
this.saleId = saleId;
}
public Long getDeliveryId() {
return deliveryId;
}
public void setDeliveryId(Long deliveryId) {
this.deliveryId = deliveryId;
}
public BigDecimal getYsAmt() {
return ysAmt;
}
public void setYsAmt(BigDecimal ysAmt) {
this.ysAmt = ysAmt;
}
public BigDecimal getSsAmt() {
return ssAmt;
}
public void setSsAmt(BigDecimal ssAmt) {
this.ssAmt = ssAmt;
}
public Byte getSkStatus() {
return skStatus;
}
public void setSkStatus(Byte skStatus) {
this.skStatus = skStatus;
}
public String getSkReamk() {
return skReamk;
}
public void setSkReamk(String skReamk) {
this.skReamk = skReamk == null ? null : skReamk.trim();
}
public Date getSkTime() {
return skTime;
}
public void setSkTime(Date skTime) {
this.skTime = skTime;
}
public Byte getHsStatus() {
return hsStatus;
}
public void setHsStatus(Byte hsStatus) {
this.hsStatus = hsStatus;
}
public Long getHsUserId() {
return hsUserId;
}
public void setHsUserId(Long hsUserId) {
this.hsUserId = hsUserId;
}
public Date getHsTime() {
return hsTime;
}
public void setHsTime(Date hsTime) {
this.hsTime = hsTime;
}
public Byte getRzStatus() {
return rzStatus;
}
public void setRzStatus(Byte rzStatus) {
this.rzStatus = rzStatus;
}
public Long getRzUserId() {
return rzUserId;
}
public void setRzUserId(Long rzUserId) {
this.rzUserId = rzUserId;
}
public Date getRzTime() {
return rzTime;
}
public void setRzTime(Date rzTime) {
this.rzTime = rzTime;
}
/************************************************Query**********************************************************/
/**
* 买家
*/
private String buyerName;
/**
* 销售
*/
private String trueName;
/**
* 配送
*/
private String deliveryName;
/**
* 核实人
*/
private String hsName;
/**
* 入账人
*/
private String rzName;
public String getBuyerName() {
return buyerName;
}
public void setBuyerName(String buyerName) {
this.buyerName = buyerName;
}
public String getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
public String getDeliveryName() {
return deliveryName;
}
public void setDeliveryName(String deliveryName) {
this.deliveryName = deliveryName;
}
public String getHsName() {
return hsName;
}
public void setHsName(String hsName) {
this.hsName = hsName;
}
public String getRzName() {
return rzName;
}
public void setRzName(String rzName) {
this.rzName = rzName;
}
/**
* 是否相同;
*/
private String alike;
public String getAlike() {
return alike;
}
public void setAlike(String alike) {
this.alike = alike;
}
/**
* 收款日期
*/
private String receiptDateQuery;
public String getReceiptDateQuery() {
return receiptDateQuery;
}
public void setReceiptDateQuery(String receiptDateQuery) {
this.receiptDateQuery = receiptDateQuery;
}
/**
* 最佳收货时间开始;
*/
private String beatTimeStart;
/**
* 最佳收货时间结束;
*/
private String beatTimeStop;
/**
* 商品总金额
*/
private BigDecimal totalAmount;
/**
* 原始商品总金额
*/
private BigDecimal oldAmt;
public BigDecimal getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
public BigDecimal getOldAmt() {
return oldAmt;
}
public void setOldAmt(BigDecimal oldAmt) {
this.oldAmt = oldAmt;
}
/**
* 配送人员;
*/
private String deliveryIds;
public String getDeliveryIds() {
return deliveryIds;
}
public void setDeliveryIds(String deliveryIds) {
this.deliveryIds = deliveryIds;
}
/**所属区
*/
private Long areaId;
public Long getAreaId() {
return areaId;
}
public void setAreaId(Long areaId) {
this.areaId = areaId;
}
/**所属区
*/
private String areaName;
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public String getBeatTimeStart() {
return beatTimeStart;
}
public void setBeatTimeStart(String beatTimeStart) {
this.beatTimeStart = beatTimeStart;
}
public String getBeatTimeStop() {
return beatTimeStop;
}
public void setBeatTimeStop(String beatTimeStop) {
this.beatTimeStop = beatTimeStop;
}
}
|
PHP
|
UTF-8
| 612 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* PhpStorm
* @access public (访问修饰符)
* @author wuhaiyan <[email protected]>
* @copyright (c) 2017, Huishoubao
*/
namespace App\Order\Modules\Inc;
class StoreAddress
{
/**
* 获取线下门店地址
* @param int $appid
* @return array
*/
public static function getStoreAddress(int $appid){
$arr = [
'139'=>'天津市西青区大学城师范大学南门华木里底商711旁100米,拿趣用数码共享便利店.电话:18611002204',
];
if(isset($arr[$appid])){
return $arr[$appid];
}
return false;
}
}
|
JavaScript
|
UTF-8
| 298 | 2.6875 | 3 |
[] |
no_license
|
/* Color picker */
const colorPicker = document.querySelector('.project__color-picker');
const editorBackground = document.querySelector('.editor__container');
colorPicker.addEventListener(
'input',
function () {
editorBackground.style = `background:${colorPicker.value}`;
},
false
);
|
C++
|
UTF-8
| 4,121 | 2.625 | 3 |
[] |
no_license
|
#include "PlayState.h"
#include <ctime>
PlayState::PlayState()
{
//ctor
}
void PlayState::Init()
{
srand(time(0));
shader.Setup("res/shaders/vertexshader.vs", "res/shaders/fragmentshader.fs");
background.Setup(shader, string("background"));
background.SetScale(glm::vec3(1,1,1));
background.update(0);
boat.Setup(shader);
numCaught = 0;
for(unsigned int i = 0; i < 5; i++)
{
addFish();
}
for(unsigned int i = 0; i < entities.size(); i++)
{
entities[i]->update(boat);
}
}
void PlayState::Update(Game *game)
{
if(Input::getKey(Input::KEY_Z))
{
game->ChangeState(1);
}
else
{
for(std::vector<Fish*>::iterator i = entities.begin(); i != entities.end(); )
{
if((*i)->GetXPos() > 1 + (*i)->GetScale().x)
{
delete *i;
i = entities.erase(i);
addFish();
}
else if((*i)->GetXPos() < -1 - (*i)->GetScale().x)
{
delete *i;
i = entities.erase(i);
addFish();
}
else if ((*i)->GetRemoveFish())
{
delete *i;
i = entities.erase(i);
addFish();
boat.SetFishHooked(false);
}
else ++i;
}
for(unsigned int i = 0; i < entities.size(); i++)
{
entities[i]->update(boat);
}
boat.update();
/********************************************************
* Check Collision
*********************************************************/
if(!boat.GetFishHooked())
{
float hookMinX = boat.GetHookXPos() - boat.GetHookScale().x;
float hookMaxX = boat.GetHookXPos() + boat.GetHookScale().x;
float hookMinY = boat.GetHookYPos() - boat.GetHookScale().y;
float hookMaxY = boat.GetHookYPos() + boat.GetHookScale().y;
for(unsigned int i = 0; i < entities.size(); i++)
{
Fish * f = static_cast<Fish*> (entities[i]);
float fishMinX = f->GetBoxMinX();
float fishMaxX = f->GetBoxMaxX();
float fishMinY = f->GetBoxMinY();
float fishMaxY = f->GetBoxMaxY();
if( fishMinX < hookMaxX && fishMaxX > hookMinX
&& fishMinY < hookMaxY && fishMaxY > hookMinY)
{
f->IsCaught(true);
if(f->GetXSpeed() < 0)
f->SetXPos(boat.GetHookXPos() + f->GetScale().x - .02);
else
f->SetXPos(boat.GetHookXPos() - f->GetScale().x);
boat.SetFishHooked(true);
numCaught++;
ap.play(1);
}
}
}
}
}
void PlayState::Render()
{
shader.bind();
background.render();
boat.render();
for(std::vector<Fish*>::iterator it = entities.begin(); it != entities.end(); it++)
{
(*it)->render();
}
std::ostringstream ss;
ss << numCaught;
tr.renderText(ss.str(), Game::windowWidth - ss.str().length()*20 -5, Game::windowHeight - 25, 20, Game::windowWidth, Game::windowHeight);
}
PlayState::~PlayState()
{
for(std::vector<Fish*>::iterator it = entities.begin(); it != entities.end(); it++)
{
delete (*it);
}
entities.clear();
}
void PlayState::addFish()
{
if(rand() % 2 == 0)
{
float s = getRand(0.05, 0.15);
float y = getRand(-.8+s, .25-s);
float xSpeed = getRand(0.005f, 0.006f)*-1;
entities.push_back(new Fish(shader, 1.0, y, xSpeed, 0.0, s, "fish"));
}
else
{
float s = getRand(0.05f, 0.15f);
float y = getRand(-0.8f+s, 0.25f-s);
float xSpeed = getRand(0.005f, 0.006f);
entities.push_back(new Fish(shader, -1.0, y, xSpeed, 0.0, s, "fishr"));
}
}
float PlayState::getRand(float a, float b)
{
return ((b-a)*((float)rand()/RAND_MAX))+a;
}
|
Java
|
UTF-8
| 985 | 2.96875 | 3 |
[] |
no_license
|
package logicaDeProgramação;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CalcularDiferencaData {
public void calcularDiferencaData(String data1, String data2) throws ParseException{
StringBuilder stringBuilder1 = new StringBuilder(data1);
stringBuilder1.insert(data1.length() - 4, '-');
stringBuilder1.insert(stringBuilder1.length() - 7, '-');
StringBuilder stringBuilder2 = new StringBuilder(data2);
stringBuilder2.insert(data2.length() - 4, '-');
stringBuilder2.insert(stringBuilder2.length() - 7, '-');
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
Date dataFormatada1 = sdf1.parse(stringBuilder1.toString());
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
Date dataFormatada2 = sdf2.parse(stringBuilder2.toString());
long diferenca = (dataFormatada2.getTime() - dataFormatada1.getTime()) + 3600000;
System.out.println(diferenca / 86400000L);
}
}
|
C++
|
UTF-8
| 648 | 2.875 | 3 |
[] |
no_license
|
#include "Peceptron.h"
Peceptron::Peceptron()
{
alpha = 0.1f;
theta = 0.2f;
w1 = 0.3f;
w2 = -0.1f;
for (int p = 0; p < 20; p++)
{
int i = p % 4;
std::cout << "i = " << i << std::endl;
X = (x1[i] * w1) + (x2[i] * w2);
std::cout << "X = " << X << std::endl;
if (X >= theta)
{
Y = 1;
std::cout << "Y = " << Y << std::endl;
}
else
{
Y = 0;
std::cout << "Y = " << Y << std::endl;
}
e = Yd[i] - Y;
std::cout << "e = " << e << std::endl;
w1 = w1 + alpha * x1[i] * e;
w2 = w2 + alpha * x2[i] * e;
std::cout << "new w1 = " << w1 << std::endl;
std::cout << "new w2 = " << w2 << "\n" << std::endl;
}
}
|
Java
|
UTF-8
| 177 | 1.71875 | 2 |
[] |
no_license
|
package cn.orditech.entity;
import java.io.Serializable;
/**
* Created by kimi on 2017/6/11.
*/
public interface BaseEntity extends Serializable {
Long getId ();
}
|
C++
|
UTF-8
| 504 | 3.09375 | 3 |
[] |
no_license
|
#include "PlayerData.h"
PlayerData::PlayerData(unsigned int cash) {
this->cash = cash;
}
void PlayerData::takeCard(Card a, std::shared_ptr<Player> const & p) {
a.setOwner(p);
cards.push_back(a);
}
void PlayerData::performCardChange(int index, Card card) {
cards[index].suit = card.suit;
cards[index].value = card.value;
}
void PlayerData::display() {
for(size_t i = 0; i < cards.size(); i++) {
std::cout << cards[i].open() << " ";
}
std::cout << std::endl;
}
|
JavaScript
|
UTF-8
| 1,212 | 3.5 | 4 |
[] |
no_license
|
/**
1- In a build system, jobs have dependencies.
We want to create a scchedule for the build system in which jobs are ordered based on their dependencies. A job should appear in the schedule when all dependent jobs are already scheduled.
{
j1: [j2],
j2: [j3, j4],
j3: [j4]
j4: []
}
**/
console.log(scheduler({
j1: ["j2"],
j2: ["j3", "j4"],
j3: ["j4"],
j4: []
}));
function scheduler(input) {
const jobs = Object.keys(input);
let job;
let sc = [];
for (let i=0; i<jobs.length; i++) {
job = jobs[i];
if (input[job].length === 0) {
sc.push(job);
jobs.splice(i, 1);
}
}
return findepnedingJobs(input, jobs, sc);
}
function findepnedingJobs(input, jobs, sc) {
if (!jobs.length) {
return sc;
}
let subT;
for (let i=0; i<jobs.length; i++) {
subT = input[jobs[i]];
if (subT.length <= sc.length) {
if (allSubtasksComplete(subT, sc) === true) {
sc.push(jobs[i]);
jobs.splice(i, 1);
}
}
}
return findepnedingJobs(input, jobs, sc)
}
function allSubtasksComplete(subT, sc) {
for (let j=0; j<subT.length; j++) {
if (sc.indexOf(subT[j]) === -1) {
return false;
}
}
return true;
}
|
Python
|
UTF-8
| 47 | 3.015625 | 3 |
[] |
no_license
|
a=int(input())
b=int(input())
c=(a*b)
print(c)
|
Markdown
|
UTF-8
| 702 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
<h1 dir="rtl">الحَجَّاجُ بن يوسُف يَحكُم العِراقَ .</h1>
<h5 dir="rtl">العام الهجري: 75
العام الميلادي: 694
</h5>
<p dir="rtl">حَكَم الحَجَّاجُ بن يوسُف بعدَ أن قَضى على ابنِ الزُّبيرِ، حَكَم الحِجازَ كُلَّها ثمَّ وَلَّاهُ عبدُ الملك أَمْرَ العِراق بدلًا مِن خالدِ بن عبدِ الله القَسْريِّ، فصارت العِراق للحَجَّاج، وخُطْبَتُهُ فيها مشهورة، فأَمْسَك زِمامَ الأُمورِ فيها بِشِدَّةٍ فدانَتْ له وخَضَعت.</p></br>
|
Java
|
UTF-8
| 2,384 | 3.453125 | 3 |
[] |
no_license
|
package io.akessler.day04;
import io.akessler.AdventUtility;
import java.util.*;
public class Day4 {
public static void main(String[] args) {
List<String> lines = AdventUtility.readInput(4);
int answer1 = part1(lines);
int answer2 = part2(lines);
System.out.println(answer1);
System.out.println(answer2);
}
private static int part1(List<String> lines) {
int validCount = 0;
for(String line : lines) {
String[] words = line.split(" ");
Set<String> seenWords = new HashSet<>();
boolean duplicate = false;
for (String w : words) {
if (seenWords.contains(w)) {
duplicate = true;
break;
}
else {
seenWords.add(w);
}
}
if (!duplicate) {
validCount++;
}
}
return validCount;
}
private static int part2(List<String> lines) {
int validCount = 0;
for(String line : lines) {
line = line.toLowerCase();
String[] words = line.split(" ");
Map<String, int[]> map = new HashMap<>();
for(String w : words) {
int[] charCount = new int[26];
for(char c : w.toCharArray()) {
charCount[c - 'a'] += 1;
}
map.put(w, charCount);
}
boolean foundAnagram = false;
for(int i=0; i<words.length; i++) {
for(int j=i+1; j<words.length; j++){
// can check length as heuristic, compare letter counts if equal
boolean foundDiff = false;
for(int k=0; k<26; k++) {
if(map.get(words[i])[k] != map.get(words[j])[k]){
foundDiff = true;
break;
}
}
if(!foundDiff) {
foundAnagram = true;
break;
}
}
if(foundAnagram) {
break;
}
}
if(!foundAnagram) {
validCount++;
}
}
return validCount;
}
}
|
C#
|
UTF-8
| 925 | 2.578125 | 3 |
[] |
no_license
|
using ThoughtWorks.Test.SalesTaxes.Library;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace ThoughtWorks.Test.SalesTaxes.LibraryTests
{
[TestClass()]
public class BasketInputOneTest_Given_input_one {
Basket basket;
[TestInitialize]
public void Setup() {
basket = new Basket();
basket.Add("book", 1);
basket.Add("music CD", 1);
basket.Add("chocolate bar", 1);
}
[TestMethod]
public void Then_it_should_return_correct_tax() {
var receipt = basket.GetReceipt();
Assert.AreEqual(1.50M, receipt.SalesTax());
}
[TestMethod]
public void Then_it_should_return_correct_totalprice() {
var receipt = basket.GetReceipt();
Assert.AreEqual(29.83M, receipt.TotalPrice());
}
}
}
|
Java
|
UTF-8
| 384 | 3.09375 | 3 |
[] |
no_license
|
package clases;
public class Pair {
private int one;
private int two;
public Pair(int a, int b){
one = a;
two = b;
}
public int getFirst(){
return one;
}
public int getSecond(){
return two;
}
public void setFirst(int a){
one = a;
}
public void setSecond(int b){
two = b;
}
}
|
C#
|
UTF-8
| 1,173 | 3.703125 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1
{
class ShellSort : AbstractSortable
{
public override void Alghorithm(int[] arr)
{
int array_size = arr.Length;
int i, j, inc, temp;
inc = 3;
while (inc > 0)
{
for (i = 0; i < array_size; i++)
{
j = i;
temp = arr[i];
while ((j >= inc) && (arr[j - inc] > temp))
{
arr[j] = arr[j - inc];
j = j - inc;
}
arr[j] = temp;
}
if (inc / 2 != 0)
inc = inc / 2;
else if (inc == 1)
inc = 0;
else
inc = 1;
}
}
public void show(int[] arr)
{
foreach (var element in arr)
{
Console.Write(element + " ");
}
Console.Write("\n");
}
}
}
|
Java
|
UTF-8
| 8,548 | 3.03125 | 3 |
[] |
no_license
|
package com.company;
import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ./p1 <Document set> <Query file>
public class p1 {
static File stopWords = new File("stop-word-list.txt");
// Create a TreeSet from the provided stopWords file. This is class-defined since only one instance is needed
static TreeSet<String> stopWordsTree= getStopWordsAsTree(stopWords);
static Porter porter = new Porter();
static ArrayList<String> queryList = new ArrayList<>();
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Please use two command line arguments.\n" +
"Example: ./p1 <Document Set> <Query Terms File>");
System.exit(0); }
String fileName;
// Set the path to the documentset folder
File documentSet = new File(args[0]);
File queryDocument = new File(args[1]);
//File queryDocument = new File("/Users/ethananderson/Downloads/query.txt");
//File documentSet = new File("/Users/ethananderson/Downloads/documentset");
File[] fileList = documentSet.listFiles(); // Get the # of total files
createQueryTermList(queryDocument);
// Create a thread pool so threads can be reused if needed
ExecutorService executorService = Executors.newFixedThreadPool(20);
// for each query
for (String query: queryList) {
// each thread will call this run() method
executorService.execute(new Runnable() {
public void run() {
long start = System.currentTimeMillis();
// call query method
HashMap<String, Double> docRanks = createPageFromDocs(fileList, query);
// Sort docRanks by value and Print top 10
displayResults(docRanks, query, start);
}
});
}
executorService.shutdown();
}
public static void createQueryTermList (File file) {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line; // the line of text from the file
// Read each line in the file
while ((line = br.readLine()) != null) {
// Stop and Stem the line
StringTokenizer st = new StringTokenizer(line, " ");
String word;
String phrase = "";
while (st.hasMoreElements()) {
word = st.nextToken().toLowerCase();
if (isStopWord(word) && !word.equals("")) {
// don't add it
}
// Send to Stemmer if needed
else {
if (!word.equals("") && !isStopWord(word)) {
word = porter.stripAffixes(word);
phrase += word + " ";
}
}
}
// Capture each query
queryList.add(phrase);
}
}catch(IOException e) {
System.err.println(e);
}
}
public static boolean isHTMLTag(String word) {
if (word.matches("<.+?>")) {
return true;
} else {
return false;
}
}
public static String removePunctuation(String word) {
return word.replaceAll("[^\\w\\s]|_", "");
}
public static int numKeyWords(HashMap<String, Integer> wordMap) {
return wordMap.size();
}
public static synchronized void displayResults(HashMap<String, Double> wordMap, String query, long start) {
Object[] sortedMap = sortMap(wordMap);
long time = System.currentTimeMillis() - start;
System.out.println("Relevant documents for query: \"" + query + "\", time to process: " + time);
for (int i = 0; i < 10; i++) {
System.out.println(sortedMap[i].toString().replaceFirst("\\.txt", "").replaceFirst("=", ":\t"));
}
System.out.println();
}
public static Object[] sortMap(HashMap<String, Double> wordMap) {
Object[] sortedMap = wordMap.entrySet().toArray();
Arrays.sort(sortedMap, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Double>) o2).getValue()
.compareTo(((Map.Entry<String, Double>) o1).getValue());
}
});
return sortedMap;
}
public static TreeSet<String> getStopWordsAsTree(File stopWords) {
TreeSet<String> ts = new TreeSet<>();
try (BufferedReader buff = new BufferedReader(new FileReader(stopWords))) {
String entry;
while ((entry = buff.readLine()) != null) {
ts.add(entry.toLowerCase());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ts;
}
public static HashMap<String, Double> createPageFromDocs(File[] fileList, String query) {
// Data structure to hold our words e.g key => value
HashMap<String, Double> wordMap = new HashMap<>();
for (File file : fileList) {
// Iterate through each file
if (file.isFile()) {
wordMap.put(file.getName(), calculateRank(file, query));
}
}
return wordMap;
}
public static Double calculateRank(File file, String query) {
String word = "";
double totalWords = 0;
HashMap<String, Integer> keywords = new HashMap<>();
TreeSet<String> queryTerms = new TreeSet<>();
StringTokenizer st = new StringTokenizer(query, " ");
while (st.hasMoreElements()) {
word = st.nextToken().toLowerCase();
queryTerms.add(word);
}
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line; // the line of text from the file
// Skip the first 12 lines of the file, as they aren't needed
for (int i = 0; i < 12; i++) {
br.readLine();
}
// Read each line in the file
while ((line = br.readLine()) != null) {
/* Preprocess the line
a) eliminate the HTML tags
b) remove punctuation
c) tokenize the text
*/
StringTokenizer str = new StringTokenizer(line, " ");
while (str.hasMoreElements()) {
word = str.nextToken().toLowerCase();
// Filter out tags
if (isHTMLTag(word) == false) {
word = removePunctuation(word);
// Send to Stopwords if needed
if (isStopWord(word) && !word.equals("")) {
// don't add it
}
// Send to Stemmer if needed
else {
if (!word.equals("") && !isStopWord(word)) {
word = porter.stripAffixes(word);
totalWords++;
if (queryTerms.contains(word)) {
keywords.put(word, keywords.getOrDefault(word, 0) + 1);
}
}
}
}
}
}
} catch (IOException x) {
System.err.println(x);
}
double rank = 0;
String queryTerm = "";
st = new StringTokenizer(query, " ");
while (st.hasMoreElements()) {
queryTerm = st.nextToken();
if(keywords.containsKey(queryTerm)) {
rank += (keywords.get(queryTerm) / totalWords);
//System.out.println(rank);
//System.out.println(queryTerm + " value: " + keywords.get(queryTerm) + ", total words: " + totalWords);
}
}
return rank;
}
// Returns false if the word is not a stopword
public static boolean isStopWord(String word) {
if (!stopWordsTree.contains(word)) {
return false;
} else {
return true;
}
}
}
|
C#
|
UTF-8
| 6,314 | 2.921875 | 3 |
[] |
no_license
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
namespace ExoActive
{
/**
* The Attribute struct starts with a base value from a NamedValue object. Each Attribute is given a GUID upon
* creation and also maintains a version that increments whenever a change is made to the Attribute. The attribute
* value can then be altered by inserting, updating and removing other Attribute objects. However, inserting
* multiple Attributes with the same GUID is not allowed. This creates a tree structure that represents the
* temporary changes to the base value.
*/
[DataContract]
public readonly partial struct Attribute
{
[DataMember] public readonly NamedValue namedValue;
[DataMember] private readonly Attribute[] modifiers;
[DataMember] public readonly NamedValue modifiedValue;
[DataMember] public readonly Guid guid;
[DataMember] public readonly ulong version;
public Attribute(string name, long baseValue) : this(new NamedValue(name, baseValue))
{
}
public Attribute(NamedValue namedValue) : this(namedValue, Array.Empty<Attribute>(),
Guid.NewGuid(), 0)
{
}
private Attribute(Attribute attribute, Attribute[] modifiers) : this(attribute.namedValue,
modifiers,
attribute.guid, attribute.version + 1)
{
}
private Attribute(Attribute attribute, long value, Attribute[] modifiers) : this(
new NamedValue(attribute.namedValue.name, value),
modifiers,
attribute.guid, attribute.version + 1)
{
}
private Attribute(Attribute attribute, NamedValue namedValue, Attribute[] modifiers) : this(
namedValue,
modifiers,
attribute.guid, attribute.version + 1)
{
}
private Attribute(NamedValue namedValue, Attribute[] modifiers, Guid guid, ulong version)
{
this.namedValue = namedValue;
this.modifiers = modifiers;
modifiedValue = modifiers.Aggregate(namedValue, (value, attribute) => value + attribute.modifiedValue);
this.guid = guid;
this.version = version;
}
private int GetModifierIdx(Attribute modifier)
{
var i = 0;
for (; i < modifiers.Length; i++)
if (modifiers[i].guid.Equals(modifier.guid))
return i;
return -1;
}
public Attribute AdjustBaseValue(long value)
{
return new(this, this.namedValue + value, this.modifiers);
}
private Attribute InsertModifierAtEnd(Attribute modifier)
{
// Do not allow self insertion
// if (this.guid.Equals(modifier.guid)) return this;
var updatedModifiers = new Attribute[modifiers.Length + 1];
modifiers.CopyTo(updatedModifiers, 0);
updatedModifiers[modifiers.Length] = modifier;
return new Attribute(this, updatedModifiers);
}
public Attribute InsertModifier(Attribute modifier)
{
var i = GetModifierIdx(modifier);
return i < 0 ? InsertModifierAtEnd(modifier) : this;
}
private Attribute UpdateModifierAtIdx(Attribute modifier, int idx)
{
// Don't update if the modifier hasn't changed
if (modifier.Equals(modifiers[idx])) return this;
var updatedModifiers = new Attribute[modifiers.Length];
modifiers.CopyTo(updatedModifiers, 0);
updatedModifiers[idx] = modifier;
return new Attribute(this, updatedModifiers);
}
public Attribute UpdateModifier(Attribute modifier)
{
var i = GetModifierIdx(modifier);
return i < 0 ? this : UpdateModifierAtIdx(modifier, i);
}
public Attribute UpsertModifier(Attribute modifier)
{
var i = GetModifierIdx(modifier);
return i < 0 ? InsertModifierAtEnd(modifier) : UpdateModifierAtIdx(modifier, i);
}
private Attribute RemoveModifierAtIdx(int idx)
{
var updatedModifiers = new Attribute[modifiers.Length - 1];
for (int i = 0; i < updatedModifiers.Length; i++)
{
updatedModifiers[i] = modifiers[i < idx ? i : i + 1];
}
// modifiers[..idx].CopyTo(updatedModifiers, 0);
// modifiers[(idx + 1)..].CopyTo(updatedModifiers, idx);
return new Attribute(this, updatedModifiers);
}
public Attribute RemoveModifier(Attribute modifier)
{
var i = GetModifierIdx(modifier);
return i < 0 ? this : RemoveModifierAtIdx(i);
}
public Attribute Reset() => new(this, Array.Empty<Attribute>());
public Attribute Flatten() => new(this, this.modifiedValue.value, Array.Empty<Attribute>());
public ReadOnlyCollection<Attribute> Modifiers => new(modifiers);
public Attribute GetModifierByName(string name)
{
try
{
return modifiers.First(attribute => attribute.namedValue.name.Equals(name));
}
catch (InvalidOperationException)
{
var attr = new Attribute(name, default);
return attr;
}
}
}
public readonly struct AttributeHelper
{
public static void PrintAttributeTree(Attribute attribute, int depth = 0)
{
var indent = "";
for (var i = 0; i < depth; i++) indent += " ";
Console.WriteLine(
$"{indent}{attribute.namedValue.name} : {attribute.namedValue.value} - {attribute.modifiedValue.value} {{{attribute.guid} : {attribute.version}}}");
foreach (var child in attribute.Modifiers) PrintAttributeTree(child, depth + 1);
}
}
public readonly partial struct NamedValue
{
public readonly string name;
public readonly long value;
public NamedValue(string name, long value)
{
this.name = name;
this.value = value;
}
}
}
|
Java
|
UTF-8
| 10,009 | 3.015625 | 3 |
[] |
no_license
|
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
/**
* This is a skeleton for realizing a very simple database user interface in java.
* The interface is an Applet, and it implements the interface ActionListener.
* If the user performs an action (for example he presses a button), the procedure actionPerformed
* is called. Depending on his actions, one can implement the database connection (disconnection),
* querying or insert.
*
* @author zmiklos
*
*/
public class TP6 extends java.applet.Applet implements ActionListener {
private TextField mStat, mCours, mParcours, mSalle, mEnseignant, mEtudiant, mHoraireMin, mHoraireMax;
TextArea mRes;
private Button b1, b2, bEnseignant, bEtudiant, bHoraireCours, bHoraireParcours, bSalle;
private static final long serialVersionUID = 1L;
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://mysql.istic.univ-rennes1.fr:3306/base_13002155";
// Database credentials
static final String USER = "user_13002155";
static final String PASS = "VousCroyezQu'onMetUnMotDePasseICI. LOL";
Connection conn = null;
Statement stmt = null;
/**
* This procedure is called when the Applet is initialized.
*
*/
public void init ()
{
/**
* Definition of text fields
*/
mStat = new TextField(150);
mStat.setEditable(false);
mRes = new TextArea(10,150);
mRes.setEditable(false);
mCours = new TextField(150);
mParcours = new TextField(150);
mSalle = new TextField(150);
mEnseignant = new TextField(150);
mEtudiant= new TextField(150);
mHoraireMin = new TextField(150);
mHoraireMax = new TextField(150);
/**
* First we define the buttons, then we add to the Applet, finally add and ActionListener
* (with a self-reference) to capture the user actions.
*/
b1 = new Button("CONNECT");
b2 = new Button("DISCONNECT");
bEnseignant = new Button("ENSEIGNANT");
bEtudiant = new Button("ETUDIANT");
bHoraireCours = new Button("HORAIRES COURS");
bHoraireParcours = new Button("HORAIRES PARCOUR");
bSalle = new Button("Salle");
add(b1) ;
add(b2) ;
add(bEnseignant) ;
add(bEtudiant) ;
add(bHoraireCours);
add(bHoraireParcours);
add(bSalle);
b1.addActionListener(this);
b2.addActionListener(this);
bEnseignant.addActionListener(this);
bEtudiant.addActionListener(this);
bHoraireCours.addActionListener(this);
bHoraireParcours.addActionListener(this);
bSalle.addActionListener(this);
add(mStat);
add(new Label("Cours: ", Label.LEFT));
add(mCours);
add(new Label("Parcours: ", Label.LEFT));
add(mParcours);
add(new Label("Salle: ", Label.LEFT));
add(mSalle);
add(new Label("Enseignant: ", Label.LEFT));
add(mEnseignant);
add(new Label("Etudiant: ", Label.LEFT));
add(mEtudiant);
add(new Label("Horaire min: ", Label.LEFT));
add(mHoraireMin);
add(new Label("Horaire max: ", Label.LEFT));
add(mHoraireMax);
add(new Label("Query results: ", Label.LEFT));
add(mRes);
setStatus("Waiting for user actions.");
}
/**
* This procedure is called upon a user action.
*
* @param event The user event.
*/
public void actionPerformed(ActionEvent event)
{
// Extract the relevant information from the action (i.e. which button is pressed?)
Object cause = event.getSource();
// Act depending on the user action
// Button CONNECT
if (cause == b1)
{
connectToDatabase();
}
// Button DISCONNECT
if (cause == b2)
{
disconnectFromDatabase();
}
if (cause == bEnseignant)
{
QueryEnseignant();
}
if (cause == bEtudiant)
{
QueryEtudiant();
}
if (cause == bHoraireCours)
{
QueryHoraireCours();
}
if (cause == bHoraireParcours)
{
QueryHoraireParcours();
}
if (cause == bSalle)
{
QuerySalle();
}
}
/**
* Set the status text.
*
* @param text The text to set.
*/
private void setStatus(String text){
mStat.setText("Status: " + text);
}
/**
* Procedure, where the database connection should be implemented.
*/
private void connectToDatabase(){
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
if(conn != null)
setStatus("Connected to the database");
} catch(Exception e){
System.err.println(e.getMessage());
setStatus("Connection failed" + e.toString());
}
}
/**
* Procedure, where the database connection should be implemented.
*/
private void disconnectFromDatabase(){
try{
setStatus("Disconnected from the database");
} catch(Exception e){
if(conn!=null)
try {
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.err.println(e.getMessage());
setStatus("Disconnection failed");
}
}
/**
* Search Enseignant in Enseigne
*/
private void QueryEnseignant(){
try{
stmt = conn.createStatement();
String sql;
sql = "SELECT prenom, nom FROM Enseigne as E, Enseignant WHERE Enseignant.idEnseignant = E.Enseignant_idEnseignant";
if(!mCours.getText().isEmpty())
sql += " AND Cours_idCours = " + mCours.getText();
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String prenom = rs.getString("prenom");
String nom = rs.getString("nom");
//Display values
mRes.append("Enseignant: " + nom + " " + prenom + "\n");
}
stmt.close();
rs.close();
} catch(Exception e){
System.err.println(e.getMessage());
setStatus("Requete ratée");
}
}
/**
* Horaire
*/
private void QueryEtudiant(){
try{
stmt = conn.createStatement();
String sql;
sql = "SELECT nom, prenom FROM estInscrit EI, Etudiant E WHERE EI.idEtudiant = E.idEtudiant";
if(!mParcours.getText().isEmpty())
sql += " And E.Parcours_idPar = " + mParcours.getText();
if(!mCours.getText().isEmpty())
sql += " And EI.idCours = " + mCours.getText();
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String prenom = rs.getString("prenom");
String nom = rs.getString("nom");
//Display values
mRes.append("Etudiant: " + nom + " " + prenom + "\n");
}
stmt.close();
rs.close();
} catch(Exception e){
System.err.println(e.getMessage());
setStatus("Requete ratée");
}
}
/**
* Horaire
*/
private void QueryHoraireCours(){
try{
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM estDans WHERE";
System.out.println(sql);
if(!mCours.getText().isEmpty())
sql += " Cours_idCours= " + mCours.getText();
else if(!mEnseignant.getText().isEmpty())
sql += " Cours_idCours = (SELECT Cours_idCours FROM Enseigne WHERE Enseignant_idEnseignant = "+mEnseignant.getText()+")";
else if(!mEtudiant.getText().isEmpty())
sql += " Cours_idCours = (SELECT idCours FROM estInscrit WHERE idEtudiant= "+mEtudiant.getText()+")";
else
sql += " Salle_idSalle = " + mSalle.getText();
if(!mHoraireMax.getText().isEmpty() && !mHoraireMin.getText().isEmpty())
sql += "AND horaire > '"+mHoraireMin.getText()+"' AND horaire < '"+mHoraireMax.getText()+"'";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String cours = rs.getString("Cours_idCours");
String salle = rs.getString("Salle_idSalle");
String horaire = rs.getString("horaire");
//Display values
mRes.append("Horaire: " + cours + "-" + salle + "-" + horaire + "\n");
}
stmt.close();
rs.close();
} catch(Exception e){
System.err.println(e.getMessage());
setStatus("Requete ratée");
}
}
/**
* Horaire
*/
private void QueryHoraireParcours(){
try{
stmt = conn.createStatement();
String sql;
sql = "SELECT DISTINCT horaire FROM estDans eD, Cours C, estInscrit eI, Etudiant E WHERE eD.Cours_idCours=C.idCours AND C.idCours=eI.idCours AND eI.idEtudiant=E.idEtudiant AND E.Parcours_idPar=" + mParcours.getText();
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String horaire = rs.getString("horaire");
//Display values
mRes.append("Horaire: " + horaire + "\n");
}
stmt.close();
rs.close();
} catch(Exception e){
System.err.println(e.getMessage());
setStatus("Requete ratée");
}
}
/**
* Salle
*/
private void QuerySalle(){
try{
stmt = conn.createStatement();
String sql;
sql = "SELECT DISTINCT Salle_idSalle FROM estDans ";
if(!mHoraireMax.getText().isEmpty() && !mHoraireMin.getText().isEmpty())
sql += "WHERE horaire > '"+mHoraireMin.getText()+"' AND horaire < '"+mHoraireMax.getText()+"'";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String Salle = rs.getString("Salle_idSalle");
//Display values
mRes.append("Salle: " + Salle + "\n");
}
stmt.close();
rs.close();
} catch(Exception e){
System.err.println(e.getMessage());
setStatus("Requete ratée");
}
}
}
|
Java
|
UTF-8
| 181 | 1.765625 | 2 |
[] |
no_license
|
package br.feevale.physis.request;
import javax.servlet.http.HttpServletRequest;
public interface RequestTypeValidator {
public boolean isValid(HttpServletRequest request);
}
|
Markdown
|
UTF-8
| 4,646 | 2.8125 | 3 |
[] |
no_license
|
2020.05.20
### social Login
- allauth - 인스톨
- 사용할 사이트에 사용할 유저들이 많이 사용하는 소셜 하나만!! 선택하는 것을 추천
- 왜?
1. 프로젝트에서 가장 중요한 건 정해진 시간안에 필요한 핵심 기능을 개발하는 것
2. 여러 개의 소셜 로그인을 쓰는 서비스를 켰을 때 어떤 경험을 했는지
편리성 ↑, 협업 발생, 데이터 분활, 복잡
## 오후 라강
- HTTP : stateless => "로그인한 상태" 성립 X
- 매번 `sessionid` 를 통해 넘겨준다. ~ 계속 로그인 유지
- 문제 발생! sessionid만 알면 누구든 로그인 가능
- 해결 방법?
브라우저 화면에서 `로그아웃`하면 된다!
- 로그아웃하게 되면 탈취한 sessionid도 의미 없어진다!!!
(session 방식을 이용하는 서버라면!!)
---
## 실습
### articles/models.py
```python
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
@classmethod
def dummy(cls, n):
articles = []
for i in range(n):
articles.append(cls(title=f'title-{i+1}', content=f'content lorem ipsum')) # 객체만 생성, save는 X => articles 리스트에 추가만 할 뿐
cls.objects.bulk_create(articles)
```
- dummy data 만들 때 .`bulk_create` 사용시 빠르게 생성된다.
이후 코드 정리
```bash
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py shell_plus
In [1]: Article
In [2]: Article.dummpy(1000) # dummy 데이터 100개 생성
In [3]: Article.objects.count() # 출력: 1000
```
### articles/views.py
```python
import 코드 복붙
def article_list(request):
articles = Article.objects.all()
paginator = Paginator(articles, 10) # 10개씩 자르겠다!
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'articles': articles,
'page_obj': page_obj,
}
return render(request, 'articles/article_list.html', context)
```
1000개를 다 보여주지 않고!!! 끊어서 보여주기 => **paginator** 이용
#### paginator
https://docs.djangoproject.com/en/3.0/topics/pagination/
`Using Paginator in a view function`에 있는 코드 + 바로 위 html 코드 참고
※ 주의 `Paginating a ListView View`는 우리가 사용하고 있는 view가 아니다!
### article_list.html
```html
{% extends 'base.html' %}
{% block content %}
코드복붙
{% for article in page_obj %}
{{ article. }}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
{% endblock %}
```
127.0.01:80000/articles/?page=1
page = 숫자 바뀌면 해당 페이지 보여준다. => 공식문서의 html 참고해서 이동 버튼 만들기
#### django bootstrap pagination
>https://pypi.org/project/django-bootstrap-pagination/
1. 터미널에 설치하기
```bash
$ pip install django-bootstrap-pagination
```
2. settings.py에 앱 추가하기
```python
INSTALLED_APPS = (
'bootstrap_pagination',
)
```
3. 사용할 html에 코드 추가하기
```html
{% load bootstrap_pagination %}
<!-- 사용할 곳 위에 추가하기 -->
<!-- 기본 (추천X) -->
{% bootstrap_paginate page_obj %}
<!-- 추가적인 설정완료된 코드 -->
{% bootstrap_paginate page_obj range=10 show_prev_next="false" show_first_last="true" %}
```
- `range` 조절을 통해 페이지 번호 얼만큼 보여지질 조절
## 프로젝트
1. 데이터 로드만 하면 된다 => 데이터준비 시작
2. 필수 기능
모든 데이터 표시 X
좋아요 => 비동기
알고리즘 => 로그인한 사람한데 random 이용해서 추천 / 뭔가의 기준에 따라 추천해줘도 된다.
3. 장르 데이터 => 무비 데이터 저장
M : N으로 되어 있다!!!!
필드만 잘 맞춰주면 모델잘 정의해주면 된다.
- 영화 데이터 500
- 제목, 포스터(이미지), 평점, .. 다 포함
사용자 설정하기
|
Python
|
UTF-8
| 322 | 3.4375 | 3 |
[] |
no_license
|
lista = ['Ala', 'ma', 'kota']
output = ''
for slowo in lista:
for i in range(len(slowo), 0, -1):
output += slowo[i-1]
print(output)
output = ''
print()
#NOTE: Znalazłem też szybsze rozwiązanie jednopętlowe (przy małej pomocy dokumentacji):
#zadanie 3.1
for x in lista:
print(x[::-1])
###
|
Shell
|
UTF-8
| 1,157 | 2.796875 | 3 |
[] |
no_license
|
#!/bin/bash
# escape არის დეფინიცია სხვადასხვა ტექსტური თუ სისტემური მნიშვნელი რომელიც გამოიყენება "\"_ის მნიშვნელით
# იმისთვის რომ "echo"_მ მიიღოს escape სიმბოლოს მნიშვნელი საჭიროა დაემატოს " -e". მაგალითად: echo -e "ტექსტი\nტექსტი\n"
# "printf" ფორმატული ბეჭდვა თავის თავში მოიცავს escape მხარდაჭერას
echo -e "alert\a"
echo -e "backspace \bbackspace"
echo -e "form feed\fform feed"
echo -e "new line\nnew line"
echo -e "carriage return\rcarriage return"
echo -e "horizontal tab\thorizontal tab"
echo -e "backslash\\backslash"
echo -e "double quotes\"double quotes"
echo -e Single quotes\'ingle quotes
echo -e "\n\nმაგალითისთვის:"
echo -e "\t\t _\n\t07\t[|] 0ffensive 7ester\n" # ASCII Art
# printf "\t\t _\n\t07\t[|] 0ffensive 7ester\n"
|
JavaScript
|
UTF-8
| 16,957 | 2.71875 | 3 |
[] |
no_license
|
/**
* Element 입력 이벤트 필터 서비스
* @author X0114723
*/
jQuery.fn.extend({
/**
* 입력 필터
* @param {Object} options - 필터 옵션
* options : {
* filter - 필터명
* minLen - 입력 최소 길이(default : 0)
* maxLen - 입력 최대 길이(default : none)
* }
*/
valid : function(options) {
Filters._initFilters(this, options);
var thisObj = this;
var filters = this._filters;
if (!filters) return;
// Element가 삭제될경우 valid check 아이템에서 제거하기 위해
this.one("remove", function() {
for (var i = 0; i < Filters._currElements.length; i++) {
var el = Filters._currElements[i];
if (el == thisObj) {
el.prop("removed", true);
Filters._currElements = $.grep(Filters._currElements, function(value) {
return value != thisObj;
});
//console.log(thisObj.prop("id"), "removed.")
break;
}
}
});
if (filters.options.filter === "file") {
// filter가 file인 경우 _fileFilter를 사용한다.
this._fileFilter(function(value, type) {
if (type === "change") { // 파일 선택시 발생하는 이벤트
if (!thisObj.enableValueFilter()) return true;
if (!filters.valueFilter) return true;
if (!filters.valueFilter.test(value)) { // 파일명에 의한 확장자 패턴 체크
Filters._fileValidStyle(thisObj, false);
thisObj.focus();
alert(Filters.toLocaleMessage(Filters.file.typeError));
return false;
} else {
if (filters.options.varType && filters.options.varType != 'file') {
if (!Filters._fileValidate(thisObj, value)) {
Filters._fileValidStyle(thisObj, false);
return false;
}
}
}
Filters._fileValidStyle(thisObj, true);
return true;
}
});
} else {
// if (filters.options.filter === 'checkbox' || filters.options.filter === 'radio' || filters.options.filter === 'select') {
// return;
// }
// 이외의 모든 필터는 blur & input 필터를 사용한다.
this._blurInputFilter(function(value, type) {
if (type === "blur") { // blur는 모든 입력이 끝났을때 발생
if (!value && !filters.options.required) return true; // 값이 없고 필수가 아닌경우 체크하지 않는다.
if (!thisObj.enableValueFilter()) return true; // value filter가 disable이면 체크하지 않는다.
if (!filters.valueFilter) return true; // value filter가 없으면 체크하지 않는다.
if (!filters.valueFilter.test(value)) { // 입력값에 대한 지정 패턴 필터 체크
thisObj.focus();
if (filters.message) alert(filters.message);
return false;
} else if (filters.options.varType === 'date') { // 날짜 필터인 경우에 실제 날짜값인지 한번 더 체크
if (!Filters._dateValidate(thisObj, value)) return false;
} else if (filters.options.varType === 'range') { // 값의 범위를 체크하는 경우, 범위내 존재하는지 체크
if (!Filters._rangeValidate(thisObj, value)) return false;
} else if (filters.options.filter === 'person_id') {
if (!Filters._personIdBirthValidate(thisObj, value)) return false;
}
// 불필요한 입력값을 제거하도록 숫자를 한번 더 변환 (ex: +.5 -> 0.5, 000123->123, 1. -> 1)
if (filters.options.varType === 'number' || filters.options.varType === 'range') {
thisObj.val(Number(value));
}
// checkbox, radio, select form element check
//if (!Filters._selectOrCheckTypeValidate(thisObj, value)) return false;
thisObj._convertPhoneNo(filters.options.filter); // 전화번호 형태 변환
return true;
} else if (type === "input") { //input은 입력길이와 숫자입력등에 사용
if (!value) return true; // 값이 없는 경우에는 체크하지 않는다.
if (!thisObj.enableLengthFilter()) return true; // length filter가 disable이면 체크하지 않는다.
if (filters.lengthFilter) { // 길이 체크 필터가 있으면 체크한다.
if (!filters.lengthFilter.test(value)) return false;
}
if (filters.options.maxLen) { // 입력길이 제한 옵션이 있으면 체크한다.
if(value.length > filters.options.maxLen) return false;
}
if (filters.options.varType === 'range') { // 범위값인 경우에 최대값 최소값 체크
if ($.isNumeric(filters.options.minVal) && $.isNumeric(value)) {
if (parseInt(value) < filters.options.minVal) return false;
}
if ($.isNumeric(filters.options.maxVal) && $.isNumeric(value)) {
if (parseInt(value) > filters.options.maxVal) return false;
}
}
return true;
}
});
}
},
/**
* element의 value filter 사용여부 설정
* @param {Boolean} enable - 사용여부
*/
enableValueFilter : function(enable) {
if (enable === undefined) {
var is = this.prop("isValueFilter");
if (is == null || is === undefined) return true;
else if (typeof is === "boolean") return is;
else if (is === "enable" || is === "true") return true;
else return false;
} else {
this.prop("isValueFilter", enable);
}
},
/**
* element의 length filter 사용여부 설정
* @param {Boolean} enable - 사용여부
*/
enableLengthFilter : function(enable) {
if (enable === undefined) {
var is = this.prop("isLengthFilter");
if (is == null || is === undefined) return true;
else if (typeof is === "boolean") return is;
else if (is === "enable" || is === "true") return true;
else return false;
} else {
this.prop("isLengthFilter", enable);
}
},
/**
* 숫자만 입력 필터
* @param {Number} maxLen - 숫자 입력 자리 수
*/
numberFilter : function(maxLen) {
var filter = null;
if (maxLen) filter = new RegExp("^\\d{0,"+maxLen+"}$");
else filter = /^\d*$/;
this._inputFilter(function(value) {
return filter.test(value);
//return /^\d*$/.test(value);
});
},
/**
* 입력 길이 제한 필터
* @param {Number} maxLen - 입력 길이
*/
lengthFilter : function(maxLen) {
var filter = new RegExp("^.{0,"+maxLen+"}$");
this._inputFilter(function(value) {
return filter.test(value);
});
},
readonly : function(isReadonly, values) {
this._readonly(this, isReadonly, values);
},
_readonly : function(elObj, isReadonly, values) {
// if (typeof Filters !== "undefined") {
// elObj = Filters._findElement(elObj.prop("uuid"));
// Filters._resetStyle(elObj);
// }
var type = elObj.prop("type");
if (!values) values = [];
else if (!$.isArray(values)) values = [values];
var isContains = true;
elObj.each(function() {
var el = $(this);
if (typeof Filters !== "undefined") {
Filters._resetStyle(Filters._findElement(el.prop("uuid")));
}
if (values.length == 0 || values.indexOf(el.val()) > -1) isContains = isReadonly;
else isContains = !isReadonly;
if (isContains) {
el.prop("readonly", true);
el.addClass("nondisable");
el.on("click", function(e) { e.preventDefault(); el.blur();});
} else {
el.removeClass("nondisable");
el.removeProp("readonly");
el.off("click");
}
if (!type || type === "text" || type === "password" || type === 'textarea') {
if (isContains) el.addClass("nondisable");
else el.removeClass("nondisable");
} else if (type === "radio") {
if (isContains) {
if (el.prop("checked")) el.next(".jqformRadio").addClass("readonly");
el.next().next('label').css('color','#cccccc');
} else {
el.next(".jqformRadio").removeClass("readonly");
el.next().next('label').css('color','');
}
} else if (type === "checkbox") {
if (isContains) {
if (el.prop("checked")) el.next(".jqformCheckbox").addClass("readonly");
el.next().next('label').css('color','#cccccc');
} else {
el.next(".jqformCheckbox").removeClass("readonly");
el.next().next('label').css('color','');
}
} else if (type.indexOf("select") == 0){
if (isContains) {
el.parent().addClass("nondisable");
//$("option", el).not(":selected").prop("disabled", true);
$("option", el).not(":selected").hide();
} else {
el.parent().removeClass("nondisable");
//$("option", el).not(":selected").removeProp("disabled");
$("option", el).not(":selected").show();
}
} else if (type === "file") {
if (isContains) {
if (el.is(":hidden")) {
$("input[name=dispFileName]", el.closest("td")).addClass("nondisable");
$("button", el.closest("td")).addClass("nondisable");
$(".photo>.image", el.closest("td")).css("background", "#F2F2F2");
} else {
el.addClass("nondisable");
}
} else {
if (el.is(":hidden")) {
$("input[name=dispFileName]", el.closest("td")).removeClass("nondisable");
$("button", el.closest("td")).removeClass("nondisable");
$(".photo>.image", el.closest("td")).css("background", "#FFFFFF");
} else {
el.removeClass("nondisable");
}
}
}
});
},
/**
* 입력폼들을 enable 시킨다.
*/
enable : function() {
this._enable(this);
},
enableAll : function() {
$.each(this, function(index) {
$(this).enable();
});
},
_enable : function(elObj) {
// if (typeof Filters !== "undefined") {
// elObj = Filters._findElement(elObj.prop("uuid"));
// Filters._resetStyle(elObj);
// }
var type = elObj.prop("type");
elObj.each(function() {
var el = $(this);
if (typeof Filters !== "undefined") {
Filters._resetStyle(Filters._findElement(el.prop("uuid")));
}
el.removeProp("disabled");
if (!type || type === "text" || type === "password" || type === 'textarea') {
el.removeClass("nondisable");
} else if (type === "radio") {
//el.prop('checked', false);
} else if (type === "checkbox") {
//el.prop('checked', false);
} else if (type.indexOf("select") == 0){
el.parent().removeClass("nondisable");
} else if (type === "file") {
if (el.is(":hidden")) {
$("input[name=dispFileName]", el.closest("td")).removeClass("nondisable");
$("button", el.closest("td")).removeClass("nondisable");
$(".photo>.image", el.closest("td")).css("background", "#FFFFFF");
} else {
el.removeClass("nondisable");
}
}
});
},
/**
* 입력폼을 disable 시킨다.
*/
disable : function() {
this._disable(this);
},
disableAll : function() {
$.each(this, function(index) {
$(this).disable();
});
},
_disable : function(elObj) {
// if (typeof Filters !== "undefined") {
// elObj = Filters._findElement(elObj.prop("uuid"));
// Filters._resetStyle(elObj);
// }
var type = elObj.prop("type");
elObj.each(function() {
var el = $(this);
if (typeof Filters !== "undefined") {
Filters._resetStyle(Filters._findElement(el.prop("uuid")));
}
el.prop("disabled", true);
if (!type || type === "text" || type === "password" || type === 'textarea') {
el.val('');
el.addClass("nondisable");
} else if (type === "radio") {
el.prop('checked', false);
} else if (type === "checkbox") {
el.prop('checked', false);
} else if (type.indexOf("select") == 0){
el.val('');
el.parent().addClass("nondisable");
} else if (type === "file") {
if (el.is(":hidden")) {
$("input[name=dispFileName]", el.closest("td")).addClass("nondisable");
$("button", el.closest("td")).addClass("nondisable");
$(".photo>.image", el.closest("td")).css("background", "#F2F2F2");
} else {
el.addClass("nondisable");
}
}
});
},
/**
* 키 입력에 따른 필터 환경 설정
* (해당 element의 키 입력에 따른 필터함수를 실행)
* (실행 후 성공하면 해당값을 저장)
* @param {Function} fnFilter - 필터 함수
*/
_inputFilter : function(fnFilter) {
// drop keydown keyup mouseup 등의 이벤트는 거의 불필요함.
//return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function(e) {
return this.on("input", function(e) {
//console.log(e);
e.preventDefault();
e.stopPropagation();
if (fnFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
if (this.oldSelectionStart != null && this.oldSelectionEnd != null) {
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
} else {
this.value = "";
}
});
},
/**
* input 및 blur 필터
* (input 및 blur 이벤트 발생시 필터 적용)
* @param {Function} fnFilter - 필터 함수
*/
_blurInputFilter : function(fnFilter) {
// focusout 은 버블링발생
//return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function(e) {
var thisObj = this;
var hintType = this._filters.hintType;
var hint = this._filters.hint;
if (this._filters.options.filter === 'checkbox' || this._filters.options.filter === 'radio' || this._filters.options.filter === 'select') {
return this.on("change", function(e) {
e.preventDefault();
e.stopPropagation();
Filters._inputValidStyle(thisObj, true);
});
} else {
return this.on("input blur focus", function(e) {
e.preventDefault();
e.stopPropagation();
// i.e인 경우 readonly라도 focus를 갖고 있는 문제(?)가 있다.
if (e.type != "blur" && thisObj.prop("readonly")) { thisObj.blur(); return; }
if (hintType === "tooltip") {
var offset = thisObj.offset();
if (e.type === "focus") Filters._tooltip.html(hint).css("top", offset.top).css("left", offset.left).show();
else if (e.type ==="blur") Filters._tooltip.hide();
} else if (hintType === "focus_only") {
if (e.type ==="focus") $(this).prop("placeholder", hint);
else if (e.type ==="blur") $(this).prop("placeholder", '');
}
///////////////////////////////////////////////
if (!this.value) return;
if (e.type === "focus") this.isInput = false;
else if (e.type === "input") this.isInput = true;
if (!this.isInput) return;
///////////////////////////////////////////////
var isValid = false;
if (fnFilter(this.value, e.type)) {
this.oldValue = this.value;
if (this.selectionStart) this.oldSelectionStart = this.selectionStart;
if (this.selectionEnd) this.oldSelectionEnd = this.selectionEnd;
if (this.value) isValid = true;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
if (this.oldSelectionStart != null && this.oldSelectionEnd != null) {
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
} else {
this.value = "";
}
// --------------------------------
if (e.type === "blur") {
Filters._inputValidStyle(thisObj, isValid);
} else {
if (isValid) {
Filters._showPasswordHint(thisObj, this.value);
}
}
// --------------------------------
});
}
},
/**
* File upload폼에 사용할 필터
* (파일 선택시 이벤트 발생)
* @param {Function} fnFilter - 필터 함수
*/
_fileFilter : function(fnFilter) {
var thisObj = this;
return this.on("change", function(e) {
if (!this.value) return;
if (!fnFilter(this.value, e.type)) {
e.preventDefault();
e.stopPropagation();
this.value = "";
}
});
},
/**
* 규칙이 없는 전화번호를 지정된 형식으로 변환
* @param {String} filterType - 전화번호 필터명
*/
_convertPhoneNo : function(filterType) {
if (filterType != 'mobile' && filterType != 'mobile_ko' && filterType != 'phone') return;
var digitStr = this.val().replace(/[^0-9]/g, '');//숫자문자열 추출
var phoneStr = null;
if (filterType === 'mobile') {
var match = digitStr.match(/^(\d{3})(\d{4})(\d{4})$/);
if (match) {
phoneStr = match[1] + '-' + match[2] + '-' + match[3];
}
/*var match = digitStr.match(/^(\d{4})(\d{7})$/);
if (match) {
phoneStr = match[1] + '-' + match[2];
}*/
} else if (filterType === 'mobile_ko') {
var match = digitStr.match(/^(\d{3})(\d{3,4})(\d{4})$/);
if (match) {
phoneStr = match[1] + '-' + match[2] + '-' + match[3];
}
} else if (filterType === 'phone') {
var match = digitStr.match(/^(\d{3})(\d{4})(\d{4})$/);
if (match) {
phoneStr = match[1] + '-' + match[2] + '-' + match[3];
}
}
if (phoneStr) this.val(phoneStr);
},
/**
* element에 포함되어 있는 모든 이벤트 목록 조회
*/
showEvents : function(type) {
$.each($._data($(this)[0], "events"), function(i, event) {
$.each(event, function(j, h) {
//console.log(h);
if (!type || type === h.type) console.log(h.type + " : " + h.handler);
});
});
}
});
|
C++
|
UTF-8
| 1,155 | 2.53125 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
//defined my macro functions
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
//defined my macro strings
#define ENDL "\n"
#define SPACE " "
//defined my constants
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const double EPS = 1e-8;
const double PI = 3.14159265358979323846;
//defined my own datatypes
typedef long long ll;
typedef unsigned long long ull;
vector<bool> oui(101 * 101 * 101, true);
vector<int> pos(101 * 101 * 101);
void precalc(int n)
{
for(int i = 2; i <= n; i++)
{
int mul = 1;
int cube = i * i * i;
while(cube * mul < 1000010) oui[cube * (mul++)] = false;
}
int counter = 0;
for(int i = 1; i < 1000010; i++)
{
if(oui[i]) counter++;
pos[i] = counter;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
precalc(101);
int t;
cin>>t;
int total = t;
while(t--)
{
int n;
cin>>n;
cout<<"Case "<<total - t<<": ";
if(oui[n]) cout<<pos[n]<<endl;
else cout<<"Not Cube Free"<<endl;
}
return 0;
}
|
Java
|
UTF-8
| 4,421 | 1.90625 | 2 |
[] |
no_license
|
/************************************************************************
* Copyright (c) 2011-2012 HONG LEIMING.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
package org.zbus.client.rpc;
import java.io.IOException;
import org.zbus.client.Broker;
import org.zbus.client.ZbusException;
import org.zbus.client.service.Caller;
import org.zbus.common.logging.Logger;
import org.zbus.common.logging.LoggerFactory;
import org.zbus.common.remoting.Message;
public class Rpc extends Caller{
private static final Logger log = LoggerFactory.getLogger(Rpc.class);
private static final Codec codec = new JsonCodec();
public static final String DEFAULT_ENCODING = "UTF-8";
private String module = "";
private String encoding = DEFAULT_ENCODING;
private int timeout = 10000;
public Rpc(Broker broker, String mq) {
super(broker, mq);
}
public Rpc(RpcConfig config){
super(config);
this.module = config.getModule();
this.timeout = config.getTimeout();
this.encoding = config.getEncoding();
}
@SuppressWarnings("unchecked")
public <T> T invokeSync(Class<T> clazz, String method, Object... args){
Object netObj = invokeSync(method, args);
try {
return (T) codec.normalize(netObj, clazz);
} catch (ClassNotFoundException e) {
throw new ZbusException(e.getMessage(), e.getCause());
}
}
@SuppressWarnings("unchecked")
public <T> T invokeSyncWithType(Class<T> clazz, String method, Class<?>[] types, Object... args){
Object netObj = invokeSyncWithType(method, types, args);
try {
return (T) codec.normalize(netObj, clazz);
} catch (ClassNotFoundException e) {
throw new ZbusException(e.getMessage(), e.getCause());
}
}
public Object invokeSync(String method, Object... args) {
return invokeSyncWithType(method, null, args);
}
public Object invokeSyncWithType(String method, Class<?>[] types, Object... args) {
Request req = new Request();
req.setModule(this.module);
req.setMethod(method);
req.setParams(args);
req.assignParamTypes(types);
req.setEncoding(this.encoding);
Message msg = null;
try {
msg = codec.encodeRequest(req);
log.debug("Request: %s", msg);
msg = this.invokeSync(msg, this.timeout);
log.debug("Response: %s", msg);
} catch (IOException e) {
throw new ZbusException(e.getMessage(), e);
}
if (msg == null) {
String errorMsg = String.format("method(%s) request timeout", method);
throw new ZbusException(errorMsg);
}
Response resp = codec.decodeResponse(msg);
if(resp.getStackTrace() != null){
Throwable error = resp.getError();
if(error != null){
if(error instanceof RuntimeException){
throw (RuntimeException)error;
}
throw new ZbusException(error.getMessage(), error.getCause());
} else {
throw new ZbusException(resp.getStackTrace());
}
}
return resp.getResult();
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public Rpc module(String module) {
this.module = module;
return this;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
|
Java
|
UTF-8
| 3,038 | 2.21875 | 2 |
[] |
no_license
|
package com.example.bautista.prueba_listar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.Serializable;
import java.util.ArrayList;
public class vsLista extends AppCompatActivity {
ListView lvLista ;
ArrayList<String> Informacion;
ArrayList<Entidades> ListaUsuario;
clOpenHelper Admin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vs_lista);
lvLista=(ListView)findViewById(R.id.lvlista);
Admin = new clOpenHelper(getApplicationContext(),"bdListar", null, 1);
ConsultarListar();
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, Informacion);
lvLista.setAdapter(adapter);
lvLista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Entidades usuario = ListaUsuario.get(i);
Intent intent = new Intent(vsLista.this, vsInformacion.class);
Bundle bundle = new Bundle();
bundle.putSerializable("entidad", (Serializable) usuario);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
private void ConsultarListar() {
SQLiteDatabase dbSql = Admin.getReadableDatabase();
Entidades entidades = null;
ListaUsuario = new ArrayList<Entidades>();
Cursor cursor = dbSql.rawQuery("select * from tblEmpleado", null);
while (cursor.moveToNext()){
entidades = new Entidades();
// entidades.setDocumento(cursor.getString(0));
entidades.setDocumento(cursor.getString(1));
entidades.setNombre(cursor.getString(2));
entidades.setApellidos(cursor.getString(3));
entidades.setFecha_Nacimiento(cursor.getString(4));
entidades.setFoto(cursor.getString(5));
entidades.setSueldo(cursor.getString(6));
entidades.setDirLat(cursor.getDouble(7));
entidades.setDirLng(cursor.getDouble(8));
entidades.setEmail(cursor.getString(9));
entidades.setTelefono(cursor.getString(10));
ListaUsuario.add(entidades);
obtenerLista();
}
}
private void obtenerLista() {
Informacion = new ArrayList<String>();
for (int i=0; i<ListaUsuario.size(); i++){
Informacion.add("\n"+"Nombres: "+ListaUsuario.get(i).getNombre()+"\n"
+"Apellidos: "+ListaUsuario.get(i).getApellidos()+"\n"
+"Email: "+ListaUsuario.get(i).getEmail());
}
}
}
|
Go
|
UTF-8
| 1,606 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
package main
import (
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"strings"
"github.com/paidright/datalab/util"
)
var version = flag.Bool("version", false, "Just print the version and exit")
var quiet = flag.Bool("quiet", false, "Tone down the output noise")
var format = flag.String("format", "kv", "Output in key-value or json format. Valid: kv, json")
var logger = util.Logger{}
func main() {
flag.Parse()
if *version {
logger.Info(currentVersion)
os.Exit(0)
}
if err := flimflam(os.Stdin, *format, os.Stdout); err != nil {
logger.Error(err)
}
logDone()
}
func flimflam(input io.Reader, format string, output io.Writer) error {
reader := csv.NewReader(input)
line, err := reader.Read()
if err != nil {
return err
}
switch format {
case "kv":
if _, err := output.Write([]byte(strings.Join(line, ":STRING,"))); err != nil {
return err
}
if _, err := output.Write([]byte(":STRING\n")); err != nil {
return err
}
case "json":
schema := []coldef{}
for _, col := range line {
schema = append(schema, coldef{
Name: col,
Type: "STRING",
})
}
result, err := json.Marshal(schema)
if err != nil {
return err
}
if _, err := output.Write(result); err != nil {
return err
}
default:
return fmt.Errorf("Invalid format specified")
}
return nil
}
type coldef struct {
Name string `json:"name"`
Type string `json:"type"`
}
func logDone() {
if *quiet {
return
}
logger.Info(`
.~~~~'\~~\
; ~~ \
| ;
,--------,______|---.
/ \-----' \
'.__________'-_______-'
`)
}
|
Markdown
|
UTF-8
| 5,922 | 2.515625 | 3 |
[] |
no_license
|
---
description: "Easiest Way to Make Ultimate Chipotle Caldo De Mariscos(&#34;7seas soup&#34;)"
title: "Easiest Way to Make Ultimate Chipotle Caldo De Mariscos(&#34;7seas soup&#34;)"
slug: 2924-easiest-way-to-make-ultimate-chipotle-caldo-de-mariscos-and-34-7seas-soup-and-34
date: 2020-05-15T22:29:03.951Z
image: https://img-global.cpcdn.com/recipes/6229962328637440/751x532cq70/chipotle-caldo-de-mariscos7seas-soup-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/6229962328637440/751x532cq70/chipotle-caldo-de-mariscos7seas-soup-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/6229962328637440/751x532cq70/chipotle-caldo-de-mariscos7seas-soup-recipe-main-photo.jpg
author: Adrian Baker
ratingvalue: 4.1
reviewcount: 13
recipeingredient:
- "4 diced potatoes"
- "2 diced zucchini"
- "2 diced chayotemexican squash"
- "1 cup diced carrots"
- "1/2 bunch diced cilantro"
- "1/2 finely diced jalapeo"
- "1/2 white onion diced"
- "3 clove garlic finely diced"
- "6 cup water"
- "1 tbsp cooking oil"
- " seasonings"
- "1 garlic salt"
- "1 old bay seasoning"
- "1 chicken bullion"
- "1 oregano"
- "1 ground cumin"
- "1 salt"
- "3 tbsp Chipotle paste"
- " seafood"
- "1 tilapia fillet or fish of choice"
- "1 Mariscos seafood mixshrimpcrabclamscrab legsoctopus"
- "8 large shrimp with head on"
recipeinstructions:
- "Start by dicing all your vehhies and set aside"
- "Now clean your shrimp buy cutting back and taking out vein, wash and add to a small pot boil till shrimp are cooked about 6 to 7 minutes let sit in stock"
- "Wash all your Mariscos seafood mix set aside"
- "In a small pot add in your diced potatoes and carrots boil till just tender rinse and set aside"
- "In a large stock pot add in 1 tablespoon oil heat then add in onion, garlic, and jalapeño cook about 3 minutes add in all seasonings as desired, I say desired cause you'll need to taste once you add your water and go from there."
- "Now add in your water and bring to a boil. Add in your diced chiote, cook about 5 minutes then add in your zucchini cook till tender."
- "Once your veggies are tender add in your potatoes, now taste for seasonings strain your shrimp stock and add to large stock pot , also Add in your fish and seafood mix simmer then add in your shrimp, and Chipotle paste turn off. Serve with cilantro, limes and tapatio hot sauce..enjoy"
- ""
categories:
- Recipe
tags:
- chipotle
- caldo
- de
katakunci: chipotle caldo de
nutrition: 249 calories
recipecuisine: American
preptime: "PT33M"
cooktime: "PT49M"
recipeyield: "1"
recipecategory: Lunch
---

Hello everybody, it's Jim, welcome to my recipe site. Today, I'm gonna show you how to make a special dish, chipotle caldo de mariscos("7seas soup"). It is one of my favorites. This time, I'm gonna make it a little bit unique. This is gonna smell and look delicious.
Chipotle Caldo De Mariscos("7seas soup") is one of the most well liked of recent trending foods on earth. It is appreciated by millions every day. It is easy, it's quick, it tastes delicious. Chipotle Caldo De Mariscos("7seas soup") is something that I have loved my whole life. They're fine and they look fantastic.
To begin with this recipe, we must first prepare a few components. You can cook chipotle caldo de mariscos("7seas soup") using 22 ingredients and 8 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Chipotle Caldo De Mariscos("7seas soup"):
1. Take 4 diced potatoes
1. Make ready 2 diced zucchini
1. Take 2 diced chayote*mexican squash*
1. Take 1 cup diced carrots
1. Get 1/2 bunch diced cilantro
1. Make ready 1/2 finely diced jalapeño
1. Prepare 1/2 white onion diced
1. Prepare 3 clove garlic finely diced
1. Get 6 cup water
1. Prepare 1 tbsp cooking oil
1. Make ready seasonings
1. Get 1 garlic salt
1. Prepare 1 old bay seasoning
1. Prepare 1 chicken bullion
1. Take 1 oregano
1. Get 1 ground cumin
1. Make ready 1 salt
1. Prepare 3 tbsp Chipotle paste
1. Prepare seafood
1. Make ready 1 tilapia fillet or fish of choice
1. Make ready 1 Mariscos seafood mix*shrimp,crab,clams,crab legs,octopus
1. Take 8 large shrimp with head on
<!--inarticleads2-->
##### Steps to make Chipotle Caldo De Mariscos("7seas soup"):
1. Start by dicing all your vehhies and set aside
1. Now clean your shrimp buy cutting back and taking out vein, wash and add to a small pot boil till shrimp are cooked about 6 to 7 minutes let sit in stock
1. Wash all your Mariscos seafood mix set aside
1. In a small pot add in your diced potatoes and carrots boil till just tender rinse and set aside
1. In a large stock pot add in 1 tablespoon oil heat then add in onion, garlic, and jalapeño cook about 3 minutes add in all seasonings as desired, I say desired cause you'll need to taste once you add your water and go from there.
1. Now add in your water and bring to a boil. Add in your diced chiote, cook about 5 minutes then add in your zucchini cook till tender.
1. Once your veggies are tender add in your potatoes, now taste for seasonings strain your shrimp stock and add to large stock pot , also Add in your fish and seafood mix simmer then add in your shrimp, and Chipotle paste turn off. Serve with cilantro, limes and tapatio hot sauce..enjoy
1.
So that is going to wrap it up with this special food chipotle caldo de mariscos("7seas soup") recipe. Thank you very much for reading. I am confident that you will make this at home. There is gonna be interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
|
SQL
|
UTF-8
| 345 | 3.703125 | 4 |
[] |
no_license
|
#12. Mostrar los actores que actuaron en la/s película/s más largas.
SELECT ac.first_name AS Nombre, ac.last_name AS Apellido, fi.title AS Pelicula, fi.length AS Duracion
FROM actor ac
LEFT OUTER JOIN film_actor fa ON ac.actor_id = fa.actor_id
LEFT OUTER JOIN film fi ON fa.film_id = fi.film_id
GROUP BY ac.actor_id
ORDER BY Duracion DESC
|
Markdown
|
UTF-8
| 2,210 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
# X-ACTION
This element holds the data that __is__ the Event Action submitted to the [Action Bus](/actions).
## Usage
This element should only ever exists within a parent **`<x-action-activator>`** tag. The parent tag defines how and when the child actions are submitted to the [Action Bus](/actions).
#### In-Attribute Data
````html
<x-action-activator ...>
<x-action
topic="<topic>"
command="<command>"
data='{"arg": "Hello world!"}'></x-action>
</x-action-activator>
````
#### Child Script Data
Alternatively, you define the data parameter in a child script tag.
````html
<x-action-activator ...>
<x-action
topic="<topic>"
command="<command>">
<script type="application/json">
{
"arg": "Hello world!"
}
</script>
</x-action>
</x-action-activator>
````
## Dependencies
### Depends on
- x-action-activator
### Graph
````mermaid
graph TD;
x-view-do --> x-action-activator
x-action-activator --> x-action
style x-action fill:#f9f,stroke:#333,stroke-width:1px
````
<!-- Auto Generated Below -->
## Properties
| Property | Attribute | Description | Type | Default |
| --------- | --------- | -------------------------------------------------------- | --------------------------------------------------------- | ----------- |
| `command` | `command` | The command to execute. | `string` | `undefined` |
| `data` | `data` | The JSON serializable data payload the command requires. | `string` | `undefined` |
| `topic` | `topic` | This is the topic this action-command is targeting. | `"audio" \| "data" \| "document" \| "routing" \| "video"` | `undefined` |
## Methods
### `getAction() => Promise<EventAction<any>>`
Get the underlying actionEvent instance. Used by the x-action-activator element.
#### Returns
Type: `Promise<EventAction<any>>`
----------------------------------------------
*Built with [StencilJS](https://stenciljs.com/)*
|
Java
|
UTF-8
| 394 | 2.46875 | 2 |
[] |
no_license
|
package mindmelt;
public class BlockGate extends BlockDoor
{
protected BlockGate(int id)
{
super((byte)id);
}
protected String getName()
{
return "gate";
}
protected int getUpper()
{
return BlockType.gate.id;
}
protected int getLower()
{
return BlockType.gate.id;
}
}
|
JavaScript
|
UTF-8
| 2,430 | 2.859375 | 3 |
[] |
no_license
|
let fileLoader = {
init(dropZoneName, url, maxFileZize) {
this.url = url || '/';
this.maxFileZize = maxFileZize || 10000;
this.dropZone = document.getElementById(dropZoneName);
if (!typeof(window.FileReader)) {
this.dropZone.innerHtml = `Your browser is bad`;
this.dropZone.classList.add('error');
};
this.dropZone.addEventListener('dragenter', this.dropZoneEnter);
this.dropZone.addEventListener('dragover', this.dropZoneOver);
this.dropZone.addEventListener('dragleave', this.dropZoneLeave);
this.dropZone.addEventListener('drop', (e) => {
this.dropZoneDrop(e);
});
},
dropZoneEnter(e) {
e.stopPropagation();
e.preventDefault();
},
dropZoneOver: (e) => {
e.stopPropagation();
e.preventDefault();
dropZone.classList.add('hover');
},
dropZoneLeave() {
dropZone.classList.remove('hover');
},
dropZoneDrop(e) {
e.stopPropagation();
e.preventDefault();
let file = e.dataTransfer.files[0];
if (file.size > this.maxFileZize) {
this.dropZone.innerHTML = 'File very large';
this.dropZone.classList.add('error');
} else {
this.dropZone.innerHTML = 'File size - '+file.size;
}
this.uploadFile('/upload.php', 'POST', file);
return false;
},
uploadFile(url, method, file){
let xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', this.uploadProgress, false);
xhr.onreadystatechange = this.stateChange;
xhr.open('POST', this.url);
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
},
uploadProgress(event) {
var percent = parseInt(event.loaded / event.total * 100);
dropZone.innerHTML = 'Загрузка: ' + percent + '%';
},
stateChange(event) {
if (event.target.readyState == 4) {
//Ответ пришел, здесь можно обработать все ответы.
if (event.target.status == 200) {
dropZone.innerHTML = 'Загрузка успешно завершена!';
dropZone.classList.add('success');
} else {
dropZone.innerHTML = 'Произошла ошибка!';
dropZone.classList.add('error');
}
}
}
}
// Аргементы: id блока дропзоны, адрес серверного обработчика, максимальный размер файла.
fileLoader.init('dropZone', '/upload.php', 100000);
|
C#
|
UTF-8
| 17,588 | 2.609375 | 3 |
[] |
no_license
|
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
using System.Drawing.Drawing2D;
namespace SolidUtils.GUI.StatusListProgress
{
[Designer(typeof(StatusListDesigner))]
public partial class StatusList
{
#region " Declarations "
// The StatusItem Collection
private StatusCollection _Items;
// The currently selected item in the designer
private StatusItem highlightedItem;
// the pending image
private Image _FailedImage;
// the complete image
private Image _CompleteImage;
// the image size
private Size _imageSize = new Size(12, 12);
// the padding between the outer bounds and the image/text
private int _pad = 3;
private int emptySpaceToNextItem = 2;
private int Indent = 30;
private bool _ShowTitle = true;
private Color _LineColor = Color.Green;
#endregion
#region " Properties "
[Category("Appearance")]
public Color LineColor
{
get { return _LineColor; }
set
{
_LineColor = value;
this.DrawItems();
}
}
[Category("Appearance")]
public bool ShowTitle
{
get { return _ShowTitle; }
set
{
_ShowTitle = value;
this.DrawItems();
}
}
[Category("Custom Properties"), Description("The padding between the outer bounds and the image/text")]
public int Pad
{
get { return _pad; }
set
{
_pad = value;
this.DrawItems();
}
}
[Category("Custom Properties"), Description("Distance between items")]
public int EmptySpaceToNextItem
{
get { return emptySpaceToNextItem; }
set
{
emptySpaceToNextItem = value;
this.DrawItems();
}
}
//[Category("Custom Properties"), Description("The default image size")]
//public Size ImageSize
//{
// get { return _imageSize; }
// set
// {
// if (value.Width < 9 | value.Height < 9)
// {
// Interaction.MsgBox("Minimum size is '12, 12'");
// return;
// }
// _imageSize = value;
// this.DrawItems();
// }
//}
public override System.Drawing.Font Font
{
get { return base.Font; }
set
{
base.Font = value;
this.DrawItems();
}
}
[Category("Custom Properties"), Description("The image used for pending items")]
public Image FailedImage
{
get { return _FailedImage; }
set
{
_FailedImage = value;
this.DrawItems();
}
}
[Category("Custom Properties"), Description("The image used for completed items")]
public Image CompleteImage
{
get { return _CompleteImage; }
set
{
_CompleteImage = value;
this.DrawItems();
}
}
[Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Category("Data"), Description("Returns a collection of all the status items")]
public StatusCollection Items
{
get { return _Items; }
set
{
_Items = value;
this.DrawItems();
}
}
#endregion
#region " Methods "
internal void DrawItems()
{
// ----------------------------
// This methods calculates the layout of all the status items, designating them certain bounds, to stop overflow
// ----------------------------
StatusItem item = null;
// The current item
int y = 0;
// Y-Axis position of the current item
Size itemSize = default(Size);
// The size of the current item
Graphics g = this.CreateGraphics();
if (!this.ShowTitle)
{
y = 0;
}
else
{
y = g.MeasureString(this.Text, new Font(Font, FontStyle.Bold)).ToSize().Height + Pad * 5;
}
try
{
foreach (StatusItem item_loopVariable in Items)
{
item = item_loopVariable;
// Measure the string size
var itemFont = (item.CustomFontSize.HasValue && item.CustomFontSize.Value > 0)
? new Font(Font.Name, item.CustomFontSize.Value, Font.Style)
: new Font(Font, FontStyle.Bold);
var itemSizeMeasureStringSize = g.MeasureString(item.Text, itemFont).ToSize();
itemSize = new Size(
itemSizeMeasureStringSize.Width - 4,
itemSizeMeasureStringSize.Height);
// Check if the image height is larger than the current height
var imageHeight = Math.Max(CompleteImage.Height, FailedImage.Height);
if (itemSize.Height < imageHeight)
{
itemSize.Height = imageHeight; // If it is, resize the control to accommodate it
}
// Set the bounds of the control to the width of the image, text and associated padding for nicer viewing
//item.Bounds = New Rectangle(Pad, y, ImageSize.Width + (Pad * 3) + itemSize.Width + (Pad * 2), (itemSize.Height + Pad * 2))
var padX = item.CustomPaddingX ?? Pad;
var padY = item.CustomPaddingY ?? Pad;
item.Bounds = new Rectangle(Indent, y, itemSize.Width + padX * 2, itemSize.Height + padY * 2);
if (string.IsNullOrEmpty(item.Text))
{
item.Bounds.Width = 10;
}
// Set the Y-Axis position of the next item
int dist = item.CustomEmptySpaceToNextItem ?? EmptySpaceToNextItem;
y = item.Bounds.Bottom + dist;
}
}
catch (Exception ex)
{
}
g.Dispose();
//Mark the control as invalid so it gets redrawn
Invalidate();
}
public new string Text
{
get { return base.Text; }
set
{
base.Text = value;
this.DrawItems();
}
}
protected override void OnResize(System.EventArgs e)
{
base.OnResize(e);
// If the control is resized, re-calculate the items and make the control invalid
this.DrawItems();
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// ----------------------------
// This method performs all the painting of the items, text and images.
// ----------------------------
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
if (this.ShowTitle)
{
e.Graphics.DrawString(this.Text, new Font(Font, FontStyle.Bold), new SolidBrush(this.ForeColor), 0, 0);
int y = e.Graphics.MeasureString(this.Text, new Font(Font, FontStyle.Bold)).ToSize().Height + Pad * 2;
LinearGradientBrush lin = new LinearGradientBrush(new Point(Pad, 0), new Point(this.Width - Pad, 0), LineColor, Color.FromArgb(0, LineColor));
e.Graphics.DrawLine(new Pen(lin), Pad, y, this.Width - Pad, y);
}
// ----------------------------------------------
// This methods needs to be cleaned up... Please don't judge just yet!
// ----------------------------------------------
StatusItem item = null;
// The current item
Brush b = null;
// The current brush
Rectangle wrct = default(Rectangle);
// The current item bounds
int yOffSet = 0;
// The offSet of each item on the Y-Axis
foreach (StatusItem item_loopVariable in Items)
{
item = item_loopVariable;
var itemFont = (item.CustomFontSize.HasValue && item.CustomFontSize.Value > 0)
? new Font(Font.Name, item.CustomFontSize.Value, Font.Style)
: new Font(Font, Font.Style);
//Create brush from button colour
if ((b != null))
b.Dispose();
b = new SolidBrush(Color.FromArgb(180, Color.SteelBlue));
//Fill rectangle with this colour
wrct = item.Bounds;
wrct.Width = this.Width - item.Bounds.Left - 30; // minus position, minus icon size
if (string.IsNullOrEmpty(item.Text) & this.DesignMode)
{
Pen p = new Pen(Color.Black);
p.DashStyle = DashStyle.Dot;
e.Graphics.DrawRectangle(p, wrct);
}
switch (item.Status)
{
case StatusItem.CurrentStatus.Complete:
e.Graphics.DrawImage(this.CompleteImage, new Rectangle(wrct.Left/3, wrct.Top + (wrct.Height - CompleteImage.Height) / 2, CompleteImage.Width, CompleteImage.Height));
break;
case StatusItem.CurrentStatus.Failed:
e.Graphics.DrawImage(this.FailedImage, new Rectangle(wrct.Left / 3, wrct.Top + (wrct.Height - FailedImage.Height) / 2, FailedImage.Width, FailedImage.Height));
break;
case StatusItem.CurrentStatus.Pending:
e.Graphics.DrawString(item.Text, itemFont, new SolidBrush(this.ForeColor), wrct.Left + Pad, wrct.Top + Pad);
break;
case StatusItem.CurrentStatus.Running:
double wid = 0;
double range = 0;
range = item.Maximum - item.Minimum;
wid = (item.Maximum - (item.Maximum - item.Value)) / range;
var alpha = 100;
wrct.Inflate(-1, 0);
e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(alpha, 227, 247, 255)), wrct.Left, wrct.Top, Convert.ToInt32(wrct.Width * wid), wrct.Height);
e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(alpha, 185, 233, 252)), wrct.Left, wrct.Bottom - Convert.ToInt32(wrct.Height * 0.55), Convert.ToInt32(wrct.Width * wid), wrct.Height - Convert.ToInt32(wrct.Height * 0.55) + 1);
wrct.Inflate(1, 0);
e.Graphics.DrawLine(new Pen(Color.FromArgb(alpha, 147, 201, 227)), wrct.Left + 1, wrct.Top, wrct.Right - 1, wrct.Top);
e.Graphics.DrawLine(new Pen(Color.FromArgb(alpha, 147, 201, 227)), wrct.Left + 1, wrct.Bottom, wrct.Right - 1, wrct.Bottom);
e.Graphics.DrawLine(new Pen(Color.FromArgb(alpha, 136, 203, 235)), wrct.Left, wrct.Top + 1, wrct.Left, wrct.Bottom - 1);
e.Graphics.DrawLine(new Pen(Color.FromArgb(alpha, 105, 187, 227)), wrct.Left, wrct.Bottom - Convert.ToInt32(wrct.Height * 0.55), wrct.Left, wrct.Bottom - 1);
e.Graphics.DrawLine(new Pen(Color.FromArgb(alpha, 136, 203, 235)), wrct.Right, wrct.Top + 1, wrct.Right, wrct.Bottom - 1);
e.Graphics.DrawLine(new Pen(Color.FromArgb(alpha, 105, 187, 227)), wrct.Right, wrct.Bottom - Convert.ToInt32(wrct.Height * 0.55), wrct.Right, wrct.Bottom - 1);
var percent = Convert.ToInt32(wid * 100);
float progressFontSize = 5;
if (item.CustomFontSize.HasValue && item.CustomFontSize.Value > 0) progressFontSize = item.CustomFontSize.Value;
var progressFont = new Font(Font.Name, progressFontSize, FontStyle.Regular);
int progressTextHeight = e.Graphics.MeasureString(percent + "%", progressFont).ToSize().Height;
e.Graphics.DrawString(percent + "%", progressFont, new SolidBrush(Color.FromArgb(alpha, 147, 201, 227)), 0, wrct.Bottom - Convert.ToInt32(wrct.Height / 2) - progressTextHeight / 2);
break;
}
int itemTextHeight = e.Graphics.MeasureString(item.Text, itemFont).ToSize().Height;
var padX = item.CustomPaddingX ?? Pad;
e.Graphics.DrawString(item.Text, itemFont, new SolidBrush(Color.FromArgb(220, this.ForeColor)), wrct.Left + padX, wrct.Bottom - Convert.ToInt32(wrct.Height / 2) - itemTextHeight / 2);
if (object.ReferenceEquals(highlightedItem, item))
{
wrct.Inflate(-1, -1);
e.Graphics.DrawRectangle(new Pen(b, 2), wrct);
}
}
}
internal void OnSelectionChanged()
{
// ----------------------------
// This methods is called by the StatusLabel control when a selection has changed in design mode
// ----------------------------
StatusItem item = null;
StatusItem newHighlightedItem = null;
ISelectionService s = (ISelectionService)GetService(typeof(ISelectionService));
//See if the primary selection is one of our buttons
foreach (StatusItem item_loopVariable in Items)
{
item = item_loopVariable;
if (object.ReferenceEquals(s.PrimarySelection, item))
{
newHighlightedItem = item;
break; // TODO: might not be correct. Was : Exit For
}
}
//Apply if necessary
if ((!object.ReferenceEquals(newHighlightedItem, highlightedItem)))
{
highlightedItem = newHighlightedItem;
Invalidate();
}
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
// ----------------------------
// This methods checks the MouseDown event within the control and determines whether an item was selected, and if so, which one
// ----------------------------
Rectangle wrct = default(Rectangle);
// The current item bounds
ISelectionService s = null;
// Selection service
ArrayList a = null;
// array of selected items
StatusItem item = null;
// the current item
if (DesignMode)
{
foreach (StatusItem item_loopVariable in Items)
{
item = item_loopVariable;
// Get the current item bounds
wrct = item.Bounds;
if (wrct.Contains(e.X, e.Y))
{
// if the current item has mouse down focus, add it to the array and exit the loop
s = (ISelectionService)GetService(typeof(ISelectionService));
a = new ArrayList();
a.Add(item);
s.SetSelectedComponents(a);
break; // TODO: might not be correct. Was : Exit For
}
}
}
// Perform any additional tasks here
base.OnMouseDown(e);
}
#endregion
public StatusList()
{
// This call is required by the Windows Form Designer.
InitializeComponent();
// Initialisations go here...
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
// IMPORTANT!!! This declares the New Collection
_Items = new StatusCollection(this);
// Set the default size of the control
this.Size = new Size(200, 100);
}
}
}
|
C#
|
UTF-8
| 6,884 | 3.015625 | 3 |
[
"Unlicense"
] |
permissive
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace LibBSP {
/// <summary>
/// Class representing a group of <see cref="Entity"/> objects. Contains helpful methods to handle Entities in the <c>List</c>.
/// </summary>
[Serializable] public class Entities : List<Entity> {
/// <summary>
/// Initializes a new instance of an <see cref="Entities"/> object copying a passed <c>IEnumerable</c> of <see cref="Entity"/> objects.
/// </summary>
/// <param name="data">Collection of <see cref="Entity"/> objects to copy.</param>
public Entities(IEnumerable<Entity> data) : base(data) { }
/// <summary>
/// Initializes a new instance of an <see cref="Entities"/> object with a specified initial capacity.
/// </summary>
/// <param name="initialCapacity">Initial capacity of the <c>List</c> of <see cref="Entity"/> objects.</param>
public Entities(int initialCapacity) : base(initialCapacity) { }
/// <summary>
/// Initializes a new empty <see cref="Entities"/> object.
/// </summary>
public Entities() : base() { }
/// <summary>
/// Initializes a new <see cref="Entities"/> object, parsing all the bytes in the passed <paramref name="file"/>.
/// </summary>
/// <param name="file">The file to read.</param>
/// <param name="type">The <see cref="MapType"/> of the source map.</param>
public Entities(FileInfo file, MapType type) : this(File.ReadAllBytes(file.FullName), type) { }
/// <summary>
/// Initializes a new <see cref="Entities"/> object, and parses the passed <c>byte</c> array into the <c>List</c>.
/// </summary>
/// <param name="data"><c>Byte</c>s read from a file.</param>
/// <param name="type">The <see cref="MapType"/> of the source map.</param>
/// <param name="version">The version of this lump.</param>
public Entities(byte[] data, MapType type, int version = 0) : base() {
// Keep track of whether or not we're currently in a set of quotation marks.
// I came across a map where the idiot map maker used { and } within a value. This broke the code before.
bool inQuotes = false;
int braceCount = 0;
// The current character being read in the file. This is necessary because
// we need to know exactly when the { and } characters occur and capture
// all text between them.
char currentChar;
// This will be the resulting entity, fed into Entity.FromString
StringBuilder current = new StringBuilder();
for (int offset = 0; offset < data.Length; ++offset) {
currentChar = (char)data[offset];
if (currentChar == '\"') {
if (offset == 0) {
inQuotes = !inQuotes;
} else if ((char)data[offset - 1] != '\\') {
// Allow for escape-sequenced quotes to not affect the state machine, but only if the quote isn't at the end of a line.
// Some Source engine entities use escape sequence quotes in values, but MoHAA has a map with an obvious erroneous backslash before a quote at the end of a line.
if (inQuotes && (offset + 1 >= data.Length || (char)data[offset + 1] == '\n' || (char)data[offset + 1] == '\r')) {
inQuotes = false;
}
} else {
inQuotes = !inQuotes;
}
}
if (!inQuotes) {
if (currentChar == '{') {
// Occasionally, texture paths have been known to contain { or }. Since these aren't always contained
// in quotes, we must be a little more precise about how we want to select our delimiters.
// As a general rule, though, making sure we're not in quotes is still very effective at error prevention.
if (offset == 0 || (char)data[offset - 1] == '\n' || (char)data[offset - 1] == '\t' || (char)data[offset - 1] == ' ' || (char)data[offset - 1] == '\r') {
++braceCount;
}
}
}
if (braceCount > 0) {
current.Append(currentChar);
}
if (!inQuotes) {
if (currentChar == '}') {
if (offset == 0 || (char)data[offset - 1] == '\n' || (char)data[offset - 1] == '\t' || (char)data[offset - 1] == ' ' || (char)data[offset - 1] == '\r') {
--braceCount;
if (braceCount == 0) {
Add(Entity.FromString(current.ToString()));
// Reset StringBuilder
current.Length = 0;
}
}
}
}
}
if (braceCount != 0) {
throw new ArgumentException(string.Format("Brace mismatch when parsing entities! Entity: {0} Brace level: {1}", Count, braceCount));
}
}
/// <summary>
/// Deletes all <see cref="Entity"/> objects with "<paramref name="key"/>" set to "<paramref name="value"/>".
/// </summary>
/// <param name="key">Attribute to match.</param>
/// <param name="value">Desired value of attribute.</param>
public void RemoveAllWithAttribute(string key, string value) {
RemoveAll(entity => { return entity[key].Equals(value, StringComparison.InvariantCultureIgnoreCase); });
}
/// <summary>
/// Gets a <c>List</c> of all <see cref="Entity"/> objects with "<paramref name="key"/>" set to "<paramref name="value"/>".
/// </summary>
/// <param name="key">Name of the attribute to search for.</param>
/// <param name="value">Value of the attribute to search for.</param>
/// <returns><c>List</c><<see cref="Entity"/>> that have the specified key/value pair.</returns>
public List<Entity> GetAllWithAttribute(string key, string value) {
return FindAll(entity => { return entity[key].Equals(value, StringComparison.InvariantCultureIgnoreCase); });
}
/// <summary>
/// Gets a <c>List</c> of <see cref="Entity"/>s objects with the specified targetname.
/// </summary>
/// <param name="targetname">Targetname attribute to find.</param>
/// <returns><c>List</c><<see cref="Entity"/>> with the specified targetname.</returns>
public List<Entity> GetAllWithName(string targetname) {
return FindAll(entity => { return entity.name.Equals(targetname, StringComparison.InvariantCultureIgnoreCase); });
}
/// <summary>
/// Gets the first <see cref="Entity"/> with "<paramref name="key"/>" set to "<paramref name="value"/>".
/// </summary>
/// <param name="key">Name of the attribute to search for.</param>
/// <param name="value">Value of the attribute to search for.</param>
/// <returns><see cref="Entity"/> with the specified key/value pair, or null if none exists.</returns>
public Entity GetWithAttribute(string key, string value) {
return Find(entity => { return entity[key].Equals(value, StringComparison.InvariantCultureIgnoreCase); });
}
/// <summary>
/// Gets the first <see cref="Entity"/> with the specified targetname.
/// </summary>
/// <param name="targetname">Targetname attribute to find.</param>
/// <returns>Entity object with the specified targetname.</returns>
public Entity GetWithName(string targetname) {
return Find(entity => { return entity.name.Equals(targetname, StringComparison.InvariantCultureIgnoreCase); });
}
}
}
|
Java
|
UTF-8
| 2,211 | 2.265625 | 2 |
[] |
no_license
|
package entity.adverstising;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 待机广告
* </p>
*
* @author hzh
* @since 2018-10-15
*/
@Entity
@Table(name = "advertising")
@DynamicInsert
@DynamicUpdate
public class Advertising implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 广告名称
*/
private String name;
/**
* 广告语
*/
private String title;
/**
* 广告语
*/
private String solgan;
/**
* 上架状态 0下架 1上架
*/
private Integer state;
/**
* 创建时间
*/
@Temporal(value = TemporalType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
/**
* 创建时间
*/
@Temporal(value = TemporalType.TIMESTAMP)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSolgan() {
return solgan;
}
public void setSolgan(String solgan) {
this.solgan = solgan;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
Swift
|
UTF-8
| 4,375 | 3.109375 | 3 |
[
"Apache-2.0"
] |
permissive
|
/// - Important: to make `@Environment` properties (e.g. `horizontalSizeClass`), internally accessible
/// to extensions, add as sourcery annotation in `FioriSwiftUICore/Models/ModelDefinitions.swift`
/// to declare a wrapped property
/// e.g.: `// sourcery: add_env_props = ["horizontalSizeClass"]`
import SwiftUI
extension Fiori {
enum ActivationScreen {
struct Title: ViewModifier {
func body(content: Content) -> some View {
content
.font(.fiori(forTextStyle: .title1).weight(.black))
.foregroundColor(.preferredColor(.primaryLabel))
.multilineTextAlignment(.center)
}
}
typealias TitleCumulative = EmptyModifier
struct DescriptionText: ViewModifier {
func body(content: Content) -> some View {
content
.font(.fiori(forTextStyle: .body))
.foregroundColor(.preferredColor(.primaryLabel))
.multilineTextAlignment(.center)
}
}
typealias DescriptionTextCumulative = EmptyModifier
struct TextInput: ViewModifier {
func body(content: Content) -> some View {
content
.font(.fiori(forTextStyle: .body))
.foregroundColor(.preferredColor(.primaryLabel))
.multilineTextAlignment(.center)
.keyboardType(.emailAddress)
.disableAutocorrection(true)
}
}
typealias TextInputCumulative = EmptyModifier
struct Action: ViewModifier {
func body(content: Content) -> some View {
content
.frame(minWidth: 169.0, minHeight: 20.0)
}
}
typealias ActionCumulative = EmptyModifier
struct Footnote: ViewModifier {
func body(content: Content) -> some View {
content
.font(.fiori(forTextStyle: .body))
.foregroundColor(.preferredColor(.primaryLabel))
}
}
typealias FootnoteCumulative = EmptyModifier
struct SecondaryAction: ViewModifier {
func body(content: Content) -> some View {
content
.font(.system(size: 15))
.foregroundColor(.preferredColor(.primaryLabel))
}
}
typealias SecondaryActionCumulative = EmptyModifier
static let title = Title()
static let descriptionText = DescriptionText()
static let textInput = TextInput()
static let action = Action()
static let footnote = Footnote()
static let secondaryAction = SecondaryAction()
static let titleCumulative = TitleCumulative()
static let descriptionTextCumulative = DescriptionTextCumulative()
static let textInputCumulative = TextInputCumulative()
static let actionCumulative = ActionCumulative()
static let footnoteCumulative = FootnoteCumulative()
static let secondaryActionCumulative = SecondaryActionCumulative()
}
}
extension ActivationScreen: View {
public var body: some View {
VStack {
title
.padding(.top, 80)
.padding(.bottom, 40)
descriptionText
.padding(.bottom, 56)
textInput
.padding(.bottom, 30)
action
.buttonStyle(StatefulButtonStyle())
.padding(.bottom, 16)
footnote
.padding(.bottom, 16)
secondaryAction
.buttonStyle(StatefulButtonStyle())
Spacer()
}
.padding(.leading, 32)
.padding(.trailing, 32)
}
}
@available(iOS 14.0, *)
struct ActivationScreenLibraryContent: LibraryContentProvider {
@LibraryContentBuilder
var views: [LibraryItem] {
LibraryItem(ActivationScreen(title: "Activation", descriptionText: "If you received a welcome email, follow the activation link in the email.Otherwise, enter your email address or scan the QR code to start onboarding. ", footnote: "Or", action: Action(actionText: "Next"), secondaryAction: Action(actionText: "Scan")),
category: .control)
}
}
|
PHP
|
ISO-8859-1
| 2,836 | 2.640625 | 3 |
[] |
no_license
|
<?php session_start();
require_once("../../../../../../data/connstat.php");
require_once '../file/Classes/PHPExcel/IOFactory.php';
$folder = "../file/documents/";
$archiv="../file/archives/";
if ($_SESSION['login']){
}
else {
header("Location:login.php");
}
$id_user = $_SESSION['id_user'];
$datesys=date("Y-m-d");
if ( isset($_REQUEST['codsous']) && isset($_REQUEST['file']) && isset($_REQUEST['id_doc']) ) {
$codsous = $_REQUEST['codsous'];
$file = $_REQUEST['file'];
$id_doc = $_REQUEST['id_doc'];
//manipuler le fichier excel file
}
$objPHPExcel = PHPExcel_IOFactory::load($folder. $file.".xlsx");
/**
* rcupration de la premire feuille du fichier Excel
* @var PHPExcel_Worksheet $sheet
*/
$sheet = $objPHPExcel->getSheet(0);
$numeroLigneMax = $sheet->getHighestRow();
$libelleColonneMax = $sheet->getHighestColumn();
$i=0;
for ($ligne=2 ; $ligne <=$numeroLigneMax; $ligne++)
{
// On boucle sur les cellules de la ligne
$nom="";$pnom="";$pass="";$datedpass="";$datenai="";$mail="";$tel="";$adr="";$age_ass="";$sexe="";$date1="";$date2="";
$sexe=$sheet-> getCellByColumnAndRow( 0 , $ligne )->getValue();
$nom=addslashes($sheet-> getCellByColumnAndRow( 1 , $ligne )->getValue());
$pnom=addslashes($sheet->getCellByColumnAndRow( 2 , $ligne )->getValue());
$pass=$sheet->getCellByColumnAndRow( 3 , $ligne )->getValue();
$datedpass=PHPExcel_Style_NumberFormat::toFormattedString($sheet->getCellByColumnAndRow( 4 , $ligne )->getValue(), 'YYYY-MM-DD');
$datenai=PHPExcel_Style_NumberFormat::toFormattedString($sheet->getCellByColumnAndRow( 5 , $ligne )->getValue(), 'YYYY-MM-DD');
$adr=addslashes($sheet->getCellByColumnAndRow( 6 , $ligne )->getValue());
$mail= $sheet->getCellByColumnAndRow( 7, $ligne )->getValue();
$tel= $sheet->getCellByColumnAndRow( 8, $ligne )->getValue();
//calcule age.
$age_ass=age($datenai,$datesys);
//insertion
try {
if(isset($sexe) && isset($nom) && isset($pnom) && isset($pass) && isset($datenai) ) {
$rqtsous3 = $bdd->prepare("INSERT INTO `souscripteurw`(`cod_sous`,`nom_sous`, `pnom_sous`, `passport`, `datedpass`, `dnais_sous`,`age`, `civ_sous`,`cod_par`, `id_user`) VALUES ('','$nom','$pnom','$pass','$datedpass','$datenai','$age_ass','$sexe','$codsous','$id_user')");
$rqtsous3->execute();
}
} catch (Exception $ex) {
echo 'Erreur : ' . $ex->getMessage() . '<br />';
echo 'N : ' . $ex->getCode();
}
}
if( file_exists ( $folder. $file.".xlsx"))
copy($folder. $file.".xlsx",$archiv. $file.".xlsx");
unlink( $folder. $file.".xlsx" ) ;
Alternative:
@unlink( $folder. $file.".xlsx" ) ;
?>
|
Markdown
|
UTF-8
| 10,046 | 2.921875 | 3 |
[] |
no_license
|
---
title: Quick Start Guide for Using Kubernetes in Rancher
layout: rancher-default-v1.6
version: v1.6
lang: en
---
## Quick Start Guide for Using Kubernetes in Rancher
---
In this guide, you'll learn how to quickly get started using Kubernetes in Rancher v1.6, including:
* Preparing a Linux Host
* Launching Rancher Server (and Accessing the Rancher UI)
* Creating a Kubernetes Environment in Rancher
* Adding Hosts
* Adding Containers
* Launching Catalog Applications
### Preparing a Linux Host
To begin, you'll need to install a [supported version of Docker]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/setup/#supported-docker-versions) on a single Linux host. You can use your laptop, a virtual machine, or a physical server.
>**Note:** The versions of Docker that Rancher supports can differ from those that Kubernetes supports. In addition, Rancher does not currently support Docker for Windows and Docker for Mac.
#### To Prepare a Linux Host:
1. Prepare a Linux host with 64-bit Ubuntu 16.04, at least **1GB** of memory, and a kernel of 3.10+.
2. Install a [supported version of Docker]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/hosts/#supported-docker-versions) on the host. To install Docker on the server, follow the instructions from [Docker](https://docs.docker.com/engine/installation/linux/ubuntu/).
### Launching Rancher Server
It only takes one command and a few minutes to install and launch Rancher Server. Once installed, you can open a web browser to access the Rancher UI.
> **Note:** We recommend configuring [access control](http://rancher.com/docs/rancher/v1.6/en/configuration/access-control/). Otherwise, your UI and API is available to anyone who can access your IP address.
#### To Launch Rancher Server:
1. Run this Docker command on your host:
```bash
$ sudo docker run -d --restart=unless-stopped -p 8080:8080 rancher/server:stable
# Tail the logs to show Rancher
$ sudo docker logs -f <CONTAINER_ID>
```
After launching the container, we'll tail the logs of the container to see when the server is up and running. When the Rancher UI is ready, a `Startup Succeeded, Listening on port` message displays. This process might take several minutes to complete.
2. To access the Rancher UI, go to `http://<SERVER_IP>:8080`, replacing `<SERVER_IP>` with the IP address of your host. The UI displays a Welcome to Rancher message.
> **Note:** If you are running your browser on the same host running Rancher Server, you will need to use the host’s real IP address, such as `http://192.168.1.100:8080,` and not `http://localhost:8080` or `http://127.0.0.1:8080`.
3. Click **Got It**. The Rancher UI displays.
### Creating a Kubernetes Environment in Rancher
Rancher supports grouping resources into multiple [environments]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/concepts/environments/). Each environment starts with an [environment template]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/concepts/environment-template) to define its set of [infrastructure services]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/concepts/infra-services/), and one or more users or groups own it.
Initially, Rancher creates a **Default** Cattle environment for you. To deploy Kubernetes in Rancher, we'll use the pre-defined Kubernetes environment template and then add the environment to Rancher.
#### To Create a Kubernetes Environment in Rancher:
1. From the **Environment** menu, select **Manage Environments**.
2. Click **Add Environment**, enter a **Name** (required) and a **Description** (optional).
3. Select the Kubernetes template, and then click **Create**.
4. From the **Environment** menu, select your Kubernetes environment. A `Setting up Kubernetes` message displays and prompts you to add at least one host.
You can access this new environment from the **Environment** menu. If you configured access control, you can add members to this environment and select their membership roles on the **Manage Environments** page.
### Adding Hosts
The process of adding hosts is the same steps for all container orchestration types, including Cattle and Kubernetes. For Kubernetes, adding your first host deploys infrastructure services, including Kubernetes services like master, kubelet, etcd, and proxy. You can see the progress of the deployment by accessing the **Kubernetes > Infrastructure Stacks** menu.
You can either add a custom host or a host from a cloud provider that Rancher v1.6 supports. If you don't see your cloud provider in the UI, don't worry. Simply use the `Custom` host option, which is selected by default. It provides the Docker command to launch the Rancher agent container. Rancher uses Docker Machine to launch hosts for the other cloud providers.
Hosts you plan to use as Kubernetes nodes require the following TCP ports open for `kubectl`: `10250` and `10255`.
If you're adding a custom host, note these requirements:
* Typically, Rancher automatically detects the IP address to register the host.
* If the host is behind a NAT or the same machine that is running the `rancher/server` container, you might need to explicitly specify its IP address.
* The host agent initiates a connection to the server, so make sure firewalls or security groups allow it to reach the URL in the command.
* All hosts in the environment must to allow traffic between each other for cross-host networking.
* IPSec: `500/udp` and `4500/udp`
* VXLAN: `4789/udp`
#### To Add a Custom Host:
1. From the **Infrastructure** menu, select **Hosts**. The Hosts page displays.
2. Click **Add Host**.
3. Enter your **Host Registration URL**, and click **Save**. This URL is where Rancher Server is running, and it must be reachable from any hosts you add. The Add Host page displays.
4. Select **Custom**.
5. If you need to specify the agent IP address, you can enter it in the field.
6. To register your host with Rancher, copy the Docker command from the UI and then run it on your host. This process might take a few minutes to complete. For example:
```bash
sudo docker run --rm --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/rancher:/var/lib/rancher rancher/agent:v1.6
http://<SERVER_IP>:8080/v3/scripts/D5433C26EC51325F9D98:1483142400000:KvILQKwz1N2MpOkOiIvGYKKGdE
```
>**Note:** The IP address in the command must match your `<SERVER_IP>` and it must be reachable from inside your host.
7. Click **Close**. On the Hosts page, you can view the status of your host.
#### To Add a Host from a Cloud Provider:
1. From the **Infrastructure** menu, select **Hosts**. The Hosts page displays.
2. Click **Add Host**.
3. Enter your **Host Registration URL**, and click **Save**. This URL is where Rancher Server is running, and it must be reachable from any hosts you add. The Add Host page displays.
4. Select your cloud provider:
* Amazon EC2
* Microsoft Azure
* DigitalOcean
* Packet
* Other
5. Follow the instructions in the Rancher UI to add your host. This process might take a few minutes to complete. Once your host is ready, you can view its status on the Hosts page.
After you add at least one host to your environment, it might take several minutes for all Rancher system services to launch. To verify the status of your environment, from the **Kubernetes** menu, select **Infrastructure Stacks**. If a service is healthy, its state displays in green.
### Adding Containers
Once you've verified that all system services are up and running, you're ready to create your first container. In Kubernetes, one or more containers is a `pod`.
The process for adding a container differs depending on your container orchestration type. The Rancher UI provides three options for using Kubernetes: Dashboard, CLI, and `kubectl`. Please refer to Kubernetes' [Overview of kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) for more details.
#### To Add a Container:
From the **Kubernetes** menu, select one of the following options:
* **Dashboard** — Access the native Kubernetes dashboard in a new browser window by clicking **Kubernetes UI**.
* **CLI** — On the Kubernetes CLI page, two options display. To configure `kubectl` for your local machine, click **Generate Config**. Copy and paste the code that displays into your `.kube/config` file, and then run `kubectl`. You can also conveniently access the shell in a managed `kubectl` instance right in your web browser.
### Launching Catalog Applications
To help you deploy complex stacks, the Rancher Catalog offers application templates.
#### To Launch a Catalog Application:
1. From the **Kubernetes** menu, select **Infrastructure Stacks**.
2. Click **Add from Catalog**. Catalog application templates display.
2. Search for the template you want to launch, and then click **View Details**.
3. Select a **Template Version**. The latest version displays by default.
4. Enter a **Name** (required) and **Description** (optional) for your template.
5. Enter the **Configuration Options**, which are specific to the template.
>**Note:** To review the `docker-compose.yml` and `rancher-compose.yml` files used to generate the stacks, click **Preview** before launching the stack.
6. Select **Start services after creating**, if applicable.
7. Click **Launch**. On the Stack page, you'll see Rancher is creating a stack based on your new application. This process might take a few minutes.
Once your new stack's services are up and running, its state displays in green.
### Next Steps
Now that you've added hosts, created your first container, and launched a catalog template, you can check out the rest of the features in Rancher v1.6:
* [Setup]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/setup/)
* [Concepts]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/concepts/)
* [Tasks]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/tasks/)
* [FAQ]({{site.baseurl}}/rancher/{{page.version}}/{{page.lang}}/faq/)
|
JavaScript
|
UTF-8
| 4,456 | 3.28125 | 3 |
[] |
no_license
|
let data = [
{value:'第一条测试',fontSize:20,color:'red',speed:2,time:0,},
{value:'第二条测试',time:1}
]
//外部类封装不彻底,想用面向对象思维那么不需要多少外部变量和方法,所以ctx,video应该都在DANMU类中
let $ = document.querySelector.bind(document)
let canvas = $('#canvas')
let video = $('#video')
let name = $('#text')
let submit = $('#submit')
let range = $('#range')
let colorE = $("#color")
let ctx = canvas.getContext('2d')
class SingleDanmu{
constructor(options){
let defaultOptions = {
color:'red',
fontSize:16,
speed:2
}
this.value = options.value
this.time = options.time
this.color = options.color || defaultOptions.color
this.fontSize = options.fontSize || defaultOptions.fontSize
this.speed = options.speed || defaultOptions.speed
this.init()
//初始化成功后,就该在主类中让其运动
}
init(){
//计算单个弹幕的高宽以及出现的x,y值
let span = document.createElement('span')
span.innerText = this.value
span.style.fontSize = this.fontSize + 'px'
span.style.position = 'absolute'
console.log(span)
document.body.appendChild(span)
this.width = span.clientWidth
this.height = span.clientHeight
console.log(span.clientWidth,this.height)
document.body.removeChild(span)
//计算x,y值
this.x = canvas.clientWidth
this.y = canvas.clientHeight * Math.random()
//让弹幕不显示一半
if(this.y < this.height){
this.y = this.height
}
if(this.y + this.height > canvas.clientHeight){
this.y = canvas.clientHeight - this.height
}
}
render(){
//渲染其实就是canvas画图操作
if(!this.flag){
//执行一次就让this.x - this.speedd
this.x = this.x - this.speed
/* console.log('x',this.x) */
//画在画布上
ctx.fillStyle = this.color
ctx.font = "bold "+ this.fontSize+'px' +" Arial"
ctx.fillText(this.value,this.x,this.y)
}
//弹幕出去后处理
if(this.x < -this.width){
/* console.log('width',this.width) */
this.flag = true//不让他画啦
}
}
}
class Danmu{
constructor(data){
this.data = data
this.init()
}
reset(){
ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight)//清空画布
let time = video.currentTime
this.danmus.forEach(item=>{
item.flag = false
if(time<=item.time){
item.x= canvas.clientWidth
item.render()
}else{
item.flag = true
}
})
}
add(obj){
this.danmus.push(new SingleDanmu(obj))
}
init(){
canvas.width = video.clientWidth
canvas.height = video.clientHeight
let danmus = []
data.forEach(item => {
danmus.push(new SingleDanmu(item))
});
this.danmus = danmus//对象是danmu对象
this.play = false
this.render()
}
//让数组中的弹幕对象动起来
render(){
ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight)//清空画布
console.log(this.play)
this.danmuRender()
if(this.play){
requestAnimationFrame(this.render.bind(this))
}
//创建动画让其动起来,每一帧执行一次回调函数
}
danmuRender(){
let currentTime = video.currentTime
this.danmus.forEach(danmu=>{
//判断是否时间到啦
if(currentTime >= danmu.time){
//到啦就让弹幕渲染
danmu.render()
}
})
}
}
let Ddanmu = new Danmu(data)
video.addEventListener('play',function(){
Ddanmu.play = true
Ddanmu.render()
})
video.addEventListener('pause',function(){
Ddanmu.play = false
})
video.addEventListener('seeked',function(){
Ddanmu.reset()
})
/* let name = $('#text')
let submit = $('#submit')
let range = $('range')
let color = $("color") */
let socket = new WebSocket("ws://localhost:3000")
socket.onopen=function(){
socket.onmessage = function(e){
let message = e.data
message = JSON.parse(message)
if(message.type == 'ADD'){
Ddanmu.add(message.data)
}
}
}
submit.addEventListener('click',function(e){
let value = name.value
let fontSize = range.value
let color = colorE.value
let time = video.currentTime
let speed = 2
let obj = {value,fontSize,color,time}
socket.send(JSON.stringify(obj))
//Ddanmu.add(obj)
})
|
Java
|
UTF-8
| 911 | 2.515625 | 3 |
[] |
no_license
|
package qilaihai.dao;
import java.util.Date;
import java.util.List;
import qilaihai.domain.User;
import qilaihai.domain.Weibo;
public interface WeiboDao extends BaseDao<Weibo> {
/**
* 查找某一用户(或所有用户)在某一间隔内的所有Weibo
* @param poster
* 发出这些微博的用户,必须包含id属性。如果为null,则查找所有用户发出的微博
* @param begin
* 发出这些微博的开始时间,可以为null
* @param end
* 发出这些微博的结束时间,可以为null
* @param isDescending
* 是否按照按照时间倒序排序,true为时间倒叙排列,false为时间正序排列
* @return
* user在[begin, end]之间发出的所有微博,按照isDescending中指定顺序排序。
* 不会为null
*/
List<Weibo> getByTimeInterval(User poster, Date begin, Date end, boolean isDescending);
Weibo get(Integer id);
}
|
Python
|
UTF-8
| 1,953 | 3.078125 | 3 |
[] |
no_license
|
import unittest
from .. import color_scale
class TestColor64(unittest.TestCase):
def ints(self, x, y):
return list(map(int, color_scale.color64(x,y)))
def test_black(self):
self.assertEqual([0, 0, 0], self.ints(0,0))
def test_white(self):
self.assertEqual([255, 255, 255], self.ints(7, 7))
class TestBasicInterps(unittest.TestCase):
minimum = 0
maximum = 1
def setUp(self):
m = self.minimum
M = self.maximum
self.ci = color_scale.ColorInterpolator(minvalue=m, maxvalue=M)
def test_min(self):
c = self.ci.interpolate_color(self.minimum)
self.assertEqual(c, "#000000")
def test_max(self):
c = self.ci.interpolate_color(self.maximum)
self.assertEqual(c, "#ff0000")
def test_middle(self):
c = self.ci.interpolate_color((self.minimum + self.maximum) * 0.5)
self.assertEqual(c, "#7f0000")
class testShift(TestBasicInterps):
minimum = -120.0
maximum = 35.0
class TestBreakPoint(unittest.TestCase):
def setUp(self):
ci = self.ci = color_scale.ColorInterpolator()
ci.add_color(0, color_scale.clr(100, 100, 100))
ci.add_color(1, color_scale.clr(100, 0, 100))
ci.add_color(0.5, color_scale.clr(0, 0, 0))
def test_min(self):
c = self.ci.interpolate_color(0)
self.assertEqual(c, "#646464")
def test_max(self):
c = self.ci.interpolate_color(1)
self.assertEqual(c, "#640064")
def test_middle(self):
c = self.ci.interpolate_color(0.5)
self.assertEqual(c, "#000000")
def test_quarter(self):
c = self.ci.interpolate_color(0.25)
self.assertEqual(c, "#323232")
class TestColor2Clr(unittest.TestCase):
def test_123456(self, hex="#123456"):
forward = color_scale.color2clr(hex)
backward = color_scale.color(forward)
self.assertEqual(hex, backward)
def test_456789(self, hex="#456789"):
return self.test_123456(hex)
|
Java
|
UTF-8
| 1,421 | 2.53125 | 3 |
[] |
no_license
|
package com.ecodeup.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.ecodeup.model.Formation;
import com.ecodeup.model.JPAUtil;
public class FormationDAO implements IFormationDAO{
EntityManager entity = JPAUtil.getEntityManagerFactory().createEntityManager();
@Override
public void sauvegarder(Formation formation) {
entity.getTransaction().begin();
entity.persist(formation);
entity.getTransaction().commit();
}
@Override
public void modifier(Formation formation) {
entity.getTransaction().begin();
entity.merge(formation);
entity.getTransaction().commit();
}
@Override
public Formation chercher(int code) {
Formation formation = new Formation();
formation = entity.find(Formation.class, code);
// JPAUtil.shutdown();
return formation;
}
@Override
public List<Formation> selectionner()
{
List<Formation> listeFormation = new ArrayList<>();
Query query = entity.createQuery("select o from Formation o");
listeFormation = query.getResultList();
return listeFormation;
}
@Override
public void supprimer(int code) {
Formation formation = new Formation();
formation = entity.find(Formation.class, code);
entity.getTransaction().begin();
entity.remove(formation);
entity.getTransaction().commit();
}
}
|
PHP
|
UTF-8
| 2,272 | 3.203125 | 3 |
[] |
no_license
|
<?php
// koneksi ke database
// (nama host database/hostname, username mysql, password, database)
$conn = mysqli_connect("localhost", "root", "", "phpdasar");
// ambil data dari tabel mahasiswa / query data mahasiswa
// (koneksi ke database=$conn diatas, querynya mau apa/ data mahasiswa)
$result = mysqli_query($conn, "SELECT * FROM mahasiswa");
// yg dibutuhkan bajunya bukan lemarinya/yg dibutuhkan isinya bukan dibawa wadahnya, jadi butuh satu step lagi
// ambil data (fetch) mahasiswa dari object result
// ada 4 cara :
// mysqli_fetch_row() >> mengembalikan array numerik
// mysqli_fetch_assoc() >> mengembalikan array assosiatif | lebih nyaman digunakan karena buat sendiri
// mysqli_fetch_array() >> mengembalikan dua"nya | lebih fleksibel | kekurangannya didalam array ada dua"nya atau double
// mysqli_fetch_object() >> nggak akan dipakai karena mengembalikan object karena tida punya key dan value | harus pakai cara object pakai panah.
// pengulangan agar diambil semua
// while( $mhs = mysqli_fetch_assoc($result) ) {
// var_dump($mhs);
// }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Halaman Admin</title>
</head>
<body>
<h1>Daftar Mahasiswa</h1>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>No.</th>
<th>Gambar</th>
<th>NIM</th>
<th>Nama</th>
<th>Email</th>
<th>Jurusan</th>
<th>Aksi</th>
</tr>
<?php $i = 1; ?>
<?php while( $row = mysqli_fetch_assoc($result) ) : ?>
<tr>
<td><?php echo $i; ?></td>
<td><img src="img/<?php echo $row["gambar"] ?>"></td>
<td><?php echo $row["nim"] ?></td>
<td><?php echo $row["nama"] ?></td>
<td><?php echo $row["email"] ?></td>
<td><?php echo $row["jurusan"] ?></td>
<td>
<a href="">ubah</a>
<a href="">hapus</a>
</td>
</tr>
<?php $i++; ?>
<?php endwhile; ?>
</table>
</body>
</html>
|
Python
|
UTF-8
| 3,004 | 2.625 | 3 |
[] |
no_license
|
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import RPi.GPIO as GPIO
import argparse
import imutils
import time
import dlib
import cv2
GPIO.setmode(GPIO.BCM)
for i in (23, 24, 25, 16, 20, 21):
GPIO.setup(i, GPIO.OUT)
def euclidean_dist(ptA, ptB):
return np.linalg.norm(ptA - ptB)
def eye_aspect_ratio(eye):
A = euclidean_dist(eye[1], eye[5])
B = euclidean_dist(eye[2], eye[4])
C = euclidean_dist(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--cascade", required=True,
help = "camino hacia donde reside la cascada de la cara")
ap.add_argument("-p", "--shape-predictor", required=True,
help="camino al predictor de hitos faciales")
ap.add_argument("-a", "--alarm", type=int, default=0,
help="boolean utilizado para indicar si TraffHat debería usarse")
args = vars(ap.parse_args())
if args["alarm"] > 0:
from gpiozero import TrafficHat
th = TrafficHat()
print("[INFO] usando la alarma TrafficHat...")
EYE_AR_THRESH = 0.3
EYE_AR_CONSEC_FRAMES = 16
COUNTER = 0
ALARM_ON = False
print("[INFO] carga predictor de hitos faciales...")
detector = cv2.CascadeClassifier(args["cascade"])
predictor = dlib.shape_predictor(args["shape_predictor"])
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
print("[INFO] Iniciando hilo de flujo de video...")
vs = VideoStream(src=0).start()
time.sleep(1.0)
while True:
frame = vs.read()
frame = imutils.resize(frame, width=450)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rects = detector.detectMultiScale(gray, scaleFactor=1.1,
minNeighbors=5, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
for (x, y, w, h) in rects:
rect = dlib.rectangle(int(x), int(y), int(x + w),
int(y + h))
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
ojoizquierdo = shape[lStart:lEnd]
ojoderecho = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(ojoizquierdo)
rightEAR = eye_aspect_ratio(ojoderecho)
ear = (leftEAR + rightEAR) / 2.0
leftEyeHull = cv2.convexHull(ojoizquierdo)
rightEyeHull = cv2.convexHull(ojoderecho)
cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)
cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)
if ear < EYE_AR_THRESH:
COUNTER += 1
if COUNTER >= EYE_AR_CONSEC_FRAMES:
if not ALARM_ON:
ALARM_ON = True
if args["alarm"] > 0:
th.buzzer.blink(0.1, 0.1, 10,
background=True)
GPIO.output(16,GPIO.HIGH)
cv2.putText(frame, "ALERTA DE SOMNOLENCIA!", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
else:
COUNTER = 0
ALARM_ON = False
GPIO.output(16,GPIO.LOW)
cv2.putText(frame, "EAR: {:.3f}".format(ear), (300, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cv2.destroyAllWindows()
vs.stop()
|
JavaScript
|
UTF-8
| 3,311 | 2.828125 | 3 |
[] |
no_license
|
/**
* PHP Email Form Validation - v3.1
* URL: https://bootstrapmade.com/php-email-form/
* Author: BootstrapMade.com
*/
(function () {
"use strict";
let forms = document.querySelectorAll('.php-email-form');
forms.forEach(function (e) {
e.addEventListener('submit', function (event) {
event.preventDefault();
let thisForm = this;
let action = thisForm.getAttribute('action');
let recaptcha = thisForm.getAttribute('data-recaptcha-site-key');
if (!action) {
displayError(thisForm, 'The form action property is not set!')
return;
}
thisForm.querySelector('.loading').classList.add('d-block');
thisForm.querySelector('.error-message').classList.remove('d-block');
thisForm.querySelector('.sent-message').classList.remove('d-block');
let formData = new FormData(thisForm);
if (recaptcha) {
if (typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
try {
grecaptcha.execute(recaptcha, { action: 'php_email_form_submit' })
.then(token => {
formData.set('recaptcha-response', token);
php_email_form_submit(thisForm, action, formData);
})
} catch (error) {
displayError(thisForm, error)
}
});
} else {
displayError(thisForm, 'The reCaptcha javascript API url is not loaded!')
}
} else {
php_email_form_submit(thisForm, action, formData);
}
});
});
function php_email_form_submit(thisForm, action, formData) {
fetch(action, {
method: 'POST',
body: formData,
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
.then(response => {
if (response.ok) {
return response.text()
} else {
throw new Error(`${response.status} ${response.statusText} ${response.url}`);
}
})
.then(data => {
thisForm.querySelector('.loading').classList.remove('d-block');
if (data.trim() == 'OK') {
thisForm.querySelector('.sent-message').classList.add('d-block');
thisForm.reset();
} else if (data.split(',')[0] == 'REDIRECT') {
thisForm.reset();
window.location.replace(data.split(',')[1]);
}
else if (isJson(data)) {
const array = JSON.parse(data);
//localStorage.setItem("prezzo", array.prezzo);
for(let key in array) {
localStorage.setItem(key, array[key]);
console.log(key + " " + array[key]);
}
window.location.replace("pagamento_prenotazione.php");
}
else {
throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action);
}
})
.catch((error) => {
displayError(thisForm, error);
});
}
function displayError(thisForm, error) {
thisForm.querySelector('.loading').classList.remove('d-block');
thisForm.querySelector('.error-message').innerHTML = error;
thisForm.querySelector('.error-message').classList.add('d-block');
}
function isJson(str) {
try {
JSON.parse(str);
} catch (error) {
return false;
}
return true;
}
})();
|
Java
|
UTF-8
| 1,814 | 2.4375 | 2 |
[] |
no_license
|
package com.qfedu.hr.service;
import com.qfedu.hr.pojo.User;
import java.sql.SQLException;
import java.util.List;
public interface UserService {
/**
* 通过用户名userName和password借助于 UeserDao操作数据库
* @param userName 用户名
* @param password 密码
* @return 在数据库中找到 User对象 找不到返回null
* @throws SQLException
*/
public User findUserByUserNameAndPassword(String userName, String password) throws SQLException;
/**
*通过User对象 借助于UserDao操作数据库
* @param user User类对象
* @return 操作成功返回影响数据库的行数,失败返回null
* @throws SQLException
*/
public int saveUser(User user) throws SQLException;
/**
* 展示所有信息 通过User对象集合 借助于UserDao操作数据库
* @return ListUser所有信息集合 包括User对象 失败返回null
* @throws SQLException
*/
public List<User> findAllUserList() throws SQLException;
/**
* 修改员工信息 借助于User对象, 借助于UserDao操作数据库
* @param user User类对象
* @return 操作成功返回影响数据库的行数,失败返回null
*/
public int updateUser(User user) throws SQLException;
/**
* 找到ID对应的信息
* @param userId User ID
* @return 操作成功返回影响数据库的行数,失败返回null
* @throws SQLException SQL异常
*/
public User findById(int userId) throws SQLException;
/**
* 删除ID对应的信息
* @param userId 用户传进来的ID
* @return 操作成功返回影响数据库的行数,失败返回null
* @throws SQLException SQL异常
*/
public int deleteUser(int userId) throws SQLException;
}
|
Java
|
UTF-8
| 1,573 | 2.109375 | 2 |
[] |
no_license
|
package com.qubuyer.business.register.model;
import com.qubuyer.bean.register.RegisterEntity;
import com.qubuyer.business.register.presenter.ISetPwdPresenter;
import com.qubuyer.constant.NetConstant;
import com.qubyer.okhttputil.callback.HttpCallback;
import com.qubyer.okhttputil.helper.HttpInvoker;
import com.qubyer.okhttputil.helper.ServerResponse;
import java.util.HashMap;
import java.util.Map;
public class SetPwdModel implements ISetPwdModel {
private ISetPwdPresenter mPresenter;
public SetPwdModel(ISetPwdPresenter loginPresenter) {
mPresenter = loginPresenter;
}
@Override
public void destroy() {
mPresenter = null;
}
@Override
public void setPwd(String token, String pushId, String password, String password2) {
Map<String, String> params = new HashMap<>();
params.put("token", token);
params.put("pushId", pushId);
params.put("password", password);
params.put("password2", password2);
HttpInvoker.createBuilder(NetConstant.WECHAT_OR_QQ_LOGIN_SET_PWD_POST)
.setParams(params)
.setMethodType(HttpInvoker.HTTP_REQUEST_METHOD_POST)
.setClz(RegisterEntity.class)
.build().sendAsyncHttpRequest(new HttpCallback() {
@Override
public void onHttpFinish(ServerResponse serverResponse, Map<String, String> requestParams, String requestUrl) {
if (null == mPresenter) return;
mPresenter.onSetPwd(serverResponse);
}
});
}
}
|
Python
|
UTF-8
| 1,750 | 2.703125 | 3 |
[] |
no_license
|
#! python3
#*--coding=utf8--*
import requests
import json
import re
import time
import openpyxl
def getVV(name, id):
url = 'http://cache.video.qiyi.com/jp/pc/' + id +'/'
headers_chrome = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}
res = requests.get(url, headers_chrome)
jsonRegex = re.compile(r'{.*}')
mo = jsonRegex.search(res.text)
# print(mo.group());
jsonData = json.loads(mo.group())
vv = jsonData.get(id, -1)
print(name + ':' + str(vv));
return str(vv)
def sleeptime(hour, min, sec):
return hour*3600 + min*60 + sec;
def main():
id = {
'严歌苓': '722633000',
'周平': '717466900',
'高博文': '685756100',
'包一峰': '681226900',
'姜鹏': '679046100',
'叶泳湘': '671149200',
'马薇薇': '656368000',
'郭培': '643499700'
}
wb = openpyxl.Workbook()
for k,v in id.items():
sheet = wb.create_sheet(k)
sheet.cell(row=1, column=1).value = '时间'
sheet.cell(row=1, column=2).value = '播放量'
currentTime = time.strftime('%Y-%m-%d%H%M', time.localtime(time.time()));
# 保存文件,根据当前时间
wbName = 'C:/Users/Chan/Desktop/temp/qiyi/log_' + currentTime + '.xlsx';
wb.save(wbName);
rows = 2; # 起始行
pauseTime = sleeptime(0, 30, 0); # 程序暂停时间
for i in range(500):
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())));
for k,v in id.items():
#print(k,v);
VV = getVV(k, v)
wb[k].cell(row=rows, column=1).value = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()));
wb[k].cell(row=rows, column=2).value = VV;
time.sleep(1)
rows += 1;
wb.save(wbName);
time.sleep(pauseTime);
if __name__ == '__main__':
main()
|
JavaScript
|
UTF-8
| 16,484 | 3.34375 | 3 |
[] |
no_license
|
var svgWidth = 960;
var svgHeight = 500;
var margin = {
top: 20,
right: 40,
bottom: 80,
left: 100
};
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
// Create an SVG wrapper, append an SVG group that will hold our chart,
// and shift the latter by left and top margins.
var svg = d3
.select("#scatter")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
// Append an SVG group
var chartGroup = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// Initial Params
var chosenXAxis = "poverty";
var chosenYAxis= "obesity"
// function used for updating x-scale var upon click on axis label
function xScale(data, chosenXAxis) {
// create scales
var xLinearScale = d3.scaleLinear()
.domain([d3.min(data, d => d[chosenXAxis]) * 0.8,
d3.max(data, d => d[chosenXAxis]) * 1.2
])
.range([0, width]);
return xLinearScale;
}
// function used for updating y-scale var upon click on axis label
function yScale(data, chosenYAxis) {
// create scales
var yLinearScale = d3.scaleLinear()
.domain([d3.min(data, d => d[chosenYAxis])*0.9, d3.max(data, d => d[chosenYAxis])*1.1])
.range([height, 0]);
return yLinearScale;
}
// function used for updating xAxis var upon click on axis label
function renderAxesX(newXScale, xAxis) {
var bottomAxis = d3.axisBottom(newXScale);
xAxis.transition()
.duration(1000)
.call(bottomAxis);
return xAxis;
}
// function used for updating yAxis var upon click on axis label
function renderAxesY(newYScale, yAxis) {
var leftAxis = d3.axisLeft(newYScale);
yAxis.transition()
.duration(1000)
.call(leftAxis);
return yAxis;
}
// function used for updating circles group with a transition to
// new circles
function renderCircles(circlesGroup, newXScale, chosenXAxis, newYScale, chosenYAxis) {
circlesGroup.transition()
.duration(1000)
.attr("cx", d => newXScale(d[chosenXAxis]))
.attr("cy", d => newYScale(d[chosenYAxis]));
return circlesGroup;
}
function renderCirclesText(circlesText, newXScale, chosenXAxis, newYScale, chosenYAxis) {
circlesText.transition()
.duration(1000)
.attr("x", d => newXScale(d[chosenXAxis]))
.attr("y", d => newYScale(d[chosenYAxis]));
return circlesText;
}
// function used for updating circles group with new tooltip
function updateToolTip(chosenXAxis, chosenYAxis, circlesGroup) {
if (chosenXAxis === "poverty") {
var labelX = "Poverty: ";
}
else if (chosenXAxis==="age"){
var labelX = "Age: ";
}
else if (chosenXAxis==="income"){
var labelX="Household Income: "
}
if (chosenYAxis==="obesity"){
var labelY="Obesity: "
}
else if (chosenYAxis==="smokes"){
var labelY="Smokes: "
}
else if (chosenYAxis==="healthcare"){
var labelY="Healthcare: "
}
var toolTip = d3.tip()
.attr("class", "d3-tip")
.offset([0, 0])
.html(function(d) {
return (`${d.state}<br>${labelX} ${d[chosenXAxis]}<br>${labelY} ${d[chosenYAxis]}`);
});
circlesGroup.call(toolTip);
circlesGroup.on("mouseover", function(data) {
toolTip.show(data, this);
})
// onmouseout event
.on("mouseout", function(data, index) {
toolTip.hide(data,this);
});
return circlesGroup;
}
// Retrieve data from the CSV file and execute everything below
d3.csv("assets/data/data.csv", function(err, Data) {
if (err) throw err;
// parse data
Data.forEach(function(data) {
data.age = +data.age;
data.healthcare=+data.healthcare;
data.income=+data.income;
data.obesity=+data.obesity;
data.poverty=+data.poverty;
data.smokes=+data.smokes
});
// xLinearScale function above csv import
var xLinearScale = xScale(Data, chosenXAxis);
var yLinearScale= yScale(Data, chosenYAxis);
// Create initial axis functions
var bottomAxis = d3.axisBottom(xLinearScale);
var leftAxis = d3.axisLeft(yLinearScale);
// append x axis
var xAxis = chartGroup.append("g")
.classed("x-axis", true)
.attr("transform", `translate(0, ${height})`)
.call(bottomAxis);
// append y axis
var yAxis= chartGroup.append("g")
.call(leftAxis);
// append initial circles
var circlesGroup = chartGroup.selectAll("circle")
.data(Data)
.enter()
.append("circle")
.attr("cx", d => xLinearScale(d[chosenXAxis]))
.attr("cy", d => yLinearScale(d[chosenYAxis]))
.attr("r", 20)
//.attr("fill", "pink")
.attr("opacity", ".5");
// Create group for 3 x-axis labels
var labelsGroupX = chartGroup.append("g")
.attr("transform", `translate(${width / 2}, ${height + 20})`);
var PovertyLabel = labelsGroupX.append("text")
.attr("x", 0)
.attr("y", 20)
.attr("value", "poverty") // value to grab for event listener
.classed("active", true)
.text("In Poverty (%)");
var AgeLabel = labelsGroupX.append("text")
.attr("x", 0)
.attr("y", 40)
.attr("value", "age") // value to grab for event listener
.classed("inactive", true)
.text("Age (Median)");
var IncomeLabel = labelsGroupX.append("text")
.attr("x", 0)
.attr("y", 60)
.attr("value", "income") // value to grab for event listener
.classed("inactive", true)
.text("Household Income (Median)");
// Create group for 3 y-axis labels
var labelsGroupY = chartGroup.append("g")
.attr("transform", `translate(${margin.left}, ${(height / 2)})`);
var ObesityLabel = labelsGroupY.append("text")
.attr("transform", "rotate(-90)")
.attr("x", 0)
.attr("y", -170)
// .attr("dy", "1em")
.attr("value", "obesity") // value to grab for event listener
.classed("active", true)
.text("Obese (%)");
var SmokesLabel = labelsGroupY.append("text")
.attr("transform", "rotate(-90)")
.attr("x", 0)
.attr("y", -150)
// .attr("dy", "1em")
.attr("value", "smokes") // value to grab for event listener
.classed("inactive", true)
.text("Smokes (%)");
var HealthcareLabel = labelsGroupY.append("text")
.attr("transform", "rotate(-90)")
.attr("x", 0)
.attr("y", -130)
// .attr("dy", "1em")
.attr("value", "healthcare") // value to grab for event listener
.classed("inactive", true)
.text("Lacks Healthcare (%)");
// updateToolTip function above csv import
var circlesGroup = updateToolTip(chosenXAxis, chosenYAxis, circlesGroup);
// x axis labels event listener
labelsGroupX.selectAll("text")
.on("click", function() {
// get value of selection
var value = d3.select(this).attr("value");
if (value !== chosenXAxis) {
// replaces chosenXAxis with value
chosenXAxis = value;
// console.log(chosenXAxis)
// functions here found above csv import
// updates x scale for new data
xLinearScale = xScale(Data, chosenXAxis);
// updates x axis with transition
xAxis = renderAxesX(xLinearScale, xAxis);
// updates circles with new x values
circlesGroup = renderCircles(circlesGroup, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis);
//update circle text with new x values
circlesText = renderCirclesText(circlesText, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis)
// updates tooltips with new info
circlesGroup = updateToolTip(chosenXAxis, chosenYAxis, circlesGroup);
// changes classes to change bold text for x axis
if (chosenXAxis === "poverty") {
PovertyLabel
.classed("active", true)
.classed("inactive", false);
AgeLabel
.classed("active", false)
.classed("inactive", true);
IncomeLabel
.classed("active", false)
.classed("inactive", true);
}
else if (chosenXAxis === "age") {
PovertyLabel
.classed("active", false)
.classed("inactive", true);
AgeLabel
.classed("active", true)
.classed("inactive", false);
IncomeLabel
.classed("active", false)
.classed("inactive", true);
}
else if (chosenXAxis === "income") {
PovertyLabel
.classed("active", false)
.classed("inactive", true);
AgeLabel
.classed("active", false)
.classed("inactive", true);
IncomeLabel
.classed("active", true)
.classed("inactive", false);
}
}
});
// y axis labels event listener
labelsGroupY.selectAll("text")
.on("click", function() {
// get value of selection
var value = d3.select(this).attr("value");
if (value !== chosenYAxis) {
// replaces chosenYAxis with value
chosenYAxis = value;
// functions here found above csv import
// updates y scale for new data
yLinearScale = yScale(Data, chosenYAxis);
// updates y axis with transition
yAxis = renderAxesY(yLinearScale, yAxis);
// updates circles with new y values
circlesGroup = renderCircles(circlesGroup, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis);
//update circle text with new y values
circlesText = renderCirclesText(circlesText, xLinearScale, chosenXAxis, yLinearScale, chosenYAxis)
// updates tooltips with new info
circlesGroup = updateToolTip(chosenXAxis, chosenYAxis, circlesGroup);
// changes classes to change bold text for x axis
if (chosenYAxis === "obesity") {
ObesityLabel
.classed("active", true)
.classed("inactive", false);
SmokesLabel
.classed("active", false)
.classed("inactive", true);
HealthcareLabel
.classed("active", false)
.classed("inactive", true);
}
else if (chosenYAxis === "smokes") {
ObesityLabel
.classed("active", false)
.classed("inactive", true);
SmokesLabel
.classed("active", true)
.classed("inactive", false);
HealthcareLabel
.classed("active", false)
.classed("inactive", true);
}
else if (chosenYAxis === "healthcare") {
ObesityLabel
.classed("active", false)
.classed("inactive", true);
SmokesLabel
.classed("active", false)
.classed("inactive", true);
HealthcareLabel
.classed("active", true)
.classed("inactive", false);
}
}
});
});
//**************************************
// var width = parseInt(d3.select("#scatter").style("width"));
// var height = width - width / 4;
// var margin = 20;
// var labelArea = 110;
// var textPaddingBottom = 40;
// var textPaddingLeft = 40;
// var svg = d3
// .select("#scatter")
// .append("svg")
// .attr("width", width)
// .attr("height", height)
// .attr("class", "chart");
// var circleRadius;
// function crGet(){
// if (width <= 530){
// circleRadius = 5;
// }
// else{
// circleRadius = 10;
// }
// }
// crGet();
// //labels
// svg.append("g").attr("class", "xText");
// var xText = d3.select("xText");
// xText.attr(
// "transform",
// "translate(" +
// ((width - labelArea) / 2 + labelArea) +
// ", " +
// (height - margin - textPaddingBottom) +
// ")"
// );
// xText
// .append("text")
// .attr("y", -26)
// .attr("data-name", "poverty")
// .attr("data-axis", "x")
// .attr("class", "aText active x")
// .text("In Poverty (%)");
// var leftTextX = margin + textPaddingLeft;
// var leftTextY = (height + labelArea) / 2 - labelArea;
// svg.append("g").attr("class", "yText");
// var yText = d3.select("yText");
// yText.attr(
// "transform",
// "translate(" + leftTextX + ", " + leftTextY + ")rotate(-90)"
// );
// //lacks healthcare
// yText
// .append("text")
// .attr("y", 26)
// .attr("data-name", "healthcare")
// .attr("data-axis", "y")
// .attr("class", "aText active y")
// .text("Lacks Healthcare (%)");
// d3.csv("assets/data/data.csv").then(function(data) {
// visualize(data);
// })
// function visualize(theData){
// var curX = "poverty";
// var curY = "healthcare";
// var xMin;
// var xMax;
// var yMin;
// var yMax;
// function xMinMax(){
// xMin = d3.min(theData, function(d){
// return parseFloat(d[curX]) * 0.90;
// });
// xMax = d3.max(theData, function(d){
// return parseFloat(d[curX]) * 1.10;
// });
// return[xMin, xMax]
// }
// function yMinMax(){
// yMin = d3.min(theData, function(d){
// return parseFloat(d[curY]) * 0.90;
// });
// yMax = d3.max(theData, function(d){
// return parseFloat(d[curY]) * 1.10;
// });
// return[yMin, yMax]
// }
// var xScale = d3
// .scaleLinear()
// .domain(xMinMax())
// .range([margin + labelArea, width - margin]);
// var yScale = d3
// .scaleLinear()
// .domain(yMinMax())
// .range([height - margin - labelArea, margin]);
// var xAxis = d3.axisBottom(xScale);
// var yAxis = d3.axisLeft(yScale);
// var newVar = height - margin - labelArea
// svg
// .append("g")
// .call(xAxis)
// .attr("class", "xAxis")
// .attr("transform", "translate(0," + (newVar) + ")");
// svg
// .append("g")
// .call(yAxis)
// .attr("class", "yAxis")
// .attr("transform", "translate(" + (margin + labelArea) + ", 0)");
// // dots and labels
// var theCircles = svg.selectAll("g theCircles").data(theData).enter();
// theCircles
// .append("circle")
// .attr("cx", function(d){
// return xScale(d[curX]);
// })
// .attr("cy", function(d){
// return xScale(d[curY]);
// })
// .attr("r", circleRadius)
// .attr("class", function(d){
// return "stateCircle " + d.abbr;
// })
// }
//#########################################################################################
// Step 1: Set up our chart
//= ================================
// var svgWidth = 960;
// var svgHeight = 500;
// var margin = {
// top: 20,
// right: 40,
// bottom: 60,
// left: 50
// };
// var width = svgWidth - margin.left - margin.right;
// var height = svgHeight - margin.top - margin.bottom;
// // Step 2: Create an SVG wrapper,
// // append an SVG group that will hold our chart,
// // and shift the latter by left and top margins.
// // =================================
// var theSvg = d3
// .select("#scatter")
// .append("svg")
// .attr("width", svgWidth)
// .attr("height", svgHeight);
// var circleRadius;
// function crGet(){
// if (width <= 530){
// circleRadius = 5;
// }
// else{
// circleRadius = 10;
// }
// }
// crGet();
// var group = theSvg.append("g")
// .attr("transform", `translate(${margin.left}, ${margin.top})`)
// .classed("groupWrap", true);
// d3.csv("assets/data/data.csv").then(function(data) {
// var dataFormatted = data.map(function(data) {
// return{
// age: +data.age,
// income: +data.income
// }
// });
// var xMin = d3.min(dataFormatted, d => d.age);
// var xMax = d3.max(dataFormatted, d => d.age);
// console.log(xMin);
// console.log(xMax);
// var yMin = d3.min(dataFormatted, d => d.income);
// var yMax = d3.max(dataFormatted, d => d.income);
// console.log(yMin);
// console.log(yMax);
// var xScale = d3
// .scaleLinear()
// .domain([xMin, xMax])
// .range([margin.top + margin.bottom, width - margin.left - margin.right]);
// var yScale = d3
// .scaleLinear()
// .domain([yMin, yMax])
// // Height is inverses due to how d3 calc's y-axis placement
// .range([height - margin.top - margin.bottom, margin.left + margin.right]);
// var xAxis = d3.axisBottom(xScale);
// var yAxis = d3.axisLeft(yScale);
// xAxis.ticks(5)
// yAxis.ticks(5)
// d3.select(".groupWrap")
// .append("g")
// .call(xAxis)
// .attr("class", "xAxis")
// .attr("transform", "translate(0," + (svgHeight - margin.top - margin.bottom) + ")");
// d3.select(".groupWrap")
// .append("g")
// .call(yAxis)
// .attr("class", "yAxis")
// .attr("transform", "translate(" + (margin.top) + ", 0)");
// //console.log("!!!!!!!!!!!!!!!!!", svgHeight + margin.top)
// });
// d3.json("assets/js/.eslintrc.json").then(function(data) {
// console.log(data);
// });
//##############################
|
Java
|
UTF-8
| 1,628 | 2.671875 | 3 |
[] |
no_license
|
package com.revature.daos;
import java.util.List;
import org.hibernate.Session;
import com.revature.models.ReimbursementType;
import com.revature.utils.HibernateUtil;
public class TypeDAO implements TypeDAOInterface{
@Override
public ReimbursementType getType(int id) {
//open a new sesssion
Session ses = HibernateUtil.getSession();
//get the type code based on the id
ReimbursementType type = ses.get(ReimbursementType.class, id);
//close the session
//ses.close();
HibernateUtil.closeSession();
//return the type object
return type;
}
@Override
public List<ReimbursementType> getAllType() {
//open a new session
Session ses = HibernateUtil.getSession();
//get a list of types
List<ReimbursementType> typeList = ses.createQuery("from ReimbursementType").list();
//close the session
HibernateUtil.closeSession();
//return the list of types
return typeList;
}
@Override
public void insertType(ReimbursementType newType) {
//open a new session
Session ses = HibernateUtil.getSession();
//insert the new type into the table
ses.save(newType);
//close the session
HibernateUtil.closeSession();
}
@Override
public void updateType(ReimbursementType type) {
//open a new session
Session ses = HibernateUtil.getSession();
//update the type in the table
ses.merge(type);
//close the session
HibernateUtil.closeSession();
}
@Override
public void deleteType(ReimbursementType type) {
Session ses = HibernateUtil.getSession();
//update the type in the table
ses.delete(type);
//close the session
HibernateUtil.closeSession();
}
}
|
Java
|
GB18030
| 1,935 | 3.515625 | 4 |
[] |
no_license
|
package ߵԪ;
import java.util.Scanner;
/*
* 3.дģ˻ܡҪ£
ԡ˺šַС
ȡѯûʾϢ
ʾԭմմ
ȡʱССܾտʾٱXXX
*/
public class yinhang {
int number;
String name;
String address;
int shengyu;
int minshengyu;
public void yinhang (int number1,String name1,String address1,int shengyu1,int minshengyu1)
{ number = number1;
name = name1;
address = address1;
shengyu = shengyu1;
minshengyu = minshengyu1;
}
public void putmoney()//
{
System.out.println("Ĵ");
int number;
Scanner in = new Scanner(System.in);
number = in.nextInt();
if(number <100)
System.out.println("100Ԫ");
else {
shengyu = shengyu +number;
System.out.println("ɹ");
}
}
public void getmoney()
{ Scanner in = new Scanner(System.in);
System.out.println("Ҫȡmoney");
int number;
number = in.nextInt();
if(shengyu-number>minshengyu)
{
shengyu = shengyu - number;
System.out.println("ȡɹ");
}
else {
System.out.println("Ǯˣֻȡ"+(shengyu-minshengyu)+"ֻҪҪ"+minshengyu);
}
}
public void getinfo() {
System.out.println(number);
System.out.println(name);
System.out.println(address);
System.out.println(shengyu);
System.out.println(minshengyu);
}
}
|
C#
|
UTF-8
| 5,198 | 2.859375 | 3 |
[] |
no_license
|
namespace OneSheeldClasses
{
public class OneSheeldPrint : ShieldParent
{
ShieldIds shieldId = 0x00;
byte print_fn_id = 0x00;
byte write_fn_id = 0x00;
public OneSheeldPrint(ShieldIds shid, byte writefnid, byte printfnid)
: base(shid)
{
shieldId = shid;
print_fn_id = printfnid;
write_fn_id = writefnid;
}
//Write character
public void write(char data)
{
FunctionArgs args = new FunctionArgs();
FunctionArg arg = new FunctionArg(data);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId, 0, write_fn_id, 1, args);
}
//Print character
public void print(char data)
{
FunctionArgs args = new FunctionArgs();
FunctionArg arg = new FunctionArg(data);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId, 0, print_fn_id, 1, args);
}
//Write unsigned byte
public void write(sbyte data)
{
FunctionArgs args = new FunctionArgs();
FunctionArg arg = new FunctionArg(data);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId,0,write_fn_id,1,args);
}
//Print unsigned byte
public void print(sbyte data)
{
FunctionArgs args = new FunctionArgs();
FunctionArg arg = new FunctionArg(data);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId,0,print_fn_id,1,args);
}
//Print integers
public void print(int data, byte b = DEC)
{
FunctionArgs args = new FunctionArgs();
string datas = data.ToString();
FunctionArg arg = new FunctionArg(datas);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId,0,print_fn_id,1,args);
}
//Print unsigned integers
public void print(uint data, byte b = DEC)
{
FunctionArgs args = new FunctionArgs();
string datas = data.ToString();
FunctionArg arg = new FunctionArg(datas);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId,0,print_fn_id,1,args);
}
//Print long integers
public void print(long data, byte b = DEC)
{
FunctionArgs args = new FunctionArgs();
string datas = data.ToString();
FunctionArg arg = new FunctionArg(datas);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId,0,print_fn_id,1,args);
}
//Print unsigned long integers
public void print(ulong data , byte b = DEC)
{
FunctionArgs args = new FunctionArgs();
string datas = data.ToString();
FunctionArg arg = new FunctionArg(datas);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId,0,print_fn_id,1,args);
}
// Print byte Array
public void print (byte[] data)
{
FunctionArgs args = new FunctionArgs();
FunctionArg arg = new FunctionArg(data);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId, 0, print_fn_id, 1, args);
}
//Print string
public void print(string stringData)
{
FunctionArgs args = new FunctionArgs();
FunctionArg arg = new FunctionArg(stringData);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId, 0, print_fn_id, 1, args);
}
public void print(double data, int precision = 3)
{
FunctionArgs args = new FunctionArgs();
string datas = Round(data, precision);
FunctionArg arg = new FunctionArg(datas);
args.Add(arg);
OneSheeldMain.OneSheeld.sendShieldFrame(shieldId, 0, print_fn_id, 1, args);
}
public void print(float data, int precision = 3)
{
print((double) data, precision);
}
protected string Round(double data, int precision)
{
string datastr = data.ToString();
string[] parts = datastr.Split('.');
string newsecondpart = ""; // just in case we don't have a second part (i.e. no decimal point)
// if there are two parts, save what we have in the second part
if (parts.Length == 2)
{
newsecondpart = parts[1];
}
// if length of the second part is < precesion required add zeros
while (newsecondpart.Length < precision)
newsecondpart += "0";
// strip and extra digits from the second part
string precise = newsecondpart.Substring(0, precision);
// put together a new string that is the precise value
string newstr = parts[0] + "." + precise;
// return the value as a double
return newstr;
}
const byte DEC = 10;
}
}
|
Markdown
|
UTF-8
| 4,535 | 2.875 | 3 |
[] |
no_license
|
# Code-Maven Workshops in Israel
Lead by [Gabor Szabo](https://www.linkedin.com/in/szabgab/).

## Schedule of the public events that are usually free to participate in
* Check out the [Meetup page](https://www.meetup.com/code-mavens/) or see the [earlier public events](history)
## Available Workshops
* [How to develop software faster and have more stable releases?](how-to-develop-software-faster-and-have-more-stable-releases)
* [Getting started with Docker](getting-started-with-docker)
* [Getting Started with Google Cloud](getting-started-with-google-cloud)
* [Setting up Continuous Integration for GitHub projects](setting-up-continuous-integration-for-github-projects)
* [XP: Pair Programming Workshop](xp-pair-programming-workshop-1)
* [Serverless AWS Lambda](serverless-aws-lambda)
* [Continuous Integration with Jenkins](continuous-integration-with-jenkins)
* [Creating Jenkins pipeline without any coding](creating-jenkins-pipelines-without-any-coding)
* [Jenkins pipeline exclusively with Groovy code](jenkins-pipeline-with-groovy-code)
* [Git for beginners](git-for-beginners-part-1)
* [Git for beginners part 2](git-for-beginners-part-2)
* [Introduction to Ansible](introduction-to-ansible)
* [Linux as a virtual environment](linux-as-a-virtual-environment)
* [Mob programming](mob-programming)
* [Your First Open Source contribution](your-first-open-source-contribution)
* [Getting started with Golang](getting-started-with-golang)
* [Mocking in Python as a testing tool](mocking-in-python-as-a-testing-tool)
* [Fixtures and Test Doubles in Pytest (e.g. Mocking)](fixtures-and-test-doubles-in-python)
* [Python Pair Programming with TDD](python-pair-programming-with-tdd)
* [Python testing workshop](python-testing)
* [Python pair programming - iteration vs recursion](python-iteration-vs-recursion)
* [Getting started with Redis](getting-started-with-redis)
* [Opening the Linux Shell](opening-the-linux-shell)
* [Regular expressions for fun and profit](regexes-intro)
* [Git advanced commands](git-advanced-commands)
* [Getting Started with Digital Ocean](getting-started-with-digital-ocean)
* [Image manipulation with Python PIL - Pillow](image-manipulation-with-python-pil-pillow)
* [Infrastructure as Code with Terraform](terraform)
* [Creating web presence with GitHub pages](creating-web-presence-with-github-pages)
* [How Open source projects are developed and how do they maintain quality?](open-source-quality-assurance)
## Host a workshop
Would you like to [host](host) a Code-Maven workshop?
## About the Code-Maven Workshops
Code Maven Workshops are short, 3-4-hours meetings with a mix or presentations and hands-on exercises to learn tools, technologies, and processes used in the world of Development,
Testing, Operations, and DevOps. They can be provided in-house at your company as a morning or afternoon half-day session.
Ocassionally they are also run via the [Code-Mavens at Meetup](https://www.meetup.com/Code-Mavens/) group in which case they can usually be attended free of charge. Below you'll see the dates
and locations of the previous events.
## Courses
In addition to the 3-4-hours long workshops Gabor also provides full-length [training courses](https://hostlocal.com/) in these
subject. Check out the list of currently available courses and let me know if you are interested in either of those or
something in a related subject.
## Further Workshops
These are just ideas. They might change. They might get abandoned. You are more than welcome to comment on them
or suggest new ones via the [GitHub repository](https://github.com/szabgab/workshops/) of this page or in
a private e-mail to gabor at szabgab.com.
* Getting Started with AWS
* [ELK - Elasticsearch - Logstash - Kibana stack](elk)
* Testing (Unit, Integration, Acceptance)
* Logging and monitoring (StatsD, ElasticSearch)
* Configuration management (Ansible, Chef, Puppet)
* Virtualization (Vagrant, Docker, Kubernetes)
* Continuous Integration ( Travis-CI, Jenkins, CircleCI, Appveyor )
* Continuous Delivery
* Continuous Deployment
* Cloud infrastructure (Amazon AWS, Google Cloud Platform, Microsoft Azure)
* Microservices Architecture
* Serverless Architecture
* [GitHub Actions to generate complex static web sites](github-actions-to-generate-complex-static-web-sites)
* [GitHub REST AP and GraphQL API](github-rest-api-and-graphql-api)
Just to name a few.
Some of workshops were also lead by [Yonit Gruber-Hazani](https://www.linkedin.com/in/yonitgruber/)
|
Java
|
UTF-8
| 4,520 | 2.25 | 2 |
[] |
no_license
|
package com.somoplay.magicworld;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Disableable;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.somoplay.magicworld.Screens.MenuScreen;
import com.somoplay.magicworld.Screens.PlayScreen;
import javax.xml.soap.Text;
public class Stats implements Disposable{
public Stage stage;
private Viewport viewport;
static Label scoreLabel;
Label timeLabel, timeTextLabel, scoreTextLabel;
Drawable menuImage;
TextButton playAgain;
PlayScreen screen;
// This is the post game menu that pops up when you complete a level or die
public Stats (SpriteBatch batch, final PlayScreen screen){
Skin skin = new Skin();
skin.add("menu",new Texture("images/scoreui.png"));
skin.add("button_up", new Texture("images/b_4.png"));
skin.add("button_down", new Texture("images/b_5.png"));
menuImage = skin.getDrawable("menu");
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/PoetsenOne-Regular.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.size = 24; // font size
BitmapFont font = generator.generateFont(parameter);
generator.dispose(); // avoid memory leaks, important
TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle(skin.getDrawable("button_up"),
skin.getDrawable("button_down"), skin.getDrawable("button_up"), font);
playAgain = new TextButton("Play Again", buttonStyle);
playAgain.addListener(new ClickListener(){
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
screen.nextLevel();
}
});
viewport = new FitViewport(MagicWorld.screenWidth, MagicWorld.screenHeight, new OrthographicCamera());
stage = new Stage(viewport, batch);
Table table = new Table();
Table globalTable = new Table();
table.top();
table.setFillParent(true);
globalTable.bottom().left();
globalTable.setFillParent(true);
scoreLabel = new Label(String.format("%06d",00), new Label.LabelStyle(font, Color.BLUE));
timeLabel = new Label(String.format("%03d", 00), new Label.LabelStyle(font, Color.BLUE));
timeTextLabel = new Label(String.format("Time", 0), new Label.LabelStyle(font, Color.BLUE));
scoreTextLabel = new Label(String.format("Score", 0), new Label.LabelStyle(font, Color.BLUE));
table.padTop(64);
table.add(timeTextLabel).padRight(50);
table.add(scoreTextLabel).padRight(112);
table.row();
table.add(timeLabel).padRight(50);
table.add(scoreLabel).padRight(112);
table.row();
table.addActor(playAgain);
table.add(playAgain).size(200,80).padTop(180).padLeft(196);
globalTable.setBackground(menuImage);
globalTable.addActor(table);
//table.setDebug(true);
stage.addActor(globalTable);
}
@Override
public void dispose() {
stage.dispose();
}
public void setScoreLabel(int score){
scoreLabel.setText(String.format("%06d",score));
}
public void setTimeLabel(float time){
timeLabel.setText(String.format("%.2f",time));
}
}
|
Markdown
|
UTF-8
| 4,663 | 3.078125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Log Package
The log package provides a common interface that can be used in applications and
libraries along with reference implementation wrappers for logrus, zap, the Go
standard library package, and for a CLI.
[](https://goreportcard.com/report/github.com/Masterminds/log-go)
[](https://github.com/Masterminds/log-go/actions)
[](https://pkg.go.dev/github.com/Masterminds/log-go)
## The Problem
The problem is that there are many logging packages where each has its own
interface. This makes it difficult to mix and match libraries and code that
depend on different interfaces. It also makes it difficult to change logging
libraries if the one you are using becomes deprecated or you would like to
switch to a different one (e.g., you want to tie into a logging service).
The log package aims to provide a solution to this problem.
## Use Cases
This library was born out of a specific problem that also presents itself as a
solution for a second use case.
### Use Case 1: Console and Logging
I was working on an application that needs to write output to the console
(sometimes with color) and to logrus. logrus is in the maintenance stage of
development (it's even recommending other logging packages) so I can see it
someday being replaced in the system I'll have to deal with.
I needed a solution that let me write messages that in some situations are sent
to console output and in other situations are sent to logs. In the first
situation it is as part of a CLI application. In the second case the code is
imported as a library in a service.
The solution is to use an interface with varying implementations.
### Use Case 2: Logging In Go Is Diverse Which Makes It Hard
Rust, PHP, and many other languages have APIs for logging that different
implementations can implement. This makes logging pluggable and improves library
interoperability.
This is a secondary use case and benefit from having an interface.
## Usage
The usage documentation is broken down into 3 types of usage depending on your
situation.
### Library / Package Authors
If you are a library or package author there are two ways you can use this log
package.
First, you can import the package and use the package level logging options. For
example:
```go
import(
"github.com/Masterminds/log-go"
)
log.Info("Send Some Info")
```
You can use this for logging within your package.
Second, if you want to pass a logger around your package you can use the
interface provided by this package. For example:
```go
import "github.com/Masterminds/log-go"
func NewConstructorExample(logger log.Logger) {
return &Example{
logger: logger,
}
}
func (e *Example) Foo() {
e.logger.Info("Send Some Info")
}
```
In your packages testing you can check log messages if you need to see that they
are working and contain what you are looking for. A simple example of doing this
is in the `_examples` directory.
### Application Developers
If you are developing an application that will be writing logs you will want to
setup and configure logging the way you want. This is where this interface
based package empowers you. You can pick your logging implementation or write
your own.
For example, if you want to use a standard logrus logger you can setup logging
like so:
```go
import(
"github.com/Masterminds/log-go"
"github.com/Masterminds/log-go/impl/logrus"
)
log.Current = logrus.NewStandard()
```
In this example a standard logrus logger is created, wrapped in a struct
instance that conforms to the interface, and is set as the global logger to use.
The `impl` directory has several reference implementations and they have
configurable setups.
Once you setup the global logger the way you want all the packages will use this
same logger.
### Logger Developers
There are many loggers and many ways to record logs. They can be written to a
file, sent to stdout/stderr, sent to a logging service, and more. Each of these
is possible with this package.
If you have logger you want to use you can write one that conforms to the
`Logger` interface found in `log.go`. That logger can then be configured as
documented in the previous section.
The `impl` directory has reference implementations you can look at for further
examples.
## Log Levels
The following log levels are currently implemented across the interface and all
the reference implementations.
- Fatal
- Panic
- Error
- Warn
- Info
- Debug
- Trace
|
Java
|
UTF-8
| 1,714 | 2.9375 | 3 |
[] |
no_license
|
package ui.gui;
import java.awt.*;
import static java.awt.GridBagConstraints.*;
public class CustomBagConstraints {
//EFFECTS: returns a GridBagConstraints with default values except for given gridx and gridy
public static GridBagConstraints customConstraint(int gridx, int gridy) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = gridx;
constraints.gridy = gridy;
return constraints;
}
//EFFECTS: returns a GridBagConstraints with default values except for given gridx, gridy, gridwidth and gridheight
public static GridBagConstraints customConstraint(int gridx, int gridy, int gridwidth, int gridheight) {
GridBagConstraints constraints = customConstraint(gridx,gridy);
constraints.gridwidth = gridwidth;
constraints.gridheight = gridheight;
return constraints;
}
//EFFECTS: returns a GridBagConstraints with default values except for given gridx, gridy, gridwidth and gridheight
public static GridBagConstraints customConstraint(int gridx, int gridy, double weightx, double weighty) {
GridBagConstraints constraints = customConstraint(gridx,gridy);
constraints.weightx = weightx;
constraints.weighty = weighty;
return constraints;
}
//EFFECTS: returns a GridBagConstraints with default values except for given gridx, gridy and inset
public static GridBagConstraints customConstraint(int gridx, int gridy, Insets insets) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = gridx;
constraints.gridy = gridy;
constraints.insets = insets;
return constraints;
}
}
|
JavaScript
|
UTF-8
| 620 | 2.734375 | 3 |
[] |
no_license
|
const term = require( 'terminal-kit' ).terminal
module.exports = function(string="foo", type='none', new_line = true){
if(new_line){
string += "\r\n"
}
switch(type){
case "msg":
term(string)
break
case "info":
term.green(string)
break
case "warn":
term.yellow.bold(string)
break
case "error":
term.red.bold(string)
break
case "question":
term.brightBlue(string)
break
default:
term.bold(string)
break
}
}
|
C++
|
UTF-8
| 950 | 3.53125 | 4 |
[] |
no_license
|
//给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
//
// 示例:
//
// 输入: [0,1,0,3,12]
//输出: [1,3,12,0,0]
//
// 说明:
//
//
// 必须在原数组上操作,不能拷贝额外的数组。
// 尽量减少操作次数。
//
// Related Topics 数组 双指针
#include <iostream>
#include <vector>
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
void moveZeroes(vector<int>& nums) {
auto nums_len = nums.size();
for (auto i= 0, j = 0; j < nums_len; j++) {
if (nums[j] != 0) {
if (j != i) {
nums[i] = nums[j];
nums[j] = 0;
}
i++;
}
}
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
cout <<"hello"<<endl;
}
|
Java
|
UTF-8
| 1,619 | 2.140625 | 2 |
[] |
no_license
|
package hochschule.de.bachelorthesis.view.onboarding;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.viewpager.widget.ViewPager;
import java.util.Objects;
import hochschule.de.bachelorthesis.R;
import hochschule.de.bachelorthesis.databinding.FragmentOnboardingThreeBinding;
/**
* @author Maik Thielen
* <p>
* View class for the third onboarding fragment.
*/
public class OnboardingThreeFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
FragmentOnboardingThreeBinding binding = DataBindingUtil
.inflate(inflater, R.layout.fragment_onboarding_three, container, false);
final ViewPager viewpager = Objects.requireNonNull(getActivity()).findViewById(R.id.onboarding_view_pager);
// Back button
binding.onboardingBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
viewpager.setCurrentItem(1);
}
});
// Next button
binding.onboardingNext.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_onboardingHostFragment_to_homeFragment));
return binding.getRoot();
}
}
|
JavaScript
|
UTF-8
| 775 | 3.4375 | 3 |
[] |
no_license
|
/*
Promise.all的规则:
传入的所有promise都是fulfilled,则返回由他们的值组成的,状态为fulfilled的新promise
只要有一个promise是rejected,则返回rejected状态的新promise,且它的值是第一个rejected的promise值
只要有一个promise是pending,则返回一个pending状态的新promise
*/
Promise.all=function (promiseArr) {
let index=0;
let result=[];
return new Promise((resolve,reject)=>{
promiseArr.forEach((p,i)=>{
Promise.resolve(p).then(val=>{
index++;
result[i]=val;
if (index===promiseArr.length){
resolve(result);
}
},err=>{
reject(err);
})
})
})
};
|
Java
|
UTF-8
| 1,082 | 3.109375 | 3 |
[] |
no_license
|
package leetcode_test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TallCompare
{
public List<ArrayList<Integer>> reconstructQueue(int[][] people) {
Arrays.sort(people, (a,b)->((b[0]-a[0])));
List<ArrayList<Integer>> array=new ArrayList<>();
ArrayList<Integer> first=new ArrayList<>();
first.add(people[0][0]);
first.add(people[0][1]);
array.add(first);
for(int i=1;i<people.length;i++){
ArrayList<Integer> every=new ArrayList<>();
every.add(people[i][0]);
every.add(people[i][1]);
if(people[i][1]>=array.size()){
array.add(every);
}else{
array.add(people[i][1], every);
}
System.out.println(array);
}
System.out.println(array);
return array;
}
public static void main(String[] args)
{
TallCompare test=new TallCompare();
int[][] people={{7,0},{4,4},{7,1},{5,0},{6,1},{5,2}};
test.reconstructQueue(people);
}
}
|
Java
|
UTF-8
| 647 | 1.78125 | 2 |
[] |
no_license
|
package com.xiaodou.server.mapi.request;
import com.xiaodou.summer.validator.annotion.NotEmpty;
/**
* @name @see com.xiaodou.course.web.request.order.PayOrderRequest.java
* @CopyRright (c) 2016 by Corp.XiaodouTech
*
* @author <a href="mailto:[email protected]">zhaodan</a>
* @date 2016年6月2日
* @description 支付订单请求
* @version 1.0
*/
public class PayOrderRequest extends MapiBaseRequest {
/** gorderId 支付订单ID */
@NotEmpty
private String gorderId;
public String getGorderId() {
return gorderId;
}
public void setGorderId(String gorderId) {
this.gorderId = gorderId;
}
}
|
Go
|
UTF-8
| 5,010 | 2.703125 | 3 |
[
"Apache-2.0"
] |
permissive
|
package fastpaxos
import (
"sync"
"time"
"github.com/op/go-logging"
"domino/common"
"domino/fastpaxos/rpc"
)
var logger = logging.MustGetLogger("fastpaxos")
const (
OP_STOP = "s"
OP_WRITE = "w"
OP_READ = "r"
)
type ClientProposal struct {
Op *rpc.Operation
Idx *common.Future
Delay time.Duration
Timestamp int64
ClientId string
}
type LeaderProposal struct {
Idx *LogIdx
Op *rpc.Operation
Done *common.Future
}
type LeaderCommit struct {
Idx *LogIdx
Op *rpc.Operation
Done *common.Future
}
type FastPaxos struct {
// Fast path manager
fpManager *FastPathManager
// The channel for a replica to execute a command including:
// (1) accpets a client's proposal via the fast path
// (2) accpets a leader's proposal via the slow path
// (3) commits a leader's proposal in the log
cmdCh chan interface{}
// The channel fo a replica to apply (execute) a committed log entry on the state machine
execCh chan *rpc.Operation
// Log manager
lm LogManager
isRun bool
runLock sync.RWMutex
// Scheduling
scheduler Scheduler
}
func NewFastPaxos(
replicaNum, majority, fastQuorum int,
voteChBufferSize int,
cmdChBufferSize int,
execChBufferSize int,
logManager LogManager,
scheduleType string,
processWindow time.Duration, // for timestamp scheduler
) *FastPaxos {
fp := &FastPaxos{
fpManager: NewFastPathManager(replicaNum, majority, fastQuorum, voteChBufferSize),
cmdCh: make(chan interface{}, cmdChBufferSize),
execCh: make(chan *rpc.Operation, execChBufferSize),
lm: logManager,
isRun: false,
}
// Scheduler
absScheduler := NewAbstractScheduler(fp.GetCmdCh())
switch scheduleType {
case common.NoScheduler:
fp.scheduler = &NoScheduler{
absScheduler,
}
case common.DelayScheduler:
fp.scheduler = &DelayScheduler{
absScheduler,
}
case common.TimestampScheduler:
fp.scheduler = NewTimestampScheduler(
absScheduler,
)
case common.DeterministicScheduler:
logger.Fatalf("Scheduler %s not implemented yet", scheduleType)
default:
logger.Fatalf("Unknow scheduler type %s", scheduleType)
}
return fp
}
func (fp *FastPaxos) Schedule(p *ClientProposal) {
fp.scheduler.Schedule(p)
}
func (fp *FastPaxos) GetCmdCh() chan<- interface{} {
return fp.cmdCh
}
func (fp *FastPaxos) RunCmd(cmd interface{}) {
fp.cmdCh <- cmd
}
func (fp *FastPaxos) GetExecCh() <-chan *rpc.Operation {
return fp.execCh
}
// Starts fast paxos
// The leader should start the fast-path manager
// Followers that are only acceptors do not need to start the fast-path manager
func (fp *FastPaxos) Run(isRunFastPathManager bool) {
fp.runLock.Lock()
defer fp.runLock.Unlock()
if fp.isRun {
return
}
fp.isRun = true
// Starts log manager
fp.lm.Run(fp.execCh)
// Starts command channel
go fp.startCmdCh()
// Starts scheduler
go fp.scheduler.Run()
// Learners starts the fast-path manager
if isRunFastPathManager {
fp.fpManager.Run()
}
}
// Single thread
func (fp *FastPaxos) startCmdCh() {
for proposal := range fp.cmdCh {
switch proposal.(type) {
case *ClientProposal:
fp.acceptClientProposal(proposal.(*ClientProposal))
case *LeaderProposal:
fp.acceptLeaderProposal(proposal.(*LeaderProposal))
case *LeaderCommit:
fp.commitLeaderProposal(proposal.(*LeaderCommit))
default:
logger.Fatalf("Unknown command type: %v", proposal)
}
}
}
func (fp *FastPaxos) acceptClientProposal(proposal *ClientProposal) {
//TODO Ignores an operation that is committed via the slow path before the
//client's proposal arrives.
entry := &Entry{proposal.Op, ENTRY_FAST_ACCEPTED}
idx, err := fp.lm.FastPathAccept(entry)
if err != nil {
logger.Errorf("Fast-path fails to accept opId = (%s), error: %v", err)
}
proposal.Idx.SetValue(idx)
logger.Debugf("Fast-path accepts opId = (%s) at idx (%s)", entry.op.Id, idx)
}
func (fp *FastPaxos) acceptLeaderProposal(proposal *LeaderProposal) {
defer proposal.Done.SetValue(true)
logger.Debugf("Slow-path tries to accept opId = (%s) at idx = (%s)",
proposal.Op.Id, proposal.Idx)
entry := &Entry{proposal.Op, ENTRY_SLOW_ACCEPTED}
err := fp.lm.SlowPathAccept(proposal.Idx, entry)
if err != nil {
logger.Errorf("Slow-path fails to accept opId = (%s) at idx = (%s), error: %v", err)
}
}
func (fp *FastPaxos) commitLeaderProposal(commit *LeaderCommit) {
defer commit.Done.SetValue(true)
logger.Debugf("Leader commits opId = (%s) at idx = (%s)", commit.Op.Id, commit.Idx)
entry := &Entry{op: commit.Op}
err := fp.lm.Commit(commit.Idx, entry)
if err != nil {
logger.Errorf("Leader fails to commit opId = (%s) at idx = (%s)", commit.Op.Id, commit.Idx)
}
}
/////////////////////////////////////////////////
// Wrapper functions for FastPathManager
func (fp *FastPaxos) LeaderVote(vote *Vote) (*common.Future, *common.Future) {
return fp.fpManager.LeaderVote(vote)
}
func (fp *FastPaxos) Vote(vote *Vote) {
fp.fpManager.Vote(vote)
}
func (fp *FastPaxos) CleanRetHandle(opId string) {
fp.fpManager.CleanRetHandle(opId)
}
|
Python
|
UTF-8
| 468 | 2.734375 | 3 |
[] |
no_license
|
"""
Device constants are used during instantiation of interface classes (such as
:class:`alphasign.interfaces.local.USB`) to describe particular sign devices.
The following constants are defined in this module:
* :const:`USB_BETABRITE_PRISM` = (0x8765, 0x1234)
--------
Examples
--------
Connect to a BetaBrite Prism sign using USB::
sign = alphasign.USB(alphasign.devices.USB_BETABRITE_PRISM)
sign.connect()
...
"""
USB_BETABRITE_PRISM = (0x8765, 0x1234)
|
TypeScript
|
UTF-8
| 902 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
import Sequence from "./Sequence";
export class Reduce {
/**
* Reduces the whole sequence to a single value by invoking `operation` with each element
* from left to right. For every invocation of the operation `acc` is the result of the last
* invocation. For the first invocation of the operation `acc` is the first element of the
* sequence.
*
* @param {(acc: S, value: T) => S} operation
* @returns {S}
*/
reduce<S, T extends S>(this: Sequence<T>, operation: (acc: S, value: T) => S): S {
const first = this.iterator.next();
if (first.done) {
throw new Error("Cannot reduce empty sequence");
}
let result: S = first.value;
for (let item = this.iterator.next(); !item.done; item = this.iterator.next()) {
result = operation(result, item.value);
}
return result;
}
}
|
Python
|
UTF-8
| 2,681 | 2.75 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
import socket
import argparse
import argparse_parent_base
from multiprocessing import Pool
import time
from printer import Printer
from misc import read_host_from_file, valid_port
class Scanner():
def __init__(self):
self.timeout = 1
socket.setdefaulttimeout(self.timeout)
self.open_ports = []
# Ports from 1-1024 (default,if not specified)
self.ports = range(1, 1025)
self.ips = []
self.number_of_process = 10
def scan(self, args):
host, port = args
try:
# Create a TCP socket and try to connect
# AF_INET for ipv4,AF_INET6 for ipv6
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.close()
return host, port, True
except (socket.timeout, socket.error):
return host, port, False
def start(self):
pool = Pool(processes=self.number_of_process)
for ip in self.ips:
for host, port, status in pool.imap_unordered(self.scan, [(ip, port) for port in self.ports]):
if status:
self.open_ports.append(
"ip:{0}->port:{1} is open".format(host, port))
def banner():
banner_txt = """
_ __ ___ _ __| |_ ___ ___ __ _ _ __ _ __ ___ _ __
| '_ \ / _ \| '__| __/ __|/ __/ _` | '_ \| '_ \ / _ \ '__|
| |_) | (_) | | | |_\__ \ (_| (_| | | | | | | | __/ |
| .__/ \___/|_| \__|___/\___\__,_|_| |_|_| |_|\___|_|
|_|
"A simple port scanner use tcp scan",Check status of given port
Author:Samray <[email protected]>
More Info:python3 tcp_scan.py -h
"""
print(banner_txt)
def main():
parser = argparse.ArgumentParser(
parents=[argparse_parent_base.parser],
description=banner(),
add_help=True)
args = parser.parse_args()
scanner = Scanner()
printer = Printer()
if args.timeout:
scanner.timeout = args.timeout
if args.number_of_process:
scanner.number_of_process = args.number_of_process
if args.ports:
ports = map(int, args.ports)
scanner.ports = filter(valid_port, ports)
if args.host_file:
scanner.ips = read_host_from_file(args.host_file)
scanner.ips += args.host
scanner.start()
if args.output_file:
printer.filepath = args.output_file
printer.list_to_file(scanner.open_ports)
else:
printer.list_to_console(scanner.open_ports)
if __name__ == "__main__":
start_time = time.time()
main()
print("---%s seconds ---" % (time.time() - start_time))
|
C
|
UTF-8
| 254 | 3.171875 | 3 |
[
"CC0-1.0"
] |
permissive
|
#include <stdio.h>
#include "part.h"
void print_part(part p) {
printf("Part - name: %10s, number: %7d, cost: $%7.2lf, count%7d\n", p.name, p.number, p.cost, p.count);
}
extern part global_part;
void print_global_part() {
print_part(global_part);
}
|
Python
|
UTF-8
| 1,111 | 4.5625 | 5 |
[] |
no_license
|
# Demonstrates simple sequence protocol implementation by Fibonacci Sequence
# NOTE: Don't use it on production, for demo purpose only
from collections.abc import Sequence
class Fibonacci(Sequence):
def __init__(self, nmax):
self.length = nmax
self._items = []
self._calculate()
def __len__(self):
return len(self._items)
def __getitem__(self, index):
return self._items[index]
def _calculate(self, a=0, b=1):
if self.length == len(self):
return
self._items.append(a)
self._calculate(b, a + b)
fibseq = Fibonacci(10)
print(f'The 6th Fibonacci number is: {fibseq[5]}')
print('Iterating through Fibonacci sequence...')
for index, number in enumerate(fibseq, 1):
print(f'{index} is {number}')
# The following implementation we get for free
print(f'Check if 27 in Fibonacci sequence: {27 in fibseq}')
print(f'Check if 13 in Fibonacci sequence: {13 in fibseq}')
print('Iterating through reversed Fibonacci sequence...')
for index, number in enumerate(reversed(fibseq), 1):
print(f'{index} is {number}')
|
Java
|
UTF-8
| 1,886 | 2.296875 | 2 |
[] |
no_license
|
package br.com.project.domain.entity;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.ReflectionUtils;
class BaseEntityTest {
@Test
void hasMethodGetCreatedDate() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("getCreatedDate")));
}
@Test
void hasMethodSetCreatedDate() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("setCreatedDate")));
}
@Test
void hasMethodGetUpdatedDate() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("getUpdatedDate")));
}
@Test
void hasMethodSetUpdatedDate() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("setUpdatedDate")));
}
@Test
void hasMethodGetDeletedDate() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("getDeletedDate")));
}
@Test
void hasMethodSetDeletedDate() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("setDeletedDate")));
}
@Test
void hasMethodEquals() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("equals")));
}
@Test
void hasMethodHashCode() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("hashCode")));
}
@Test
void hasMethodToString() {
assertTrue(
ReflectionUtils.isMethodPresent(
BaseEntity.class, method -> method.getName().equals("toString")));
}
}
|
Ruby
|
UTF-8
| 311 | 3.828125 | 4 |
[] |
no_license
|
=begin
Crea un programa llamado solo_impares.rb que dado n muestre en pantalla los primeros n
números impares.
Tip: el número siguiente a un par siempre es un impar :)
Uso:
ruby solo_impares.rb 5
1 3 5 7 9
=end
#Programa creado.
n=ARGV[0].to_i
n.times do |i|
i +=1
print "#{2*i-1} "
end
puts
|
C#
|
UTF-8
| 2,585 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
namespace Village.Games.Api
{
public class ConnectionStrings
{
public string AzureStorageConnectionString { get; set; }
}
public class QueueResolver : IQueueResolver
{
private readonly CloudQueueClient _queueClient;
public QueueResolver(IOptions<ConnectionStrings> settings)
{
var storageAccount = CloudStorageAccount.Parse(settings.Value.AzureStorageConnectionString);
_queueClient = storageAccount.CreateCloudQueueClient();
}
public CloudQueue GetQueue(string queueName)
{
return _queueClient.GetQueueReference(queueName);
}
}
public interface IQueueResolver
{
CloudQueue GetQueue(string queueName);
}
public class AzureQueues
{
public static string EmailQueue
{
get { return "email-queue"; }
}
public static IEnumerable<string> KnownQueues
{
get { return new[] {EmailQueue}; }
}
}
public class BootstrapAzureQueues
{
public static void CreateKnownAzureQueues(string azureConnectionString)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(azureConnectionString);
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
foreach (var queueName in AzureQueues.KnownQueues)
{
AsyncHelper.RunSync(() => queueClient.GetQueueReference(queueName).CreateIfNotExistsAsync());
}
}
}
internal static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new
TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return AsyncHelper._myTaskFactory
.StartNew<Task<TResult>>(func)
.Unwrap<TResult>()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
AsyncHelper._myTaskFactory
.StartNew<Task>(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
}
}
|
C#
|
UTF-8
| 6,504 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using UnityEngine;
namespace Zios.Containers{
public class Mutant{
public object original;
public object current;
public override string ToString(){return this.current.ToString();}
public static implicit operator int(Mutant value){return (int)value.current;}
public static implicit operator float(Mutant value){return (float)value.current;}
public static implicit operator bool(Mutant value){return (bool)value.current;}
public static implicit operator string(Mutant value){return (string)value.current;}
public static implicit operator Mutant(float value){return new Mutant(value);}
public static implicit operator Mutant(int value){return new Mutant(value);}
public static implicit operator Mutant(bool value){return new Mutant(value);}
public static implicit operator Mutant(string value){return new Mutant(value);}
public Mutant(object value){this.original = this.current = value;}
public void Scale(float value){this.Set((float)this.original * value);}
public object Get(){return this.current;}
public void Set(object value){this.current = value;}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
[Serializable]
public class MFloat{
public float original;
public float current;
public float min;
public float max;
public override string ToString(){return this.current.ToString();}
public static implicit operator int(MFloat value){return (int)value.current;}
public static implicit operator float(MFloat value){return value.current;}
public static implicit operator MFloat(float value){return new MFloat(value);}
public MFloat(float value){this.original = this.current = value;}
public MFloat(float min,float max){
this.original = this.current = min;
this.min = min;
this.max = max;
}
public MFloat(float value,float min,float max){
this.original = this.current = value;
this.min = min;
this.max = max;
}
public float Lerp(float value){return Mathf.Lerp(this.min,this.max,value);}
public void Add(float value){this.Set(this.current + value);}
public void Scale(float value){this.Set(this.original * value);}
public float Get(){return this.current;}
public void Set(float value){
if(!(this.min == 0 && this.max == 0)){
current = Mathf.Clamp(value,this.min,this.max);
}
this.current = value;
}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
[Serializable]
public class MInt{
public int original;
public int current;
public int min;
public int max;
public override string ToString(){return this.current.ToString();}
public static implicit operator int(MInt value){return value.current;}
public static implicit operator MInt(int value){return new MInt(value);}
public MInt(int value){this.original = this.current = value;}
public MInt(int min,int max){
this.original = this.current = min;
this.min = min;
this.max = max;
}
public MInt(int value,int min,int max){
this.original = this.current = value;
this.min = min;
this.max = max;
}
public int Lerp(float value){return (int)Mathf.Lerp(this.min,this.max,value);}
public void Add(int value){this.Set(this.current + value);}
public void Scale(int value){this.Set(this.original * value);}
public int Get(){return this.current;}
public void Set(int value){
if(!(this.min == 0 && this.max == 0)){
current = Mathf.Clamp(value,this.min,this.max);
}
this.current = value;
}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
[Serializable]
public class MBool{
public bool original;
public bool current;
public override string ToString(){return this.current.ToString();}
public static implicit operator bool(MBool value){return value.current;}
public static implicit operator MBool(bool value){return new MBool(value);}
public MBool(bool value){this.original = this.current = value;}
public bool Get(){return this.current;}
public void Set(bool value){this.current = value;}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
[Serializable]
public class MString{
public string original;
public string current;
public override string ToString(){return this.current.ToString();}
public static implicit operator string(MString value){return value.current;}
public static implicit operator MString(string value){return new MString(value);}
public MString(string value){this.original = this.current = value;}
public string Get(){return this.current;}
public void Set(string value){this.current = value;}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
[Serializable]
public class MVector2{
public Vector2 original;
public Vector2 current;
public override string ToString(){return this.current.ToString();}
public static implicit operator Vector2(MVector2 value){return value.current;}
public static implicit operator MVector2(Vector2 value){return new MVector2(value);}
public MVector2(Vector2 value){this.original = this.current = value;}
public Vector2 Get(){return this.current;}
public void Set(Vector2 value){this.current = value;}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
[Serializable]
public class MVector3{
public Vector3 original;
public Vector3 current;
public override string ToString(){return this.current.ToString();}
public static implicit operator Vector3(MVector3 value){return value.current;}
public static implicit operator MVector3(Vector3 value){return new MVector3(value);}
public MVector3(Vector3 value){this.original = this.current = value;}
public Vector3 Get(){return this.current;}
public void Set(Vector3 value){this.current = value;}
public void Revert(){this.current = this.original;}
public void Morph(){this.original = this.current;}
public bool HasChanged(){return this.current != this.original;}
}
}
|
Java
|
UTF-8
| 326 | 2.109375 | 2 |
[] |
no_license
|
package com.ironhack.RestAPI.controller.dto;
import com.ironhack.RestAPI.enums.Department;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
@Getter
@Setter
public class DepartmentDTO {
@Enumerated(EnumType.STRING)
private Department department;
}
|
Swift
|
UTF-8
| 2,437 | 2.890625 | 3 |
[] |
no_license
|
//
// AppExtensions.swift
// ChatMessageSplitApp
//
// Created by Stuti on 31/03/19.
// Copyright © 2019 iOS. All rights reserved.
//
import UIKit
extension NSObject {
class var className: String {
return String(describing: self)
}
}
extension UIViewController {
func showAlert(for message: String, alertTitle: String = "Alert", alertActionTitle: String = "OK") {
let alertController = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: alertActionTitle, style: .default, handler: nil)
alertController.addAction(action)
present(alertController, animated: true, completion: nil)
}
}
extension UIView {
func setCorners() {
layer.cornerRadius = 10.0
layer.masksToBounds = true
}
func setGradient() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.zPosition = -1
gradientLayer.colors = [
UIColor(red: 152.0/255.0, green: 219.0/255.0, blue: 198.0/255.0, alpha: 1.0).cgColor,
UIColor(red: 91.0/255.0, green: 200.0/255.0, blue: 172.0/255.0, alpha: 1.0).cgColor]
layer.addSublayer(gradientLayer)
}
}
extension UITableView {
func scrollToLastRow(count: Int) {
if count > 0 {
let indexPath = NSIndexPath(row: count - 1, section: 0)
scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: true)
}
}
}
extension UITextView {
func setPlaceholder() {
let placeholderLabel = UILabel()
placeholderLabel.text = Constants.Type_Message
placeholderLabel.sizeToFit()
placeholderLabel.tag = 222
placeholderLabel.frame.origin = CGPoint(x: 5, y: (font?.pointSize)! / 2)
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.isHidden = !text.isEmpty
addSubview(placeholderLabel)
contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
func checkPlaceholder() {
let placeholderLabel = viewWithTag(222) as! UILabel
placeholderLabel.isHidden = !text.isEmpty
}
}
extension String {
var containsWhitespace: Bool {
return (rangeOfCharacter(from: .whitespaces) != nil)
}
func trim() -> String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
}
|
Java
|
UTF-8
| 3,508 | 3.140625 | 3 |
[] |
no_license
|
package Eligorithms;
import java.util.ArrayList;
public class MonteCarloSearchTreeNode
{
private ArrayList<MonteCarloSearchTreeNode> children;
private MonteCarloSearchTreeNode parent;
private ConnectFourGame game;
private ConnectFourMove move;
private int wins;
private int possibilities;
public MonteCarloSearchTreeNode(MonteCarloSearchTreeNode _parent)
{
parent = _parent;
wins = 0;
possibilities = 0;
move = null;
game = new ConnectFourGame();
children = null;
}
public MonteCarloSearchTreeNode(MonteCarloSearchTreeNode _parent, ConnectFourMove _move)
{
wins = 0;
possibilities = 0;
parent = _parent;
move = _move;
game = new ConnectFourGame(_parent);
assert (move != null);
game.addMove(_move);
if(game.isSolved() || game.isFull())
{
children = new ArrayList<MonteCarloSearchTreeNode>();
if(game.winner() == ConnectFourPlayer.getAI())
updateWithWin();
else
updateWithLoss();
}
}
public static MonteCarloSearchTreeNode getRoot(ConnectFourPlayer player)
{
MonteCarloSearchTreeNode ret = new MonteCarloSearchTreeNode(null);
generateChildren(ret, player);
return ret;
}
private static void generateChildren(MonteCarloSearchTreeNode node, ConnectFourPlayer player)
{
ArrayList<ConnectFourMove> moves = node.game.getAvailableMoves(player);
node.children = new ArrayList<MonteCarloSearchTreeNode>();
// Check for winning move (prevents stupid game states)
boolean foundWinningMove = false;
for(ConnectFourMove move : moves)
{
if(move == null)
continue;
if(node.game.testMove(move))
{
foundWinningMove = true;
node.children.add(new MonteCarloSearchTreeNode(node, move));
break;
}
}
if(!foundWinningMove)
{
// If no winning move found, add all possible children
for(ConnectFourMove move : moves)
{
if(move == null)
continue;
node.children.add(new MonteCarloSearchTreeNode(node, move));
}
}
}
public void generateChildren()
{
if(needToGenerateChildren())
generateChildren(this, move.player().opposite());
}
private boolean needToGenerateChildren()
{
return children == null;
}
public void updateWithWin()
{
++wins;
++possibilities;
if(parent != null)
parent.updateWithWin();
}
public void updateWithLoss()
{
++possibilities;
if(parent != null)
parent.updateWithLoss();
}
public double score()
{
return (double) wins / (double) possibilities;
}
public int wins()
{
return wins;
}
public int possibilities()
{
return possibilities;
}
public ArrayList<MonteCarloSearchTreeNode> children()
{
return children;
}
public MonteCarloSearchTreeNode parent()
{
return parent;
}
public ConnectFourMove move()
{
return move;
}
}
|
Python
|
UTF-8
| 604 | 4.5 | 4 |
[] |
no_license
|
#Ryan Walters Dec3 2020 -- Practicing for statement loops using a list of animals that share a similar characteristic
#Initial list and for statement loop with initial print
animal_list = ['bear', 'lion', 'shark', 'panther', 'anaconda']
for animal in animal_list:
print(animal.title())
#New loop with a message
for animal in animal_list:
print(f"If you ever come across a {animal.title()} in the wild, "
"be alert! They might try to eat you.")
print("All of these animals are at the top of their respective food chain, "
"and while fascinating, are very dangerous!")
#END OF PROGRAM
|
JavaScript
|
UTF-8
| 1,833 | 2.53125 | 3 |
[] |
no_license
|
const Component = require('./Component')
const ContentPage = require('./ContentPage')
/**
* 模板中的占位符默认配置,可覆盖
*/
const TEMPLATE_KEY = {
styleKey: 'page-style',
conentKey: 'page-content',
scriptKey: 'page-script',
exScriptKey: 'external-script',
exStyleKey: 'external-style'
}
/**
* 表示全局模板的类,根据模板编译所有的页面
*/
module.exports = class Template extends Component {
/**
* 构造函数
*/
constructor({template, content, container}) {
super({url: template.url, content, container})
if(typeof(template) === "string") {
template = {url: template}
}
this.conf = Object.assign({}, TEMPLATE_KEY, template)
}
/**
* 重写初始化script函数,template无需获取出来
*/
_initScripts() {
this.inlineScripts = ''
this.externalScripts = []
// 获取页面中的外部script,有src表示外部
let external = this.$('script[src^="@module/"]')
if(external && external.length) {
Array.prototype.forEach.call(external, v=>{
this.container.getResource('script', v.attribs.src)
})
}
}
/**
* template无需获取style
*/
_initStyles() {
this.inlineStyles = ''
this.externalStyles = []
// 获取外部的样式文件
let external = this.$('link[rel="stylesheet"][href^="@module/"]')
if(external && external.length) {
Array.prototype.forEach.call(external, v=>{
this.externalStyles.push(this.container.getResource('style', v.attribs.href))
})
}
}
/**
* template 无需转出到字符串
*/
toString() {
return ''
}
/**
* 将content对象按照当前模板进行填充,返回编译后的完整html字符串
*/
fillTemplate(fragement) {
return new ContentPage(this, fragement).toString()
}
}
|
Markdown
|
UTF-8
| 1,886 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
# State Backstage
State can be very slippery to work with, as it's not normally directly visible in your story--you can only infer from its side effects. Chapbook provides tools to track and even change state as you test your story.
## The State Tab
Under the State tab, you'll find a Variables heading. This shows the current state of your story as you play. You can also select a value on the right side of the variables table and enter a new one--press the Return or Enter key when you're done to set the variable. You may only enter values in the variables table, not expressions.
If the Show Defaults checkbox is ticked, Chapbook will show various built-in variables--mainly related to Chapbook's configuration. See [Customization][../customization/index.md] for more details.
## State Snaphots
Beneath the variables table is the Snapshots heading. Snapshots allow you to quickly save and restore the state of your story at any point. For example, if you'd like to skip the prologue or test a specific scene, play through your story as usual. When you've reached the point you'd like to skip to, use the Add Snapshot button. After giving your snapshot a name, it will appear under the Snapshots heading as a button. Using this button will immediately set the state of your story, including the passage you were viewing, to what it was.
Use the × button at the end of a snapshot button to remove it. Snapshots are saved to your web browser only.
<aside data-hint="working">
Exporting snapshots for use by other people working on your story may come in a future version of Chapbook.
</aside>
## State in History
The History tab also shows changes to state as you navigate through a story. If a passage changes a variable, you'll see a separate row in the history table showing that change. This is informational only--you cannot change variables from the History tab.
|
Python
|
UTF-8
| 194 | 3.125 | 3 |
[] |
no_license
|
# coding:utf-8
print('%c' % 97)
print('%c' % 'a')
print('%u' % -1)
print('{:d}'.format(1))
print('{:f}'.format(1.2))
print('%o' % 24)
print('%x' % 32)
number = int('123ab', 16)
print(number)
|
Python
|
UTF-8
| 1,993 | 3.15625 | 3 |
[] |
no_license
|
import sys
import multiprocessing
from time import perf_counter as timer
from utils import get_prime_factors
def get_num_factors_for_prime(n, prim):
counter = 0
while n%prim == 0:
counter += 1
n /= prim
return counter
def get_num_factors(n):
# very slow but works ¯\_(ツ)_/¯
factors = get_prime_factors(n)
num_facs = len(factors)
for prim in factors:
fac = prim * 2
while fac <= n**(1/2):
if n%fac == 0 and fac not in factors:
num_facs += 1
factors.append(fac)
fac += prim
return num_facs, factors
def get_max_divisors(N, start, step):
# get triangle numbers starting from N
num = 0
facs = None
i = start
while True:
if i%1000 == 0:
print(i, end='\r')
tri = ((i + 1) * i) / 2
num, _ = get_num_factors(tri)
if num > N/2:
print(f"{tri} is the first triangle number n=({i}) to have more than {N} factors ({num})")
break
i += step
return True
def get_stolen(N):
# from https://www.xarg.org/puzzle/project-euler/problem-12/
def tau(num):
n = num
i = 2
p = 1
if num == 1:
return 1
while i*i <= n:
c = 1
while n%i == 0:
n /= i
c += 1
i += 1
p *= c
if n == num or n > 1:
p *= 1+1
return p
n = 1
d = 1
while tau(d) <= N:
n+=1
d+=n
print("stolen: ", d)
#print(sorted(get_factors(N)))
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1].isnumeric():
N = int(sys.argv[1])
else:
N = 500
if len(sys.argv) > 2:
start = int(sys.argv[2])
else:
start = N
if len(sys.argv) > 3:
step = int(sys.argv[3])
else:
step = 1
# does not work :(
get_stolen(N)
get_max_divisors(N, start, step)
|
Java
|
UTF-8
| 325 | 3.15625 | 3 |
[] |
no_license
|
package com.toolsq.javafundamentals;
// Can not inherit the class
public class FinalKeywordDemo {
// Member is a constant
int i=0;
public void setI(int a)
{
i = a;
}
// final keyword will stop it from being overridden
public void showMessage()
{
System.out.println("SuperClas");
}
}
|
Python
|
UTF-8
| 590 | 2.6875 | 3 |
[] |
no_license
|
#get ip list from /var/log/auth.log
# use key word from cause each connection starts being recorded using a "From" word
import re
l=list()
mystr="from"
f = open("auth.log")
f_ip = open("ip.txt", "r+")
for line in f:
line=line.strip()
if mystr in line:
x=re.findall('from\S* [0-9.]+', line) # read line, find the word "from", then a space, then [0-9] till next blank
#x=re.findall('\S* [0-9.]+',line)
l.append(x)
# print(type(x))
#print(x[1])
for a in l:
# print(str(a)[7:-2])
f_ip.write((str(a)[7:-2]))
f_ip.write("\n")
f.close()
f_ip.close()
|
Java
|
UTF-8
| 751 | 3.4375 | 3 |
[] |
no_license
|
//Demonstrates the use of an array of objects.
public class GameDriver
{
//Creates a GameCollection object and adds some games to it.
//Prints reports on the status of the collection.
public static void main(String [] args)
{
GameCollection games = new GameCollection();
games.addGame("Call of Duty", "Avtivision", "PlayStation 2", 2003, 12.99, true);
games.addGame("Kerbal Space Program", "Squad", "PC", 2011, 29.99, false);
games.addGame("Rainbow Six: Siege", "Ubisoft", "PC", 2015, 35.49, false);
System.out.println(games);
games.addGame("Luigi's Mansion", "Nintendo", "GameCube", 2001 , 15.49, true);
System.out.println(games);
}
}
|
C#
|
UTF-8
| 1,816 | 3.234375 | 3 |
[] |
no_license
|
using FOS.Models.Interfaces;
using FOS.Models.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Flooring_Ordering_System
{
public class LiveProductRepository : IProductRepository
{
private const string path = @"C:\Data\Products.txt";
List<Product> products = new List<Product>();
public LiveProductRepository()
{
products = LoadProduct();
}
public List<Product> LoadProduct()
{
using (StreamReader sr = new StreamReader(path))
{
sr.ReadLine();
string line;
while ((line = sr.ReadLine()) != null)
{
Product product = new Product();
string[] columns = line.Split(',');
product.ProductType = columns[0];
product.CostPerSquareFoot = decimal.Parse(columns[1]);
product.LaborCostPerSquareFoot = decimal.Parse(columns[2]);
products.Add(product);
}
}
return products;
}
public void SaveProduct(Product product)
{
products.Add(product);
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("ProductType, CostPerSquareFoot, LaborCostPerSquareFoot");
while (sw != null)
{
foreach (var _product in products)
{
sw.WriteLine(_product.ProductType + "," + _product.CostPerSquareFoot + "," + _product.LaborCostPerSquareFoot);
}
}
}
}
}
}
|
Python
|
UTF-8
| 741 | 2.671875 | 3 |
[] |
no_license
|
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
baseDir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(baseDir , 'test.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
u =User(username = 'cc' , email = 'cc')
db.session.add(u)
db.session.commit()
|
Python
|
UTF-8
| 2,081 | 3.171875 | 3 |
[] |
no_license
|
def merge_ranges(input_range_list):
res=list()
for i in range(len(input_range_list)):
isMatched=False
for j in range(len(res)):
#case A
if input_range_list[i].lower_bound==res[j].lower_bound \
and input_range_list[i].upper_bound==res[j].upper_bound:
isMatched=True
#case B
if input_range_list[i].lower_bound>=res[j].lower_bound \
and input_range_list[i].lower_bound<=res[j].upper_bound:
isMatched=True
res[j].lower_bound=(min(res[j].lower_bound, input_range_list[i].lower_bound))
res[j].upper_bound=(max(res[j].upper_bound, input_range_list[i].upper_bound))
#case C
if input_range_list[i].upper_bound>=res[j].lower_bound \
and input_range_list[i].upper_bound<=res[j].upper_bound:
isMatched=True
res[j].lower_bound=(min(res[j].lower_bound, input_range_list[i].lower_bound))
res[j].upper_bound=(max(res[j].upper_bound, input_range_list[i].upper_bound))
#case D
if input_range_list[i].lower_bound<=res[j].lower_bound \
and input_range_list[i].upper_bound>=res[j].upper_bound:
isMatched=True
res[j].lower_bound=(min(res[j].lower_bound, input_range_list[i].lower_bound))
res[j].upper_bound=(max(res[j].upper_bound, input_range_list[i].upper_bound))
if input_range_list[i].lower_bound>=res[j].lower_bound \
and input_range_list[i].upper_bound<=res[j].upper_bound:
isMatched=True
res[j].lower_bound=(min(res[j].lower_bound, input_range_list[i].lower_bound))
res[j].upper_bound=(max(res[j].upper_bound, input_range_list[i].upper_bound))
if not isMatched:
res.append(Range(input_range_list[i].lower_bound,input_range_list[i].upper_bound))
return res
# [[1,4], [3,7], [5,10], [11,15]]
|
Markdown
|
UTF-8
| 5,443 | 3 | 3 |
[] |
no_license
|
---
layout: page
title: "Q190966: BUG: IntelliSense Limitations with Templates"
permalink: /kb/190/Q190966/
---
## Q190966: BUG: IntelliSense Limitations with Templates
{% raw %}
Article: Q190966
Product(s): Microsoft C Compiler
Version(s): 6.0
Operating System(s):
Keyword(s): kbVC600bug
Last Modified: 05-MAR-2002
-------------------------------------------------------------------------------
The information in this article applies to:
- Microsoft Visual C++, 32-bit Enterprise Edition, version 6.0
- Microsoft Visual C++, 32-bit Professional Edition, version 6.0
- Microsoft Visual C++, 32-bit Learning Edition, version 6.0
- Microsoft Visual C++.NET (2002)
-------------------------------------------------------------------------------
SYMPTOMS
========
This article focuses on the limitations of IntelliSense when working with
templates.
- IntelliSense does not recognize template member functions defined outside of
the template class.
When a template member function is defined outside of the template class, it
does not appear in an instantiated template object's Member list, and does
not provide Parameter and Type Info. It also does not appear in the ClassView
pane. With Visual C++ 6.0, the only way to have IntelliSense work correctly
with template member functions is to define all member functions inside of
the template class declaration.
- Coding inside of nonclass template functions does not fully utilize
IntelliSense.
IntelliSense does not parse the bodies of template functions that are not
member functions of a class. As a result, most IntelliSense features do not
work inside of a template function definition.
- Template class specializations are not properly interpreted by IntelliSense.
STATUS
======
Microsoft has confirmed this to be a bug in the Microsoft products listed at the
beginning of this article. We are researching this bug and will post new
information here in the Microsoft Knowledge Base as it becomes available.
MORE INFORMATION
================
Consider the following code sample. Comments that are examples are marked with
\\EXAMPLE. The code directly below needs to be uncommented in order to reproduce
the problem. The comments following the code explain the problem:
Sample Code
-----------
//Test.cpp
#include <stdio.h>
// A Template Class
//
template <class T, int i>
class TempClass
{
public:
TempClass(void){}
~TempClass(void){}
int MemberSet(T a, int b);
int GetSize()
{
return arraysize;
}
private:
T Tarray[i];
int arraysize;
};
// A Simple Class
//
class TestClass
{
public:
TestClass(void){}
~TestClass(void){}
int m;
int n;
};
// Template Member Function Defined outside of the template class
//
template <class T, int i>
int TempClass<T, i>::MemberSet(T a, int b)
{
if( ( b >= 0 ) && (b < i) )
{
Tarray[b++] = a;
return sizeof( a );
}
else
return -1;
};
// Template Class
//
template <class T>
class Print
{
public:
// Declare an instance of TestClass
TestClass te;
// EXAMPLE
//te.
// #2 No members displayed
// all types but char
void f(int, double)
{
printf("Print<T>\n");
}
};
// Specialization of Print<class T>
//
template <>
class Print<char>
{
public:
// just for chars
void f(char*)
{
printf("Print<char>\n");
}
};
void main()
{
TempClass<char,10> t;
// EXAMPLE
//t.
// #1 MemberSet is absent from the member list
// MemberSet does not appear in the ClassView pane
// Define MemberSet in the TempClass declaration
// to correct this problem
Print<char> pc;
// EXAMPLE
//pc.f(
// #3
// pc.f Tool tip shows all types but char
// pc.f( Parameter list is int, double
}
REFERENCES
==========
For additional information, please see the following article in the Microsoft
Knowledge Base:
Q153284 Limitations of IntelliSense in Visual C++ 6.0
"Template Topics"; Visual C++ Documentation, Using Visual C++, Visual C++
Programmers Guide, Adding Program Functionality, Details, Template Topics.
"About Automatic Statement Completion;" Visual C++ Documentation, Using Visual
C++, Visual C++ Users Guide, Text Editor, Overview: Text Editor, About Automatic
Statement Completion.
"Automatically Completing Statements;" Visual C++ Documentation, Using Visual
C++, Visual C++ Users Guide, Text Editor, How do I ... Topics: Text Editor,
Automatically completing Statements.
Additional query words: kbvc600bug
======================================================================
Keywords : kbVC600bug
Technology : kbVCsearch kbAudDeveloper kbVC600 kbVC32bitSearch kbVCNET
Version : :6.0
Issue type : kbbug
Solution Type : kbpending
=============================================================================
{% endraw %}
|
C++
|
UTF-8
| 685 | 2.53125 | 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.
*/
/*
* File: NodoCurso.cpp
* Author: Steven
*
* Created on July 12, 2018, 8:21 PM
*/
#include "NodoCurso.h"
NodoCurso::NodoCurso() {
setSiguiente(NULL);
}
NodoCurso::~NodoCurso(){
}
void NodoCurso::setInfo(Curso nuevoCurso){
curso = nuevoCurso;
}
Curso* NodoCurso::getInfo(){
return &curso;
}
void NodoCurso::setSiguiente(NodoCurso* nuevo){
siguiente = nuevo;
}
NodoCurso* NodoCurso::getSiguiente(){
return siguiente;
}
|
Markdown
|
UTF-8
| 931 | 2.6875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
#Requirements
Plugin requires the following
- Stellar Javascript SDK
- Jquery
#Installation
Include Jquery
`<script src="jquery-min.js"></script>`
Include `stellar-js-sdk`
`<script src="stellar-sdk.js"></script>`
Include `stellar-instant-transfer.js`
`<script src="stellar-instant-transfer.js"></script>`
Add the following tag to your page
`<div id="stellar-instant-transfer" data-rcvr="GCRUQO55VBD2P......"></div>`
**Note:** The value of `data-rcvr` should be your Stellar Account ID
That's It! You should have a form as shown in the demo below and ready to receive payments instantly from your website.
#New Features
- You can now send other asset types not just Lumens
- You can choose network type; Test or Public
#Demo
See demo here: [Demo URL](https://eyecandydev.github.io/stellar-instant-transfer/)
#Contact
This plugin is still under development. Please report any issues using the issue tracker.
Thank you.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.