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
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 3,904
| 2.65625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 05 19:26:22 2017
@author: hp
"""
import tkFileDialog
import xlrd
import quopri
from tkinter import *
from tkinter.ttk import *
import os
reload(sys)
sys.setdefaultencoding("utf-8")
def tovcf():
listbox.delete(0,END)
dic={}
#path=r"C:\Users\hp\Desktop\新建.xls"
try:
path=e1.get()
global path
if u'\u202a' in path:
path=re.split(u'\u202a',path)[1]
data = xlrd.open_workbook(path)
strs="BEGIN:VCARD\nVERSION:2.1\nFN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:{0}\nTEL;CELL;PREF:{1}\nEND:VCARD\n"
dst=os.path.join(os.path.expanduser("~"), "Desktop")
with open(dst+'\\all.vcf',"w") as f:
for sheet in data.sheets():
n=0
global dic
try:
while not dic.has_key('姓名') or not dic.has_key('电话'):
for col in range(sheet.ncols):
if sheet.cell(n,col).value==u'姓名':
dic['姓名']=col
if sheet.cell(n,col).value==u'电话':
dic['电话']=col
n+=1
except:
dic['姓名']=0
dic['电话']=1
n=1
for row in range(n,sheet.nrows):
try:
a=sheet.cell(row,dic['姓名']).value+'家长'
a=a.encode('utf-8')
name = quopri.encodestring(a)
tel=int(sheet.cell(row,dic['电话']).value)
f.write(strs.format(name,tel))
except:
g='第'+str(row+1)+'行出现错误'
listbox.insert(END, g)
if os.path.getsize(dst+'\\all.vcf')!=0:
listbox.insert(END, '*******************转换完成********************')
listbox.insert(END, '已在桌面生成名为all.vcf的文件,将其导入手机通讯录即可')
listbox.insert(END, '可通过数据线或者qq将vcf文件传至手机')
listbox.insert(END, '不管手机什么系统,点击文件,打开方式选择通讯录导入')
listbox.insert(END, '然后就可以看到导入成功的联系人名片了')
else:
os.remove(dst+'\\all.vcf')
listbox.delete(0,END)
listbox.insert(END, '该文件格式不规范')
listbox.insert(END,"注意excel内姓名那列最顶上一格为 姓名")
listbox.insert(END,"电话号码那列最顶上一格为 电话")
listbox.insert(END,"如果还是不行,可以将姓名放第一列,电话放第二列再尝试")
except:
listbox.insert(END, '该文件并非excel文件')
def findroad():
filename = tkFileDialog.askopenfilename(initialdir = 'E:/Python')
sv.set(filename)
root=Tk()
root.title('excel生成vcf文件')
root.geometry('400x270')
sv=StringVar()
frm1=Frame(root,width=150,height=50).pack()
frm2=Frame(root,width=100,height=30).pack()
Label(frm1,text='excel文件路径:').place(x=20,y=20)
e1=Entry(frm1,textvariable=sv,width=35)
e1.place(x=110,y=20)
Button(frm1,text='开始转换',command=tovcf).place(x=250,y=50)
Button(frm1,text='选择路径',command=findroad).place(x=110,y=50)
listbox=Listbox(frm2,width=50,height=10)
listbox.pack()
listbox.insert(END,"请在上方的方框内输入源excel文件地址,然后点击'开始转换'")
listbox.insert(END,"注意excel内姓名那列最顶上一格为 姓名")
listbox.insert(END,"电话号码那列最顶上一格为 电话")
listbox.insert(END,"点击'选择路径'以选择待转换excel文件路径")
root.mainloop()
|
Ruby
|
UTF-8
| 1,253
| 4.03125
| 4
|
[] |
no_license
|
require 'pry'
class Board
attr_accessor :board, :cells
def initialize
reset!
end
#why is this reset! ? how will this create a new instance? Does it already have a board defined?
def reset!
@cells = Array.new(9, " ")
#binding.pry
# I was originally doing
#cells.clear
#cells = Array.new(9, " ")
#did this fail because I was calling on the cells object? Class? If I don't have an initialize method it's ok to use an instance var to perform the behavior? I hope I'm even asking this question correctly.
end
def display
puts " #{@cells[0]} | #{@cells[1]} | #{@cells[2]} "
puts " ----------- "
puts " #{@cells[3]} | #{@cells[4]} | #{@cells[5]} "
puts " ----------- "
puts " #{@cells[6]} | #{@cells[7]} | #{@cells[8]} "
end
def position(user_input)
cells[user_input.to_i - 1]
end
def full?
cells.all?{|square| square != " " }
end
def turn_count
cells.count{|square| square != " " }
end
def taken?(input)
!(position(input) == " " || position(input) == "")
end
def valid_move?(input)
input.to_i.between?(1,9) && !taken?(input)
end
def update(input, player)
cells[input.to_i-1] = player.token
end
end
|
Java
|
UTF-8
| 1,868
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.madhawav.j2pbind;
import java.util.ArrayList;
import java.util.List;
public class Config {
private String javaExportPath;
private String pythonExportPath;
private String pythonPrefix;
private List<Class> classList;
private String javaExportPathRelativeToPythonExportPath;
private List<String> compilerClassPaths;
public Config(String rootPath){
this.javaExportPath = rootPath + "/java";
this.pythonExportPath = rootPath + "/python";
this.pythonPrefix = "pybind";
this.javaExportPathRelativeToPythonExportPath = "../java";
this.classList = new ArrayList<>();
this.compilerClassPaths = new ArrayList<>();
}
public List<String> getCompilerClassPaths() {
return compilerClassPaths;
}
public void addClass(Class c){
this.classList.add(c);
}
public void removeClass(Class c){
this.classList.remove(c);
}
public List<Class> getClasses(){
return this.classList;
}
public String getPythonPrefix() {
return pythonPrefix;
}
public void setPythonPrefix(String pythonPrefix) {
this.pythonPrefix = pythonPrefix;
}
public String getJavaExportPath() {
return javaExportPath;
}
public String getPythonExportPath() {
return pythonExportPath;
}
public void setJavaExportPath(String javaExportPath) {
this.javaExportPath = javaExportPath;
}
public void setPythonExportPath(String pythonExportPath) {
this.pythonExportPath = pythonExportPath;
}
public String getJavaExportPathRelativeToPythonExportPath() {
return javaExportPathRelativeToPythonExportPath;
}
public void setJavaExportPathRelativeToPythonExportPath(String value){
this.javaExportPathRelativeToPythonExportPath = value;
}
}
|
Python
|
UTF-8
| 753
| 2.671875
| 3
|
[] |
no_license
|
# coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
from lpsd import lpsd
from scipy import signal
N = int(1e5) # Number of data points in the timeseries
fs = 2. # sampling rate
fmin = float(fs) / N # lowest frequency of interest
fmax = float(fs) / 2. # highest frequency of interest
Jdes = 1000 # desired number of points in the spectrum
Kdes = 100 # desired number of averages
Kmin = 2 # minimum number of averages
xi = 0.5 # fractional overlap
x = np.random.normal(size=N)
X, f, C= lpsd(x, signal.hann, fmin, fmax, Jdes, Kdes, Kmin, fs, xi)
# Compare to Pwelch
nfft = np.ceil(fs / float(fmin))
f_Pwelch, Pxx=signal.welch(x, fs, nperseg=N)
plt.loglog(f_Pwelch, Pxx)
plt.loglog(f, X*C['PSD'])
plt.show()
|
JavaScript
|
UTF-8
| 2,471
| 2.515625
| 3
|
[] |
no_license
|
const youtube = require('ytdl-core');
const fileSize = require('filesize');
// const fs = require('fs')
const readline = require('readline');
// const http = require('https')
const ffmpeg = require('fluent-ffmpeg');
const ytmp3 = (url, sender) => new Promise(async (resolve, reject) => {
try {
const info = await youtube.getInfo(url)
const details = info.videoDetails
let title = details.title
let link = details.video_url
let thumbnail = details.thumbnails[2].url
const dl = youtube.filterFormats(info.formats, 'audioonly')[0]
let size = fileSize(dl['contentLength'])
let dlurl = dl['url']
let stream = youtube(url, { quality: 'highestaudio' })
let start = Date.now();
ffmpeg(stream)
.audioBitrate(128)
.save(`./temp/${sender}_ytmp3.mp3`)
.on('progress', p => {
readline.cursorTo(process.stdout, 0);
process.stdout.write(`${p.targetSize}kb downloaded`);
})
.on('end', () => {
const arr = {
code: 200,
status: true,
link,
title,
size,
thumbnail,
dlurl
}
console.log(`\ndone, thanks - ${(Date.now() - start) / 1000}s`);
resolve(arr)
});
} catch (err) {
reject({ code: 404, status: false, msg: err })
}
})
const ytdl = (url) => new Promise(async (resolve, reject) => {
try {
const info = await youtube.getInfo(url)
const details = info.videoDetails
let title = details.title
let link = details.video_url
let thumbnail = details.thumbnails[0].url
const dl = youtube.chooseFormat(info.formats, { quality: 'highest' })
let size = fileSize(dl['contentLength'])
let dlurl = dl['url']
const arr = {
code: 200,
status: true,
link,
title,
size,
thumbnail,
dlurl
}
resolve(arr)
} catch (err) {
reject({
code: 404, status: false, msg: err
})
}
})
// ytmp3('https://www.youtube.com/watch?v=r1Fx0tqK5Z4', 'kikiaf')
// .then(async (res) => {
// console.log(res);
// }).catch((err) => console.error(err))
module.exports = { ytdl, ytmp3 }
|
Python
|
UTF-8
| 2,156
| 3.328125
| 3
|
[] |
no_license
|
with open('input.txt') as f:
player1, player2 = f.read().strip().split('\n\n')
player1 = [int(c) for c in player1.split('\n')[1:]]
player2 = [int(c) for c in player2.split('\n')[1:]]
# PART 1
while len(player1) > 0 and len(player2) > 0:
c1 = player1.pop(0)
c2 = player2.pop(0)
if c1 > c2:
player1.append(c1)
player1.append(c2)
else:
player2.append(c2)
player2.append(c1)
winner = player1 if len(player1) > 0 else player2
print(sum(c*(i+1) for i, c in enumerate(reversed(winner))))
# PART 2
# Reload b/c modified in PART 1
with open('input.txt') as f:
player1, player2 = f.read().strip().split('\n\n')
player1 = ','.join([c for c in player1.split('\n')[1:]])
player2 = ','.join([c for c in player2.split('\n')[1:]])
# I misread the instructions => tried to use memoization to speed it up. After fixing the logic per the instructions
# I may not need the memoization but I kept it in
import functools
@functools.lru_cache(maxsize=None)
def play(deck1_str, deck2_str, is_main):
# Returns winner and final decks
deck1 = deck1_str.split(',')
deck2 = deck2_str.split(',')
seen = set()
while True:
id_str = f"{','.join(deck1)} {','.join(deck2)}"
if is_main:
print(len(seen))
if id_str in seen:
# Automatic Player 1 win
return (1, None, None)
seen.add(id_str)
c1 = int(deck1.pop(0))
c2 = int(deck2.pop(0))
if len(deck1) >= c1 and len(deck2) >= c2:
# Recurse!
winner, _, _ = play(','.join(deck1[:c1]), ','.join(deck2[:c2]), False)
else:
winner = 1 if c1 > c2 else 2
if winner == 1:
deck1.append(str(c1))
deck1.append(str(c2))
else:
deck2.append(str(c2))
deck2.append(str(c1))
if len(deck1) == 0 or len(deck2) == 0:
return (winner, deck1, deck2)
winner, final_deck1, final_deck2 = play(player1, player2, True)
winning_deck = final_deck1 if winner == 1 else final_deck2
print(sum(int(c)*(i+1) for i, c in enumerate(reversed(winning_deck))))
|
Markdown
|
UTF-8
| 2,778
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
---
keyword: [云原生AI, 监控, GPU资源]
---
# 云原生AI监控
云原生AI的监控组件能够帮助您监控集群的GPU资源使用情况以及集群的各命名空间下的资源配额使用情况。本文介绍如何安装和使用云原生AI的监控组件。
- ACK的Kubernetes集群版本大于等于1.18.8。
- Arena组件版本大于等于0.7.0。具体操作,请参见[通过组件安装最新版的Arena](/cn.zh-CN/解决方案/AI解决方案/环境准备/通过组件安装最新版的Arena.md)。
- 安装ARMS Prometheus监控组件,具体操作,请参见[arms-prometheus](https://cs.console.aliyun.com/#/k8s/catalog/detail/incubator_ack-arms-prometheus)。
- 安装AI-Dashboard组件。具体操作,请参见[安装云原生AI套件及访问AI Dashbaord](/cn.zh-CN/云原生AI用户指南/安装云原生AI套件及访问AI Dashbaord.md)。
## 安装云原生AI监控组件
1. 登录[容器服务管理控制台](https://cs.console.aliyun.com)。
2. 在控制台左侧导航栏中,单击**集群**。
3. 在集群列表页面中,单击目标集群名称或者目标集群右侧**操作**列下的**详情**。
4. 在左侧导航栏,选择**应用** \> **AI工程加速(公测)**。
5. 安装监控组件。
- 如果您之前已经部署过云原生AI套件:
在云原生AI套件页面,找到云原生AI监控组件**ack-alibaba-cloud-metrics-adapter**,然后单击右侧**操作**列下的**部署**。
- 如果您之前未部署过云原生AI套件:
在云原生AI套件页面,单击**一键部署**,然后在**监控**区域,选中**监控组件**后,单击**部署云原生AI套件**。
## 使用云原生AI监控组件查看GPU资源及不同命名空间下的资源配额
**说明:** 使用云原生AI监控组件前,您需要安装**ack-ai-dashboard**组件并且设置AI-Dashboard访问配置。关于如何安装和访问AI-Dashboard,请参见[安装云原生AI套件及访问AI Dashbaord](/cn.zh-CN/云原生AI用户指南/安装云原生AI套件及访问AI Dashbaord.md)。
进入云原生AI Dashboard页面后,可以进行以下操作:
- 登录云原生AI Dashboard后,系统默认呈现集群维度的资源信息。您可以查看集群相关的资源,例如节点个数、运行Job数、GPU使用率等。
- 在云原生AI Dashboard页面右上角,单击**Nodes**查看节点GPU资源信息。

- 在云原生AI Dashboard页面右上角,单击**TrainingJobs**查看Training Job的监控信息。
- 在云原生AI Dashboard页面右上角,单击**Quota**查看集群各命名空间的资源配额使用情况。
|
C++
|
UTF-8
| 2,983
| 2.9375
| 3
|
[] |
no_license
|
/**
* @file cdc_vcp.hpp
* @author Petr Malaník (TheColonelYoung(at)gmail(dot)com)
* @version 0.1
* @date 28.09.2020
*/
/*
Some modifications of HAL USb middleware layer are needed for proper function
Add this to usbd_cdc_if.h (anywhere to begining of file where this will not be rewritten)):
extern void USB_VCP_RX_Callback(uint8_t* Buf, uint32_t Len);
extern void USB_VCP_TX_Callback();
Add this to usbd_cdc_if.c -> CDC_Receive_FS (around line 260) as first line of function:
USB_VCP_RX_Callback(Buf, *Len);
Add this to usbd_cdc_if.c -> CDC_TransmitCplt_FS (around line 310) as first line of function:
USB_VCP_TX_Callback();
*/
#pragma once
#include <string>
#include <vector>
#include "uart/serial_line.hpp"
#include "usbd_cdc_if.h"
using namespace std;
/**
* @brief Class for comunication via USB CDC, based on USB middleware layer of STM
* Mostly similar to UART
*/
class USB_CDC : public Serial_line
{
private:
/**
* @brief Vector of messages which are wainting to be send over USB CDC VCP
*/
vector<string> TX_buffer;
public:
/**
* @brief Construct a new usb cdc object
*/
USB_CDC() = default;
/**
* @brief Transmitt C++ string over USB CDC char by char
*
* @param message Message to send
* @return int Error code
*/
virtual int Send(string message) override final;
/**
* @brief Unused function for receive but must be implemented
* Buffer is allocated dynamicly by USb middleware layer and this pointer can change,
* mostly during changing of power modes, due to this pointer must be updated in every callback
*
* @return int Nothing
*/
virtual int Receive() override final { return 0; };
/**
* @brief Loads received character into RX buffer and notify all IRQ observers
*
* @param Buf Pointer to USB buffer from which will be character laoded
* @param Len Length of text in buffer, only 1 is supported, 2 and more are for non ascii character
* and special symbols
* @return int Size of buffer
*/
virtual int Receive(uint8_t *Buf, unsigned int Len);
/**
* @brief Routine which is called when transmittion is done, will check if buffer contains
* another content to send, if yes will send it.
*
* @return int Actual size of transmitt buffer
*/
int Resend();
};
/**
* @brief Callback function for USB CDC receive complete, must be called from
* CDC_Receive_FS(Src/usbd_cdc_if.c line around 260)
*
* @param Buf Pointer to USB buffer in which are data stored
* @param Len Number of characters in buffer
*/
void USB_VCP_RX_Callback(uint8_t *Buf, uint32_t Len);
/**
* @brief Callback function fot USB CDC transmit complete, must be called from
* CDC_TransmitCplt_FS(Src/usbd_cdc_if.c line around 310)
*/
void USB_VCP_TX_Callback();
|
Java
|
UTF-8
| 1,669
| 2.421875
| 2
|
[] |
no_license
|
//package com.example.weixin;
//
//import lombok.extern.slf4j.Slf4j;
//
//import org.apache.commons.lang3.StringUtils;
//import org.apache.commons.codec.digest.DigestUtils;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.Arrays;
//
//
//@Slf4j
//@RestController
//@RequestMapping("/wx/portal")
//public class WxPortalController {
//
// @GetMapping(produces = "text/plain;charset=utf-8")
// public String authGet(@RequestParam(name="signature",required = false) String signature,
// @RequestParam(name="timestamp",required = false) String timestamp,
// @RequestParam(name="nonce",required = false) String nonce,
// @RequestParam(name="echostr",required = false) String echostr){
// log.info("接收到来自微信服务器的认证消息:[{},{},{},{}]",signature,timestamp,nonce,echostr);
// if (StringUtils.isAnyBlank(signature,timestamp,nonce,echostr)){
// throw new IllegalArgumentException("请求参数非法,请核实!");
// }
// if (this.checkSignature(timestamp,nonce,signature)){
// log.info("成功");
// return echostr;
// }
// return "非法请求";
// }
//
// private boolean checkSignature(String timestamp, String nonce, String signature) {
// String TOKEN = "wanglei";
// String[] arr = {TOKEN,timestamp,nonce};
// Arrays.sort(arr);
// StringBuilder sb = new StringBuilder();
// for (String a : arr) {
// sb.append(a);
// }
// return DigestUtils.sha1Hex(sb.toString()).equals(signature);
// }
//}
|
Java
|
UTF-8
| 3,427
| 2.296875
| 2
|
[] |
no_license
|
package com.example.administrator.appctct.View;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.appctct.Component.CustomView.SetupView;
import com.example.administrator.appctct.Entity.Student;
import com.example.administrator.appctct.Interfaces.Login.PresenterNotifyViewLogin;
import com.example.administrator.appctct.Presenter.PresenterLogin;
import com.example.administrator.appctct.R;
import com.example.administrator.appctct.Service.Retrofit.APIUtils;
import com.example.administrator.appctct.Service.Retrofit.DataClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.widget.Toast.LENGTH_SHORT;
public class Login_Activity extends AppCompatActivity implements View.OnClickListener, PresenterNotifyViewLogin {
EditText edUserName,edPassword;
Button btLogin;
TextView tvRegister;
ProgressBar indicator;
private PresenterLogin presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_);
setID();
}
private void setID(){
edUserName = findViewById(R.id.edUser);
edPassword = findViewById(R.id.edPassword);
btLogin = findViewById(R.id.btLogin);
tvRegister = findViewById(R.id.tvRegister);
indicator = findViewById(R.id.pbIndicator);
tvRegister.setOnClickListener(this);
btLogin.setOnClickListener(this);
presenter = new PresenterLogin(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btLogin:
String userName = edUserName.getText().toString();
String password = edPassword.getText().toString();
presenter.notifyodelProcessLogin(userName,password);
break;
case R.id.tvRegister:
Intent intent = new Intent(Login_Activity.this,Register_Activity.class);
startActivity(intent);
break;
}
}
@Override
public void userIsEmpty() {
edUserName.setError("User Name is empty");
}
@Override
public void passwordIsEmpty() {
edPassword.setError("Password is empty");
}
@Override
public void loginSuccess(String account, String password) {
indicator.setVisibility(View.VISIBLE);
DataClient dataClient = APIUtils.getData();
Call<Student> call = dataClient.login(account,password);
call.enqueue(new Callback<Student>() {
@Override
public void onResponse(@NonNull Call<Student> call,@NonNull Response<Student> response) {
if (response.body() != null){
Toast.makeText(Login_Activity.this,"Login Success", LENGTH_SHORT).show();
return;
}
Toast.makeText(Login_Activity.this,response.message(), LENGTH_SHORT).show();
}
@Override
public void onFailure(@NonNull Call<Student> call,@NonNull Throwable t) {
}
});
}
}
|
JavaScript
|
UTF-8
| 1,993
| 2.6875
| 3
|
[] |
no_license
|
const studentsModel = require('../models/studentModells');
const getAllStudent = async (req, res) => {
try {
await studentsModel.find({}, (err, result) => {
if (err) console.log(err);
res.json({ massage: "success", data: result })
})
} catch (err) {
res.json({ massage: "problem in database", error: err });
}
}
const addStudent = async (req, res) => {
try {
await studentsModel.insertMany(
req.body.students,
(err, result) => {
if (err) console.log(err);
res.json({ massage: "add student", data: req.body.students });
})
} catch (err) {
res.json({ massage: "adding is failing", error: err });
}
}
const updateStudent = async (req, res) => {
try {
await studentsModel.findByIdAndUpdate(
req.params.id,
req.body.students,
(err, result) => {
if (err) throw err;
res.json({ massage: `${req.body.students.firstName} update students` });
})
}
catch (err) {
res.json({ massage: "problem withe update", error: err });
}
}
const deleteStudent = async (req, res) => {
try {
await studentsModel.findByIdAndDelete (req.params.id, (err, result) => {
if (err) throw err;
res.json({ massage: "delete student success" })
})
}
catch (err) {
res.json({ massage: "problem with update", error: err });
}
}
const getStudentByName = async (req, res) => {
try {
await studentsModel.find({firstName:req.params.firstName}, (err, result) => {
if (err) console.log(err);
res.json({ massage: "success", data: result })
})
} catch (err) {
res.json({ massage: "problem in database", error: err });
}
}
module.exports = {
getAllStudent,
addStudent,
updateStudent,
deleteStudent,
getStudentByName
}
|
Python
|
UTF-8
| 517
| 4.40625
| 4
|
[] |
no_license
|
#fahrenheit = float(input("This program will convert a temperature in Fahrenheit to Celsius. Enter a value to continue: "))
#answer = (fahrenheit - 32) * 5 / 9
#print(fahrenheit,"degrees Fahrenheit is",answer,"degrees Celsius.")
#import random
#while True:
#r = random.randrange(0, 101 ,10)
#print(str(r))
import math
angleD = float(input("Enter a value in degrees: "))
angleR = angleD*360/(2*math.pi)
answer = math.sin(angleR)**2 + math.cos(angleR)**2
print("sin(",angleD,"°)^2 + cos(",angleD,"°)^2 =",answer)
|
PHP
|
UTF-8
| 768
| 2.625
| 3
|
[] |
no_license
|
<html>
<head>
<meta charset="utf-8"/>
<title>FUSSBALL!!!!</title>
</head>
<body>
<form action="/vote.php" method="post">
<select name="voted">
<option></option>
<?php
mb_internal_encoding("UTF-8");
$db = mysqli_connect("localhost", "root", "", "fussball");
$abfrage = "Select Vereinsname from Vereine;";
$ergebnis = mysqli_query($db,$abfrage) OR die(mysql_error());
while($zeile = mysqli_fetch_assoc($ergebnis)){
echo "<option value='$zeile[Vereinsname]'>".$zeile["Vereinsname"]."</option>";
}
?>
</select>
<button type="submit">Abstimmen</button>
<br>
</form>
<form action="/vote.php" method="post">
<input type="text" name="voted"/>
<button type="submit">Hinzufügen und Abstimmen</button>
</form>
</body>
</html>
|
Java
|
UTF-8
| 1,733
| 3.375
| 3
|
[] |
no_license
|
package SecondExam;
import java.util.Scanner;
public class JoroTheNaughty {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int rows = in.nextInt();
int cols = in.nextInt();
int jumpNumber = in.nextInt();
int[] start = new int[2];
for (int i = 0; i < start.length; i++) {
start[i] = in.nextInt();
}
int[][] jumps = new int[jumpNumber][2];
for (int i = 0; i < jumps.length; i++) {
for (int j = 0; j < jumps[0].length; j++) {
jumps[i][j] = in.nextInt();
}
}
int[][] playground = new int[rows][cols];
int temp = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
playground[i][j] = temp;
temp++;
}
}
escape(rows, cols, start, jumps, playground);
}
static void escape(int rows, int cols, int[] start, int[][] jumps, int[][] playground) {
long sum = playground[start[0]][start[1]];
playground[start[0]][start[1]] = 0;
for (int i = 0; i < jumps.length; i++) {
start[0] += jumps[i][0];
start[1] += jumps[i][1];
if (start[0] >= rows || start[1] >= cols || start[0] < 0 || start[1] < 0) {
System.out.println("escaped " + sum);
return;
}
if (playground[start[0]][start[1]] == 0) {
System.out.println("caught " + sum);
return;
}
sum += playground[start[0]][start[1]];
playground[start[0]][start[1]] = 0;
if (i == jumps.length - 1) i = -1;
}
}
}
|
Java
|
UTF-8
| 5,347
| 2.609375
| 3
|
[] |
no_license
|
package com.team3824.akmessing1.scoutingapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.team3824.akmessing1.scoutingapp.R;
import com.team3824.akmessing1.scoutingapp.list_items.Team;
import com.team3824.akmessing1.scoutingapp.utilities.ScoutValue;
import com.team3824.akmessing1.scoutingapp.views.CustomOrdinalRank;
import java.util.ArrayList;
/**
* Adapter for the Ordinal rank view (Used for qualitative rankings)
*
* @author Andrew Messing
* @version
*/
public class OrdinalRankListAdapter extends ArrayAdapter<Team> implements View.OnClickListener{
private final String TAG = "OrdinalRankListAdapter";
private ArrayList<Team> teams;
/**
* @param context
* @param teams
*/
public OrdinalRankListAdapter(Context context, ArrayList<Team> teams) {
super(context, R.layout.list_item_ordinal_rank, teams);
this.teams = teams;
}
/**
* @param position
* @param convertView
* @param parentView
* @return
*/
@Override
public View getView(int position, View convertView, ViewGroup parentView) {
//if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_ordinal_rank, null);
//}
final Team team = teams.get(position);
TextView textView = (TextView) convertView.findViewById(R.id.textView);
Button button = (Button)convertView.findViewById(R.id.tie);
if(team.containsMapElement(CustomOrdinalRank.TIE) && team.getMapElement(CustomOrdinalRank.TIE).getInt() > 0)
{
button.setText("-");
}
button.setId(position);
button.setOnClickListener(this);
textView.setText(String.format("%d) %4d", team.getMapElement(CustomOrdinalRank.RANK).getInt(), team.getTeamNumber()));
return convertView;
}
public void remove(int teamNumber)
{
int i;
for(i = 0; i < teams.size(); i++)
{
if(teamNumber == teams.get(i).getTeamNumber())
{
teams.remove(i);
break;
}
}
notifyDataSetChanged();
}
/**
* @param position position where to add the team
* @param number number of the team to add
*/
public void add(int position, int number) {
Team team = new Team(number,"");
teams.add(position, team);
for(int i = 0; i < teams.size(); i++)
{
team = teams.get(i);
team.setMapElement(CustomOrdinalRank.RANK,new ScoutValue(i+1));
team.setMapElement(CustomOrdinalRank.TIE, new ScoutValue(0
));
}
notifyDataSetChanged();
}
public void add(int position, Team team) {
team.setMapElement(CustomOrdinalRank.RANK, new ScoutValue(position + 1));
if(team.getMapElement(CustomOrdinalRank.RANK).getInt() > teams.size())
{
team.setMapElement(CustomOrdinalRank.RANK,new ScoutValue(teams.size()));
}
teams.add(position, team);
for(int i = position+1; i < teams.size(); i++)
{
team = teams.get(i);
int rank = team.getMapElement(CustomOrdinalRank.RANK).getInt();
team.setMapElement(CustomOrdinalRank.TIE,new ScoutValue(0));
rank++;
if(rank > teams.size())
{
rank = teams.size();
}
team.setMapElement(CustomOrdinalRank.RANK,new ScoutValue(rank));
}
notifyDataSetChanged();
}
@Override
public Team getItem(int position)
{
return teams.get(position);
}
public int getTeamNumber(int position)
{
return teams.get(position).getTeamNumber();
}
/**
* @return number of teams in the ranking
*/
public int size() {
return teams.size();
}
@Override
public void onClick(View v) {
Button thisButton = (Button)v;
int position = thisButton.getId();
String text = String.valueOf(thisButton.getText());
Team team = teams.get(position);
if(text.equals("+"))
{
team.setMapElement(CustomOrdinalRank.TIE,new ScoutValue(1));
thisButton.setText("-");
for(int i = position + 1; i < teams.size(); i++) {
Team team2 = teams.get(i);
int rank = team2.getMapElement(CustomOrdinalRank.RANK).getInt();
rank--;
team2.setMapElement(CustomOrdinalRank.RANK, new ScoutValue(rank));
}
}
else
{
team.setMapElement(CustomOrdinalRank.TIE, new ScoutValue(0));
thisButton.setText("+");
for(int i = position + 1; i < teams.size(); i++) {
Team team2 = teams.get(i);
int rank = team2.getMapElement(CustomOrdinalRank.RANK).getInt();
rank++;
team2.setMapElement(CustomOrdinalRank.RANK, new ScoutValue(rank));
}
}
notifyDataSetChanged();
}
}
|
Java
|
UTF-8
| 384
| 2.109375
| 2
|
[] |
no_license
|
package model.inheritance.singletable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@DiscriminatorValue("BA")
public class BankAccount extends BillingDetails {
@Id
@GeneratedValue
protected Long id;
@NotNull
protected String account;
@NotNull
protected String bankName;
@NotNull
protected String swift;
}
|
Java
|
UTF-8
| 5,127
| 2.15625
| 2
|
[] |
no_license
|
/*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package thesis.thesis;
import haibison.android.lockpattern.LockPatternActivity;
import thesis.thesis.contentprovider.UsersDataContentProvider;
import thesis.thesis.database.UserTable;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
*
* @author Enno Eller
*
*/
public class EditUserActivity extends Activity {
private EditText currentPass;
private EditText newPass;
private EditText verifyNewPass;
private Button bChangePass;
private Button bChangePattern;
private String oldPass;
private char[] pattern;
private static final int REQ_CREATE_PATTERN = 1;
private Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user);
currentPass = (EditText) this.findViewById(R.id.enter_old_password);
newPass = (EditText) this.findViewById(R.id.enter_new_password);
verifyNewPass = (EditText) this.findViewById(R.id.verify_new_password);
receiveExtras(savedInstanceState);
bChangePass = (Button) this.findViewById(R.id.bChangePassword);
bChangePass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (TextUtils.isEmpty(currentPass.getText().toString())) {
Toast.makeText(getApplicationContext(),
"You need to enter the Current Password!",
Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(newPass.getText().toString())
|| !newPass.getText().toString()
.equals(verifyNewPass.getText().toString())) {
Toast.makeText(
getApplicationContext(),
"Enter New Password or make sure the New Password and verification match!",
Toast.LENGTH_SHORT).show();
} else {
String[] projection = { UserTable.COLUMN_PASSWORD };
Cursor cursor = getContentResolver().query(uri, projection,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
oldPass = cursor.getString(cursor
.getColumnIndexOrThrow(UserTable.COLUMN_PASSWORD));
}
if (oldPass.equals(currentPass.getText().toString())) {
ContentValues values = new ContentValues();
values.put(UserTable.COLUMN_PASSWORD, newPass.getText()
.toString());
getContentResolver().update(uri, values, null, null);
finish();
}
}
}
});
bChangePattern = (Button) this.findViewById(R.id.bChangePattern);
bChangePattern.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
changePattern();
}
});
}
/**
* Start activity for pattern changing.
*/
private void changePattern() {
if (TextUtils.isEmpty(currentPass.getText().toString())) {
Toast.makeText(getApplicationContext(),
"You need to enter the Current Password!",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(
LockPatternActivity.ACTION_CREATE_PATTERN, null,
getApplicationContext(), LockPatternActivity.class);
startActivityForResult(intent, REQ_CREATE_PATTERN);
}
}
/**
* Get extras if passed.
*
* @param savedInstanceState
*/
private void receiveExtras(Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
uri = (savedInstanceState == null) ? null : (Uri) savedInstanceState
.getParcelable(UsersDataContentProvider.CONTENT_ITEM_TYPE);
if (extras != null) {
uri = extras
.getParcelable(UsersDataContentProvider.CONTENT_ITEM_TYPE);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_user, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQ_CREATE_PATTERN: {
if (resultCode == RESULT_OK) {
pattern = data
.getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
String patternText = new String(pattern);
ContentValues values = new ContentValues();
values.put(UserTable.COLUMN_PATTERN, patternText);
getContentResolver().update(uri, values, null, null);
finish();
}
break;
}// REQ_CREATE_PATTERN
}
}
}
|
JavaScript
|
UTF-8
| 1,556
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import { RESET_STATE } from '../actions'
import capitalize from 'lodash/capitalize'
import orderBy from 'lodash/orderBy'
import filter from 'lodash/filter'
import moment from 'moment'
export default store => next => action => {
const { type } = action;
if (type === 'INIT') {
try {
const now = moment()
const storedEntities = JSON.parse(localStorage.getItem('entities'))
const filteredEntities = filter(storedEntities, function(entity) {
const entityDate = moment(entity.date)
const entityUpdatedAt = moment(entity.updatedAt)
return now.diff(entityDate, 'days') <= 0 && now.diff(entityUpdatedAt, 'days') < 7
})
const entities = orderBy(filteredEntities, 'updatedAt', 'desc')
localStorage.setItem('entities', JSON.stringify(entities))
let prevSearch
const data = entities.map((entity, i) => {
const date = moment(entity.date).diff(now, 'days') >= 0 ? moment(entity.date).toDate() : now
const formData = {
date: date,
city: capitalize(entity.city),
region: entity.region.length == 2 ? entity.region.toUpperCase() : capitalize(entity.region)
}
if (i == 0) {
entity.formData = formData
prevSearch = entity
}
return formData
})
if (prevSearch) {
store.dispatch({
type: RESET_STATE,
mostRecentSearch: prevSearch,
prevSearches: data
})
}
return;
} catch (e) {
console.log(e)
}
}
next(action);
}
|
Java
|
UTF-8
| 4,164
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
package com.conveyal.r5.streets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for tests of turn costs and restrictions..
*/
public abstract class TurnTest {
public StreetLayer streetLayer;
private static final Logger LOG = LoggerFactory.getLogger(TurnTest.class);
// center vertex index, n/s/e/w vertex indices, n/s/e/w edge indices (always starting from center).
public int vcenter, vn, vs, ve, vw, vne, vnw, vsw, en, es, ee, ew, ene, enw, esw;
public void setUp (boolean southernHemisphere) {
// generate a street layer that looks like this
// vnw vn
// | |
// | |/--vne
// vw--*-- ve
// | |
// vsw vs
// Edges have the same names (ew, ee, etc), and all start from the central vertex (except enw/vsw which starts at vw)
double latOffset = southernHemisphere ? -60 : 0;
streetLayer = new StreetLayer();
vcenter = streetLayer.vertexStore.addVertex(37.363 + latOffset, -122.123);
vn = streetLayer.vertexStore.addVertex(37.364 + latOffset, -122.123);
vs = streetLayer.vertexStore.addVertex(37.362 + latOffset, -122.123);
ve = streetLayer.vertexStore.addVertex(37.363 + latOffset, -122.122);
vne = streetLayer.vertexStore.addVertex(37.3631 + latOffset, -122.122);
vw = streetLayer.vertexStore.addVertex(37.363 + latOffset, -122.124);
vnw = streetLayer.vertexStore.addVertex(37.364 + latOffset, -122.124);
vsw = streetLayer.vertexStore.addVertex(37.362 + latOffset, -122.124);
en = streetLayer.edgeStore.addStreetPair(vcenter, vn, 15000, 4).getEdgeIndex();
ee = streetLayer.edgeStore.addStreetPair(vcenter, ve, 15000, 2).getEdgeIndex();
es = streetLayer.edgeStore.addStreetPair(vcenter, vs, 15000, 3).getEdgeIndex();
ew = streetLayer.edgeStore.addStreetPair(vcenter, vw, 15000, 1).getEdgeIndex();
ene = streetLayer.edgeStore.addStreetPair(vcenter, vne, 15000, 5).getEdgeIndex();
enw = streetLayer.edgeStore.addStreetPair(vw, vnw, 15000, 6).getEdgeIndex();
esw = streetLayer.edgeStore.addStreetPair(vw, vsw, 15000, 7).getEdgeIndex();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor(0);
do {
e.setFlag(EdgeStore.EdgeFlag.ALLOWS_PEDESTRIAN);
e.setFlag(EdgeStore.EdgeFlag.ALLOWS_CAR);
e.setFlag(EdgeStore.EdgeFlag.LINKABLE);
} while (e.advance());
streetLayer.indexStreets();
streetLayer.buildEdgeLists();
}
/** create a turn restriction */
public void restrictTurn (boolean onlyTurn, int from, int to, int... via) {
TurnRestriction restriction = new TurnRestriction();
restriction.fromEdge = from;
restriction.toEdge = to;
restriction.only = onlyTurn;
restriction.viaEdges = via;
LOG.debug("{}", restriction);
int ridx = streetLayer.turnRestrictions.size();
streetLayer.turnRestrictions.add(restriction);
streetLayer.edgeStore.turnRestrictions.put(restriction.fromEdge, ridx);
streetLayer.addReverseTurnRestriction(restriction, ridx);
}
/**
* Creates turn restriction without adding it to turnRestriction maps
*
* Used to create expected turn restrictions
*/
static TurnRestriction makeTurnRestriction(boolean onlyTurn, int from, int to) {
TurnRestriction turnRestriction = new TurnRestriction();
turnRestriction.fromEdge = from;
turnRestriction.toEdge = to;
turnRestriction.only = onlyTurn;
return turnRestriction;
}
/**
* Creates turn restriction without adding it to turnRestriction maps
*
* Used to create expected turn restrictions
*/
static TurnRestriction makeTurnRestriction(boolean onlyTurn, int from, int to,
int viaEdge) {
TurnRestriction turnRestriction = new TurnRestriction();
turnRestriction.fromEdge = from;
turnRestriction.toEdge = to;
turnRestriction.only = onlyTurn;
turnRestriction.viaEdges = new int[]{viaEdge};
return turnRestriction;
}
}
|
C#
|
UTF-8
| 681
| 2.78125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Empl
{
[Serializable]
public class Emp
{
[NonSerialized]
private string _Password = "abc@123";
private int _No;
public int No
{
get { return _No; }
set { _No = value; }
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string GetDetails()
{
return string.Format("No = {0}, Name = {1}", this.No, this.Name);
}
}
}
|
JavaScript
|
UTF-8
| 135
| 3.03125
| 3
|
[] |
no_license
|
let updateFunctions = [];
for (var i=0;i<2;i++)
{
updateFunctions.push(function(){return i;});
}
console.log(updateFunctions[0]());
|
Markdown
|
UTF-8
| 5,311
| 2.609375
| 3
|
[] |
no_license
|
1. >Есть скрипт: a=1 b=2 c=a+b d=$a+$b e=$(($a+$b)) -> Какие значения переменным c,d,e будут присвоены? Почему?
В переменной "c" будет храниться алгоритм сложения переменной "a" и "b"
В переменной "d" будет храниться суммирование значений переменных a и b, т.е. 3
В переменной "e" будет храниться суммирование значений переменных a и b, т.е. 3. Это синтаксис баша... без двойных скобок баш не поймет арифметику
#------------------------------------
###Доработка:
Переменной "c" будет присвоен набор символов a+b. Это стринговая строка, поэтому баш это будет воспринимать как обычные символы.
Переменной "d" будет присвоено 1+3. Произойдет конкатинация строки. Т.е. для баша - это строка, он склеит 3 значения: то, что лежит в переменной "a", "+" как символ, значение переменной "b"
Переменной "e" будет присвоено 3. Произойдет стандартная операция с целыми числами. В первых скобках будет происходить арифметика, а вторые скобки обернут все это в переменную и в итоге результат арифметики запишется в переменную "e"
#------------------------------------
2. >На нашем локальном сервере упал сервис и мы написали скрипт, который постоянно проверяет его доступность, записывая дату проверок до тех пор, пока сервис не станет доступным. В скрипте допущена ошибка, из-за которой выполнение не может завершиться, при этом место на Жёстком Диске постоянно уменьшается. Что необходимо сделать, чтобы его исправить
```#!/bin/bash
while ((1==1))
do
curl https://localhost:4757
if (($? != 0))
then
echo "`date` -> Service is Down" > curl.log
else
echo "`date` -> Service is UP" > curl.log
break
fi
sleep 30s
done
```
Можно еще с перенаправлением поиграться, мб более интересно было бы перезаписывать, а не дозаписывать.
3. >Необходимо написать скрипт, который проверяет доступность трёх IP: `192.168.0.1, 173.194.222.113, 87.250.250.242` по `80` порту и записывает результат в файл log. Проверять доступность необходимо пять раз для каждого узла.
первый вариант с пингом. Отправляем по 5 пакетов, но 80 порт не затронули, ибо пинг же...
```#!/bin/bash
hosts=("192.168.0.1" "173.194.222.113" "87.250.250.242")
for host in ${hosts[@]}; do
result=$(ping -c 5 -W 1 -q $host | grep transmitted)
pattern="0 received";
if [[ $result =~ $pattern ]]; then
echo "$host is down" >> result_chk-PING.log
else
echo "$host is up" >> result_chk-PING.log
fi
done
```
Попробуем сделать все тоже самое, только через `nc`, но только добавим кол-во переборов
```#!/bin/bash
for n in {1..5}; do {
hosts=("192.168.0.1" "173.194.222.113" "87.250.250.242")
port=("80")
for host in ${hosts[@]}; do
nc -z $host $port
if (($?==0)); then
echo "`date` -> $host:$port is available" >> result_chk-NC.log
else
echo "`date` -> $host:$port is Not_available" >> result_chk-NC.log
fi
done
}
done
```

4. >Необходимо дописать скрипт из предыдущего задания так, чтобы он выполнялся до тех пор, пока один из узлов не окажется недоступным. Если любой из узлов недоступен - IP этого узла пишется в файл error, скрипт прерывается
```#!/bin/bash
while ((1==1))
do {
hosts=("192.168.0.1" "173.194.222.113" "87.250.250.242")
port=("80")
for host in ${hosts[@]}; do
nc -z $host $port
if (($?==0)); then
echo "`date` -> $host:$port is available" > ok.log
else
echo "`date` -> $host:$port is Not_available" > error.log
break
fi
sleep 30s
done
}
done
```
|
JavaScript
|
UTF-8
| 1,509
| 3.71875
| 4
|
[] |
no_license
|
// var maxSubarrayProduct = function (nums) {
// n = nums.length;
// var max_ending_here = 1;
// var min_ending_here = 1;
// var max_so_far = 1;
// var flag = 0;
// if(nums.length === 1){
// return nums[0];
// }
// for(var i=0; i<n;i++) {
// if(nums[i] > 0){
// max_ending_here = max_ending_here * nums[i];
// min_ending_here = Math.min((min_ending_here * nums[i]), 1)
// flag = 1;
// }else if(nums[i] === 0){
// max_ending_here = 1;
// min_ending_here = 1;
// } else {
// temp = max_ending_here;
// max_ending_here = Math.max(min_ending_here * nums[i], 1);
// min_ending_here = temp *nums[i];
// }
// if (max_so_far < max_ending_here){
// max_so_far = max_ending_here;
// }
// }
// if (flag === 0 && max_so_far === 1) {
// return 0;
// }
// return max_so_far;
// }
// console.log(maxSubarrayProduct([-2, 0, -1]));
// test cases [-2, 3, -4]; [0,2] [3,-1,4] [-2, 3, -4] [-2, 0, -1] [-3, -1, -1]
// Time complexity : O(n)
var maxProduct = function (nums) {
var ans = -Infinity,
res = 1,
tmp = 1;
nums.forEach(function (item) {
var _res = res * item,
_tmp = tmp * item;
ans = Math.max(ans, _res, _tmp);
res = Math.max(_res, _tmp, 1);
tmp = Math.min(_res, _tmp, 1);
console.log(ans, _res, _tmp, res, tmp)
});
return ans;
};
console.log(maxProduct([-2, -3, -1 ]));
// Time complexity : O(n)
|
C
|
UTF-8
| 3,837
| 3.921875
| 4
|
[] |
no_license
|
/**
* Example of a main() function using a binary search tree (BST),
* reading information about plants to add one by one from the
* standard input.
*
* Course: High Performance Programming, Uppsala University
*
* Authors: Anastasia Kruchinina <anastasia.kruchinina@it.uu.se>
* Elias Rudberg <elias.rudberg@it.uu.se>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree_node
{
int ID;
char *name;
struct tree_node *left;
struct tree_node *right;
} node_t;
void print_bst(node_t *node)
{
if(node == NULL) {printf("Tree is empty!\n"); return;}
if (node != NULL) printf("%d %s: \t", node->ID, node->name);
if (node->left != NULL) printf("L%d,", node->left->ID);
if (node->right != NULL) printf("R%d", node->right->ID);
printf("\n");
if (node->left != NULL)
print_bst(node->left);
if (node->right != NULL)
print_bst(node->right);
}
void delete_tree(node_t **node)
{
//deletes node if it has no childs
if ((*node)->left != NULL) {
delete_tree(&(*node)->left);
} else if ((*node)->right != NULL) {
delete_tree(&(*node)->right);
} else {
/* both are null so we can free this node*/
free((*node)->name);
free((*node)->right);
free((*node)->left);
free((*node));
(*node)=NULL;
}
if ((*node) != NULL)
delete_tree(&(*node));
}
void insert(node_t **node, int ID, char *name)
{
//If passed node doesnt exists, ie is NULL then create the root
if((*node) == NULL){
*node=(node_t*)malloc(sizeof(node_t));
(*node)->ID = ID;
(*node)->name = strdup(name);
(*node)->right = NULL;
(*node)->left = NULL;
}else{
if((*node)->ID > ID){
//run insert with left node
node = &(*node)->left;
insert(node, ID, name);
}else if((*node)->ID < ID){
//run insert with right node
node = &(*node)->right;
insert(node, ID, name);
}else{
printf("Node with ID %d already exists\n", ID);
}
}
}
void search(node_t *node, int ID)
{
//checks ID within the node, if not goes to the childs, left if id smaller than ID
//right if id bigger.
int id=0;
while(id != ID && node != NULL){
id =node->ID;
printf("Current node id %d\n", id);
printf("Target %d\n", ID);
if (id < ID){
node = node->right;//go one deeper on the left
} else if (id > ID) {
node = node->left; //deeper on the right
} else {
id = ID;
}
}
if( node != NULL){
printf("Plat with ID %d, has name %s\n", id, node->name);
}else{
printf("Plant with ID Plat with ID %d does not exist", id);
}
}
int main(int argc, char const *argv[])
{
node_t *root = NULL;
while(1) {
printf("================================================\n");
printf("Please enter ID of plant to add (zero to stop): ");
int id;
int r = scanf("%d", &id);
if(r != 1 || id == 0) {
printf("Breaking loop now.\n");
break;
}
printf("OK, you entered id %d\n", id);
printf("Please enter name of plant to add: ");
char nameString[100]; /* Note: this will only work if the name entered is less than 100 characters long! */
r = scanf("%s", nameString);
if(r != 1) {
printf("Failed to read name, breaking loop now.\n");
break;
}
printf("OK, you have entered the following: id = %d nameString = %s\n", id, nameString);
printf("Now insterting that into the tree...\n");
insert(&root, id, nameString);
printf("Now printing the tree:\n");
print_bst(root);
}
int id;
printf("After loop.\n");
printf("What node do you want to look for? \n");
scanf("%d", &id);
printf("\n");
search(root, id);
delete_tree(&root);
printf("Deleting the tree.\n");
print_bst(root);
printf("================================================\n");
return 0;
}
|
Ruby
|
UTF-8
| 409
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
module Hirsute
# defines the interface for a Constraint object that can correct a field that would otherwise break a constraint
class Constraint
def correct(field_value)
end
end
# this just adds
class UniqueConstraint < Constraint
@counter = 1
def correct(field_value)
ret_val = field_value.to_s + @counter.to_s
@counter = @counter + 1
ret_val
end
end
end
|
Java
|
WINDOWS-1251
| 3,158
| 2.640625
| 3
|
[] |
no_license
|
package rtorrent.torrent;
import bittorrent.TorrentFile;
import java.io.File;
import java.io.IOException;
/**
* User: welvet
* Date: 18.05.2010
* Time: 18:53:01
*/
public class ActionTorrent extends ActionTorrentBase implements TorrentFacade{
private File file;
private transient TorrentFile torrentFile;
/**
* . .
* ,
*
* @param file
* @throws TorrentValidateException
*/
public ActionTorrent(File file) throws TorrentValidateException {
TorrentFile torrentFile = initTorrentFile(file);
this.file = file;
setHash(getTorrentFileHash());
setName(torrentFile.getName());
setNeedAdd(true);
}
/**
* ,
*
* @param file
* @return
* @throws TorrentValidateException
*/
private TorrentFile initTorrentFile(File file) throws TorrentValidateException {
try {
if ((file != null) && (torrentFile == null))
torrentFile = new TorrentFile(file);
if ((file != null))
if (!torrentFile.getFile().equals(file))
torrentFile = new TorrentFile(file);
} catch (IOException e) {
throw new TorrentValidateException(" ");
}
return torrentFile;
}
public TorrentFile getFile() throws TorrentValidateException {
return initTorrentFile(this.file);
}
public String getTorrentFileHash() throws TorrentValidateException {
return initTorrentFile(file).getHexHash().toUpperCase();
}
/**
*
* updateHashFromFile() ;
*
* @param file
* @throws TorrentValidateException
*/
public void setFile(File file) throws TorrentValidateException {
torrentFile = initTorrentFile(file);
this.file = file;
}
public void updateFile(ActionTorrent torrent) {
file = torrent.file;
}
public void updateAll(ActionTorrent torrent) {
updateInfo(torrent);
updateAction(torrent);
updateFile(torrent);
}
public void updateHashFromFile() throws TorrentValidateException {
setHash(getTorrentFileHash());
}
/**
* , RtorrentService
*/
public ActionTorrent() {
}
}
|
C++
|
SHIFT_JIS
| 2,216
| 3.078125
| 3
|
[] |
no_license
|
#ifndef SCENE_TRANSITION_H
#define SCENE_TRANSITION_H
#include "..\Widget.h"
class CTransition; // gWVNX.
class CSceneTransition
{
const float ALPHA_ADD_VALUE = 0.01f; // ߂̉Zl.
const float ALPHA_MAX = 1.0f;
private:
// tF[h̏.
enum class enFadeState
{
In, // tF[hC.
Out, // tF[hAEg.
Finish, // tF[hI.
} typedef EFadeState;
public:
CSceneTransition();
~CSceneTransition();
// CX^X̐.
static CSceneTransition* GetInstance()
{
static std::unique_ptr<CSceneTransition> pInstance = std::make_unique<CSceneTransition>();
return pInstance.get();
}
// .
static bool Init();
//`.
static void Render();
// tF[h.
static inline bool GetIsFade() { return GetInstance()->m_FadeState != EFadeState::Finish; }
// tF[hԎ擾.
static inline EFadeState GetFadeState() { return GetInstance()->m_FadeState; }
// tF[hCݒ.
static void SetFadeIn();
static void SetTexture(){ GetInstance()->m_FadeState = EFadeState::Out; }
// ƂȂeNX`̐ݒ.
static void SetDestTexture( ID3D11ShaderResourceView* pDestTexture );
// eNX`̐ݒ.
static void SetSrcTexture( ID3D11ShaderResourceView* pSrcTexture );
private:
// XV.
void Update();
// XvCgݒ.
bool SpriteSetting();
private:
std::unique_ptr<CTransition> m_pTransition; // gWV.
ID3D11ShaderResourceView* m_pDestTexture; // ƂȂeNX`.
ID3D11ShaderResourceView* m_pSrcTexture; // eNX`.
EFadeState m_FadeState; // tF[h̏.
float m_NowAlpha; // ݂̓ߒl.
bool m_IsFade; // tF[h.
private:
//Rs[E[uRXgN^AZq̍폜.
CSceneTransition( const CSceneTransition & ) = delete;
CSceneTransition( CSceneTransition && ) = delete;
CSceneTransition& operator = ( const CSceneTransition & ) = delete;
CSceneTransition& operator = ( CSceneTransition && ) = delete;
};
#endif // #ifndef SCENE_TRANSITION_H.
|
Markdown
|
UTF-8
| 8,441
| 3
| 3
|
[
"MIT"
] |
permissive
|
+++
title = "What can the labor flow of 500 million people on LinkedIn tell us about the structure of the global economy?"
date = 2019-08-02T20:53:37-04:00
draft = true
# Authors. Comma separated list, e.g. `["Bob Smith", "David Jones"]`.
authors = ["Jaehyuk Park"]
# Tags and categories
# For example, use `tags = []` for no tags, or the form `tags = ["A Tag", "Another Tag"]` for one or more tags.
tags = ['linkedin', 'labor market', 'global economy', 'network science',
'future of work', 'labor flow network']
categories = []
# Featured image
# Place your image in the `static/img/` folder and reference its filename below, e.g. `image = "example.jpg"`.
# Use `caption` to display an image caption.
# Markdown linking is allowed, e.g. `caption = "[Image credit](http://example.org)"`.
# Set `preview` to `false` to disable the thumbnail in listings.
[header]
image = "linkedin_featured_image.png"
caption = ""
preview = true
+++
This post is what I wrote on *LinkedIn* as [a blog post](https://www.linkedin.com/pulse/what-can-labor-flow-500-million-people-linkedin-tell-us-jaehyuk-park/).
You can find the original article here: [Global labor flow network reveals the hierarchical organization and dynamics of geo-industrial clusters](https://www.nature.com/articles/s41467-019-11380-w)
Recent advancement of information technology, such as artificial intelligence and robotics, makes business owners, city planners, and policy makers challenging to prepare for the future of the labor market. Between all the news articles and company reports depicting either utopian or dystopian future of labor they feel lost, but at the same time, feel pressured to be the next Silicon Valley, as the competition for the Amazon's second headquarters showed. How can we prepare for our journey to the future of labor market more strategically? Similar to the wars in human history, it should be begun with having a good map to visualize the landscape of the whole economy.
Unfortunately, visualizing the landscape of the global economy is much harder than drawing a map of geographical landscape. The global economy is a complex system of heterogeneous level of agents - worker, firm, and country - and keeps evolving, so it is difficult to capture a snapshot of the whole structure. Also, the economic structure is influenced by both geographical and industrial constraints, we cannot assume the similar structure would be appealed for the same industry in different regions, and vice versa.
One of the most popular concepts for policy makers and business economists to understand the structure of the global economy is "cluster", the geographical agglomeration of interconnected firms such as Silicon Valley, Wall Street, and Hollywood. By studying those well-known clusters, we become to understand the advantage of participating in a geo-industrial cluster for firms and how it is related to the economic growth of a region.
However, the existing definition of geo-industrial cluster is not systematic enough to reveal the whole picture of the global economy. Often, after defining as a group of firms in a certain area, the geo-industrial clusters are considered as independent to each other. As we should consider the interaction between accounting team and marketing team to understand the organizational structure of a firm, the relationships among those geo-industrial clusters are the essential part of the whole picture.
Also, since geo-industrial clusters are related to each other, they can't be defined just in one level. Rather, they should be defined in multiple levels in the hierarchical ladder of the global economy. Again, in the example of a firm, a core data science team can be a part of an analytics team, separated from accounting team, but also consists of other sub-teams based on its sub-projects. Thus, we need to understand the geo-industrial clusters in the view of hierarchical structure, which allows us to map them in different scales based on our interests.
In this new study, my colleagues and I at Indiana University -- with support from LinkedIn -- have finally overcome these limitations by defining geo-industrial clusters through labor flow and constructing a global labor flow network from LinkedIn’s individual-level job history dataset. Our access to this data was made possible by our selection as one of 11 teams selected to participate in the [LinkedIn Economic Graph Challenge](http://archive.news.indiana.edu/releases/iu/2015/06/iu-linkedin-project.shtml).
The transitioning of workers between jobs and firms -- also known as labor flow -- is considered central in driving firms towards geo-industrial clusters due to knowledge spillover and labor market pooling. In response, we mapped the cluster structure of the world economy based on labor mobility between firms during the last 25 years, constructing a “labor flow network.”
To do this, we leverage LinkedIn’s data on professional demographics and employment histories from more than 500 million people between 1990 and 2015. The network, which captures approximately 130 million job transitions between more than 4 million firms, is the first-ever flow network of global labor.
The resulting “map” allows us to:
- identify geo-industrial clusters systematically and organically using network community detection
- verify the importance of region and industry in labor mobility
compare the relative importance between the two constraints in different hierarchical levels, and
- reveal the practical advantage of the geo-industrial cluster as a unit of future economic analyses.
- show a better picture of what industry in what region leads the economic growth of the industry or the region, at the same time
- find out emerging and declining skills based on the representativeness of them in growing and declining geo-industrial clusters
As the first attempt, in our best knowledge, to map the hierarchical structure of the global economy our approach suggests a lot of possible directions for future studies including the relationship between different skills, the job mobility pattern of workers based on their skill similarities, the role of skill influx on the growth of a geo-industrial cluster and etc.
Furthermore, we expect this study will provide a powerful foundation for further systematic analysis of geo-industrial clusters in the context of business strategy, urban economics, regional economics, and international development fields - as well as providing useful insights for policymakers and business leaders.
{{< figure library="true" src="linkedin_blog_figure.png" title="A caption" lightbox="true" >}}
**Figure 1**. **A**, A labor flow network is comprised of organizations (nodes) and the flows of people between them (directed, weighted edges) as defined by historical records of job changes. **B and C**, Two illustrative examples of geo-industrial clusters defined as hierarchically-organized geo-industrial clusters in the labor flow network with high intra-cluster talent mobility. **D and E**, A transition matrix of labor flows between LinkedIn users’ self- reported industries (normalized with the expected transition volume) highlights labor flows within and between macroeconomic sectors. The effect of geographic proximity on labor mobility is also evident in the matrix of labor flows between US states. **F**, The large-scale organization of geo-industrial clusters in the labor flow network. Each circle represents a geo-industrial cluster, with size proportional to its number of employees. The colors represent the highest-level community membership. **G–J**, Two examples of hierarchical sub-structures in the labor flow network are illustrated. Each circle represents a firm and the bar charts show the reduction in industry and region entropy within the cluster as a proportion of the parent cluster’s entropy. **K–N**, The influx of educated labor force is linked to the growth of geo-industrial clusters. The horizontal axis represents the five-year trend in college-degree labor flux from 2010 to 2014. Similarly, the vertical axis represents the five-year trend in log-scaled market capitalization within the cluster over time. **K**, The trends for individual firms, **L**, The trends for geographical regions, **M**, The trends for industries, and **N**, The trends for geo-industrial clusters, which displays the strongest relationship.
|
Markdown
|
UTF-8
| 2,973
| 3.359375
| 3
|
[] |
no_license
|
# 第6回 価値反復法の導入
## 報酬の導入
- 迷路課題であればゴールをした時に、ロボットの歩行であれば転ばずに歩けている間、毎ステップ**報酬**を与える
- 時刻tでもらえる報酬を即時報酬(immediate reward)$$R_t$$と呼ぶ -> $$R_t$$は課題に合わせて自分で設定
- 今後未来にわたって得られるであろう報酬の合計を報酬和$$G_t$$と呼ぶ -> $$G_t = R_{t+1} + R_{t+2} + R_{t+3} + ...$$
- **時間割引**を考慮した割引報酬和(discounted total reward)$$G_t$$ -> $$G_t = R_{t+1} + \gammaR_{t+2} + \gamma^2R_{t+3} + ...$$
## 価値の導入
- **行動価値**(action Value)と**状態価値**(state Value)を定義
- ゴールにたどり着いた瞬間Rt=1がもらえると設定
- 行動価値(S7にいる場合の例)
- 行動価値は行動価値観数$$Q^{\pi}(s, a)$$と書かれる
- もし、行動a=右だった場合、次のステップでゴールにたどりつき報酬Rt+1=1を手にすることができる
- 上記を関数で表すと、$$Q^{\pi}(s=7, a=1)=1$$
- もし、行動a=上だった場合、S7→S4→S7→S8と言うように2ステップ余分に時間がかかる
- 上記を関数で表すと、$$Q^{\pi}(s=7, a=0)=\gamma^2\times1$$
- ゴールにたどり着くために2ステップ多めにかかるのでその時間分だけ割り引いた報酬が得られる
- 状態価値
= 状態sにおいて方策πにしたがって行動することで、その後将来にわたって得られることが期待される割引報酬和Gt
- 状態sの状態価値観数を$$V^{\pi}(s)$$と書く
- エージェントがS7にいる場合、右に移動すればゴールして報酬1を手に入れることができるので、$$V^{\pi}(s=7)=1$$
- エージェントがS4にいる場合、S7に移動して右に移動すればゴールできるので、$$V^{\pi}(s=4)=\gamma\times1$$
- S4にいる場合、V(s=4)=Rt+1 + γV(s=7)と表現することができる(πは省略/ゴール以外では報酬得られないのでRt+1=0)
## ベルマン方程式とマルコフ過程
- 価値観数を一般的な書き方で表した式(連載ページ参照)を**ベルマン方程式**と呼ぶ
- 状態sでの状態価値Vは、右辺が最も大きくなる行動aをとった時の期待値
- Rs,aは状態sで行動aをとった時に得られる即時報酬(ゴールにたどり着く場合以外は全部0)
- s(s,a)状態sで行動aを採用して移動した先の新たな状態sを示す
- ベルマン方程式が成り立つための前提条件 -> **マルコフ決定過程**(Markov Decision Process)
- 次のステップの状態st+1が現在の状態sと選択した行動aで確定するシステム
## 方策と価値の決定方法
- 行動価値、状態価値を決めるアルゴリズム -> Sarsa、Q学習、モンテカルロ法
- 方策は行動価値に基づいて決める
|
Python
|
UTF-8
| 593
| 4.3125
| 4
|
[] |
no_license
|
print("Python interprets any non-zero value as True. None and 0 are interpreted as False.")
while 20:
print("Works with int")
break
while "string":
print("Works with string")
break
a = None
while a:
print("Works with None")
else:
print("Does not Work with None")
while 0:
print("Works with 0")
else:
print("Does not Work with 0")
print("\nA while loop's else part runs if no break occurs. even if condition is false always")
print("\n\n")
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
|
Python
|
UTF-8
| 135
| 3.09375
| 3
|
[] |
no_license
|
import sys
m = int(sys.stdin.readline().rstrip('\n'))
if m == 2:
print(29)
elif m in [4,6,9,11]:
print(30)
else:
print(31)
|
Java
|
UTF-8
| 6,551
| 2.125
| 2
|
[] |
no_license
|
package gui;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import com.sun.org.apache.bcel.internal.generic.NEW;
import Entity.User;
import client.ClientConsole;
import common.Message;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
/**
* This class represents a controller for the gui ProfileSettings
* @author mahmoud odeh
*
*/
public class ProfileSettingsController implements Initializable{
public static ProfileSettingsController acainstance;
@FXML
private TextField txtFirstName;
@FXML
private ImageView imageProfile;
@FXML
private TextField txtLastName;
@FXML
private TextField txtID;
@FXML
private TextField txtEmail;
@FXML
private Button btnUpdate;
@FXML
public Label status;
@FXML
private Button btnPasswordChange;
@FXML
private Label labelPassword;
@FXML
private Label labelConfirm;
@FXML
private TextField txxPassword;
@FXML
private TextField txtConfirm;
@FXML
private Button btnSetPassword;
@FXML
private static SplitPane splitpane;
private FXMLLoader loader;
private static User user;
private static String userrank;
public static ProfileSettingsController ProfileSetting;
public static Stage primaryStage;
private AnchorPane lowerAnchorPane;
public ClientConsole details= new ClientConsole("localhost", 5555);
ArrayList<User> userdetails= new ArrayList<User>();
User detailsUser;
/**
*
* @param splitpane this parameter from the type splitpane
* @param user this paramater from the type user that contains id,firtstname,lastname,email,username,password,rank,clienttype,status,image
* @param userJob this parameter from the type string
*/
public void start(SplitPane splitpane, User user,String userJob) {
this.splitpane=splitpane;
this.user=user;
this.userrank=userJob;
primaryStage=LoginController.primaryStage;
try{
loader = new FXMLLoader(getClass().getResource("/gui/ProfileSetting.fxml"));
lowerAnchorPane = loader.load();
splitpane.getItems().set(1, lowerAnchorPane);
} catch(Exception e) {
e.printStackTrace();
}
}
/**
*
* @param user this paramater from the type user that contains id,firtstname,lastname,email,username,password,rank,clienttype,status,image
*/
public void Acceptor(User user) {
detailsUser=new User(user.getId(), user.getFirstname(), user.getLastname(), user.getEmail(), user.getUsername(), user.getPassword(), user.getRank(),user.getClientType(), user.getStatus(),user.getImage());
}
/**
* This methode get notification from the chatclient
* @param event event of button
*/
@FXML
void UpdateDetails(ActionEvent event) {
if(txtID.getText().isEmpty() ||txtEmail.getText().isEmpty()|| txtFirstName.getText().isEmpty()|| txtLastName.getText().isEmpty())
{
Platform.runLater(new Runnable() {
@Override
public void run() {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setAlertType(AlertType.INFORMATION);
alert.setContentText("There is missing field");
alert.show();
}
});
}
else {
User user=new User(txtID.getText(), txtFirstName.getText(), txtLastName.getText(), txtEmail.getText(), null, null, null, null,null,null);
ProfileSettingsController.acainstance.details.accept(new Message(5, user));;
Platform.runLater(new Runnable() {
@Override
public void run() {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setAlertType(AlertType.INFORMATION);
alert.setContentText("Details updated!");
alert.show();
}
});
}
}
/**
* This methode give the user accesbility to change the password
* @param event event of button
*/
@FXML
void ChangePassword(ActionEvent event) {
btnPasswordChange.setVisible(true);
labelPassword.setVisible(true);
labelConfirm.setVisible(true);
txxPassword.setVisible(true);
txtConfirm.setVisible(true);
btnSetPassword.setVisible(true);
}
/**
* This methode make the user to reset the password
* @param event event of button
*/
@FXML
void SetPassword(ActionEvent event) {
System.out.println(txxPassword.getText());
System.out.println(txtConfirm.getText());
if(txxPassword.getText().isEmpty() || txtConfirm.getText().isEmpty())
{
Platform.runLater(new Runnable() {
@Override
public void run() {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setAlertType(AlertType.INFORMATION);
alert.setContentText("There is missing field");
alert.show();
}
});
}
else if(txxPassword.getText().equals(txtConfirm.getText()))
{
User user2=new User(txtID.getText(), txtFirstName.getText(), txtLastName.getText(), txtEmail.getText(), null, txxPassword.getText(), null, null,null,null);
ProfileSettingsController.acainstance.details.accept(new Message(12, user2));;
Alert alert = new Alert(AlertType.INFORMATION);
alert.setAlertType(AlertType.INFORMATION);
alert.setContentText("Password Changes Successfully!!");
alert.show();
}
else {
Alert alert = new Alert(AlertType.ERROR);
alert.setAlertType(AlertType.ERROR);
alert.setContentText("Password not match");
alert.show();
}
}
/**
* This methode get notification from the chatclient
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
acainstance = this;
details.accept(new Message(4, null));
txtID.setText(detailsUser.getId());
txtFirstName.setText(detailsUser.getFirstname());
txtLastName.setText(detailsUser.getLastname());
txtEmail.setText(detailsUser.getEmail());
}
}
|
C#
|
UTF-8
| 3,122
| 2.96875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Serialization;
using MaksDipl.Models;
using MaksDipl.View;
namespace MaksDipl.Services
{
/// <summary>
/// Класс работы с данными
/// </summary>
public static class BaseDataStore
{
/// <summary>
/// Путь к файлу с данными
/// </summary>
public const string DATA_FOLDER_PATH = "data\\";
/// <summary>
/// Список всех элементов
/// </summary>
public static List<Element> Elements { get; set; }
/// <summary>
/// Список всех типов элементов
/// </summary>
public static Dictionary<int, string> ElementTypes { get; set; }
/// <summary>
/// Создание списка типов элементов
/// </summary>
private static void CreateDictionary()
{
int i = 0;
ElementTypes = new Dictionary<int, string>();
StreamReader sr = new StreamReader(DATA_FOLDER_PATH + "elements.txt");
while (!sr.EndOfStream)
{
i++;
ElementTypes.Add(i, sr.ReadLine());
}
}
/// <summary>
/// Добавить элемент в базу
/// </summary>
/// <param name="el"></param>
public static void AddElement(Element el)
{
Elements.Add(el);
SaveData();
}
/// <summary>
/// Удалить элемент из базы
/// </summary>
/// <param name="el"></param>
public static void RemoveElement(Element el)
{
Elements.Remove(Elements.First(c => c.Id == el.Id));
SaveData();
}
/// <summary>
/// Сохранить все данные в файл
/// </summary>
public static void SaveData()
{
XmlSerializer formatter = new XmlSerializer(typeof(List<Element>));
using (FileStream fs = new FileStream(DATA_FOLDER_PATH+"db.xml", FileMode.Create))
{
formatter.Serialize(fs, Elements);
}
}
/// <summary>
/// Загрузить данные из файла
/// </summary>
public static void LoadData()
{
CreateDictionary();
Elements = new List<Element>();
XmlSerializer formatter = new XmlSerializer(typeof(List<Element>));
using (FileStream fs = new FileStream(DATA_FOLDER_PATH+"db.xml", FileMode.OpenOrCreate))
{
try
{
Elements=(List<Element>)formatter.Deserialize(fs);
}
catch (Exception e)
{
//ignore
MessageBox.Show(e.Message);
}
}
}
}
}
|
Java
|
UTF-8
| 2,398
| 2.453125
| 2
|
[] |
no_license
|
package com.polymart.service.impl;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import com.polymart.dao.IHoaDonNhapHangDAO;
import com.polymart.dao.impl.HoaDonNhapHangDAO;
import com.polymart.model.HoaDonNhapHangModel;
import com.polymart.service.IHoaDonNhapHangService;
public class HoaDonNhapHangService implements IHoaDonNhapHangService {
private static IHoaDonNhapHangDAO hoaDonNhapHangDAO = new HoaDonNhapHangDAO();
private static List<HoaDonNhapHangModel> lstHoaDonNhapHangModels = hoaDonNhapHangDAO.findAll();
@Override
public List<HoaDonNhapHangModel> findAll() {
Collections.reverse(lstHoaDonNhapHangModels);
return lstHoaDonNhapHangModels;
}
@Override
public HoaDonNhapHangModel save(HoaDonNhapHangModel hoaDonNhapHangModel) {
if (hoaDonNhapHangModel != null) {
int id = hoaDonNhapHangDAO.save(hoaDonNhapHangModel);
hoaDonNhapHangModel = hoaDonNhapHangDAO.findById(id);
if (hoaDonNhapHangModel != null) {
lstHoaDonNhapHangModels.add(hoaDonNhapHangModel);
return hoaDonNhapHangModel;
}
}
return null;
}
@Override
public boolean remove(HoaDonNhapHangModel hoaDonNhapHangModel) {
if (hoaDonNhapHangModel != null) {
if (hoaDonNhapHangDAO.remove(hoaDonNhapHangModel) > 0) {
lstHoaDonNhapHangModels.remove(hoaDonNhapHangModel);
return true;
}
}
return false;
}
@Override
public HoaDonNhapHangModel findById(Integer id) {
var ref = new Object() {
HoaDonNhapHangModel hoaDonNhapHangModel = null;
};
lstHoaDonNhapHangModels.forEach(e -> {
if (e.getId().equals(id)) {
ref.hoaDonNhapHangModel = e;
}
});
return ref.hoaDonNhapHangModel;
}
@Override
public List<HoaDonNhapHangModel> filterByDate(Timestamp timestamp) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
return lstHoaDonNhapHangModels.stream()
.filter(e -> simpleDateFormat.format(e.getNgayNhap()).equals(simpleDateFormat.format(timestamp)) && e.isRemove())
.collect(Collectors.toList());
}
}
|
C#
|
UTF-8
| 1,791
| 2.796875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
using System;
using Common.Schema;
namespace Common.SchemaWrapper
{
public class Piece
{
private Schema.Piece schemaPiece;
public Piece()
{
this.SchemaPiece = new Schema.Piece();
}
public Piece(ulong id, PieceType type, DateTime timeStamp)
{
this.SchemaPiece = new Schema.Piece();
Id = id;
Type = type;
TimeStamp = timeStamp;
IsCarried = false;
}
public Schema.Piece SchemaPiece
{
get { return schemaPiece; }
private set { schemaPiece = value; }
}
public ulong Id
{
get { return schemaPiece.id; }
set { schemaPiece.id = value; }
}
public PieceType Type
{
get { return schemaPiece.type; }
set { schemaPiece.type = value; }
}
public DateTime TimeStamp
{
get { return schemaPiece.timestamp; }
set { schemaPiece.timestamp = value; }
}
public ulong? PlayerId
{
get { return schemaPiece.playerIdSpecified ? schemaPiece.playerId : (ulong?)null; }
set
{
if (value.HasValue)
{
schemaPiece.playerIdSpecified = true;
schemaPiece.playerId = value.Value;
}
else
{
schemaPiece.playerIdSpecified = false;
schemaPiece.playerId=UInt64.MaxValue;
}
}
}
public Location Location { get; set; }
public bool IsCarried { get; set; }
}
}
|
C#
|
UTF-8
| 3,486
| 2.953125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Xml.Serialization;
namespace LauncherLesAuDacieuX
{
[Serializable]
public class Config
{
/// <summary>
/// Le nom du serveur à afficher
/// </summary>
public string ServerName;
/// <summary>
/// Le port du serveur de jeu
/// </summary>
public int ServerPort;
/// <summary>
/// L'ip du serveur de jeu
/// </summary>
public string ServerIp;
/// <summary>
/// Liste des Mods
/// </summary>
public List<Mod> Mods = new List<Mod>();
/// <summary>
/// AppData pour tous les utilisateurs
/// </summary>
public static string CommonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
public const string AppName = "ADX";
public static string CommonAppFolderPath => Path.Combine(CommonAppData,AppName);
internal static string FilePath = Path.Combine(CommonAppFolderPath, "test.cfg");
/// <summary>
/// Sauvegarde de l'objet courant au format XML
/// </summary>
/// <param name="path"></param>
public void Save()
{
if (!Directory.Exists(CommonAppFolderPath))
Directory.CreateDirectory(CommonAppFolderPath);
XmlSerializer serializer = new XmlSerializer(typeof(Config));
serializer.Serialize(File.OpenWrite(FilePath), this);
}
/// <summary>
/// Chargement d'un objet config
/// </summary>
/// <returns></returns>
public static Config LoadLocal()
{
if(!File.Exists(FilePath))
return new Config();
return DeserializeInternal(File.OpenRead(FilePath));
}
/// <summary>
/// Chargement d'un objet config en TCP
/// </summary>
/// <param name="hostname"></param>
/// <param name="port"></param>
/// <returns></returns>
public static Config LoadRemote(string uri)
{
var request = WebRequest.Create(uri);
var stream = request.GetResponse().GetResponseStream();
return DeserializeInternal(stream);
}
/// <summary>
/// Fonction de deserialisation interne
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
internal static Config DeserializeInternal(Stream stream)
{
XmlSerializer serializer = new XmlSerializer(typeof(Config));
return (Config)serializer.Deserialize(stream);
}
/// <summary>
/// Recupère la liste de mod a mettre a jour
/// </summary>
/// <param name="oldConfig"></param>
/// <param name="newConfig"></param>
/// <returns></returns>
public static List<Mod> ModsDifferencies(Config oldConfig, Config newConfig)
{
var modsToUpdate = new List<Mod>(newConfig.Mods);
foreach (var oldMod in oldConfig.Mods)
{
foreach (var newMod in newConfig.Mods)
{
if (oldMod.Version == newMod.Version)
modsToUpdate.Remove(newMod);
}
}
return modsToUpdate;
}
}
}
|
Markdown
|
UTF-8
| 856
| 2.859375
| 3
|
[
"ISC"
] |
permissive
|
# `locations(query, [opt])`
`query` must be an string (e.g. `'Alexanderplatz'`).
With `opt`, you can override the default options, which look like this:
```js
{
fuzzy: true // find only exact matches?
, results: 10 // how many search results?
, stations: true
, addresses: true
, poi: true // points of interest
}
```
## Response
With `query = 'Alexanderplatz'` and `results: 2`, the response looks like this:
```js
[{
type: 'station',
id: '900000100003',
name: 'S+U Alexanderplatz',
coordinates: {latitude: 52.521508, longitude: 13.411267},
products: {
suburban: true,
subway: true,
tram: true,
bus: true,
ferry: false,
express: false,
regional: true
}
}, {
type: 'poi',
id: '9980709',
name: 'Berlin, Holiday Inn Centre Alexanderplatz****',
coordinates: {latitude: 52.523549, longitude: 13.418441}
}]
```
|
Java
|
UTF-8
| 1,170
| 2.1875
| 2
|
[] |
no_license
|
package freem.android;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super(Config.GCM_SENDER_ID);
}
@Override
protected void onRegistered(Context context, String regId) {
SharedPreferences prefs = getSharedPreferences("registration", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("gcm_id", regId);
editor.commit();
}
@Override
protected void onMessage(Context context, Intent intent) {
// Recupera il tipo della notifica.
String type = intent.getStringExtra("type");
if ("message".equals(type)) {
// Avvia il servizio per il download dei nuovi messaggi.
Intent intent2 = new Intent(this, RetrieveMessagesService.class);
intent2.putExtra("failed_attempts", 0);
startService(intent2);
}
}
@Override
protected void onUnregistered(Context context, String regId) {
}
@Override
protected void onError(Context context, String regId) {
}
}
|
Shell
|
UTF-8
| 3,253
| 2.921875
| 3
|
[] |
no_license
|
#!/bin/bash
xterm -geometry 500x500 -bg black -fg black -e "exit"
yad --center --image="/usr/share/images/conectando.jpg" --no-buttons --auto-close --no-escape --undecorated &
timeout 1 ping -q -i 0.2 -c 2 172.18.20.200
ping="$?"
nc -z -w5 172.18.20.200 8000
nc="$?"
killall -9 yad
if [ "$ping" = "2" ]; then
yad --center --image="/usr/share/images/conexao-servidor-fora.jpg" --button="Tentar novamente":0 --button="Desligar":"systemctl poweroff -i" --buttons-layout=center --no-escape --timeout=60 --timeout-indicator=bottom
if [ "$?" = "0" ]; then
yad --center --image="/usr/share/images/conectando.jpg" --no-buttons --auto-close --no-escape --undecorated &
sudo dhclient ens3
/home/aluno/.xsession
fi
elif [ "$nc" = "0" ]; then
test -e /home/aluno/.jpmsb
if [ "$?" = "0" ]; then
echo "Arquivo .jpmsb encontrado!!"
conteudo_arquivo=$(cat /home/aluno/.jpmsb)
if [ "$conteudo_arquivo" = "rancher" ]; then
echo "Restaurando ambiente sem compartilhamento de som"
yad --center --image="/usr/share/images/conectando-ambiente-trabalho.jpg" --no-buttons --auto-close --no-escape --undecorated &
sleep 30 && killall -9 yad &
x2goclient --hide --sessionid=rancher
elif [ "$conteudo_arquivo" = "rancher-som" ]; then
echo "Restaurando ambiente com compartilhamento de som"
yad --center --image="/usr/share/images/conectando-ambiente-trabalho.jpg" --no-buttons --auto-close --no-escape --undecorated &
/opt/SoundWireServer/SoundWireServer &
sleep 30 && killall -9 yad &
x2goclient --hide --sessionid=rancher-som
fi
elif [ "$?" = "1" ]; then
echo "Início normal"
xterm -geometry 500x500 -bg black -fg black -e "exit"
yad --center --button="Cancelar":1 --button="Entendido":0 --image='/usr/share/images/informativo600.jpg' --timeout=240 --timeout-indicator=bottom
if [ "$?" = "0" ]; then
yad --center --image="/usr/share/images/informativo-audio-permitir.jpg" --button="Recusar":1 --button="Permitir":0
if [ "$?" = "0" ]; then
echo "rancher-som" > /home/aluno/.jpmsb
yad --center --image="/usr/share/images/conectando-ambiente-trabalho.jpg" --no-buttons --auto-close --no-escape --undecorated &
/opt/SoundWireServer/SoundWireServer &
sleep 30 && killall -9 yad &
x2goclient --hide --sessionid=rancher-som
elif [ "$?" = "1" ]; then
echo "rancher" > /home/aluno/.jpmsb
yad --center --image="/usr/share/images/conectando-ambiente-trabalho.jpg" --no-buttons --auto-close --no-escape --undecorated &
sleep 30 && killall -9 yad &
x2goclient --hide --sessionid=rancher
fi
elif [ "$?" = "1" ]; then
systemctl poweroff
fi
fi
elif [ "$ping" = "0" ] && [ "$nc" = "1" ]; then
yad --center --image="/usr/share/images/conexao-porta-fora.jpg" --button="Ok":"systemctl poweroff -i" --buttons-layout=center --no-escape --timeout=60 --timeout-indicator=bottom
fi
|
Swift
|
UTF-8
| 825
| 2.875
| 3
|
[] |
no_license
|
//
// ForecastAPI.swift
// BikeOrNot
//
// Created by Joel Bell on 5/19/16.
// Copyright © 2016 Joel Bell. All rights reserved.
//
import Foundation
class ForecastAPI {
class func getLocalWeatherData(_ completion: @escaping (_ results: NSDictionary) -> Void) {
let url = URL(string: "https://api.forecast.io/forecast/fd6c971c5244ead13ee4229060a2af9f/39.8255502,-74.1893672")!
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
print(jsonDictionary)
completion(jsonDictionary)
} catch {
print("something went wrong")
}
}) .resume()
}
}
|
Shell
|
UTF-8
| 800
| 3.15625
| 3
|
[] |
no_license
|
#!/usr/bin/env sh
# clang++ main.cpp # results in:
# /usr/bin/ld: /tmp/main-6066d4.o: in function `main':
# main.cpp:(.text+0x2d): undefined reference to `MakeItRain()'
# /usr/bin/ld: main.cpp:(.text+0x32): undefined reference to `MakeItSunny()'
# clang: error: linker command failed with exit code 1 (use -v to see invocation)
# compile library with c++17 target (don't forget the "-c"!)
c++ -std=c++17 -c tools.cpp -o tools.o
# demangle compiled library
# nm -gC tools.o
# create an archive of multiple library files
ar rcs libtools.a tools.o
# compile again, but this time, tell the linker where to
# find the symbols.
# "-L" is the base path to look
# -ltools means to look for library "tools"
# then, compile to main.o
c++ -std=c++17 main.cpp -L . -ltools -o main
# DONE! Run with "./main"
|
SQL
|
UTF-8
| 791
| 3.59375
| 4
|
[] |
no_license
|
CREATE TABLE User (
username varchar(200) PRIMARY KEY,
fullname varchar(200)
);
CREATE TABLE Room (
room_id integer auto_increment PRIMARY KEY,
name varchar(200)
);
CREATE TABLE Participant (
participant_id integer auto_increment PRIMARY KEY,
room_id integer NOT NULL,
name varchar(200),
username varchar(200),
FOREIGN KEY(Room_id) REFERENCES Room(room_id),
FOREIGN KEY(username) REFERENCES User(username)
);
CREATE TABLE Message (
message_id integer auto_increment PRIMARY KEY,
room_id integer NOT NULL,
sender integer NOT NULL,
recipient integer NOT NULL,
message TEXT NOT NULL,
FOREIGN KEY(Room_id) REFERENCES Room(room_id),
FOREIGN KEY(sender) REFERENCES Participant(participant_id),
FOREIGN KEY(recipient) REFERENCES Participant(participant_id)
);
|
PHP
|
UTF-8
| 1,449
| 2.71875
| 3
|
[] |
no_license
|
<?php
namespace App\Http\Middleware;
use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use App\Models\Customer;
class CustomerAuthJwtMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$token = $request->bearerToken();
if (!$token) {
return response()->json(['error' => 'Token is not provided!'], 401);
}
try {
# decoded token
$credentials = JWT::decode($token, env('JWT_SECRET'), ['HS256']);
} catch (ExpiredException $e) {
# if token is expired
return response()->json(['error' => 'Token is expired!'], 400);
} catch (\Exception $e) {
# if error when decoding
return response()->json(['error' => 'Error when decoding token!'], 400);
}
# if is not customer
if ($credentials->level != 'customer') {
return response()->json(['error' => 'Unauthorized!'], 401);
}
# extract data
$customer = Customer::find($credentials->sub);
if (!$customer) {
return response()->json(['error' => 'User not found!'], 400);
}
# FIXME: cari cara lain
$request->user = $customer;
return $next($request);
}
}
|
Go
|
UTF-8
| 1,290
| 3.125
| 3
|
[] |
no_license
|
package card
import (
"bank/pkg/bank/types"
"fmt"
)
func ExampleWithdraw_positive() {
card := types.Card{Balance: 20_000_00, Active: true}
result := Withdraw(&card, 10_000_00)
fmt.Println(result.Balance)
//Output:
//1000000
}
func ExampleWithdraw_noMoney() {
card := types.Card{Balance: 0, Active: true}
result := Withdraw(&card, 30_000_00)
fmt.Println(result.Balance)
//Output:
//0
}
func ExampleWithdraw_inactive() {
card := types.Card{Balance: 0, Active: false}
result := Withdraw(&card, 5_000_00)
fmt.Println(result.Balance)
//Output:
//0
}
func ExampleWithdraw_limit() {
card := types.Card{Balance: 20_000_00, Active: true}
result := Withdraw(&card, 40_000_00)
fmt.Println(result.Balance)
//Output:
//2000000
}
func ExampleDeposit_limitEqual() {
card := types.Card{Balance: 20_000_00, Active: true}
result := Deposit(&card, 10_000_00)
fmt.Println(result.Balance)
//Output:
//3000000
}
func ExampleDeposit_inactive() {
card := types.Card{Balance: 20_000_00, Active: false}
result := Deposit(&card, 10_000_00)
fmt.Println(result.Balance)
//Output:
//2000000
}
func ExampleDeposit_limitAbove() {
card := types.Card{Balance: 20_000_00, Active: true}
result := Deposit(&card, 60_000_00)
fmt.Println(result.Balance)
//Output:
//2000000
}
|
Markdown
|
UTF-8
| 1,332
| 3.203125
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Crowd Funding
## Overview
This example models the concept of crowd funding campaign where backers contribute money to a project, but the collected funds can only be released if they exceed a predefined threshold. If the threshold is not reached the funds can be reclaimed. A suggested extension to this model is to introduce a time threshold, which controls when claims or reclaims can happen.
## Workflow
1. The `originator` creates a `Project` contract defining the required `threshold` to reach.
2. The originator invites backers via invite/accept, collecting signatures from each on the `Project` contract.
3. Backers can then `Pledge` `Iou`s to the project, which get locked up in the process. Pledges can only be done before the project's `deadline`.
4. Once the `deadline` has passed and if the raised amount exceeds the `threshold` of the `Project` the `originator` can `Claim` the raised funds, which subsequently get transferred to him using the collected authorization on the `Project` contract.
5. If the raised funds are below the `threshold` the backers can trigger a `Reclaim` for the `Iou`s to be returned.
## Building
To compile the project:
```
daml build
```
## Testing
To test all scripts:
```
daml test --color
```
## Running
To load the project into the sandbox and start navigator:
```
daml start
```
|
PHP
|
UTF-8
| 484
| 2.578125
| 3
|
[] |
no_license
|
<?php
class MsgController extends BaseController{
public function addAction(){
if ($this->getRequest()->isPost()) {
$name = $this->getRequest()->getPost('name');
$content = $this->getRequest()->getPost('content');
$result = (new MsgModel())->add("insert into msg(name,content,create_at) values('{$name}','{$content}',".time().")");
if ($result) {
$this->success('/msg/index','添加成功');
}else{
$this->error('/msg/index','添加失败');
}
}
}
}
|
Python
|
UTF-8
| 940
| 3.625
| 4
|
[
"MIT"
] |
permissive
|
# 49 Ritcher Scale
a = float(input("Enter the magnitude: "))
if a < 2.0:
print("Magnitude of ",a," earthquake is considered Micro earthquake")
elif 2.0 <= a < 3.0:
print("Magnitude of ",a," earthquake is considered Very minor earthquake")
elif 3.0 <= a < 4.0:
print("Magnitude of ",a," earthquake is considered Minor earthquake")
elif 4.0 <= a < 5.0:
print("Magnitude of ",a," earthquake is considered Light earthquake")
elif 5.0 <= a < 6.0:
print("Magnitude of ",a," earthquake is considered Moderate earthquake")
elif 6.0 <= a < 7.0:
print("Magnitude of ",a," earthquake is considered Strong earthquake")
elif 7.0 <= a < 8.0:
print("Magnitude of ",a," earthquake is considered Major earthquake")
elif 8.0 <= a < 10.0:
print("Magnitude of ",a," earthquake is considered Great earthquake")
elif 10.0 <= a:
print("Magnitude of ",a," earthquake is considered Meteoric earthquake")
|
Java
|
UTF-8
| 756
| 3.140625
| 3
|
[] |
no_license
|
package ca.bcit.comp2526.a2b;
import java.awt.Color;
/**
* Sets a piece.
* @author Yan Wang
* @version 1
*
*/
public class Bishop extends Piece {
private static final long serialVersionUID = 1L;
private boolean value;
/**
* Bishop constructor.
* @param color.
*/
public Bishop(Color color) {
super(color, "B");
}
/**
* Moves piece.
*/
public boolean isMoveLegal(Square curB, Square preB) {
value = false;
if (((curB.getRow1() - preB.getRow1()) != 0)
&& (curB.getCol1() - preB.getCol1()) != 0) {
if (preB.getBoard().isValiddiagonal(curB, preB)) {
value = true;
}
}
return value;
}
}
|
Java
|
UTF-8
| 9,364
| 2.234375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package studentdatabase;
import java.sql.*;
import javax.swing.JOptionPane;
import studentdatabase.Sqlite;
/**
*
* @author MoMo
*/
public class Delete extends javax.swing.JFrame {
/**
* Creates new form Delete
*/
public Delete() {
initComponents();
this.setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(153, 153, 153));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setLayout(null);
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon("E:\\2-1\\code\\Studentdatabase\\rsz_ac300d10397017560e44856933e.png")); // NOI18N
jPanel1.add(jLabel1);
jLabel1.setBounds(280, 10, 120, 120);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Delete Account");
jPanel1.add(jLabel2);
jLabel2.setBounds(280, 130, 120, 20);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Username :");
jPanel1.add(jLabel3);
jLabel3.setBounds(90, 180, 110, 30);
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jPanel1.add(jTextField1);
jTextField1.setBounds(220, 180, 260, 30);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Security Kay :");
jPanel1.add(jLabel4);
jLabel4.setBounds(90, 250, 110, 30);
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextField2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jPanel1.add(jTextField2);
jTextField2.setBounds(220, 250, 260, 30);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel5.setText("#please re-entre your security key for confirmation ");
jPanel1.add(jLabel5);
jLabel5.setBounds(210, 230, 283, 15);
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setIcon(new javax.swing.ImageIcon("E:\\2-1\\code\\Studentdatabase\\rsz_delete-button-md.png")); // NOI18N
jPanel1.add(jLabel6);
jLabel6.setBounds(270, 340, 110, 30);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton1.setBounds(270, 340, 110, 30);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jPanel1.add(jLabel7);
jLabel7.setBounds(490, 180, 150, 30);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jPanel1.add(jLabel8);
jLabel8.setBounds(490, 250, 150, 30);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 654, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
username=jTextField1.getText();
security_key=jTextField2.getText();
ResultSet rs=null;
PreparedStatement ps=null;
String query=new String();
if(jTextField1.getText().length()==0)
{
jLabel7.setText("Username is Empty");
flag1=1;
}
else{
jLabel7.setText(null);
}
if(jTextField2.getText().length()==0)
{
jLabel8.setText("Security key is Empty");
flag1=1;
}
else{
jLabel8.setText(null);
}
/*************** how to remove data **************/
if(flag1==0){
try{
query="Delete from admin where username='"+username+"'and security_key='"+security_key+"'";
ps=conn.prepareStatement(query);
ps.execute();
JOptionPane.showMessageDialog(null,"Delete Successfully");
this.setVisible(false);
All a = new All();
a.setVisible(true);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Try again"); //don't work
}
finally{
try{
ps.close();
rs.close();
}catch(Exception e) {
}
}
}
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
conn = Sqlite.ConnectDB();
// TODO add your handling code here:
}//GEN-LAST:event_formWindowOpened
public Connection conn=null;
public String username=new String();
public String security_key=new String();
public static int flag1=0;
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Delete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Delete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Delete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Delete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Delete().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
}
|
Python
|
UTF-8
| 1,310
| 2.734375
| 3
|
[] |
no_license
|
# coding: utf-8
# In[2]:
import numpy as np
from keras.preprocessing import image
from keras.models import Sequential
from keras.models import load_model
import h5py
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def predict_pose():
classifier = load_model('my_model_multiclass10.h5') #load the model that was created using cnn_multiclass.py
test_image = request.files('file')
#test_image = image.load_img('C:/Users/dojha/yogapose/plank.jpg', target_size = (64, 64)) #folder predictions with images that I want to test
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image) # returns array
if result[0][0] == 1:
prediction = 'bridge' #predictions in array are in alphabetical order
elif result[0][1] == 1:
prediction = 'childspose'
elif result[0][2] == 1:
prediction = 'downwarddog'
elif result[0][3] == 1:
prediction = 'mountain'
elif result[0][4] == 1:
prediction = 'plank'
elif result[0][5] == 1:
prediction = 'seatedforwardbend'
elif result[0][6] == 1:
prediction = 'tree'
elif result[0][7] == 1:
prediction = 'trianglepose'
elif result[0][8] == 1:
prediction = 'warrior1'
elif result[0][9] == 1:
prediction = 'warrior2'
return prediction
|
Go
|
UTF-8
| 614
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
package repo
import (
"errors"
"os"
"path"
)
// Locate returns the absolute path of the Git repository containing the current working directory.
func Locate() (*string, error) {
potentialGitRepoPath, err := os.Getwd()
if err != nil {
return nil, err
}
for potentialGitRepoPath != "/" {
_, err := os.Stat(path.Join(potentialGitRepoPath, ".git"))
if err == nil {
return &potentialGitRepoPath, nil
} else if os.IsNotExist(err) {
potentialGitRepoPath = path.Join(potentialGitRepoPath, "..")
} else {
return nil, err
}
}
return nil, errors.New("please call Jit from a Git repository")
}
|
Python
|
UTF-8
| 868
| 4.0625
| 4
|
[] |
no_license
|
# Summary: 先定义一个温度类,然后定义两个描述符类用于描述摄氏度和华氏度两个属性
# 要求两个属性会自动进行转换,也就是你可以给摄氏度这个属性赋值,然后打印的华氏度属性是自动转换后的结果
# 华氏度 = 摄氏度*1.8 + 32
# Author: Fangjie Chen
# Date: 2017-11-23
# 摄氏度
class Celsius:
def __init__(self, value = 26.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
# 华氏度
class Fahrenheit:
def __get__(self, instance, owner):
return instance.cel*1.8 + 32
def __set__(self, instance, value):
instance.cel = (float(value)-32) / 1.8
# 温度
class Temperature:
cel = Celsius()
fah = Fahrenheit()
|
C
|
UTF-8
| 15,503
| 2.515625
| 3
|
[] |
no_license
|
#include "mini.h"
int ft_putchar(int smb)
{
int res;
res = write (1, &smb, 1);
return (res);
}
void parser_echo(char **massiv)
{
int flag;
int i;
int j;
flag = 0;
j = 1;
i = 0;
while (!ft_strncmp(massiv[++i], "-n", 2))
{
while (massiv[i][j] == 'n')
j++;
if (massiv[i][j] == '\0')
flag = 1;
else
break ;
}
while (massiv[i] != NULL)
{
write(1, massiv[i], ft_strlen(massiv[i]));
i++;
}
if (!flag)
write(1, "\n", 1);
}
char *parser_key_export(char *value)
{
int len_key;
char *save_v;
char *key;
int count;
len_key = 0;
save_v = value;
count = -1;
while(*value != '\0')
{
if(*value == '=')
break;
len_key++;
value++;
}
value = save_v;
key = (char*)malloc((sizeof(char) * len_key) + 1);
if (key == NULL)
exit(-1); //TODO придумать функцию по очистке и выводе ошибок
//error("Malloc error", 13);
while(++count < len_key)
{
if(*value == '=')
break;
key[count] = value[count];
}
return(key);
}
char *parser_env_export(char *value)
{
int len_str;
char *str;
int count;
int i;
char *save_v;
len_str = 0;
count = 0;
save_v = value;
while (*value != '=')
{
value++;
count++;
}
if (*value == '=')
{
while(*value != '\0')
{
len_str++;
value++;
}
}
str = (char*)malloc((sizeof(char) * len_str) + 1); // плюс 2 для /0 и для =
if (str == NULL)
exit(-1); //TODO придумать функцию по очистке и выводе ошибок
//error("Malloc error", 13);
i = 0;
value=save_v;
while (value[count] != '\0')
{
str[i] = value[count];
count++;
i++;
}
return (str);
}
int ft_isalnum(int smbl)
{
if (ft_isalpha(smbl) || ft_isdigit(smbl))
return (1);
else
return (0);
}
char *return_key(char *str) //из экспорта
{
int i;
char *res;
i = 0;
while (str[i] != '=')
i++;
res = (char*)malloc(i + 1);
i = 0;
while (str[i] != '=')
{
res[i] = str[i];
i++;
}
return (res);
}
void parser_export2(char **massiv, t_env *env_struct, char **env)
{
// int i;
// int j;
// int sm; // 1 если ошибка
// char *r;
//
// i = 1;
//env_struct->exp_arg =
// env_struct->str = ft_strdup(massiv); // вся строка (str=3ptr)
// env_struct->key = parser_key_export(env_struct->str); //ключ (str)
// // if (massiv))
// // env_struct->value = NULL;
// while(*massiv)
// {
// if (*massiv == '=')
// env_struct->value = parser_env_export(env_struct->str); //значение с равно (=ptr3)
// // else
// // env_struct->value = NULL;
// massiv++;
// }
// sm = 0;
// i = 0;
// if (env_struct->key[i] == '_' || !(ft_isalpha(env_struct->key[i])))// если ПЕРВЫЙ символ в ключе цифры или символ, кроме _ : ошибка
// sm = 1;
// i = -1;
// while (env_struct->key[++i]) //если в ключе содержаться символы кроме букв, цифр и _ ошибка
// {
// if (!(ft_isalnum(env_struct->key[i])) && env_struct->key[i] != '_')
// sm = 1;
// }
// if (sm != 1)
// ft_start_exp(env, env_struct);
// if (sm == 1) // в случае ошибки в ключе
// {
// write(2,"export: ", 8);
// write(2,"\'", 1);
// ft_putstr_fd(env_struct->str, 2); //TODO + очищение памяти
// free(env_struct->key);
// free(env_struct->str);
// write(2,"\'", 1);
// write(2,": not a valid identifier\n", 25);
// }
int i;
int j;
i = 0;
while (massiv[i])
i++;
env_struct->env_arg = (char**)malloc((sizeof(char*) * i));
i = 1;
j = 0;
while (massiv[i])
{
printf("massiv %s\n", massiv[i]);
env_struct->env_arg[j] = ft_strdup(massiv[i]);
printf("env %s\n", env_struct->env_arg[i]); //не записывает стрдап
i++;
j++;
}
i = 0;
while (env_struct->env_arg[i])
{
env_struct->key = return_key(env_struct->env_arg[i]);
env_struct->value = ft_strchr(env_struct->env_arg[i], '=');
printf("key %s\n", return_key(env_struct->env_arg[i]));
printf("value %s\n", env_struct->value);
i++;
}
//проверка ключа и значения как раньше, в случае ошибки вывод ошибки
}
void parser_export(char **massiv, t_env *env_struct, char **env)
{
// env_struct->key = NULL; // инициаилизатор
if (massiv[1] == NULL)
ft_out_exp(env_struct);
else
{
parser_export2(massiv, env_struct, env);
export(env_struct);
}
}
void my_exit(char **str)
{
if (str[1] == NULL)
exit (0);
}
void work_with_execve(t_all *all, char *mass)
{
char **new_str;
// if (mass[0] == '.')
// {
// }
if (!(find_element(&all->env, "PATH")))
{
write(1, "Minishell>> 2: command not found\n", 20);
return ;
// return(ft_putchar(2));
}
//new_str = ft_split(find_element(&all->env, "PATH"), ':');
}
void find_command(t_all *all, char **env)
{
printf("%d\n", all->env_struct.count_lines);
if (!ft_strncmp(all->result[0], "echo", 5))
parser_echo(all->result);
else if (!ft_strncmp(all->result[0], "export", 7))
parser_export(all->result, &all->env_struct, env);
else if (!ft_strncmp(all->result[0], "cd", 3))
ft_cd(&all->env_struct);// если пусто тильда или записать new_dir
else if (!ft_strncmp(all->result[0], "pwd", 4))
ft_pwd();
// else if (!ft_strncmp(all->result[0], "unset", 6))
// parser_unset(all->result);
else if (!ft_strncmp(all->result[0], "env", 4))
ft_out_env(&all->env_struct);
else if (!ft_strncmp(all->result[0], "exit", 5))
my_exit(all->result);
else
work_with_execve(all, all->result[0]);
}
char *skip_space(char *str)
{
while (*str != '\0' && *str == ' ')
str++;
return(str);
}
char *ft_new(char *str, int len)
{
char *s;
int i;
i = 0;
s = malloc(sizeof(char) * (len + 1));
while (str && i < len)
{
s[i++] = *str;
str++;
}
s[i] = '\0';
return (s);
}
char *before(char **str)
{
char *s;
int i;
s = *str;
i = 0;
while (s[i] && s[i] != ' ' && s[i] != '\"' && s[i] != '\'' \
&& s[i] != '$' && s[i] != '>' && s[i] != '<' && s[i] != '|')
{
i++;
}
s = ft_new(*str, i);
*str += i;
return (s);
}
static void ft_free_arr(char **arr)
{
unsigned int i;
i = 0;
while (arr[i])
{
free(arr[i]);
i++;
}
free(arr);
arr = NULL;
}
char *find_element(t_list_env **list, char *key)
{
t_list_env *tmp;
int len;
if (list == NULL || key == NULL)
return (NULL);
else
{
len = ft_strlen(key);
tmp = *list;
while (tmp != NULL)
{
if (!ft_strncmp(tmp->key, key, len + 1))
return (tmp->value);
tmp = tmp->next;
}
return (NULL);
}
}
char *ft_new_m(char *str, int len)
{
char *s;
int i;
i = 0;
s = malloc(sizeof(char) * (len + 1));
while (str && i < len)
{
s[i++] = *str;
str++;
}
s[i] = '\0';
return (s);
}
char *check_env(char **str, t_all *all)
{
char *s;
char *p;
int i;
*str += 1;
p = *str;
if(!**str)
{
write(1, "Minishell>> $: No such file or directory\n", 42);
return (ft_strdup("$"));
}
if (**str == ' ')
{
write(1, "Minishell>> $: command not found\n", 33);
return (ft_strdup("$"));
}
else if (**str == '?')
{
p++;
*str = p;
write(1, "Minishell>> 258: command not found\n", 36);
return (ft_strdup("258"));
}
i = 0;
while (p[i] && p[i] != ' ' && p[i] != '\"' && p[i] != '\''
&& p[i] != '$' && p[i] != '>' && p[i] != '<')
i++;
p = ft_new_m(*str, i);
// printf("p: %s/n", p);
*str += i;
s = find_element(&all->env, p);
free(p);
if (s)
return (ft_strdup(s));
return (s);
}
char *parser_result(char **str, t_all *all)
{
if(**str == '\"')
return(check_double_quotes(str));
else if(**str == '\'')
return(check_single_quotes(str));
else if (**str == '$')
return(check_env(str, all));
else
return(before(str));
}
void list_count(t_cnt *words, void *s)
{
ft_lstadd_back(&words->list, ft_lstnew(s));
words->count++;
}
void mem_for_result(t_all *all, t_cnt *words, int count_w)
{
int n;
t_list *tmp;
n = 0;
all->result = (char *)malloc(sizeof(char *) * (count_w + 1));
all->result[count_w] = NULL;
tmp = words->list;
while (n < count_w)
{
all->result[n++] = tmp->content;
tmp = tmp->next;
}
}
static void pipe_function(t_all *matur, int **buf_fd, int max, int i)
{
if (i == 0)
{
close(buf_fd[i][0]);
dup2(buf_fd[i][1], 1);
}
else
{
if (i < max)
{
close(buf_fd[i - 1][1]);
dup2(buf_fd[i - 1][0], 0);
close(buf_fd[i][0]);
dup2(buf_fd[i][1], 1);
}
else
{
close(buf_fd[i - 1][1]);
dup2(buf_fd[i - 1][0], 0);
}
}
matur->pipe_f = 1;
}
// static int **create_arr_fd_and_pid(int count_pipe, int **buf_pid)
// {
// int **buf_fd;
// int i;
// buf_fd = (int **)malloc(sizeof(int *) * count_pipe);
// if (!buf_fd)
// return (NULL);
// i = -1;
// while (++i < count_pipe)
// {
// buf_fd[i] = (int *)malloc(sizeof(int) * 2);
// pipe(buf_fd[i]);
// }
// *buf_pid = (int *)malloc(sizeof(int) * (count_pipe + 1));
// return (buf_fd);
// }
// void parser_pipes(int p, t_list **mass, t_all *all, char **env)
// {
// int *buf_pid;
// int **buf_fd;
// t_list *tmp;
// int i;
// p = p - 1;
// buf_fd = create_arr_fd_and_pid(p, &buf_pid);
// tmp = *mass;
// i = 0;
// while (tmp != NULL)
// {
// all->result = tmp->content;
// buf_pid[i] = fork();
// if (buf_pid[i] > 0 && i != p)
// close(buf_fd[i][1]);
// else if (buf_pid[i] == 0)
// {
// pipe_function(all, buf_fd, p, i);
// find_command(all, env);
// free(buf_fd);
// exit (0);
// }
// i++;
// tmp = tmp->next;
// }
// while (--i >= 0)
// waitpid(buf_pid[i], NULL, 0);
// }
void process(t_all *all, t_cnt *words, t_cnt *pipes, char **str, char **env)
{
if (words->count > 0)
{
mem_for_result(all, words, words->count);
list_count(pipes, all->result);
if(pipes->count == 1)
find_command(all, env);
// else
// parser_pipes(pipes->count, &pipes->list, all, env);
}
clear_list(words);
clear_list(pipes);
}
void clear_list_w(t_cnt *words)
{
t_list *tmp;
tmp = words->list;
while (tmp)
{
tmp = tmp->next;
free(words->list);
words->list = tmp;
}
words->list = NULL;
words->count = 0;
}
char *strjoin_free(char *str1, char *str2)
{
char *p;
if (!str1)
return (str2);
if (!str2)
return (str1);
p = ft_strjoin(str1, str2);
free(str1);
free(str2);
return (p);
}
t_all *parser(char *str, t_all *all, char **env)
{
t_cnt words;
t_cnt pipes;
int j;
//int len;
char *s;
ft_bzero(&words, sizeof(t_cnt));
ft_bzero(&pipes, sizeof(t_cnt));
while (*str != '\0')
{
str = skip_space(str);
check_sim(str);
// if (*str == '<' || *str == '>')
// parser_redirect(&str, all, &words);
s = parser_result(&str, all);
while (*str != '\0' && *str != ' ' && *str != '|')
s = strjoin_free(s, parser_result(&str, all));
list_count(&words, s);
str = skip_space(str);
if (*str == '|')
{
if (words.count > 0)
{
mem_for_result(all, &words, words.count);
if (**all->result)
list_count(&pipes, all->result);
// else
// {
// write(1, "syntax error ", 14);
// all->error = 258;
// *(str + 1) = 0;
// }
clear_list_w(&words);
str++;
}
}
}
process(all, &words, &pipes, &str, env);
// clear_list(&words);
// clear_list(&pipes);
return (all);
}
void ft_quit(int sig)
{
int pid;
int status;
(void)sig;
pid = waitpid(-1, &status, WNOHANG);
if (!pid)
ft_putendl_fd("Quit: 3", 1);
}
void ft_sigint(int sig)
{
int pid;
int status;
pid = waitpid(-1, &status, WNOHANG);
if (sig == SIGINT)
{
write(1,"\n", 2);
if (pid)
write (1, "Minishell>> ", 12);
}
}
void error(char *str, int error)
{
char *id;
char *res;
ft_putendl_fd(str, 2);
id = ft_itoa(error);
res = ft_strjoin("error=", id);
// export_var(res);
free(id);
free(res);
exit(error);
}
int make_fd(void)
{
int fd;
fd = open("minishell_history", O_CREAT, S_IWRITE | S_IREAD);
if (!(fd))
error("Error when creating a file history", 1);
fd = open("minishell_history", O_RDWR | O_TRUNC);
if (!fd)
error("Error occurred while opening the history file", 1);
return (fd);
}
t_list_env *get_val_ket(char *key,char *val)
{
t_list_env *list;
list = (t_list_env *)malloc(sizeof(t_list_env));
if(!list)
return(NULL);
list->key = key;
list->value = val;
list->next = NULL;
list->previous = NULL;
return (list);
}
int create_new_env(t_list_env **list, t_list_env *new)
{
t_list_env *tmp;
if (!list || !new)
return (1);
if (*list)
{
tmp = *list;
while (tmp->next)
tmp = tmp->next;
tmp->next = new;
new->previous = tmp;
}
else
*list = new;
return (0);
}
int ft_len(char **env, int n)
{
while (env[n] != '\0' && !ft_strchr(env[n], '='))
n++;
return (n);
}
void ft_redir(char *str, t_env *env_struct)
{
FILE *fp;
char *cp;
int len;
int file;
int fd[2];
len = ft_strlen(str);
cp = (char*)malloc(len + 4);
cp = ft_strjoin(str,".txt");
if (env_struct->flags.redir2_b == 1)
{
file = open(cp, O_WRONLY | O_APPEND | O_CREAT, 0666);
if (file < 0)
ft_errors("error");
dup2(file, fd[1]);
close(file);
}
else if (env_struct->flags.redir_b == 1)
{
file = open(cp, O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (file < 0)
ft_errors("error");
dup2(file, fd[1]);
close(file);
}
}
t_list_env *new_element(char *key, char *value)
{
t_list_env *lst;
lst = (t_list_env *)malloc(sizeof(t_list_env));
if (!lst)
return (NULL);
lst->key = key;
lst->value = value;
lst->next = NULL;
lst->previous = NULL;
return (lst);
}
int add_element(t_list_env **list, t_list_env *new)
{
t_list_env *tmp;
if (!list || !new)
return (1);
if (*list)
{
tmp = *list;
while (tmp->next)
tmp = tmp->next;
tmp->next = new;
new->previous = tmp;
}
else
*list = new;
return (0);
}
void get_env(t_all *all, char **env)
{
char *key;
char *value;
int count;
int len;
int len_env;
count = 0;
while (env[count] && env[count] != NULL)
{
len = 0;
while (env[count][len] != '=' && env[count][len] != '\0')
len++;
key = ft_substr(env[count], 0, len);
if (env[count][len] == '=')
{
len++;
len_env = ft_strlen(&env[count][len]);
value = ft_substr(env[count], len, len_env);
}
else
value = NULL;
add_element(&all->env, new_element(key, value));
count++;
printf("%s\n",key);
}
}
void ft_out_env(t_env *env_struct)
{
int i;
int j;
i = 0;
j = 0;
while (i < env_struct->count_lines)
{
while (env_struct->env[i][j])
{
write(1, &env_struct->env[i][j], 1);
j++;
}
write(1, "\n", 1);
j = 0;
i++;
}
}
int main(int ac, char **av, char **env)
{
char *str;
int i;
t_all *all;
int fd;
// t_env env_struct;
// all->env_struct.key = "name";
// env_struct.value = "=";
all = (t_all *) ft_calloc(1, sizeof(t_all));
get_env(all, env);
ft_init_flags(&all->env_struct, env);
// ft_copy_env(env, &all->env_struct); //вынесла в инициализатор
if (ac > 1 && av[1] != NULL)
ft_putstr_fd("Invalid arguments\n", 1);
signal(SIGINT, signal_ctrlc);
while (1)
{
str = readline ("Minishell>> ");
if (str == NULL)
{
write(1, " exit\n", 6);
// write(fd, "exit\n", 5);
free(str);
free(all);
return (0);
}
if (str && *str)
{
write(fd, str, ft_strlen(str));
write(fd, "\n", 1);
add_history(str);
parser(str, all, env);
free(str);
}
}
// close(fd);
return 0;
}
|
Java
|
UTF-8
| 54,260
| 1.6875
| 2
|
[] |
no_license
|
package com.spock.core;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import java.util.Timer;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import entities.AkamaiFailedLink;
import entities.Attribute;
import entities.Configs;
import entities.Parameter;
import entities.Path;
import entities.PathQos;
import entities.Program;
import entities.Run;
import entities.SystemQos;
import entities.Video;
import entities.VideoMeasurementXref;
import entities.VideoTranslation;
import com.spock.utils.CSVParser;
import com.spock.utils.FeedDataHelper;
import com.spock.utils.JsonHelper;
import com.spock.utils.SignatureGenerator;
import com.spock.utils.XMLHelper;
public class VideosWatchdog {
public static SyndicationChecker syndicationChecker = new SyndicationChecker();
public static HashMap<String, HashMap<String, String>> content = new HashMap<String, HashMap<String, String>>();
public static HashMap<String, Integer> pathAssetsCount = new HashMap<String, Integer>();
static HashMap<String, String> programs = new HashMap<String, String>();
static HashMap<String, String> programToTagId = new HashMap<String, String>();
public static String mcpVideosList = System.getProperty("user.dir") + "/xml/mcpVideosList.xml";
public static String mcpProgramsPath = System.getProperty("user.dir") + "/xml/mcpPrograms.xml";
static long timestamp = unixtime();
public static Date runStartedAt;
static String startDate = "";
static String endDate = "";
static ArrayList<Path> paths = new ArrayList<Path>();
static ArrayList<String> videoIds = new ArrayList<String>();
public static Configs configs = new Configs();
public static Run run = new Run();
static HashMap<String, Float> SystemSyndicaytionOfSuccess = new HashMap<String, Float>();
static HashMap<String, Float> SystemAttributeAccuracy = new HashMap<String, Float>();
static HashMap<String, Float> SystemAdServer = new HashMap<String, Float>();
static HashMap<String, Float> SystemTransmissionDelay = new HashMap<String, Float>();
public static ArrayList<String> apps = new ArrayList<String>();
public static entities.System mcpSystem = new entities.System();
public static entities.System brightSpotSystem = new entities.System();
public static TimeZone estTimeZone = TimeZone.getTimeZone("EST");
public static String getCurrentApp(String parentTopic) {
for (String app : apps) {
String[] appNames = app.split("\\|");
for (String appName : appNames) {
if (appName.toLowerCase().equals(parentTopic.toLowerCase())) {
return parentTopic.toLowerCase();
}
}
}
return null;
}
public static void main(String[] args) {
configs = FeedDataHelper.getConfigs();
Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask
// class
time.schedule(st, 0, 1000 * 60 * configs.ScheduledDuration); // Create
// Repetitively
// task
// for
// every 1 secs
}
public static void resetData() {
syndicationChecker = new SyndicationChecker();
content = new HashMap<String, HashMap<String, String>>();
pathAssetsCount = new HashMap<String, Integer>();
programs = new HashMap<String, String>();
programToTagId = new HashMap<String, String>();
mcpProgramsPath = System.getProperty("user.dir") + "/xml/mcpPrograms.xml";
mcpVideosList = System.getProperty("user.dir") + "/xml/mcpVideosList.xml";
timestamp = unixtime();
startDate = "";
endDate = "";
configs = FeedDataHelper.getConfigs();
run = new Run();
paths = new ArrayList<Path>();
videoIds = new ArrayList<String>();
SystemSyndicaytionOfSuccess = new HashMap<String, Float>();
SystemAttributeAccuracy = new HashMap<String, Float>();
SystemAdServer = new HashMap<String, Float>();
SystemTransmissionDelay = new HashMap<String, Float>();
apps = new ArrayList<String>();
mcpSystem = new entities.System();
brightSpotSystem = new entities.System();
}
public static void run() {
/*
* Code that will ping all MCP ID's that have been syndicated every time
* interval which is configurable
*/
resetData();
DateFormat runFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// runFormat.setTimeZone(estTimeZone);
DateFormat runFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// runFormat1.setTimeZone(estTimeZone);
runStartedAt = new Date();
Run previousRun = getLastRun();
paths = new ArrayList<Path>();
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss 'EDT'");
DateFormat dateFormat2 = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss 'EDT'");
// dateFormat.setTimeZone(estTimeZone);
// get current date time with Date()
DateTime dateTime = new DateTime();
try {
startDate = dateFormat.format(new DateTime(runFormat1.parse(previousRun.endDate)).toDate());
} catch (Exception e) {
System.out.println("Warining: could not parse previuos run end date");
dateFormat.setTimeZone(estTimeZone);
startDate = dateFormat.format(dateTime.minusHours(configs.FirstRunPreviousPeriod).toDate());
}
dateFormat.setTimeZone(estTimeZone);
// startDate =
// dateFormat.format(dateTime.minusHours(FirstRunPreviousPeriod).toDate());
endDate = dateFormat.format(dateTime.toDate());
timestamp = unixtime();
System.out.println("start date:" + startDate + ", end date:" + endDate);
// startDate = "Oct 07, 2016 17:07:20 EDT";
// endDate = "Oct 07, 2016 18:07:20 EDT";
try {
run.startDate = runFormat.format(dateFormat2.parse(startDate));
} catch (ParseException e) {
e.printStackTrace();
}
//startDate = "Oct 07, 2016 17:07:20 EDT";
//endDate = "Oct 07, 2016 18:07:20 EDT";
run.QosValue = 0;
run.endDate = "";
run.totalAssets = 0;
run.movingWeight = 0;
paths = FeedDataHelper.getPaths();
defineCurrentApps(paths);
programToTagId = new HashMap<String, String>();
programToTagId = CSVParser.parseCsvToProgramAndTagHash("mcp-mapping.csv");
QosPathManager pathMng = new QosPathManager();
QosPathSystemManager systemManeger = new QosPathSystemManager();
QosCalculatorEngine qosCalculater = new QosCalculatorEngine(pathMng, systemManeger);
brightSpotSystem = getSystemByName(paths, "brightspot");
mcpSystem = getSystemByName(paths, configs.MCPSystemName);
// Syndicator.syndicateVideo("3066281","10812");
if (mcpSystem != null) {
programs = getmcpPrograms();
System.out.println("Programmes count:" + programs.size());
timestamp = unixtime();
// videoIds = new ArrayList<>();
// videoIds.add("3178734");
// checkLastRunFailedVideos();
getmcpsyndicatedids();
if (content.size() >= configs.NumberOfAssetsToRun) {
run.Id = FeedDataHelper.insertRun(run);
System.out.println(content.size());
} else {
System.out.println("run not started, asstes count is:" + content.size());
return;
}
for (String key : content.keySet()) {
// if(!key.equals("3243966")){
// continue;
//
// }
String programName = content.get(key).get("program_name");
//Date publishDate = getDateFromString(content.get(key).get("published"), "MMM d,yyyy HH:mm:ss");
if(!content.get(key).get("published").toString().toLowerCase().equals("yes") && !content.get(key).get("published").toString().toLowerCase().equals("true")){
continue;
}
Date expirationDate = getDateFromString(content.get(key).get("ts_expire"), "MMM d,yyyy HH:mm:ss");
if (expirationDate.before(new Date())) {
System.out.println(expirationDate.toString() + " before " + (new Date().toString()));
Video video = new Video();
video.Title = content.get(key).get("def_title");
video.Duration = content.get(key).get("duration");
video.RunId = run.Id;
if(content.get(key).get("syndicator_name").toLowerCase().trim().equals("brightspot 2"))
{
video.isBrightspot=1;
}else{
video.isBrightspot=0;
}
video.isExpired = true;
try {
video.McpID = Integer.parseInt(key);
} catch (Exception e) {
continue;
}
video.Id = FeedDataHelper.insertVideo(video);
continue;
}
Date mcpDate = getDateFromString(content.get(key).get("syndication_date"), "MMM d,yyyy HH:mm:ss");
String programId = programs.get(programName);
String primaryTagId = programToTagId.get(programId);
String parentTopicName = getParentTopicValue(primaryTagId);
String app = getCurrentApp(parentTopicName);
if (app == null) {
continue;
}
Video video = new Video();
video.Title = content.get(key).get("def_title");
video.Duration = content.get(key).get("duration");
video.RunId = run.Id;
video.isExpired = false;
if(content.get(key).get("syndicator_name").toLowerCase().trim().equals("brightspot 2"))
{
video.isBrightspot=1;
}else{
video.isBrightspot=0;
}
try {
video.McpID = Integer.parseInt(key);
} catch (Exception e) {
continue;
}
video.Id = FeedDataHelper.insertVideo(video);
System.out.println(app);
Program program = new Program();
program.Title = programName;
program.Id = FeedDataHelper.insertProgram(program);
int pathIndex = getPathIndexByAppName(paths, app);
if (pathIndex > -1) {
Path currentPath = paths.get(pathIndex);
boolean assetSyndicationSuccess = true;
ArrayList<Float> attributeAccuracy = new ArrayList<Float>();
ArrayList<Float> transmisionDelayAccuracy = new ArrayList<Float>();
if (pathAssetsCount.containsKey(currentPath.Name.toLowerCase())) {
pathAssetsCount.put(currentPath.Name.toLowerCase(),
pathAssetsCount.get(currentPath.Name.toLowerCase()) + 1);
} else {
pathAssetsCount.put(currentPath.Name.toLowerCase(), 1);
}
boolean adsSuccess = true;
for (entities.System system : currentPath.Systems) {
VideoTranslation videoTranslation = new VideoTranslation();
videoTranslation.VideoId = video.Id;
videoTranslation.SystemId = system.Id;
if (!system.Name.toLowerCase().equals(configs.MCPSystemName)) {
VideoMeasurementXref videoMeasurementXref = new VideoMeasurementXref();
videoMeasurementXref.ProgramID = program.Id;
videoMeasurementXref.VideoID = video.Id;
videoMeasurementXref.PathId = currentPath.Id;
videoMeasurementXref.RunID = run.Id;
videoMeasurementXref.SystemId = system.Id;
videoMeasurementXref.AttributeAccuracy = -1;
videoMeasurementXref.TransmissionDelay = -1;
videoMeasurementXref.AdServer = -1;
videoMeasurementXref.SysndicationOfSuccess = -1;
String syndicationDate = "";
syndicationDate = runFormat.format(mcpDate);
videoMeasurementXref.SyndicationDate = syndicationDate;
String result = getSystemResult(system, key);
videoTranslation.SystemRetrievedData = StringEscapeUtils.escapeJava(result);
boolean isXML = false;
if (system.responseType.toLowerCase().equals("xml")) {
isXML = true;
}
if (system.Name.toLowerCase().equals("akamai")) {
assetSyndicationSuccess = checkSuccessOfMcpAkamaiLinks(result, video.Id);
if (assetSyndicationSuccess) {
videoMeasurementXref.SysndicationOfSuccess = 1;
} else {
videoMeasurementXref.SysndicationOfSuccess = 0;
}
systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id),
assetSyndicationSuccess);
} else if (system.hasAdsServer && (content.get(key).get("syndicator_name").toLowerCase().trim().equals("brightspot 2") )) {
adsSuccess = syndicationChecker.attributeHasValueInXml(result);
if (adsSuccess) {
videoMeasurementXref.AdServer = 1;
} else {
videoMeasurementXref.AdServer = 0;
}
if (!system.VideoIdPath.isEmpty()) {
try {
videoTranslation.SystemVideoId = XMLHelper.getXmlValueByPath(result,
system.VideoIdPath);
} catch (Exception ex) {
System.out.println("could not parse video id path: " + system.VideoIdPath
+ " for system " + system.Name);
}
}
systemManeger.addAdsSuccess(String.valueOf(system.Id), adsSuccess);
} else if (system.hasSyndicationOfSuccess) {
JSONObject resultAsJson = syndicationChecker.jsonResponseHasValues(result);
if (resultAsJson == null) {
System.out.println("######## key:" + key + ",, result:" + result);
assetSyndicationSuccess = false;
videoMeasurementXref.SysndicationOfSuccess = 0;
systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id), false);
} else if (system.Name.toLowerCase().equals("brightspot")
&& (content.get(key).get("syndicator_name").toLowerCase().trim().equals("brightspot 2") )
&& !checkBrightspotSyndication(video.Id, resultAsJson, brightSpotSystem,
videoMeasurementXref)) {
System.out.println("######## key:" + key + ",, result:" + result);
assetSyndicationSuccess = false;
videoMeasurementXref.SysndicationOfSuccess = 0;
systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id), false);
} else {
if (system.Name.toLowerCase().equals("brightspot")) {
if(!content.get(key).get("syndicator_name").toLowerCase().trim().equals("brightspot 2") ){
continue;
}
String frontEndUrl = JsonHelper.getJsonValueByPath(resultAsJson,
"data|items|url");
video.FrontEndLink = frontEndUrl;
FeedDataHelper.updateVideo(video);
}
systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id), true);
videoMeasurementXref.SysndicationOfSuccess = 1;
if (!system.VideoIdPath.isEmpty()) {
try {
videoTranslation.SystemVideoId = JsonHelper.getJsonValueByPath(resultAsJson,
system.VideoIdPath);
} catch (Exception ex) {
System.out.println("could not parse video id path: " + system.VideoIdPath
+ " for system " + system.Name);
}
}
if (system.hasAttributeAcuraccy) {
HashMap<String, String> attributePaths = getAttributesAsHashmap(
system.Attributes);
HashMap<String, String> mcpAttributeMap = getMcpToOtherSystemAttributeMap(
mcpSystem.Attributes, system.Attributes, false);
HashMap<String, String> attributesToCompare = syndicationChecker
.jsonAttributes(resultAsJson, attributePaths);
float assetAttributeAccuracy = syndicationChecker.CompareAttributes(
content.get(key), attributesToCompare, mcpAttributeMap, mcpSystem,
system, video.Id);
attributeAccuracy.add(assetAttributeAccuracy);
videoMeasurementXref.AttributeAccuracy = assetAttributeAccuracy;
systemManeger.addAttributeAccuracy(String.valueOf(system.Id),
assetAttributeAccuracy);
}
if (system.hasTransmissionDelay) {
String strPubDate = JsonHelper.getJsonValueByPath(resultAsJson,
system.DateFieldPath);
Date pubDate = getDateFromString(strPubDate, system.DateFormat);
float transmissionDelay = syndicationChecker
.assetTansmissionDelayAccuracy(mcpDate, pubDate);
transmisionDelayAccuracy.add(transmissionDelay);
videoMeasurementXref.TransmissionDelay = transmissionDelay;
systemManeger.addTransmisionDelay(String.valueOf(system.Id), transmissionDelay);
}
}
}
if((system.Name.equalsIgnoreCase("akamai") || (content.get(key).get("syndicator_name").toLowerCase().trim().equals("brightspot 2") )) ){
FeedDataHelper.insertVideoTranslation(videoTranslation);
FeedDataHelper.insertVideoMeasurementXref(videoMeasurementXref);
}
}
}
VideoTranslation mcpVideoTranslation = new VideoTranslation();
mcpVideoTranslation.VideoId = video.Id;
mcpVideoTranslation.SystemId = mcpSystem.Id;
mcpVideoTranslation.SystemVideoId = key;
try {
mcpVideoTranslation.SystemRetrievedData = QosPathSystemManager.getMcpVideoById(mcpSystem, key);
} catch (Exception ex) {
mcpVideoTranslation.SystemRetrievedData = QosPathSystemManager.getMcpVideoById(mcpSystem, key);
}
FeedDataHelper.insertVideoTranslation(mcpVideoTranslation);
pathMng.addAssetSyndicationSuccess(currentPath.Name.toLowerCase(), assetSyndicationSuccess);
pathMng.addAdsSuccess(currentPath.Name.toLowerCase(), adsSuccess);
float pathAssetAttributeAccuracy = qosCalculater.averageToListOfIntegers(attributeAccuracy);
if (pathAssetAttributeAccuracy > -1) {
pathMng.addAttributeAccuracy(currentPath.Name.toLowerCase(), pathAssetAttributeAccuracy);
}
float pathAssetTransmisionDelayAccuracy = qosCalculater
.averageToListOfIntegers(transmisionDelayAccuracy);
if (pathAssetTransmisionDelayAccuracy > -1) {
pathMng.addTransmisionDelay(currentPath.Name.toLowerCase(), pathAssetTransmisionDelayAccuracy);
}
}
}
float qosValue = qosCalculater.CalculateQOS(paths);
System.out.println("qos value =" + qosValue);
try {
run.endDate = runFormat.format(dateFormat2.parse(endDate));
} catch (ParseException e) {
e.printStackTrace();
}
run.QosValue = qosValue;
run.totalAssets = qosCalculater.getTotalAssetsCount();
run.movingWeight = qosCalculater.calculateMovingWeight(run, previousRun);
System.out.println("run.movingWeight =" + run.movingWeight);
videoIds = FeedDataHelper.getLastRunFailedVideos();
if (run.totalAssets > 0) {
FeedDataHelper.updateRun(run);
} else {
}
qosCalculater.calculatePathSystemQos(run.Id);
for (SystemQos systemQos : systemManeger.systemQos) {
FeedDataHelper.insertSystemQos(systemQos);
}
for (String key : pathMng.pathQos.keySet()) {
PathQos pathQos = pathMng.pathQos.get(key);
pathQos.PathID = getPathId(paths, pathQos.PathName);
pathQos.RunID = run.Id;
pathQos.TotalPathAssets = pathAssetsCount.get(key);
FeedDataHelper.insertPathQos(pathQos);
}
} else {
System.out.println("Could not find mcp system in the current paths...");
}
System.out.println("check last run videos");
checkLastRunFailedVideos();
System.out.println("finished last run videos check");
}
public static int getPathId(ArrayList<Path> paths, String pathName) {
for (Path path : paths) {
if (path.Name.toLowerCase().equals(pathName.toLowerCase())) {
return path.Id;
}
}
return 0;
}
public static void defineCurrentApps(ArrayList<Path> paths) {
for (Path path : paths) {
apps.add(path.AppName);
}
}
public static entities.System getSystemByName(ArrayList<Path> paths, String systemName) {
for (Path path : paths) {
for (entities.System system : path.Systems) {
if (system.Name.toLowerCase().equals(systemName.toLowerCase())) {
return system;
}
}
}
return null;
}
public static HashMap<String, String> getMcpToOtherSystemAttributeMap(ArrayList<Attribute> mcpAttributes,
ArrayList<Attribute> otherSystemAttributes, boolean isMcpList) {
HashMap<String, String> mcpMap = new HashMap<String, String>();
for (Attribute attr : otherSystemAttributes) {
Attribute currMcpAttribute = new Attribute();
for (Attribute mcpAttr : mcpAttributes) {
if (attr.BaseId == mcpAttr.BaseId) {
currMcpAttribute = mcpAttr;
}
}
String mcpName = currMcpAttribute.Name;
if (isMcpList) {
mcpName = currMcpAttribute.Name.replace("def_", "");
}
mcpMap.put(mcpName, attr.Name);
}
return mcpMap;
}
public static HashMap<String, String> getAttributesAsHashmap(ArrayList<Attribute> attributes) {
HashMap<String, String> attrbiutesHash = new HashMap<String, String>();
for (Attribute attr : attributes) {
attrbiutesHash.put(attr.Name, attr.path);
}
return attrbiutesHash;
}
public static String getSystemResult(entities.System system, String mcpId) {
long largeTimeStamp = unixtime() + 1209600;
HashMap<String, String> parameters = new HashMap<String, String>();
int signitureIndex = -1;
String clientID = "";
for (int index = 0; index < system.Parameters.size(); index++) {
if (system.Parameters.get(index).Type.toLowerCase().equals("param")) {
if (system.Parameters.get(index).Name.toLowerCase().equals("client_id")) {
clientID = system.Parameters.get(index).Value;
}
if (system.Parameters.get(index).Value.equals("TimeStampValue")) {
parameters.put(system.Parameters.get(index).Name, Long.toString(timestamp));
} else if (system.Parameters.get(index).Value.equals("LargeTimeStamp")) {
parameters.put(system.Parameters.get(index).Name, Long.toString(largeTimeStamp));
} else if (system.Parameters.get(index).Value.equals("SignitureValue")) {
signitureIndex = index;
} else {
parameters.put(system.Parameters.get(index).Name, system.Parameters.get(index).Value);
}
}
}
if (!system.ContentIdParamName.trim().equals("") && !system.ContentIdParamName.trim().equals("undefined")) {
parameters.put(system.ContentIdParamName, mcpId);
}
HashMap<String, String> headers = new HashMap<String, String>();
for (int index = 0; index < system.Parameters.size(); index++) {
if (system.Parameters.get(index).Type.toLowerCase().equals("header")) {
headers.put(system.Parameters.get(index).Name, system.Parameters.get(index).Value);
}
}
RequestInfo requestInfo = new RequestInfo();
requestInfo.setHttpMethod(system.HttpMethod.toUpperCase());
requestInfo.setIsHttps(system.IsHttps);
if (system.ContentIdParamName.trim().equals("") || system.ContentIdParamName.trim().equals("undefined")) {
requestInfo.setRequestPath(system.RequestPath + mcpId);
} else {
requestInfo.setRequestPath(system.RequestPath);
}
requestInfo.setHost(system.Host);
requestInfo.setParameters(parameters);
requestInfo.setHeaders(headers);
requestInfo.setData(system.Data.replace("$$startDate$$", startDate).replace("$$endDate$$", endDate));
requestInfo.setApiKey(system.ApiKey);
requestInfo.setSecretKey(system.SecretKey);
requestInfo.setSignatureType(system.SignitureType.trim());
String signiture = "";
if (system.SignitureType.trim().equals("SHA-1")) {
requestInfo.setTextToSign(system.HttpMethod.toUpperCase() + clientID + requestInfo.getRequestPath() + "?"
+ SignatureGenerator.concatenateParams(parameters, "&") + system.SecretKey);
signiture = requestInfo.getSignature();
} else if (system.SignitureType.trim().equals("SHA-256")) {
requestInfo.setTextToSign(
requestInfo.getSecretKey() + requestInfo.getHttpMethod() + requestInfo.getRequestPath());
signiture = requestInfo.getSignature();
} else if (system.SignitureType.trim().equals("HmacSHA256")) {
signiture = SignatureGenerator.generatebase64(system.Data, system.SecretKey, timestamp, startDate, endDate,
false);
}
Parameter signitureParameter = new Parameter();
if (signitureIndex > -1) {
signitureParameter.Name = system.Parameters.get(signitureIndex).Name;
signitureParameter.Value = signiture;
} else {
signitureParameter = null;
}
PullingManager pullingManager = new PullingManager();
String result = "";
if (requestInfo.getHttpMethod().equals("GET")) {
result = pullingManager.getFeedData(requestInfo, signitureParameter);
} else {
result = pullingManager.postFeedData(requestInfo, signitureParameter);
}
return result;
}
public static int getPathIndexByAppName(ArrayList<Path> paths, String appName) {
for (int index = 0; index < paths.size(); index++) {
String[] apps = paths.get(index).AppName.split("\\|");
for (String app : apps) {
if (app.toLowerCase().equals(appName.toLowerCase())) {
return index;
}
}
}
return -1;
}
public class listwatcher extends Thread {
public void run() {
/*
* Code that checks for the ArrayList/DB and looks for rows that
* have one or more failures that need to be reverified
*/
}
}
public static String encodeURIComponent(String s) {
String result = null;
try {
result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!")
.replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
}
// This exception should never occur.
catch (UnsupportedEncodingException e) {
result = s;
}
return result;
}
public static void getmcpsyndicatedids() {
int numberOfIterations = 1;
for (int i = 0; i < numberOfIterations; i++) {
// System.out.println("Getting mcp id's number of iterations:" +
// numberOfIterations + ", current iteration:" +i);
long largeTimeStamp = unixtime() + 1209600;
HashMap<String, String> parameters = new HashMap<String, String>();
int signitureIndex = -1;
for (int index = 0; index < mcpSystem.Parameters.size(); index++) {
if (mcpSystem.Parameters.get(index).Type.toLowerCase().equals("param")) {
if (mcpSystem.Parameters.get(index).Value.equals("TimeStampValue")) {
parameters.put(mcpSystem.Parameters.get(index).Name, Long.toString(timestamp));
} else if (mcpSystem.Parameters.get(index).Value.equals("LargeTimeStamp")) {
parameters.put(mcpSystem.Parameters.get(index).Name, Long.toString(largeTimeStamp));
} else if (mcpSystem.Parameters.get(index).Value.equals("SignitureValue")) {
signitureIndex = index;
} else if (mcpSystem.Parameters.get(index).Value.equals("CounterValue")) {
parameters.put(mcpSystem.Parameters.get(index).Name, String.valueOf((i + 1)));
} else {
parameters.put(mcpSystem.Parameters.get(index).Name, mcpSystem.Parameters.get(index).Value);
}
}
}
SignatureGenerator.signrequest(mcpSystem.Data, timestamp);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-type", "text/xml; charset=ISO-8859-1");
RequestInfo requestInfo = new RequestInfo();
requestInfo.setHttpMethod("POST");
requestInfo.setApiKey(mcpSystem.ApiKey);
requestInfo.setSecretKey(mcpSystem.SecretKey);
requestInfo.setData(mcpSystem.Data.replace("$$startDate$$", startDate).replace("$$endDate$$", endDate));
requestInfo.setIsHttps(mcpSystem.IsHttps);
requestInfo.setRequestPath(mcpSystem.RequestPath);
requestInfo.setHost(mcpSystem.Host);
requestInfo.setParameters(parameters);
requestInfo.setHeaders(headers);
requestInfo.setSignatureType("");
Parameter signitureParameter = new Parameter();
if (signitureIndex > -1) {
signitureParameter.Name = mcpSystem.Parameters.get(signitureIndex).Name;
signitureParameter.Value = SignatureGenerator.generatebase64(mcpSystem.Data, mcpSystem.SecretKey,
timestamp, startDate, endDate, false);
} else {
signitureParameter = null;
}
PullingManager pm = new PullingManager();
Document doc = null;
try {
doc = XMLHelper.XMLfromString(pm.postFeedData(requestInfo, signitureParameter));
} catch (Exception ex) {
System.out.println("i has changed from:" + i);
i = i - 1;
System.out.println("i has changed to:" + i);
continue;
}
if (numberOfIterations == 1) {
if (doc.getElementsByTagName("num_pages") == null
|| doc.getElementsByTagName("num_pages").item(0) == null) {
return;
}
numberOfIterations = Integer.parseInt(doc.getElementsByTagName("num_pages").item(0).getTextContent());
}
NodeList nlist = doc.getElementsByTagName("item");
for (int x = 0; x < nlist.getLength(); x++) {
Element e = (Element) nlist.item(x);
String completedDate = e.getElementsByTagName("completed_date").item(0).getTextContent();
boolean isDateInRange = false;
if (!completedDate.equals("")) {
// Jul 13, 2015 02:27:55 EDT
DateFormat mcpFormatter = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss 'EST'");
DateFormat mcpFormatter2 = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss 'EDT'");
try {
Date datetime;
try {
datetime = (Date) mcpFormatter.parse(completedDate);
} catch (Exception ex) {
datetime = (Date) mcpFormatter2.parse(completedDate);
}
Date startDateValue;
try {
startDateValue = ((Date) mcpFormatter2.parse(startDate));
} catch (Exception ex2) {
startDateValue = ((Date) mcpFormatter.parse(startDate));
}
Date endDateValue;
try {
endDateValue = ((Date) mcpFormatter2.parse(endDate));
} catch (Exception ex3) {
endDateValue = ((Date) mcpFormatter.parse(endDate));
}
if (datetime.after(startDateValue) && datetime.before(endDateValue)) {
isDateInRange = true;
}
} catch (ParseException e1) {
isDateInRange = false;
}
}
if (isDateInRange) {
String mcpId = e.getElementsByTagName("upload_id").item(0).getTextContent();
if (!content.containsKey(mcpId)) {
NodeList childNodes = nlist.item(x).getChildNodes();
HashMap<String, String> childContents = new HashMap<String, String>();
for (int childNodesIndex = 0; childNodesIndex < childNodes.getLength(); childNodesIndex++) {
Node childNode = childNodes.item(childNodesIndex);
childContents.put(childNode.getNodeName(), childNode.getTextContent());
}
content.put(mcpId, childContents);
}
}
}
}
}
public static HashMap<String, String> getmcpPrograms() {
HashMap<String, String> programs = new HashMap<String, String>();
boolean notPassed = true;
String data = "";
while (notPassed) {
try {
int numberOfIterations = 1;
for (int i = 0; i < numberOfIterations; i++) {
long largeTimeStamp = unixtime() + 1209600;
HashMap<String, String> parameters = new HashMap<String, String>();
int signitureIndex = -1;
for (int index = 0; index < mcpSystem.Parameters.size(); index++) {
if (mcpSystem.Parameters.get(index).Type.toLowerCase().equals("param")) {
if (mcpSystem.Parameters.get(index).Value.equals("TimeStampValue")) {
parameters.put(mcpSystem.Parameters.get(index).Name, Long.toString(timestamp));
} else if (mcpSystem.Parameters.get(index).Value.equals("LargeTimeStamp")) {
parameters.put(mcpSystem.Parameters.get(index).Name, Long.toString(largeTimeStamp));
} else if (mcpSystem.Parameters.get(index).Value.equals("SignitureValue")) {
signitureIndex = index;
} else if (mcpSystem.Parameters.get(index).Value.equals("CounterValue")) {
parameters.put(mcpSystem.Parameters.get(index).Name, String.valueOf((i + 1)));
} else {
parameters.put(mcpSystem.Parameters.get(index).Name,
mcpSystem.Parameters.get(index).Value);
}
}
}
String strXMLFilename = mcpProgramsPath;
String xml = XMLHelper.xmlparser(strXMLFilename);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-type", "text/xml; charset=ISO-8859-1");
RequestInfo requestInfo = new RequestInfo();
requestInfo.setHttpMethod("POST");
requestInfo.setApiKey(mcpSystem.ApiKey);
requestInfo.setSecretKey(mcpSystem.SecretKey);
requestInfo.setData(xml);
requestInfo.setIsHttps(mcpSystem.IsHttps);
requestInfo.setRequestPath(mcpSystem.RequestPath);
requestInfo.setHost(mcpSystem.Host);
requestInfo.setParameters(parameters);
requestInfo.setHeaders(headers);
requestInfo.setSignatureType("");
Parameter signitureParameter = new Parameter();
if (signitureIndex > -1) {
signitureParameter.Name = mcpSystem.Parameters.get(signitureIndex).Name;
signitureParameter.Value = SignatureGenerator.generatebase64(mcpProgramsPath,
mcpSystem.SecretKey, timestamp, startDate, endDate, true);
} else {
signitureParameter = null;
}
long expiration_time = unixtime() + 1209600;
PullingManager pm = new PullingManager();
Document doc = null;
try {
data = pm.postFeedData(requestInfo, signitureParameter);
doc = XMLHelper.XMLfromString(data);
} catch (Exception ex) {
System.out.println("i has changed from:" + i);
i = i - 1;
System.out.println("i has changed to:" + i);
continue;
}
if (numberOfIterations == 1) {
numberOfIterations = Integer
.parseInt(doc.getElementsByTagName("num_pages").item(0).getTextContent());
}
NodeList nlist = doc.getElementsByTagName("program");
for (int x = 0; x < nlist.getLength(); x++) {
Element e = (Element) nlist.item(x);
String programId = e.getElementsByTagName("program_id").item(0).getTextContent();
programs.put(e.getElementsByTagName("program_title").item(0).getTextContent(), programId);
}
}
notPassed = false;
} catch (Exception ex) {
System.out.println(data);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ex.printStackTrace();
}
}
return programs;
}
public static boolean checkSuccessOfMcpAkamaiLinks(String response, int videoID) {
Document doc = null;
try {
doc = doc = XMLHelper.XMLfromString(response);
} catch (Exception ex) {
}
if (doc != null) {
NodeList nlist = doc.getElementsByTagName("video_published_url");
for (int x = 0; x < nlist.getLength(); x++) {
Element element = (Element) nlist.item(x);
String videoFormat = element.getElementsByTagName("format").item(0).getTextContent();
String videoUrl = element.getElementsByTagName("suburl").item(0).getTextContent();
videoFormat = videoFormat.replace("-mp", "").replace("-", "").replace("bp", "").replace("hpv3", "");
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(
"http://h.univision.com/media" + videoUrl + "." + videoFormat).openConnection();
con.setRequestMethod("HEAD");
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
AkamaiFailedLink failedLink = new AkamaiFailedLink();
failedLink.videoId = videoID;
failedLink.AkamaiLink = "http://h.univision.com/media" + videoUrl + "." + videoFormat;
failedLink.typeId = 1;
FeedDataHelper.insertFailedAkmaiLinkRun(failedLink);
return false;
}
} catch (Exception e) {
AkamaiFailedLink failedLink = new AkamaiFailedLink();
failedLink.videoId = videoID;
failedLink.AkamaiLink = "http://h.univision.com/media" + videoUrl + "." + videoFormat;
failedLink.typeId = 1;
FeedDataHelper.insertFailedAkmaiLinkRun(failedLink);
return false;
}
}
} else {
AkamaiFailedLink failedLink = new AkamaiFailedLink();
failedLink.videoId = videoID;
failedLink.AkamaiLink = "No Data Retrieved";
failedLink.typeId = 1;
FeedDataHelper.insertFailedAkmaiLinkRun(failedLink);
return false;
}
return true;
}
public static ArrayList<Integer> parsemcpresponse(String response) {
ArrayList<Integer> idreturnlist = new ArrayList();
return idreturnlist;
}
public static String getParentTopicValue(String primaryTagId) {
try {
String restMethod = "GET";
String client_id = brightSpotSystem.ApiKey;
String signature = "";
HttpClient client = HttpClientBuilder.create().build();
HttpGet httpget = null;
String secret_key = brightSpotSystem.SecretKey;
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("client_id", client_id);
HashMap<String, String> headers = new HashMap<String, String>();
for (int index = 0; index < brightSpotSystem.Parameters.size(); index++) {
if (brightSpotSystem.Parameters.get(index).Type.toLowerCase().equals("header")) {
headers.put(brightSpotSystem.Parameters.get(index).Name,
brightSpotSystem.Parameters.get(index).Value);
}
}
String urlPath = "/feed/taxonomy/" + primaryTagId + "?client_id=" + client_id;
RequestInfo requestInfo = new RequestInfo();
requestInfo.setHttpMethod(restMethod);
requestInfo.setIsHttps(false);
requestInfo.setRequestPath("/feed/taxonomy/" + primaryTagId);
requestInfo.setHost(brightSpotSystem.Host);
requestInfo.setParameters(parameters);
requestInfo.setHeaders(headers);
requestInfo.setTextToSign(restMethod + client_id + urlPath + secret_key);
requestInfo.setSignatureType("SHA-1");
Parameter signitureParameter = new Parameter();
signitureParameter.Name = "signature";
signitureParameter.Value = requestInfo.getSignature();
PullingManager pm = new PullingManager();
String response = pm.getFeedData(requestInfo, signitureParameter);
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getJSONObject("data").getString("primaryTopicName");
} catch (Exception ex) {
return "";
}
}
public static Date getDateFromString(String strDate, String format) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static long unixtime() {
long unixTime = System.currentTimeMillis() / 1000L;
return unixTime;
}
public static Run getLastRun() {
Run LastRun = null;
int maxId = -1;
for (Run run : FeedDataHelper.getRuns()) {
if (maxId == -1) {
maxId = run.Id;
LastRun = run;
} else if (run.Id > maxId) {
maxId = run.Id;
LastRun = run;
}
}
return LastRun;
}
public static void checkLastRunFailedVideos() {
System.out.println("Last run videos:" + videoIds.size());
HashMap<String, HashMap<String, String>> videos = getmcpVideosByIds(videoIds);
for (String key : videos.keySet()) {
String programId = videos.get(key).get("program_id");
// try{
// Date publishDate = getDateFromString(videos.get(key).get("ts_upload_publish"), "MMM d,yyyy HH:mm:ss");
// if(publishDate.after(new Date())){
// continue;
// }
// }
// catch(Exception ex){
//
// }
//
Date expirationDate = getDateFromString(videos.get(key).get("ts_expire"), "MMM d,yyyy HH:mm:ss");
if (expirationDate.before(new Date())) {
System.out.println(expirationDate.toString() + " before " + (new Date().toString()));
Video video = new Video();
video.Title = videos.get(key).get("title");
video.Duration = videos.get(key).get("duration");
video.RunId = run.Id;
video.isExpired = true;
video.isBrightspot = FeedDataHelper.isVideoSyndicatedToBrightspot(Integer.parseInt(key));
try {
video.McpID = Integer.parseInt(key);
} catch (Exception e) {
continue;
}
video.Id = FeedDataHelper.insertVideo(video);
continue;
}
Video video = new Video();
video.Title = videos.get(key).get("title");
video.Duration = videos.get(key).get("duration");
video.RunId = run.Id;
video.isRerun = true;
video.isExpired = false;
try {
video.McpID = Integer.parseInt(key);
} catch (Exception e) {
continue;
}
video.Id = FeedDataHelper.insertVideo(video);
Date mcpDate = getDateFromString(videos.get(key).get("ts_upload_publish"), "MMM d,yyyy HH:mm:ss");
String programName = getKeyByValueForHash(programs, programId);// .get(programName);
String primaryTagId = programToTagId.get(programId);
String parentTopicName = getParentTopicValue(primaryTagId);
String app = getCurrentApp(parentTopicName);
System.out.println(app);
Program program = new Program();
program.Title = programName;
program.Id = FeedDataHelper.insertProgram(program);
int pathIndex = getPathIndexByAppName(paths, app);
if (pathIndex > -1) {
Path currentPath = paths.get(pathIndex);
boolean assetSyndicationSuccess = true;
ArrayList<Float> attributeAccuracy = new ArrayList<Float>();
ArrayList<Float> transmisionDelayAccuracy = new ArrayList<Float>();
if (pathAssetsCount.containsKey(currentPath.Name.toLowerCase())) {
pathAssetsCount.put(currentPath.Name.toLowerCase(),
pathAssetsCount.get(currentPath.Name.toLowerCase()) + 1);
} else {
pathAssetsCount.put(currentPath.Name.toLowerCase(), 1);
}
boolean adsSuccess = true;
for (entities.System system : currentPath.Systems) {
VideoTranslation videoTranslation = new VideoTranslation();
videoTranslation.VideoId = video.Id;
videoTranslation.SystemId = system.Id;
if (!system.Name.toLowerCase().equals(configs.MCPSystemName)) {
VideoMeasurementXref videoMeasurementXref = new VideoMeasurementXref();
videoMeasurementXref.ProgramID = program.Id;
videoMeasurementXref.VideoID = video.Id;
videoMeasurementXref.PathId = currentPath.Id;
videoMeasurementXref.RunID = run.Id;
videoMeasurementXref.SystemId = system.Id;
videoMeasurementXref.AttributeAccuracy = -1;
videoMeasurementXref.TransmissionDelay = -1;
videoMeasurementXref.AdServer = -1;
videoMeasurementXref.SysndicationOfSuccess = -1;
String result = getSystemResult(system, key);
videoTranslation.SystemRetrievedData = StringEscapeUtils.escapeJava(result);
boolean isXML = false;
if (system.responseType.toLowerCase().equals("xml")) {
isXML = true;
}
if (system.Name.toLowerCase().equals("akamai")) {
assetSyndicationSuccess = checkSuccessOfMcpAkamaiLinks(result, video.Id);
if (assetSyndicationSuccess) {
videoMeasurementXref.SysndicationOfSuccess = 1;
} else {
videoMeasurementXref.SysndicationOfSuccess = 0;
}
// systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id)
// , assetSyndicationSuccess);
} else if (system.hasAdsServer && video.isBrightspot==1) {
adsSuccess = syndicationChecker.attributeHasValueInXml(result);
if (adsSuccess) {
videoMeasurementXref.AdServer = 1;
} else {
videoMeasurementXref.AdServer = 0;
if (FeedDataHelper.getAdServerFailedCount(key) > 1) {
String bsResult = "";
JSONObject bsResultAsJson = null;
try {
bsResult = getSystemResult(brightSpotSystem, key);
bsResultAsJson = syndicationChecker.jsonResponseHasValues(bsResult);
} catch (Exception ex) {
}
String bsFrontendUrl = "";
try {
bsFrontendUrl = bsResultAsJson.getJSONObject("data").getJSONArray("items")
.getJSONObject(0).getString("url");
} catch (Exception ex) {
}
String bsId = "";
try {
bsId = bsResultAsJson.getJSONObject("data").getJSONArray("items")
.getJSONObject(0).getString("uid");
} catch (Exception ex) {
}
sendVideoFailureEmail(key, bsFrontendUrl, bsId);
}
}
// systemManeger.addAdsSuccess(String.valueOf(system.Id)
// , adsSuccess);
} else if (system.hasSyndicationOfSuccess) {
JSONObject resultAsJson = syndicationChecker.jsonResponseHasValues(result);
if (resultAsJson == null) {
System.out.println("######## key:" + key + ",, result:" + result);
assetSyndicationSuccess = false;
videoMeasurementXref.SysndicationOfSuccess = 0;
// systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id)
// , false);
} else if (system.Name.toLowerCase().equals("brightspot") && video.isBrightspot==1
&& !checkBrightspotSyndication(video.Id, resultAsJson, brightSpotSystem,
videoMeasurementXref)) {
System.out.println("######## key:" + key + ",, result:" + result);
assetSyndicationSuccess = false;
videoMeasurementXref.SysndicationOfSuccess = 0;
// systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id),
// false);
} else {
if (system.Name.toLowerCase().equals("brightspot")) {
if(!(video.isBrightspot ==1) ){
continue;
}
String frontEndUrl = JsonHelper.getJsonValueByPath(resultAsJson, "data|items|url");
video.FrontEndLink = frontEndUrl;
FeedDataHelper.updateVideo(video);
}
// systemManeger.addAssetSyndicationSuccess(String.valueOf(system.Id)
// , true);
videoMeasurementXref.SysndicationOfSuccess = 1;
if (!system.VideoIdPath.isEmpty()) {
try {
videoTranslation.SystemVideoId = JsonHelper.getJsonValueByPath(resultAsJson,
system.VideoIdPath);
} catch (Exception ex) {
System.out.println("could not parse video id path: " + system.VideoIdPath
+ " for system " + system.Name);
}
}
if (system.hasAttributeAcuraccy) {
HashMap<String, String> attributePaths = getAttributesAsHashmap(system.Attributes);
HashMap<String, String> mcpAttributeMap = getMcpToOtherSystemAttributeMap(
mcpSystem.Attributes, system.Attributes, true);
HashMap<String, String> attributesToCompare = syndicationChecker
.jsonAttributes(resultAsJson, attributePaths);
float assetAttributeAccuracy = syndicationChecker.CompareAttributes(videos.get(key),
attributesToCompare, mcpAttributeMap, mcpSystem, system, video.Id);
attributeAccuracy.add(assetAttributeAccuracy);
videoMeasurementXref.AttributeAccuracy = assetAttributeAccuracy;
// systemManeger.addAttributeAccuracy(String.valueOf(system.Id)
// , assetAttributeAccuracy);
}
if (system.hasTransmissionDelay) {
String strPubDate = JsonHelper.getJsonValueByPath(resultAsJson,
system.DateFieldPath);
Date pubDate = getDateFromString(strPubDate, system.DateFormat);
float transmissionDelay = syndicationChecker.assetTansmissionDelayAccuracy(mcpDate,
pubDate);
transmisionDelayAccuracy.add(transmissionDelay);
videoMeasurementXref.TransmissionDelay = transmissionDelay;
// systemManeger.addTransmisionDelay(String.valueOf(system.Id),
// transmissionDelay);
}
}
}
if(video.isBrightspot==1 || system.Name.equalsIgnoreCase("akamai")){
FeedDataHelper.insertVideoTranslation(videoTranslation);
FeedDataHelper.insertVideoMeasurementXref(videoMeasurementXref);
}
}
}
VideoTranslation mcpVideoTranslation = new VideoTranslation();
mcpVideoTranslation.VideoId = video.Id;
mcpVideoTranslation.SystemId = mcpSystem.Id;
mcpVideoTranslation.SystemVideoId = key;
FeedDataHelper.insertVideoTranslation(mcpVideoTranslation);
}
}
}
public static String getKeyByValueForHash(HashMap<String, String> table, String value) {
String key_you_look_for = "";
Iterator<Map.Entry<String, String>> iter = table.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
if (entry.getValue().equals(value)) {
key_you_look_for = entry.getKey();
}
}
return key_you_look_for;
}
public static HashMap<String, HashMap<String, String>> getmcpVideosByIds(ArrayList<String> videoIds) {
HashMap<String, HashMap<String, String>> videos = new HashMap<String, HashMap<String, String>>();
for (int i = 0; i < videoIds.size(); i++) {
Document doc = null;
try {
doc = XMLHelper.XMLfromString(QosPathSystemManager.getMcpVideoById(mcpSystem, videoIds.get(i)));
} catch (Exception ex) {
System.out.println("i has changed from:" + i);
i = i - 1;
System.out.println("i has changed to:" + i);
continue;
}
try {
Node videoNode = doc.getElementsByTagName("video").item(0);
NodeList childNodes = videoNode.getChildNodes();
Element e = (Element) videoNode;
String mcpId = e.getElementsByTagName("upload_id").item(0).getTextContent();
String ts_published = e.getElementsByTagName("ts_published").item(0).getTextContent();
String ts_expired = e.getElementsByTagName("ts_expire").item(0).getTextContent();
//String publishDate = e.getElementsByTagName("published").item(0).getTextContent();
HashMap<String, String> childContents = new HashMap<String, String>();
childContents.put("ts_upload_publish", ts_published);
childContents.put("ts_expire", ts_expired);
// childContents.put("published", publishDate);
for (int childNodesIndex = 0; childNodesIndex < childNodes.getLength(); childNodesIndex++) {
Node childNode = childNodes.item(childNodesIndex);
childContents.put(childNode.getNodeName(), childNode.getTextContent());
}
videos.put(mcpId, childContents);
} catch (Exception ex) {
System.out.println(videoIds.get(i) + ":" + ex.getMessage());
}
}
return videos;
}
public static boolean checkBrightspotSyndication(int key, JSONObject brightspotInfo,
entities.System brightspotSystem, VideoMeasurementXref videoMeasurementXref) {
String restMethod = "GET";
String client_id = brightSpotSystem.ApiKey;
String secret_key = brightSpotSystem.SecretKey;
String videoId = JsonHelper.getJsonValueByPath(brightspotInfo, "data|items|uid");
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("client_id", client_id);
HashMap<String, String> headers = new HashMap<String, String>();
for (int index = 0; index < brightSpotSystem.Parameters.size(); index++) {
if (brightSpotSystem.Parameters.get(index).Type.toLowerCase().equals("header")) {
headers.put(brightSpotSystem.Parameters.get(index).Name, brightSpotSystem.Parameters.get(index).Value);
}
}
String urlPath = "/feed/content/video/" + videoId + "?client_id=" + client_id;
RequestInfo requestInfo = new RequestInfo();
requestInfo.setHttpMethod(restMethod);
requestInfo.setIsHttps(false);
requestInfo.setRequestPath("/feed/content/video/" + videoId);
requestInfo.setHost(brightSpotSystem.Host);
requestInfo.setParameters(parameters);
requestInfo.setHeaders(headers);
requestInfo.setTextToSign(restMethod + client_id + urlPath + secret_key);
requestInfo.setSignatureType("SHA-1");
Parameter signitureParameter = new Parameter();
signitureParameter.Name = "signature";
signitureParameter.Value = requestInfo.getSignature();
PullingManager pm = new PullingManager();
String response = pm.getFeedData(requestInfo, signitureParameter);
// System.out.println(response);
JSONObject jsonObject = new JSONObject(response);
JSONArray arr = null;
try {
arr = jsonObject.getJSONObject("data").getJSONArray("videoLocations");
} catch (Exception ex) {
}
videoMeasurementXref.Note = "";
boolean hasMp4 = false;
boolean hasM3u8 = false;
boolean hasFailedLink = false;
String strFailedLink = "";
if (arr != null) {
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
String url = obj.getString("url");
if (url.trim().toLowerCase().endsWith(".mp4")) {
hasMp4 = true;
}
if (url.trim().toLowerCase().endsWith(".m3u8")) {
hasM3u8 = true;
}
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con;
try {
con = (HttpURLConnection) new URL(url.trim()).openConnection();
con.setRequestMethod("HEAD");
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
hasFailedLink = true;
AkamaiFailedLink failedLink = new AkamaiFailedLink();
failedLink.videoId = key;
failedLink.AkamaiLink = url;
strFailedLink = url;
failedLink.typeId = 2;
FeedDataHelper.insertFailedAkmaiLinkRun(failedLink);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
videoMeasurementXref.Note += "No video locations specified ";
}
if (arr != null && !hasMp4) {
videoMeasurementXref.Note += "Does not have mp4 link,";
}
if (arr != null && !hasM3u8) {
videoMeasurementXref.Note += "Does not have m3u8 link,";
}
if (arr != null && hasFailedLink) {
videoMeasurementXref.Note += "This link does not return 200 status:" + strFailedLink;
}
if (arr != null && hasMp4 && hasM3u8 && !hasFailedLink) {
return true;
} else {
return false;
}
}
static void sendVideoFailureEmail(String mcpId, String frontendUrl, String bsId) {
String username = "univisionvideofailure@gmail.com";
String password = "univision123";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("univisionvideofailure-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
"kabdelqader@aspire-infotech.net,DigitalOperations@univision.net,pmadan@US.UNIVISION.COM,ashriber@US.UNIVISION.COM,VSankar@us.univision.com,ssrinivasan@us.univision.com,JNassar@aspire-infotech.net"));
message.setSubject("Video not in Add server");
message.setText("Video with mcp id:" + mcpId + ", does not exist in ad server." + "\r\n Frontend Url:"
+ frontendUrl + ".\r\n"
+ "Brightspot link:https://cms.uvn.io/manage/content/edit.jsp?typeId=00000147-f39e-d38e-a5f7-f79f74ce0026&id="
+ bsId);
Transport.send(message);
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
C
|
UTF-8
| 5,663
| 2.59375
| 3
|
[] |
no_license
|
//! \file func_s.h
//! \brief Realize functions compatible with VC++ 6.0 and below
#ifndef FUNCTIONS_COMPATIBLE_VC60_H
#define FUNCTIONS_COMPATIBLE_VC60_H
#if !defined(_MSC_VER) || _MSC_VER < 1400 // not VC8
#ifdef __GNUC__
#include <wchar.h>
#include <wctype.h>
#endif
#ifndef max
#define max(a,b) ((a)>(b)?(a):(b))
#endif
#ifndef min
#define min(a,b) ((a)<(b)?(a):(b))
#endif
#if defined(_STDIO_DEFINED) // stdio.h
inline int sprintf_s(char *buffer, size_t, const char *format, ...)
{
va_list arglist;
va_start(arglist, format);
return vsprintf(buffer, format, arglist);
}
inline int swprintf_s(wchar_t *buffer, size_t size, const wchar_t *format, ...)
{
va_list arglist;
va_start(arglist, format);
#if !defined(_WIN32)
return vswprintf(buffer, size, format, arglist);
#else
size; return vswprintf(buffer, format, arglist);
#endif
}
inline int vsprintf_s(char *buffer, size_t, const char *format, va_list arglist)
{ return vsprintf(buffer, format, arglist); }
inline int vswprintf_s(wchar_t *buffer, size_t size, const wchar_t *format, va_list arglist)
#if !defined(_WIN32)
{ return vswprintf(buffer, size, format, arglist); }
#else
{ size; return vswprintf(buffer, format, arglist); }
#endif
#endif // _INC_STDIO
inline int strcpy_s(char *str, size_t size, const char *src)
{ return strncpy(str, src, size) ? 0 : -1; }
inline int wcscpy_s(wchar_t *str, size_t size, const wchar_t *src)
{ return wcsncpy(str, src, size) ? 0 : -1; }
inline int strncpy_s(char *str, size_t size, const char *src, size_t len)
{ return strncpy(str, src, min(size, len)) ? 0 : -1; }
inline int wcsncpy_s(wchar_t *str, size_t size, const wchar_t *src, size_t len)
{ return wcsncpy(str, src, min(size, len)) ? 0 : -1; }
inline int strcat_s(char *str, size_t, const char *src)
{ return strcat(str, src) ? 0 : -1; }
inline int wcscat_s(wchar_t *str, size_t, const wchar_t *src)
{ return wcscat(str, src) ? 0 : -1; }
inline wchar_t * _wcslwr_s(wchar_t *str)
{ for (wchar_t* p = str; *p; p++) towlower(*p); return str; }
inline wchar_t * _wcsupr_s(wchar_t *str)
{ for (wchar_t* p = str; *p; p++) towupper(*p); return str; }
#if defined(_WIN32)
inline int _ltoa_s(long value, char *str, size_t, int radix)
{ _ltoa(value, str, radix); return errno; }
inline int _ltow_s(long value, wchar_t *str, size_t, int radix)
{ _ltow(value, str, radix); return errno; }
inline int _itoa_s(int value, char *str, size_t, int radix)
{ _itoa(value, str, radix); return errno; }
inline int _itow_s(int value, wchar_t *str, size_t, int radix)
{ _itow(value, str, radix); return errno; }
inline int _ultow_s(unsigned long value, wchar_t *str, size_t, int radix)
{ _ultow(value, str, radix); return errno; }
#elif defined(_STDIO_DEFINED)
inline int _ltoa_s(long value, char *str, size_t size, int radix)
{ sprintf_s(str, size, 16 == radix ? "%lx" : "%ld", value); return 0; }
inline int _ltow_s(long value, wchar_t *str, size_t size, int radix)
{ swprintf_s(str, size, 16 == radix ? L"%lx" : L"%ld", value); return 0; }
inline int _itoa_s(int value, char *str, size_t size, int radix)
{ return _ltoa_s(value, str, size, radix); }
inline int _itow_s(int value, wchar_t *str, size_t size, int radix)
{ return _ltow_s(value, str, size, radix); }
inline int _ultow_s(unsigned long value, wchar_t *str, size_t size, int radix)
{ swprintf_s(str, size, 16 == radix ? L"%ulx" : L"%uld", value); return 0; }
#endif
#if (defined(_INC_STDLIB) || defined(_STDLIB_H_)) && defined(_WIN32)
inline int _splitpath_s(
const char * path, char * drive, size_t,
char * dir, size_t,
char * fname, size_t,
char * ext, size_t)
{
_splitpath(path, drive, dir, fname, ext);
return errno;
}
inline int _wsplitpath_s(
const wchar_t * path, wchar_t * drive, size_t,
wchar_t * dir, size_t,
wchar_t * fname, size_t,
wchar_t * ext, size_t)
{
_wsplitpath(path, drive, dir, fname, ext);
return errno;
}
inline int _makepath_s(char *path, size_t,
const char *drive, const char *dir, const char *fname, const char *ext)
{
_makepath(path, drive, dir, fname, ext);
return errno;
}
inline int _wmakepath_s(wchar_t *path, size_t,
const wchar_t *drive, const wchar_t *dir, const wchar_t *fname, const wchar_t *ext)
{
_wmakepath(path, drive, dir, fname, ext);
return errno;
}
#endif // _INC_STDLIB
#ifdef _INC_TIME // time.h
inline void localtime_s(struct tm *tmOut, const time_t *timer)
{
struct tm * p = localtime(timer);
if (tmOut != NULL && p != NULL)
*tmOut = *p;
}
#endif // _INC_TIME
#define _sopen_s(fileHandler, filename, oflag, pmode, rw) \
(*fileHandler = _open(filename, oflag, pmode), errno)
#ifdef UNICODE
#define _stprintf_s swprintf_s
#define _vstprintf_s vswprintf_s
#define _tcscpy_s wcscpy_s
#define _tcsncpy_s wcsncpy_s
#define _tcscat_s wcscat_s
#define _tsplitpath_s _wsplitpath_s
#define _tmakepath_s _wmakepath_s
#define _ltot_s _ltow_s
#define _itot_s _itow_s
#else
#define _stprintf_s sprintf_s
#define _vstprintf_s vsprintf_s
#define _tcscpy_s strcpy_s
#define _tcsncpy_s strncpy_s
#define _tcscat_s strcat_s
#define _tsplitpath_s _splitpath_s
#define _tmakepath_s _makepath_s
#define _ltot_s _ltoa_s
#define _itot_s _itoa_s
#endif // UNICODE
#endif // _MSC_VER
#ifndef GET_WHEEL_DELTA_WPARAM
#define GET_WHEEL_DELTA_WPARAM(wParam) ((short)HIWORD(wParam))
#endif
#ifndef _countof
#define _countof(array) (sizeof(array)/sizeof(array[0]))
#endif
#endif // FUNCTIONS_COMPATIBLE_VC60_H
|
Markdown
|
UTF-8
| 998
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
teamcity-notifier
=================
Node-project that can fire events when a build fails or is fixed in Teamcity
```js
var TeamCity = require('teamcity-notifier');
var tc = new TeamCity({
host: 'teamcity-server',
port: 80,
user: 'username',
password: 'password'
});
tc.on('unauthorized', function() {
console.log('Invalid teamcity credentials, stopping');
test.stop();
});
tc.on('new-build', function(build) {
console.log('New build started for ' + build.buildTypeId);
});
tc.on('finished-build', function(build) {
console.log('Build finished for ' + build.buildTypeId);
});
tc.on('error', function(e) {
console.log('An error occured: ' + e.message);
test.stop();
});
tc.on('status-changed', function(oldBuild, newBuild) {
if(oldBuild.status === 'SUCCESS' && newBuild.status === 'FAILURE') {
console.log('Build for ' + build.buildTypeId + ' broke!');
}
});
tc.on('state-changed', function(oldBuild, newBuild) {
// Well, do something!
});
tc.start();
```
|
PHP
|
UTF-8
| 1,147
| 2.5625
| 3
|
[] |
no_license
|
<?php
session_start();
if (empty($_POST['answer']))
{
exit(0);
}
$memcache = new Memcache;
$memcache->connect('localhost',11211) or die("Could not connect to memcache");
// Check user answer against correct answer ($memcache->get('answer'))
// Create new database connection if correct and update user score
similar_text($memcache->get('answer'), $_POST['answer'], $compare);
// echo $memcache->get('answer')." ".$_POST['answer']." ".$compare;
if ($compare >= 80.0)
{
// echo "correct";
$servername = "localhost";
$username = "webmaster";
$password = "triviadb";
$dbname = "CXC";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
$_SESSION['score'] = $_SESSION['score'] + 1;
$sql = "UPDATE player SET score=".$_SESSION['score']." WHERE ip='".$_SESSION['ip']."';";
if ($conn->query($sql) === TRUE)
{
echo "Score Updated";
}
else
{
echo "Failed updating ".$sql;
}
$conn->close();
exit(0);
}
echo $memcache->get('answer')." ".$_POST['answer']." ".$compare;
exit(0);
?>
|
PHP
|
UTF-8
| 748
| 2.6875
| 3
|
[] |
no_license
|
<?php
// Load Environment Variables from .env
require_once __DIR__.'/vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$host = getenv('MYSQL_HOST');
$user = getenv('MYSQL_USERNAME');
$password = getenv('MYSQL_PASSWORD');
$db = getenv('MYSQL_DATABASE');
$port = getenv('MYSQL_PORT');
try{
$pdo = new \PDO('mysql:host='.$host.';port='.$port.';dbname='.$db.';charset=utf8mb4',
$user,
$password,
array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
}
catch(\PDOException $ex){
print($ex->getMessage());
}
?>
|
SQL
|
UTF-8
| 3,978
| 2.765625
| 3
|
[] |
no_license
|
CREATE TABLE OrdLine
( OrdNo CHAR(8),
ProdNo CHAR(8),
Qty INTEGER DEFAULT 1,
CONSTRAINT PKOrdLine PRIMARY KEY (OrdNo, ProdNo),
CONSTRAINT FKOrdNo FOREIGN KEY (OrdNo) REFERENCES OrderTbl
ON DELETE CASCADE,
CONSTRAINT FKProdNo FOREIGN KEY (ProdNo) REFERENCES Product );
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1116324','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1231231','P0036566',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1231231','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1241518','P0036577',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1455122','P4200344',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1579999','P1556678',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1579999','P6677900',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1579999','P9995676',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1615141','P0036566',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1615141','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1615141','P4200344',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1656777','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O1656777','P1556678',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O2233457','P0036577',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O2233457','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O2334661','P0036566',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O2334661','P1412138',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O2334661','P1556678',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3252629','P4200344',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3252629','P9995676',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3331222','P1412138',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3331222','P1556678',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3331222','P3455443',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3377543','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O3377543','P9995676',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O4714645','P0036566',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O4714645','P9995676',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O5511365','P1412138',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O5511365','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O5511365','P1556678',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O5511365','P3455443',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O5511365','P6677900',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O6565656','P0036566',10);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7847172','P1556678',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7847172','P6677900',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7959898','P1412138',5);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7959898','P1556678',5);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7959898','P3455443',5);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7959898','P6677900',5);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7989497','P1114590',2);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7989497','P1412138',2);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O7989497','P1445671',3);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O8979495','P1114590',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O8979495','P1412138',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O8979495','P1445671',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O9919699','P0036577',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O9919699','P1114590',1);
INSERT INTO ordline
(OrdNo, ProdNo, Qty)
VALUES('O9919699','P4200344',1);
|
Swift
|
UTF-8
| 5,188
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// EventDispatcher.swift
// Player
//
// Created by Fredrik Sjöberg on 2017-11-23.
// Copyright © 2017 emp. All rights reserved.
//
import Foundation
import AVFoundation
/// Dispatch class used by the player to trigger registered event callbacks.
///
/// `Tech` implementations should trigger the related events where appropriate.
public class EventDispatcher<Context: MediaContext, Tech: PlaybackTech> {
/// Should be triggered when the requested media is created, but not yet loaded
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackCreated: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered once the requested media is loaded
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackPrepared: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered when playback is ready to start
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackReady: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered once the playback starts for the first time
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackStarted: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered by the user pausing playback
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackPaused: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered by the user resuming playback
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackResumed: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered by the user aborting playback
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackAborted: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered once playback reaches end of stream
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onPlaybackCompleted: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered if an error during its lifetime
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
/// - parameter error: `Error` encountered
internal(set) public var onError: (Tech?, Context.Source?, PlayerError<Tech, Context>) -> Void = { _,_,_ in }
/// Should be triggered when the bitrate changes
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
/// - parameter bitrate: New bitrate
internal(set) public var onBitrateChanged: (Tech, Context.Source, Double) -> Void = { _,_,_ in }
/// Should be triggered when buffering is required
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onBufferingStarted: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered when buffering finished
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onBufferingStopped: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered by the user seeking to time
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
/// - parameter offset: New offset
internal(set) public var onPlaybackScrubbed: (Tech, Context.Source, Int64) -> Void = { _,_,_ in }
/// Should be triggered when the duration of `source` changes
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
internal(set) public var onDurationChanged: (Tech, Context.Source) -> Void = { _,_ in }
/// Should be triggered when a *warning* for either the `Tech` or the `Context` occurs.
///
/// - parameter tech: `Tech` broadcasting the event
/// - parameter source: `MediaSource` causing the event
/// - parameter warning: `Warning` encountered
internal(set) public var onWarning: (Tech, Context.Source?, PlayerWarning<Tech, Context>) -> Void = { _,_,_ in }
/// Should be triggered when a *DateRangeMetadataChanged*.
internal(set) public var onDateRangeMetadataChanged: (_ metaDataGroup: [AVDateRangeMetadataGroup], _ indexesOfNewGroups: IndexSet, _ indexesOfModifiedGroups: IndexSet ) -> Void = { _, _, _ in }
}
|
Python
|
UTF-8
| 2,088
| 4.125
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 24 09:32:26 2019
@author: Training29
"""
####1.Write a Python program to create a tuple. ####
x = (4,6,7)
print(x)
###2. Write a Python program to create a tuple with different data types ###
tuple = ("vijay", True, 7.5, 1)
print(tuple)
###3. Write a Python program to add an item in a tuple ###
#### To add 3 methods #######
tuple = (4, 6, 2, 8, 3, 1)
print(tuple)
### Method 1 Using + Operator
tuple = tuple + (9,10,52)
print(tuple)
### Method 2 adding specific index ####
tuple = tuple[:4] + (22,15,41) + tuple[:3]
print(tuple)
### Method 3 converting the tuple to list ####
list = list[(tuple)]
list.append(25)
tuple = tuple(list)
print(tuple)
##### Pending #############
####4. Write a Python program to convert a tuple to a string. #####
a = ('v', 'i', 'j', 'a', 'y', 'a', 'k', 'u', 'm','a','r')
str = ''.join(a)
print(str)
###5. Write a Python program to check whether an element exists within a tuple ####
a = ("v", "i", "j", "a", "y", "a", "k", "u", "m", "a","r",5,4)
print("r" in a)
print(2 in a)
####6. Write a Python program to convert a list to a tuple #######
a = [4, 8, 2, 42, 11]
print(a)
tuple = tuple(a)
print(a)
####7. Write a Python program to remove an item from a tuple #######
a = ("v", "i", "j", "a", "y", "a", "k", "u", "m","a","r",8,4)
print(a)
### Method 1 Using + Operator remove an item #####
a = a[:4] + a[5:]
print(a)
#converting the tuple to list ######
listx = list(a)
listx.remove("i")
a = tuple(listx)
print(a)
########## PENDING #################
###8. Write a Python program to find the length of a tuple ####
a = tuple("vijayakumar")
print(a)
print(len(a))
########## PENDING ###############
###9. Write a Python program to convert a tuple to a dictionary ***
tuple = (('vijay','name'),('raj','name'))
print(dict((a,b) for a,b in tuple))
###10. Write a Python program to reverse a tuple ######
a = ("vijay")
b = reversed(a)
print(tuple(b))
####### PENDING ####################3
|
JavaScript
|
UTF-8
| 437
| 2.796875
| 3
|
[] |
no_license
|
(function (exports) {
let count = 0;
function Headline(webTitle, webUrl) {
this.webTitle = webTitle;
this.webUrl = webUrl;
this.id = count++;
console.log(this.id);
Object.defineProperty(this, 'title', {
get() {
return this.webTitle;
},
});
Object.defineProperty(this, 'url', {
get() {
return this.webUrl;
},
});
}
exports.Headline = Headline;
})(this);
|
SQL
|
UTF-8
| 1,801
| 3.578125
| 4
|
[] |
no_license
|
CREATE DATABASE roster;
DROP TABLE IF EXISTS `Member`;
DROP TABLE IF EXISTS `User`;
DROP TABLE IF EXISTS `Course`;
CREATE TABLE `User` (
user_id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(128) UNIQUE,
PRIMARY KEY(user_id)
) ENGINE=InnoDB CHARACTER SET=utf8;
INSERT INTO `user`(`user_id`, `name`) VALUES
(1,"Greer"),
(2,"Aiva"),
(3,"Eduards"),
(4,"Finnen"),
(5,"Suzi"),
(6,"Zak"),
(7,"Aisha"),
(8,"Astra"),
(9,"Nick"),
(10,"Oluwatoni"),
(11,"Janie"),
(12,"Andrew"),
(13,"Christy"),
(14,"Peggy"),
(15,"Shaw");
CREATE TABLE Course (
course_id INTEGER NOT NULL AUTO_INCREMENT,
title VARCHAR(128) UNIQUE,
PRIMARY KEY(course_id)
) ENGINE=InnoDB CHARACTER SET=utf8;
INSERT INTO `course`(`course_id`, `title`) VALUES
(1,"si106"),
(2,"si110"),
(3,"si206");
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
CONSTRAINT FOREIGN KEY (user_id) REFERENCES `User` (user_id)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (course_id) REFERENCES Course (course_id)
ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (user_id, course_id)
) ENGINE=InnoDB CHARACTER SET=utf8;
INSERT INTO `member`(`user_id`, `course_id`, `role`) VALUES
(6,2,1),
(12,3,0),
(7,2,0),
(13,3,0),
(8,2,0),
(9,2,0),
(2,1,0),
(14,3,0),
(15,3,0),
(3,1,0),
(4,1,0),
(11,3,1),
(1,1,1),
(10,2,0),
(5,1,0);
-- Greer, si106, Instructor
-- Aiva, si106, Learner
-- Eduards, si106, Learner
-- Finnen, si106, Learner
-- Suzi, si106, Learner
-- Zak, si110, Instructor
-- Aisha, si110, Learner
-- Astra, si110, Learner
-- Nick, si110, Learner
-- Oluwatoni, si110, Learner
-- Janie, si206, Instructor
-- Andrew, si206, Learner
-- Christy, si206, Learner
-- Peggy, si206, Learner
-- Shaw, si206, Learner
|
PHP
|
UTF-8
| 856
| 2.609375
| 3
|
[] |
no_license
|
<?php
namespace App\Exports;
use App\Models\User;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
class StaffsExport implements FromCollection, WithMapping, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::where('role', 'admin')->orWhere('role', 'doctor')->get();
}
public function headings(): array
{
return [
'Name',
'Email',
'Role',
'Created date',
];
}
public function map($user): array
{
return [
$user->name,
$user->email,
$user->role,
Carbon::parse($user->created_at)->toDateTimeString(),
];
}
}
|
Python
|
UTF-8
| 2,931
| 2.578125
| 3
|
[] |
no_license
|
"""perform feature extraction, produce training dataset
"""
from __future__ import division
from copy import deepcopy
from datetime import datetime
from functools import partial
from multiprocessing.pool import ThreadPool as Pool
from os import listdir as _dir
import numpy as np
import pandas as pd
from common import counter
from common import feature_extraction
from common import logger
__author__ = 'ceidKaggle: gryllos@ceid.upatras.gr'
safe = pd.read_csv('train_and_test_data_labels_safe.csv')
safe = set(safe[safe['safe']==1]['image'])
def create_dataset(folder):
# checking last letter of folder name to see if testing or training stage
if folder.split('_')[0][-1] == 'n':
from common import FEATURES as features
stage = 'train'
else:
from common import PREDICTORS as features
stage = 'test'
columns = deepcopy(features)
columns.extend(['File', 'Class'])
ds = pd.DataFrame(columns=columns)
if stage == 'test':
if len(folder.split('_')) == 3:
files = [f for f in _dir(folder)]
else:
files = [f for f in _dir(folder) if f in safe]
ds['File'] = files
if stage == 'train':
# extract names and labels of files to put them in the ds
file_cl = [(f, f.split('_')[-1].split('.')[0]) for f in _dir(folder)]
file_cl = [(f, p) for f, p in file_cl if f in safe]
ds['File'] = np.asarray(file_cl)[:, 0]
ds['Class'] = np.asarray(file_cl)[:, 1]
logger.info('Creating ds: {} rows'.format(len(ds)))
_counter = counter().next
_feature_extraction = partial(
feature_extraction, _counter, stage, len(ds))
ds[features] = map(_feature_extraction, ds['File'])
return ds, folder
if __name__ == '__main__':
# set those options to enable creation of both testing dataset and
# training dataset
dt = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
train_folders = ['../train_1', '../train_2', '../train_3']
test_folders = ['../test_1_new', '../test_2_new', '../test_3_new']
data_folders = train_folders + test_folders
# parallel creation of training and testing datasets
pool = Pool(9)
results = pool.map(create_dataset, data_folders)
pool.close()
pool.join()
tr_results = [ds for ds, folder in results if folder in train_folders]
train_ds = pd.concat(tr_results)
logger.info('train_ds Created')
print(train_ds)
train_ds = train_ds.iloc[np.random.permutation(len(train_ds))]
train_ds.dropna(inplace=True)
train_ds = train_ds[train_ds['avg_4']!=0] # throwing away zero sig
train_ds.to_csv('training_dataset_{}.csv'.format(dt), index=False)
te_results = [ds for ds, folder in results if folder in test_folders]
test_ds = pd.concat(te_results)
logger.info('test_ds Created')
print(test_ds)
test_ds.to_csv('testing_dataset_{}.csv'.format(dt), index=False)
|
C++
|
UTF-8
| 327
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
#include "TimeUtils.h"
TimeUtils::TimeUtils()
{
}
TimeUtils::~TimeUtils()
{
}
void TimeUtils::start()
{
startTime = high_resolution_clock::now();
}
void TimeUtils::stop()
{
endTime= high_resolution_clock::now();
}
long TimeUtils::getDuration()
{
return (long)duration_cast<nanoseconds>(endTime - startTime).count();
}
|
Markdown
|
UTF-8
| 532
| 2.5625
| 3
|
[] |
no_license
|
# React
### Setting up
1. Install yarn
- Installing on Windows:
1. Get Node.js
https://nodejs.org/en/
2. Install Yarn package
https://yarnpkg.com/latest.msi
2. Run `yarn create react-app your-app-name`
- if you come across an issue like `is not recognized as an internal or external command, operable program or batch file`, then run the following:
```sh
yarn global add create-react-app
create-react-app my-app
```
3. Run your app
```sh
cd your-app-name
yarn start
```
- This will run your app on localhost:3000
|
Java
|
UTF-8
| 2,549
| 1.789063
| 2
|
[] |
no_license
|
package org.muhia.app.psi.portal.controllers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.muhia.app.psi.integ.wsdl.mpesa.cbp.request.ObjectFactory;
import org.muhia.app.psi.integ.wsdl.mpesa.cbp.request.Response;
import org.muhia.app.psi.integ.wsdl.mpesa.cbp.request.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
Copyright 2015-2017 the original author or authors.
<p>
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
<p>
http://www.apache.org/licenses/LICENSE-2.0
<p>
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.
Created by Kenneth Muhia <muhia@muhia.org>
Project: psi
Package: org.muhia.app.psi.portal
Generated on: 17-Feb-17, 06:28.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MpesaControllerTests {
@Autowired
private
MpesaController mockMpesaController;
@Test
public void mpesaResultsCallBackProcessorTest() {
String testXml = "</s:Envelope>";
ObjectFactory objectFactory = new ObjectFactory();
Result mockrequest = objectFactory.createResult();
mockrequest.setConversationID("1233");
QName qName = new QName("http://api-v1.gen.mm.vodafone.com/mminterface/request");
mockrequest.setOriginatorConversationID(new JAXBElement<>(qName, String.class, "12345"));
mockrequest.setResultCode("0");
mockrequest.setResultType(new JAXBElement<>(qName, BigInteger.class, new BigInteger("1")));
MockHttpServletRequest request = new MockHttpServletRequest("POST", testXml);
ResponseEntity<Response> response = mockMpesaController.mpesaResultsCallBackProcessor(mockrequest);
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Response " + response.getBody());
}
}
|
Python
|
UTF-8
| 845
| 3.671875
| 4
|
[
"Apache-2.0"
] |
permissive
|
import json
def get_user():
"""Get the users name if it exists"""
filename = 'user_db.json'
try:
with open(f'txt_files/{filename}') as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def create_new_user():
"""Prompt user to enter desired username"""
username = input('Vad är ditt användarID?: ')
filename = 'user_db.json'
with open(f'txt_files/{filename}', 'w') as f:
json.dump(username, f)
return username
def greet_user():
"""Greet user by name"""
username = get_user()
if username:
print(f"Välkommen tillbaks {username.title()}!!")
else:
username = create_new_user()
print(f"Vi kommer ihåg dig när du återvänder {username}")
greet_user()
|
Java
|
UTF-8
| 16,092
| 2.09375
| 2
|
[
"Unlicense"
] |
permissive
|
package de.azrael.commandsContainer;
import java.awt.Color;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.azrael.constructors.Cache;
import de.azrael.constructors.Guilds;
import de.azrael.constructors.Ranking;
import de.azrael.constructors.WeaponAbbvs;
import de.azrael.constructors.WeaponStats;
import de.azrael.constructors.Weapons;
import de.azrael.core.Hashes;
import de.azrael.enums.Translation;
import de.azrael.randomshop.RandomshopItemDrawer;
import de.azrael.randomshop.RandomshopRewardDrawer;
import de.azrael.sql.RankingSystem;
import de.azrael.sql.RankingSystemItems;
import de.azrael.util.STATIC;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public class RandomshopExecution {
private static final Logger logger = LoggerFactory.getLogger(RandomshopExecution.class);
public static void runHelp(GuildMessageReceivedEvent e, List<WeaponAbbvs> abbreviations, List<String> categories) {
EmbedBuilder message = new EmbedBuilder().setColor(Color.BLUE);
if(abbreviations.size() == 0 && categories.size() == 0) {
e.getChannel().sendMessage(message.setColor(Color.RED).setDescription(STATIC.getTranslation(e.getMember(), Translation.RANDOMSHOP_NOT_AVAILABLE)).build()).queue();
}
else {
message.setTitle(STATIC.getTranslation(e.getMember(), Translation.EMBED_TITLE_DETAILS)).setDescription(STATIC.getTranslation(e.getMember(), Translation.RANDOMSHOP_HELP));
if(abbreviations.size() > 0) {
//display all weapons
StringBuilder out1 = new StringBuilder();
StringBuilder out2 = new StringBuilder();
boolean switcher = false;
for(WeaponAbbvs abbv : abbreviations) {
if(switcher == false) {
switcher = true;
out1.append(abbv.getDescription()+"\n");
}
else {
switcher = false;
out2.append(abbv.getDescription()+"\n");
}
}
message.addField(STATIC.getTranslation(e.getMember(), Translation.RANDOMSHOP_WEP_TYPES), "_"+out1.toString()+"_", true);
message.addField("", "_"+out2.toString()+"_", true);
message.addBlankField(false);
}
if(categories.size() > 0) {
//display all categories
StringBuilder out1 = new StringBuilder();
StringBuilder out2 = new StringBuilder();
boolean switcher = false;
for(String category : categories) {
if(switcher == false) {
switcher = true;
out1.append(category+"\n");
}
else {
switcher = false;
out2.append(category+"\n");
}
}
message.addField(STATIC.getTranslation(e.getMember(), Translation.RANDOMSHOP_WEP_CATEGORIES), "_"+out1.toString()+"_", true);
message.addField("", "_"+out2.toString()+"_", true);
}
//print message
e.getChannel().sendMessage(message.build()).queue();
}
}
public static void runRound(GuildMessageReceivedEvent e, List<WeaponAbbvs> abbreviations, List<String> categories, String input) {
var cache = Hashes.getTempCache("randomshop_playDelay_gu"+e.getGuild().getId()+"us"+e.getMember().getUser().getId());
if(cache == null || cache.getExpiration() - System.currentTimeMillis() <= 0) {
Hashes.addTempCache("randomshop_playDelay_gu"+e.getGuild().getId()+"us"+e.getMember().getUser().getId(), new Cache(3000));
//first, search for results from the available lists
final String abbv;
final String category;
WeaponAbbvs weapon_abbv = abbreviations.parallelStream().filter(a -> a.getDescription().equalsIgnoreCase(input)).findAny().orElse(null);
if(weapon_abbv != null) {
abbv = weapon_abbv.getAbbv();
}
else {
abbv = null;
}
if(abbv == null) {
category = categories.parallelStream().filter(c -> c.equalsIgnoreCase(input)).findAny().orElse(null);
}
else {
category = null;
}
//second, check if anything has been found, else interrupt the process
if(abbv != null || category != null) {
Guilds guild_settings = RankingSystem.SQLgetGuild(e.getGuild().getIdLong());
Ranking user_details = RankingSystem.SQLgetWholeRankView(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong());
final long price = guild_settings.getRandomshopPrice();
if(user_details.getCurrency() >= price) {
List<WeaponStats> stats = RankingSystemItems.SQLgetWeaponStats(e.getGuild().getIdLong());
if(stats.size() > 0) {
final int rand = ThreadLocalRandom.current().nextInt(0, stats.size());
user_details.setCurrency(user_details.getCurrency()-price);
long extend = 0;
var weapon_id = 0;
var editedRows = 0;
//get a random weapon id basing of either abbreviation or category and the random stat
var number = 0;
if(abbv != null) {
weapon_id = RankingSystemItems.SQLgetRandomWeaponIDByAbbv(abbv, stats.get(rand).getID(), e.getGuild().getIdLong());
number = RankingSystemItems.SQLgetNumberOfWeaponID(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong(), weapon_id);
}
else {
weapon_id = RankingSystemItems.SQLgetRandomWeaponIDByCategory(e.getGuild().getIdLong(), category, stats.get(rand).getID());
number = RankingSystemItems.SQLgetNumberOfWeaponID(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong(), weapon_id);
}
if(number == -1) {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(e.getMember(), Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(e.getMember(), Translation.GENERAL_ERROR)).build()).queue();
logger.error("It couldn't be verified if weapon {} already exists in inventory of user {} in guild {}", weapon_id, e.getMember().getUser().getId(), e.getGuild().getId());
return;
}
if(weapon_id > 0) {
final var weapons = RankingSystemItems.SQLgetWholeWeaponShop(e.getGuild().getIdLong());
if(weapons != null) {
final var selWeapon = weapon_id;
//since the first query to retrieve the weapon id worked, we will assume that the weapon has been found
final var weapon = weapons.parallelStream().filter(w -> w.getWeaponID() == selWeapon).findAny().orElse(null);
//calculate if weapon will be timed or permanent
switch(weapon.getOverlayLevel()) {
case 1, 2 -> {
extend = randomizeWeaponDuration(false);
}
case 3 -> {
extend = randomizeWeaponDuration(true);
}
}
if(extend == 0) {
editedRows = RankingSystemItems.SQLUpdateCurrencyAndInsertWeaponRandomshop(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong(), user_details.getCurrency(), weapon_id, new Timestamp(System.currentTimeMillis()), (number+1));
}
else {
final var inventoryItem = RankingSystemItems.SQLgetNumberAndExpirationFromInventory(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong(), weapon_id, "limit", true);
if(inventoryItem != null) {
editedRows = RankingSystemItems.SQLUpdateCurrencyAndInsertTimedInventory(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong(), user_details.getCurrency(), weapon_id, System.currentTimeMillis(), inventoryItem.getExpiration().getTime(), (inventoryItem.getNumber()+1), true, extend);
}
else {
final long time = System.currentTimeMillis();
editedRows = RankingSystemItems.SQLUpdateCurrencyAndInsertTimedInventory(e.getMember().getUser().getIdLong(), e.getGuild().getIdLong(), user_details.getCurrency(), weapon_id, time, time, 1, true, extend);
}
}
}
else {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(e.getMember(), Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(e.getMember(), Translation.GENERAL_ERROR)).build()).queue();
}
}
else if (weapon_id == 0) {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setDescription(STATIC.getTranslation(e.getMember(), Translation.RANDOMSHOP_WEP_TYPE_NA)).build()).queue();
logger.error("Available weapons couldn't be retrieved in guild {}", e.getGuild().getId());
Hashes.clearTempCache("randomshop_play_"+e.getMember().getUser().getId());
}
else {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(e.getMember(), Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(e.getMember(), Translation.GENERAL_ERROR)).build()).queue();
if(abbv != null)
logger.error("Random weapon couldn't be retrieved by abbreviation abbreviation {} in guild {}", abbv, e.getGuild().getId());
else
logger.error("Random weapon couldn't be retrieved by category {} in guild {}", category, e.getGuild().getId());
Hashes.clearTempCache("randomshop_play_"+e.getMember().getUser().getId());
}
if(editedRows > 0) {
//draw won item from the Randomshop
final int weapon = weapon_id;
RandomshopRewardDrawer.drawReward(e, RankingSystemItems.SQLgetWholeWeaponShop(e.getGuild().getIdLong()).parallelStream().filter(w -> w.getWeaponID() == weapon).findAny().orElse(null), user_details.getCurrency(), guild_settings, extend);
Hashes.addTempCache("randomshop_play_"+e.getMember().getUser().getId(), new Cache(600000, input));
}
else if(weapon_id > 0) {
EmbedBuilder message = new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(e.getMember(), Translation.EMBED_TITLE_ERROR));
e.getChannel().sendMessage(message.setDescription(STATIC.getTranslation(e.getMember(), Translation.GENERAL_ERROR)).build()).queue();
logger.error("The user {} couldn't receive the weapon with the weapon_id {} in guild {}", e.getMember().getUser().getId(), weapon_id, e.getGuild().getId());
}
}
else {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(e.getMember(), Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(e.getMember(), Translation.GENERAL_ERROR)).build()).queue();
logger.error("Weapon stats couldn't be retrieved in guild {}", e.getGuild().getId());
}
}
else {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setDescription(STATIC.getTranslation(e.getMember(), Translation.RANDOMSHOP_BALANCE_ERR)+user_details.getCurrency()).build()).queue();
}
}
else {
e.getChannel().sendMessage(new EmbedBuilder().setColor(Color.RED).setDescription(STATIC.getTranslation(e.getMember(), Translation.PARAM_NOT_FOUND)).build()).queue();
}
}
}
public static void inspectItems(Member member, TextChannel channel, List<WeaponAbbvs> abbreviations, List<String> categories, String input, int page, boolean overrideDelay) {
var cache = Hashes.getTempCache("randomshop_playDelay_gu"+member.getGuild().getId()+"us"+member.getUser().getId());
if(cache == null || cache.getExpiration() - System.currentTimeMillis() <= 0 || overrideDelay) {
Hashes.addTempCache("randomshop_playDelay_gu"+member.getGuild().getId()+"us"+member.getUser().getId(), new Cache(3000));
final String abbv;
final String category;
WeaponAbbvs weapon_abbv = abbreviations.parallelStream().filter(a -> a.getDescription().equalsIgnoreCase(input)).findAny().orElse(null);
if(weapon_abbv != null) {
abbv = weapon_abbv.getAbbv();
}
else {
abbv = null;
}
if(abbv == null) {
category = categories.parallelStream().filter(c -> c.equalsIgnoreCase(input)).findAny().orElse(null);
}
else {
category = null;
}
if(abbv != null || category != null) {
final var guild_settings = RankingSystem.SQLgetGuild(member.getGuild().getIdLong());
if(guild_settings != null) {
List<Weapons> weapons;
if(abbv != null) {
weapons = RankingSystemItems.SQLgetWholeWeaponShop(member.getGuild().getIdLong());
if(weapons == null) {
channel.sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(member, Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(member, Translation.GENERAL_ERROR)).build()).queue();
logger.error("Weapons couldn't be retrieved in guild {}", member.getGuild().getId());
Hashes.clearTempCache("randomshop_bot_gu"+member.getGuild().getId()+"ch"+channel.getId());
return;
}
weapons = weapons.parallelStream().filter(w -> w.getWeaponAbbv().equalsIgnoreCase(abbv) && w.getStat() == 1).collect(Collectors.toList());
}
else {
weapons = RankingSystemItems.SQLgetWholeWeaponShop(member.getGuild().getIdLong());
if(weapons == null) {
channel.sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(member, Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(member, Translation.GENERAL_ERROR)).build()).queue();
logger.error("Weapons couldn't be retrieved in guild {}", member.getGuild().getId());
Hashes.clearTempCache("randomshop_bot_gu"+member.getGuild().getId()+"ch"+channel.getId());
return;
}
weapons = weapons.parallelStream().filter(w -> w.getCategoryDescription().equalsIgnoreCase(category) && w.getStat() == 1).collect(Collectors.toList());
}
var maxItems = guild_settings.getRandomshopMaxItems();
ArrayList<Weapons> filteredWeapons = new ArrayList<Weapons>();
final var lastPage = (page*maxItems)-1;
for(var i = (page-1)*maxItems; i <= lastPage; i++) {
if(i < weapons.size() && weapons.get(i) != null)
filteredWeapons.add(weapons.get(i));
else
break;
}
if(filteredWeapons != null && filteredWeapons.size() > 0) {
final int last_page = ((weapons.size()-1)/maxItems)+1; //using modulo for the page size
//draw page
Hashes.addTempCache("randomshop_bot_gu"+member.getGuild().getId()+"ch"+channel.getId(), new Cache(180000, member.getUser().getId()+"_"+page+"_"+input+"_"+last_page));
RandomshopItemDrawer.drawItems(member, channel, filteredWeapons, page, last_page, guild_settings);
}
else {
//no items to display
channel.sendMessage(new EmbedBuilder().setColor(Color.RED).setDescription(STATIC.getTranslation(member, Translation.RANDOMSHOP_NO_ITEMS)).build()).queue();
logger.warn("Randomshop content couldn't be displayed in guild {}", member.getGuild().getId());
}
}
else {
channel.sendMessage(new EmbedBuilder().setColor(Color.RED).setTitle(STATIC.getTranslation(member, Translation.EMBED_TITLE_ERROR)).setDescription(STATIC.getTranslation(member, Translation.GENERAL_ERROR)).build()).queue();
logger.error("Guild ranking information couldn't be retrieved in guild {}", member.getGuild().getId());
}
}
else {
channel.sendMessage(new EmbedBuilder().setColor(Color.RED).setDescription(STATIC.getTranslation(member, Translation.PARAM_NOT_FOUND)).build()).queue();
}
}
}
private static long randomizeWeaponDuration(final boolean highRank) {
final int rand = ThreadLocalRandom.current().nextInt(0, 100);
if(!highRank) {
if(rand <= 28) {
return TimeUnit.DAYS.toMillis(1);
}
else if(rand > 28 && rand <= 54) {
return TimeUnit.DAYS.toMillis(7);
}
else if(rand > 54 && rand <= 80) {
return TimeUnit.DAYS.toMillis(30);
}
else {
return 0L;
}
}
else {
if(rand <= 50) {
return TimeUnit.DAYS.toMillis(30);
}
else {
return 0L;
}
}
}
}
|
PHP
|
UTF-8
| 3,463
| 2.640625
| 3
|
[] |
no_license
|
<?php
/**
* Class and Function List:
* Function list:
* - __construct()
* - CreateContentControls()
* - CreateFieldControls()
* - CreateReferenceControls()
* - btnSave_click()
* - btnDelete_click()
* - IsNew()
* Classes list:
* - AWSInstanceEditPanelBase extends MJaxPanel
*/
class AWSInstanceEditPanelBase extends MJaxPanel {
protected $objAWSInstance = null;
public $intIdInstance = null;
public $txtAwsId = null;
public $txtNamespace = null;
public $txtDns = null;
public $txtCreDate = null;
public $txtIdAccount = null;
//Regular controls
public $btnSave = null;
public $btnDelete = null;
public function __construct($objParentControl, $objAWSInstance = null) {
parent::__construct($objParentControl);
$this->objAWSInstance = $objAWSInstance;
$this->strTemplate = __VIEW_ACTIVE_APP_DIR__ . '/www/ctl_panels/AWSInstanceEditPanelBase.tpl.php';
$this->CreateFieldControls();
$this->CreateContentControls();
$this->CreateReferenceControls();
}
public function CreateContentControls() {
$this->btnSave = new MJaxButton($this);
$this->btnSave->Text = 'Save';
$this->btnSave->AddAction(new MJaxClickEvent() , new MJaxServerControlAction($this, 'btnSave_click'));
$this->btnDelete = new MJaxButton($this);
$this->btnDelete->Text = 'Delete';
$this->btnDelete->AddAction(new MJaxClickEvent() , new MJaxServerControlAction($this, 'btnDelete_click'));
if (is_null($this->objAWSInstance)) {
$this->btnDelete->Style->Display = 'none';
}
}
public function CreateFieldControls() {
$this->txtAwsId = new MJaxTextBox($this);
$this->txtAwsId->Name = 'awsId';
$this->txtNamespace = new MJaxTextBox($this);
$this->txtNamespace->Name = 'namespace';
$this->txtDns = new MJaxTextBox($this);
$this->txtDns->Name = 'dns';
$this->txtCreDate = new MJaxTextBox($this);
$this->txtCreDate->Name = 'creDate';
$this->txtIdAccount = new MJaxTextBox($this);
$this->txtIdAccount->Name = 'idAccount';
if (!is_null($this->objAWSInstance)) {
$this->intIdInstance = $this->objAWSInstance->idInstance;
$this->txtAwsId->Text = $this->objAWSInstance->awsId;
$this->txtNamespace->Text = $this->objAWSInstance->namespace;
$this->txtDns->Text = $this->objAWSInstance->dns;
$this->txtCreDate->Text = $this->objAWSInstance->creDate;
$this->txtIdAccount->Text = $this->objAWSInstance->idAccount;
}
}
public function CreateReferenceControls() {
// if(!is_null($this->objAWSInstance->i)){
// }
}
public function btnSave_click() {
if (is_null($this->objAWSInstance)) {
//Create a new one
$this->objAWSInstance = new AWSInstance();
}
$this->objAWSInstance->awsId = $this->txtAwsId->Text;
$this->objAWSInstance->namespace = $this->txtNamespace->Text;
$this->objAWSInstance->dns = $this->txtDns->Text;
$this->objAWSInstance->creDate = $this->txtCreDate->Text;
$this->objAWSInstance->idAccount = $this->txtIdAccount->Text;
$this->objAWSInstance->Save();
}
public function btnDelete_click() {
$this->objAWSInstance->Delete();
}
public function IsNew() {
return is_null($this->objAWSInstance);
}
}
?>
|
Python
|
UTF-8
| 1,911
| 3.28125
| 3
|
[] |
no_license
|
Mouse = '''
class Mouse:
"""STOP!!! DON'T USE THIS UNLESS YOU'RE REALLY SURE YOU KNOW HOW TO USE IT!!
Nothing bad will happen, but it just won't really help you much. Peace.
"""
def __init__(self):
"""Mouse.__init__()"""
## button press things
self.justpressed = (0,0,0)
## visible
self.visible = True
@property
def pos(self): return py.mouse.get_pos()
@property
def x(self): return self.pos[0]
@property
def y(self): return self.pos[1]
@property
def arepressed(self): return py.mouse.get_pressed()
@property
def leftbutton(self): return self.arepressed[0]
@property
def scrollwheel(self): return self.arepressed[1]
@property
def rightbutton(self): return self.arepressed[2]
@property
def leftbuttonpressed(self): return self.justpressed[0]
@property
def scrollwheelpressed(self): return self.justpressed[1]
@property
def rightbuttonpressed(self): return self.justpressed[2]
def __setattr__(self, name, value) -> None:
"set self.name to value"
## These actually aren't pointless!
## These are the mouse things we can change in pygame
if name == 'justpressed':
self.__dict__['justpressed'] = value
elif name == 'visible':
py.mouse.set_visible(value)
elif name == 'pos':
py.mouse.set_pos(value)
elif name == 'x':
py.mouse.set_pos([value,self.y])
elif name == 'y':
py.mouse.set_pos([self.x,value])
else:
if name in self.__dict__:
raise AttributeError(f"You can't change Mouse attribute '{name}'")
else:
raise AttributeError(f"Mouse has no attribute '{name}'")
'''
|
Python
|
UTF-8
| 2,468
| 3.5
| 4
|
[] |
no_license
|
"""
@author: Khor Peak Siew
@since: 14/9/2018
@modified: 14/9/2018
"""
import unittest
from linked_list import linkedList
class MyTest(unittest.TestCase):
def test_is_empty_true(self):
my_list = linkedList()
self.assertTrue(my_list.is_empty())
def test_is_empty_false(self):
my_list = linkedList()
my_list.append(1)
self.assertFalse(my_list.is_empty())
def test_reset_list(self):
my_list = linkedList()
my_list.append(1)
my_list.reset()
self.assertTrue(my_list.is_empty())
def test_append_empty_list(self):
my_list = linkedList()
my_list.append(2)
self.assertEqual(my_list[0].value, 2)
def test_insert_valid_index_empty_list(self):
my_list = linkedList()
self.assertTrue(my_list.insert(0, 1))
def test_insert_invalid_index_empty_list(self):
my_list = linkedList()
self.assertFalse(my_list.insert(1, 1))
def test_insert_valid_index_full_list(self):
my_list = linkedList()
my_list.append(1)
self.assertTrue(my_list.insert(1, 2))
def test_remove_valid_item(self):
my_list = linkedList()
my_list.append("remove this")
self.assertTrue(my_list.remove("remove this"))
def test_remove_invalid_item(self):
my_list = linkedList()
my_list.append(1)
self.assertFalse(my_list.remove("remove this"))
def test_delete_at_valid_index(self):
my_list = linkedList()
for i in range(10):
my_list.append(i)
self.assertTrue(my_list.delete(1))
def test_delete_at_invalid_index(self):
my_list = linkedList()
for i in range(10):
my_list.append(i)
self.assertFalse(my_list.delete(-11))
def test_sort_reversed(self):
my_list = linkedList()
for i in range(20):
my_list.append(i)
comparison_list = linkedList()
for i in range(19, -1, -1):
comparison_list.append(i)
my_list.sort(True)
self.assertEqual(my_list, comparison_list)
def test_sort_not_reversed(self):
my_list = linkedList()
for i in range(19, -1, -1):
my_list.append(i)
comparison_list = linkedList()
for i in range(20):
comparison_list.append(i)
my_list.sort(False)
self.assertEqual(my_list, comparison_list)
if __name__ == '__main__':
unittest.main()
|
Java
|
UTF-8
| 684
| 1.804688
| 2
|
[
"MIT"
] |
permissive
|
package uk.co.mccnet.soapNagios;
import uk.co.mccnet.simplenrpe.enums.NRPEStatus;
public class TestSuiteRequest {
private NRPEStatus nrpeStatus;
private String projectName;
private String testCaseName;
public NRPEStatus getNrpeStatus() {
return nrpeStatus;
}
public void setNrpeStatus(NRPEStatus nrpeStatus) {
this.nrpeStatus = nrpeStatus;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getTestCaseName() {
return testCaseName;
}
public void setTestCaseName(String testCaseName) {
this.testCaseName = testCaseName;
}
}
|
Markdown
|
UTF-8
| 2,664
| 2.96875
| 3
|
[] |
no_license
|
# Twisted Neurons (v0.3a)
### Web app showcasing boardgames with AI that's build with machine learning techniques such as artificial neural network
## Usage/Setup
Note: The chess AI is still under active developement and is not very good right now.
View the deployed app [here](https://twisted-neurons-heroku.herokuapp.com).
OR
With npm and node.js installed, clone the git repo then while in the app directory run
```
npm install
npm start
```
Then open browser to localhost:3000
## Chess
The chess program is built from scratch in Javascript. It has 4 main components:
1. Game logic (chessGame.js)
* The game logic component takes care of all the game rules, states and integration with the neural network.
2. Artificial neural network (chessNN.js)
* The ANN component contains the neural network, the forward and backward propagation functions and other helper function for it. The architecture of the ANN is inspired by the paper by Matthew Lai: [Giraffe: Using Deep Reinforcement Learning to Play Chess](https://arxiv.org/pdf/1509.01549.pdf)
3. Minimax search (chessMinimax.js)
* The minimax search component is just a simple minimax search. Optimization techniques will be added to increase the speed of the search algorithm.
4. Trainer for the ANN (chessTrainer.js)
* The trainer component reads chess FEN positions from file and trains the neural network using standard backpropagation, where the loss is determined using TDLeaf algorithm. It is trained through reinforcement learning by having the program play itself for a number of moves, each time after reading a unique chess position from file.
## Limitations and Areas to Improve
Currently the minimax search is quite slow even with alpha-beta pruning implemented. Thus the program is only able to look ahead 2 to 3 moves within 'reasonable' waiting time.
Training completely using reinforcement learning does not give very good results. A better idea is to use supervised learning initially to give reinforcement learning a better starting point. For supervised learning I would feed it large amounts of chess games.
## References and Resources
1. Matthew Lai. Giraffe: Using Deep Reinforcement Learning to Play Chess (https://arxiv.org/pdf/1509.01549.pdf)
2. Matthew D. Zeiler. ADADELTA: AN ADAPTIVE LEARNING RATE METHOD (https://arxiv.org/pdf/1212.5701v1.pdf)
3. Jonathan Baxter, Andrew Tridgell and Lex Weaver. TDLeaf(λ): Combining Temporal Difference Learning with Game-Tree Search. (https://arxiv.org/pdf/cs/9901001v1.pdf)
4. Warren S. Sarle. Neural Network FAQ (ftp://ftp.sas.com/pub/neural/FAQ.html)
5. Fei-Fei Li, Andrej Karpathy and Justin Johnson. CS231n: Convolutional Neural Networks for Visual Recognition (http://cs231n.stanford.edu/)
|
Markdown
|
UTF-8
| 1,896
| 3.03125
| 3
|
[] |
no_license
|
# NodeJS based Continuous Integration Server
A CI for node applications. It simply run the following on your repo:
```bash
npm install
npm test
npm run build
```
If running arbitrary code on bare metal scares you, the CI support also
to run in a VM using vagrant.
If your repository provides a Vagrantfile, the CI will use it. Otherwise,
the one at the root of this repository will be used.
## Installation
To use this CI, make sure you have:
* `node` and `npm` installed.
* `git` installed.
* **[optional]** `vagrant` installed.
Once, those requirements are satisfied, clone this repo
and at the root simply run `./ci.js`.
In summary:
```
git clone https://github.com/Nemikolh/nodejs-ci.git
cd node-ci
npm install
./ci.js
```
## Vagrant mode
If you use this project in `vagrant` mode, then you will need
to generate a private/public key pair that vagrant can use.
For this, simply ssh on the vagrant VM (`vagrant ssh`), generate
a key pair (`ssh-keygen -b 4096`) and then copy the public key
in **Settings > Deploy keys > Add deploy key** in your github
repository.
> Note: You need to start the CI first before doing this.
## Usage
The CI can be run with various options. Here is the usage string:
```
Start a ci for node apps. It will run the following commands
in the repo:
npm install
npm test
All generated output will be available at /build/:resId
Usage:
ci -at=<auth_token> -p=<port> <repo> [--vagrant || --bare-metal]
ci -h | --help | --version
Arguments:
<repo> Repository of the form 'user/repo'
-h --help Show this message.
--version Show the version number.
-p=<port> Port number for the ci.
-at=<auth_token> Authorization token.
--vagrant Use a Vagrantfile provided in the repo or default one if there's none.
--bare-metal Bare metal CI. Run tests here.
```
|
JavaScript
|
UTF-8
| 1,561
| 2.609375
| 3
|
[] |
no_license
|
import {createStore} from "redux";
import {applyMiddleware} from "redux";
import {composeWithDevTools} from "redux-devtools-extension";
import thunk from "redux-thunk";
const initialState = {
"selected": 0,
"cities": [
{
"name" : "Moscow",
"index": "RU",
"temp": 0,
"pres": 0,
"him": 0,
},
{
"name": "London",
"index": "UK",
"temp": 0,
"pres": 0,
"him": 0,
},
{
"name" : "Paris",
"index": "FR",
"temp": 0,
"pres": 0,
"him": 0,
},
]
};
function Reducer(state = initialState, action) {
if (action.type === 'GET_WEATHER') {
console.log("GET_WEATHER called");
let copy = state;
let id = action.payload[0];
let data = action.payload[1];
copy.cities[id].temp = (data.temp - 273).toFixed(2);
copy.cities[id].pres = data.pressure;
copy.cities[id].him = data.humidity;
console.log("New ", copy.cities[id].name, " temp is ", copy.cities[id].temp);
return copy;
}
if (action.type === 'CHANGE_CITY') {
console.log("CHANGE_CITY called");
let copy = state;
copy.selected = action.payload;
return copy;
}
return state;
}
const store = createStore(Reducer, composeWithDevTools(applyMiddleware(thunk)));
store.subscribe(() => {
//console.log('subscribe', store.getState());
});
export default store;
|
JavaScript
|
UTF-8
| 7,406
| 2.765625
| 3
|
[] |
no_license
|
import {noteService} from '../services/note-service.js';
class NoteController {
constructor() {
this.modeSelector = document.querySelector('#mode');
this.createBtn = document.querySelector('#create');
this.popup = document.querySelector('#popup');
this.closePopupBtn = document.querySelector('#close-popup');
this.filterButtons = document.querySelectorAll('.filter-button');
this.showFinishedBtn = document.querySelector('#show-finished');
this.notesContainer = document.querySelector('#notes-container');
this.noteForm = document.querySelector('#note-form');
this.noteTemplate = document.querySelector('#note-template');
this.noteRenderer = Handlebars.compile(this.noteTemplate.innerHTML);
this.currentSortField = undefined;
this.currentSortOrder = undefined;
this.showFinished = false;
}
toggleMode() {
let defaultMode;
if (localStorage.getItem('mode')) {
defaultMode = localStorage.getItem('mode');
} else {
defaultMode = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
const selectedMode = this.modeSelector.options[this.modeSelector.selectedIndex].value;
const mode = selectedMode === 'default' ? defaultMode : selectedMode;
document.body.classList.remove('dark', 'light');
document.body.classList.add(mode);
localStorage.setItem('mode', mode);
}
openPopup() {
document.body.classList.add('has-popup');
this.popup.classList.add('is-open');
}
closePopup() {
this.noteForm.reset();
this.noteForm.querySelector('#noteId').value = '';
document.body.classList.remove('has-popup');
this.popup.classList.remove('is-open');
}
registerEvents() {
this.modeSelector.addEventListener('input', () => this.toggleMode());
this.createBtn.addEventListener('click', () => this.openPopup());
this.closePopupBtn.addEventListener('click', () => this.closePopup());
this.noteForm.addEventListener('submit', (event) => this.submitNote(event));
this.filterButtons.forEach((e) => {
e.addEventListener('click', (event) => this.sortNotes(event));
});
this.showFinishedBtn.addEventListener('click', () => this.toggleShowFinished());
}
async submitNote(event) {
event.preventDefault();
const formData = this.noteForm.elements;
if (formData.noteId.value.length > 0) {
const noteId = formData.noteId.value;
await noteService.updateNote(noteId, formData);
} else {
await noteService.createNote(formData);
}
this.closePopup();
await this.loadNotes();
await this.renderNotes();
}
async renderNotes() {
if (!this.notes) {
await this.loadNotes();
}
if (this.showFinished) {
this.notes = this.notes.filter((note) => note.finished);
} else {
this.notes = this.notes.filter((note) => !note.finished);
}
this.notesContainer.innerHTML = this.noteRenderer(this.notes);
document.querySelectorAll('.done-note').forEach((note) => note.addEventListener('click', (e) => this.markAsDone(e)));
document.querySelectorAll('.edit-note').forEach((note) => note.addEventListener('click', (e) => this.editNote(e)));
document.querySelectorAll('.delete-note').forEach((note) => note.addEventListener('click', (e) => this.deleteNote(e)));
document.querySelectorAll('.show-note-controls').forEach((note) => note.addEventListener('click', (e) => this.showControls(e)));
document.querySelectorAll('.notes > .note').forEach((note) => note.addEventListener('click', (e) => this.openDetails(e)));
}
async markAsDone(event) {
const noteId = event.target.closest('li').dataset.note;
await noteService.setAsDone(noteId);
await this.loadNotes();
await this.renderNotes();
}
editNote(event) {
const noteId = event.target.closest('li').dataset.note;
const note = this.notes.find((n) => (noteId === n.id));
this.popup.querySelector('#noteId').value = note.id;
this.popup.querySelector('#title').value = note.title;
this.popup.querySelector('#description').value = note.description;
this.popup.querySelector('#importance').value = note.importance;
this.popup.querySelector('#duedate').value = new Date(note.duedate).toISOString().substring(0, 10);
this.openPopup();
}
async deleteNote(event) {
event.preventDefault();
if (window.confirm('Are you sure?')) {
const noteId = event.target.closest('li').dataset.note;
await noteService.deleteNote(noteId);
await this.loadNotes();
await this.renderNotes();
}
}
async loadNotes() {
this.notes = await noteService.getNotes();
}
sortNotes(e) {
this.currentSortField = e.target.dataset.sortBy;
switch (this.currentSortOrder) {
case 'desc':
this.currentSortOrder = 'asc';
break;
default:
this.currentSortOrder = 'desc';
break;
}
this.filterButtons.forEach((button) => {
button.classList.remove('arrow-asc', 'arrow-desc');
});
e.target.classList.add(`arrow-${this.currentSortOrder}`);
this.notes = noteService.sortNotes(this.currentSortField);
this.notes = this.currentSortOrder === 'asc' ? this.notes : this.notes.reverse();
this.renderNotes();
}
async toggleShowFinished() {
await this.loadNotes();
if (!this.showFinished) {
this.showFinished = true;
this.showFinishedBtn.classList.add('is-active');
} else {
this.showFinished = false;
this.showFinishedBtn.classList.remove('is-active');
}
await this.renderNotes();
}
registerHandlebarHelpers() {
Handlebars.registerHelper('showImportance', (importance) => {
let i = importance;
let html = `<span class="stars stars-${i}">`;
while (i > 0) {
html += '<span class="star">🗲</span>';
--i;
}
html += '</span>';
return html;
});
Handlebars.registerHelper('formatDate', (date) => {
if (date instanceof Date) {
return date.toLocaleString('de-CH').split(',')[0];
}
return new Date(date).toLocaleString('de-CH').split(',')[0];
});
Handlebars.registerHelper('br', (content) => {
let c = content;
c = Handlebars.Utils.escapeExpression(c);
c = c.replace(/(\r\n|\n|\r)/gm, '<br>');
return new Handlebars.SafeString(c);
});
}
openDetails(e) {
document.querySelectorAll('li.note').forEach((note) => note.classList.remove('show-details'));
e.target.closest('li').classList.add('show-details');
}
init() {
this.toggleMode();
this.registerHandlebarHelpers();
this.registerEvents();
this.renderNotes();
}
}
new NoteController().init();
|
C++
|
UTF-8
| 2,241
| 3.46875
| 3
|
[] |
no_license
|
/*
Dado un conjunto de valores, la moda es el valor (o valores) que más se
repite en dicho conjunto. Diseñar un algoritmo iterativo de coste lineal que dado un
vector de enteros positivos menores que 1000 devuelva una moda del vector.
*/
#include <iostream>
#include <fstream>
#include <algorithm> // std::max
#include <climits>
using namespace std;
#define MAX 10000
#ifndef DOMJUDGE
ifstream in("test.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
int solve1(int v[],int N ){
int n = 0, frecAux[MAX] = {0};
while(n < N){
frecAux[v[n]]++;
n++;
}
int pos = 1, mas_grande = 0, valor_moda = 0;
for ( ; pos <= N; pos++ ) {
if ( frecAux[pos] > mas_grande ) {
mas_grande = frecAux[pos];
valor_moda = pos;
}
}
return valor_moda;
}
int solve2(int v[],int N ){
int valor_moda = 0, contModa = 0;
int n = 0;
while(n < N){
cout << v[n] << endl;
n++;
}
return valor_moda;
}
bool solveRecursiveGen(int v[], int n, int tam, int &maxResta){
/*if(tam - 1 == n){
int resta = v[n] - v[n + 1];
cout << " v[n] " << v[n] << endl;
cout << "" << v[] << endl;
if(resta > maxResta){
maxResta = resta;
}
}else{
if(n < tam - 1){
int resta = v[n] - v[n + 1];
if(resta > maxResta){
maxResta = resta;
}
solveRecursiveGen(v,n+1, tam, maxResta);
}
}*/
}
int solveRecursive(int V[], int n ){
int maxResta = 0;
solveRecursiveGen(V,0,n-1, maxResta);
}
int main(){
int numCasos, pos = 0, longArray = 0;
int V[MAX];
cin >> numCasos;
while( pos < numCasos ){
int posV = 0;
cin >> longArray;
while(posV < longArray){
cin >> V[posV];
posV++;
}
cout << "Iterative:\t ";
cout << solve1( V,posV ) << endl;
cout << "Iterative----V2: \t ";
sort(V,V+longArray);
cout << solve2( V,posV ) << endl;
//cout << "Recursive:\t ";
//cout << solveRecursive(V, posV) << endl;
pos++;
}
return 0;
}
|
Java
|
UTF-8
| 710
| 2.515625
| 3
|
[] |
no_license
|
import javax.servlet.*;
import java.io.IOException;
/**
* Created by USER on 05.09.2017.
*/
public class FilterConnect implements Filter {
private FilterConfig config = null;
private boolean active = false;
public void destroy() {
config = null;
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
if (active)
{
System.out.println("Фильтр работает");
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
this.active = Boolean.parseBoolean(config.getInitParameter("active"));
}
}
|
Java
|
UTF-8
| 15,845
| 1.992188
| 2
|
[
"MIT"
] |
permissive
|
/*
* The MIT License
*
* Copyright 2014 Sebastian Russ <citeaux at https://github.com/citeaux/JAHAP>.
*
* 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.jahap.business.base;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.apache.log4j.Logger;
import org.jahap.entities.JahapDatabaseConnector;
import org.jahap.entities.base.Cat;
import org.jahap.entities.base.Location;
import org.jahap.entities.base.Rooms;
import org.jahap.entities.views.Housekeeping;
import org.jahap.entities.views.Maintenance;
/**
*
* @author russ
*/
public class roomsbean extends DatabaseOperations implements rooms_i {
static Logger log = Logger.getLogger(roomsbean.class.getName());
JahapDatabaseConnector dbhook;
private static List<Rooms> allrecordlist;
public roomsbean(){
long testg;
dbhook = JahapDatabaseConnector.getConnector();
try {
query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rooms t ORDER BY t.id");
List<Rooms>allroomslist= query_AllDbRecords.getResultList();
numberOfLastRecord= allroomslist.size()-1;
} catch (Exception e) {
numberOfLastRecord=-1;
}
query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rooms t ORDER BY t.id");
allrecordlist= query_AllDbRecords.getResultList();
try {
testg=allrecordlist.get(currentRecordNumber).getId();
tabelIsEmpty=false;
tabelIsInit=true;
} catch (Exception e) {
tabelIsEmpty=true;
}
log.trace("DB connected");
// If the table is yet empty, init List
}
private void RefreshAllRecords(){
log.debug("Function entry RefreshAllRecords");
try {
allrecordlist.clear();
query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rooms t ORDER BY t.id");
allrecordlist = query_AllDbRecords.getResultList();
numberOfLastRecord=allrecordlist.size()-1;
} catch (Exception e) {
e.printStackTrace();
}
log.debug("Function exit RefreshAllRecords");
}
public void createNewEmptyRecord() {
log.debug("Function entry createNewEmptyRecord");
if(tabelIsEmpty==true){
allrecordlist = new ArrayList<Rooms>();
numberOfLastRecord++;
currentRecordNumber=numberOfLastRecord;
}
if(tabelIsEmpty==false){
RefreshAllRecords();
numberOfLastRecord++;
}
Rooms emptyacc = new Rooms();
allrecordlist.add(emptyacc);
currentRecordNumber=numberOfLastRecord;
setNewEmptyRecordCreadted();
tabelIsInit=true; // Set Tabel iniated - List is connected
log.debug("Function exit createNewEmptyRecord");
}
public List<Rooms>SearchForRooms(String searchstring){
return allrecordlist;
}
public void setRoomsinListclean(List<Rooms>rooms){
log.debug("Function entry setRoomsinListclean ");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setClean(true);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListclean");
}
public void setRoomsinListcleanHSK(List<Housekeeping>rooms){
log.debug("Function entry setRoomsinListclean ");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setClean(true);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListclean");
}
public void setRoomsinListdirtyHSK(List<Housekeeping>rooms){
log.debug("Function entry setRoomsinListdirty");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setClean(false);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListdirty");
}
public void setRoomsinListdirty(List<Rooms>rooms){
log.debug("Function entry setRoomsinListdirty");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setClean(false);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListdirty");
}
public void setRoomsinListNotunderMaintenance(List<Rooms>rooms){
log.debug("Function entry setRoomsinListNotunderMaintenance ");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setNo_maintenance(true);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListNotunderMaintenance");
}
public void setRoomsinListNotunderMaintenanceMN(List<Maintenance>rooms){
log.debug("Function entry setRoomsinListNotunderMaintenance ");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setNo_maintenance(true);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListNotunderMaintenance");
}
public void setRoomsinListunderMaintenance(List<Rooms>rooms){
log.debug("Function entry setRoomsinListunderMaintenance");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setNo_maintenance(false);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListunderMaintenance");
}
public void setRoomsinListunderMaintenanceMN(List<Maintenance>rooms){
log.debug("Function entry setRoomsinListunderMaintenance");
int i,p;
for(i=0;i<=allrecordlist.size()-1;i++){
for(p=0;p<=rooms.size()-1;p++){
if(allrecordlist.get(i).getId()==rooms.get(p).getId()){
allrecordlist.get(i).setNo_maintenance(false);
currentRecordNumber=i;
saveRecord();
}
}
}
log.debug("Function exit setRoomsinListunderMaintenance");
}
private void saveNewRecord(){
log.debug("Function entry saveNewRecord");
if ( newEmptyRecordCreated==true){
try{
dbhook.getEntity().getTransaction().begin();
dbhook.getEntity().merge(allrecordlist.get(currentRecordNumber));
System.out.printf(dbhook.getEntity().getProperties().toString());
dbhook.getEntity().getTransaction().commit();
newEmptyRecordCreated=false;
allrecordlist.clear();
query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rooms t ORDER BY t.id"); // Refresh list
allrecordlist= query_AllDbRecords.getResultList();
//currentRecordNumber++;
}
catch (Exception e){
log.error("SaveNewRecord " );
e.printStackTrace();
}
}
}
public void setDataRecordId(Long id){
int inl=-1;
try {
do {
inl++;
} while (allrecordlist.get(inl).getId() != id && allrecordlist.size() - 1 > inl);
currentRecordNumber=inl;
} catch (Exception e) {
e.printStackTrace();
}
}
public Rooms getDataRecord(Long id){
log.debug("Function entry getDataRecord");
int inl=-1;
try {
do {
inl++;
} while (allrecordlist.get(inl).getId() != id && allrecordlist.size() - 1 > inl);
currentRecordNumber = inl;
} catch (Exception e) {
e.printStackTrace();
}
log.debug("Function exit getDataRecord");
return allrecordlist.get(currentRecordNumber);
}
public void saveRecord() {
log.debug("Function entry saveRecord");
if (newEmptyRecordCreated==true){
saveNewRecord();
setNewEmptyRecordSaved();
RefreshAllRecords();
}
if (newEmptyRecordCreated==false){
saveOldRecord();
}
log.debug("Function exit saveRecord ");
}
private void saveOldRecord(){
log.debug("Function entry saveOldRecord");
if(newEmptyRecordCreated==false){
dbhook.getEntity().getTransaction().begin();
dbhook.getEntity().find(Rooms.class,allrecordlist.get(currentRecordNumber).getId() );
dbhook.getEntity().merge(allrecordlist.get(currentRecordNumber));
dbhook.getEntity().getTransaction().commit();
}
log.debug("Function exit saveOldRecord");
}
public void quitDBaccess(){
dbhook.getEntity().close();
}
public void nextRecordBackward() {
if (currentRecordNumber>0) {
currentRecordNumber--;
}
}
public void nextRecordForeward() {
if (currentRecordNumber<numberOfLastRecord) {
currentRecordNumber++;
}
}
public void jumpToFirstRecord(){
currentRecordNumber=0;
}
/**
*
*/
public void jumpToLastRecord(){
currentRecordNumber=numberOfLastRecord;
}
public List<Rooms>getCurrentRoom(){
List<Rooms>hh=new ArrayList<Rooms>();
hh.add(allrecordlist.get(currentRecordNumber));
return hh;
}
//--------------------- Getters & Setters ---------------
public String getName() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getName();
return "";
}
public Cat getCategory() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getCategory();
return null;
}
public String getCode() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getCode();
return "";
}
public void setCategory(Cat category) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setCategory(category);
}
public void setCode(String code) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setCode(code);
}
public void setName(String name) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setName(name);
}
@Override
public Location getLocation() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).getLocation();
return null;
}
@Override
public boolean isNo_maintenance() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).isNo_maintenance();
return false;
}
@Override
public boolean isClean() {
if( tabelIsEmpty!=true)
return allrecordlist.get(currentRecordNumber).isClean();
return false;
}
@Override
public void setLocaton(Location location) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setLocation(location);
}
@Override
public void setClean(boolean clean) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setClean(clean);
}
@Override
public void setNo_maintenance(boolean no_maintenance) {
if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord();
allrecordlist.get(currentRecordNumber).setNo_maintenance(no_maintenance);
}
public void setCheckedinRoomsDirty(){
log.debug("Function entry setCheckedinRoomsDirty");
Hotelbean hbean= new Hotelbean();
LocalDateTime ldate;
Instant instant=Instant.from(hbean.getOperationdate().toInstant());
ldate=LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
List<Rooms> Lroom= new ArrayList<>();
Query checkedinRooms=null;
try{
checkedinRooms=dbhook.getEntity().createQuery("select t from Rooms t JOIN t.occCollection k where k.arrivaldate<='" + ldate.format(DateTimeFormatter.ISO_DATE) + "' AND k.departuredate>='" + ldate.format(DateTimeFormatter.ISO_DATE) +"' ORDER BY t.id");
}catch(Exception e){
}
Lroom=checkedinRooms.getResultList();
log.trace("setCheckedinRoomsDirty Rooms Amount:" + Lroom.size());
setRoomsinListdirty(Lroom);
}
}
|
TypeScript
|
UTF-8
| 454
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { BitmapImage2D } from '../image/BitmapImage2D';
import { Image2D } from '../image/Image2D';
import { IImageFactory } from './IImageFactory';
export class DefaultStageFactory implements IImageFactory {
public createImage2D(
width: number,
height: number,
transparent: boolean = true,
fillColor: number = null,
powerOfTwo: boolean = true
): Image2D {
return new BitmapImage2D(width, height, transparent, fillColor, powerOfTwo);
}
}
|
C++
|
UTF-8
| 686
| 3.375
| 3
|
[] |
no_license
|
void RecordOddEven(int A[], int len){
int i=0, j = len - 1;
while(i < j){
while(i<len && A[i] % 2 == 1)
i++;
while(j>=0 && A[j] % 2 == 0)
j--;
if(i<j){
A[i] ^= A[j] ^= A[i] ^= A[j];
}
}
}
void RecordOddEvenTest(){
int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11};
int len = sizeof(A) / sizeof(A[0]);
RecordOddEven(A, len);
for(int i=0; i<len; i++){
cout << A[i] << " ";
}
cout << endl;
for(int i=0; i<len; i++){
A[i] = 2;
}
RecordOddEven(A, len);
for(int i=0; i<len; i++){
cout << A[i] << " ";
}
cout << endl;
for(int i=0; i<len; i++){
A[i] = 1;
}
RecordOddEven(A, len);
for(int i=0; i<len; i++){
A[i] = 1;
}
}
|
JavaScript
|
UTF-8
| 2,830
| 4.28125
| 4
|
[] |
no_license
|
// ********* Historical Life Expectancy ************
// When we looked up all the people in our data set that lived more than
// 90 years, only the latest generation in the data came out. Let’s take a closer
// look at that phenomenon.
// Compute and output the average age of the people in the ancestry
// data set per century. A person is assigned to a century by taking their year
// of death, dividing it by 100, and rounding it up, as in Math.ceil(person.died /
// 100).
var
ancestry = JSON.parse(ANCESTRY_JSON),
centuries = {}; // object that keys are the century and values are the people
/*
handle an object to include correct values for this
*/
function includeCenturyValues(object, century, value) {
if (object[century] == null || object[century] == undefined) {
object[century] = [value]
} else {
object[century].push(value)
}
};
/*
verify if have already any person in the century or not
if have, just include a new value to this, if not, initialize it ;)
*/
function groupPeopleByCentury(century, person) {
includeCenturyValues(centuries, century, person);
};
/*
populates the century object
where the key is the century value as a integer
and the body/value is a list of people lived in it
*/
function centuryWrapper() {
ancestry.forEach(function(person) {
var century = Math.ceil(person.died/100);
groupPeopleByCentury(century, person);
});
};
/*
catch each person by century and calculate your living time.
includes this value into an array, based on century =)
*/
function agesByCentury(century, callback) {
var ages = {};
centuries[century].forEach(function(person) {
includeCenturyValues(ages, century, (person.died - person.born))
});
return ages;
};
function increment(prev, curr) {
return prev + curr;
};
function sumAgesByCentury(ages, century, callback) {
var total = ages[century].reduce(increment);
callback(total);
};
function averageCalc(century, value) {
var average = Math.floor(value / centuries[century].length);
console.log(
"The life expectancy for ancestry at century " + century + " is " + average
);
};
function expectancyCalc(century) {
var ages = agesByCentury(century);
sumAgesByCentury(ages, century, function(total) {
averageCalc(century, total);
});
};
function lifeExpectancy() {
centuryWrapper();
for (var century in centuries) {
expectancyCalc(century);
};
};
lifeExpectancy();
// output - result
// The life expectancy for ancestry at century 16 is 43
// The life expectancy for ancestry at century 17 is 51
// The life expectancy for ancestry at century 18 is 52
// The life expectancy for ancestry at century 19 is 54
// The life expectancy for ancestry at century 20 is 84
// The life expectancy for ancestry at century 21 is 94
|
JavaScript
|
UTF-8
| 935
| 2.515625
| 3
|
[] |
no_license
|
import {
PIKCHA100_LOADED,
PIKCHA100_LOADING,
PIKCHA100_ERROR,
PIKCHA100_RESET
} from "../actions/types";
const initialState = {
top100: [],
count: 15,
start: 1,
loading: true,
error: null,
hasMore: true
};
export default (state = initialState, { type, payload }) => {
switch (type) {
case PIKCHA100_LOADED:
return {
...state,
top100: [...state.top100, ...payload],
loading: false,
start: state.start + state.count
};
case PIKCHA100_ERROR:
!payload.data === "You have reached the end." && console.error(payload);
return {
...state,
error: payload,
loading: false,
hasMore: !payload.data === "You have reached the end."
};
case PIKCHA100_LOADING:
return {
...state,
loading: true
};
case PIKCHA100_RESET:
return initialState;
default:
return state;
}
};
|
Markdown
|
UTF-8
| 1,835
| 2.640625
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: '方法 : ペンを定義する'
ms.date: 03/30/2017
dev_langs:
- csharp
- vb
helpviewer_keywords:
- pens [WPF], defining
- creating [WPF], pens
ms.assetid: 7a4f2900-cdf9-49de-84e0-ba5d0ded4d33
ms.openlocfilehash: 7c5be5eff06df55e465f3e34646ba1c34e8b7e07
ms.sourcegitcommit: 3d5d33f384eeba41b2dff79d096f47ccc8d8f03d
ms.translationtype: MT
ms.contentlocale: ja-JP
ms.lasthandoff: 05/04/2018
ms.locfileid: "33559865"
---
# <a name="how-to-define-a-pen"></a>方法 : ペンを定義する
この例では、<xref:System.Windows.Media.Pen>図形の要点を説明します。 単純なを作成する<xref:System.Windows.Media.Pen>、のみ指定する必要があるその<xref:System.Windows.Media.Pen.Thickness%2A>と<xref:System.Windows.Media.Pen.Brush%2A>です。 複雑なペンを作成するには指定することによって、 <xref:System.Windows.Media.Pen.DashStyle%2A>、 <xref:System.Windows.Media.Pen.DashCap%2A>、 <xref:System.Windows.Media.Pen.LineJoin%2A>、 <xref:System.Windows.Media.Pen.StartLineCap%2A>、および<xref:System.Windows.Media.Pen.EndLineCap%2A>です。
## <a name="example"></a>例
次の例では、<xref:System.Windows.Media.Pen>によって定義された図形を説明する、<xref:System.Windows.Media.GeometryDrawing>です。
[!code-csharp[PenExamples_snip#PenExampleWholePage](../../../../samples/snippets/csharp/VS_Snippets_Wpf/PenExamples_snip/CSharp/PenExample.cs#penexamplewholepage)]
[!code-vb[PenExamples_snip#PenExampleWholePage](../../../../samples/snippets/visualbasic/VS_Snippets_Wpf/PenExamples_snip/VisualBasic/PenExample.vb#penexamplewholepage)]

GeometryDrawing
|
C++
|
UTF-8
| 3,352
| 3.890625
| 4
|
[] |
no_license
|
/*************************************************
* @Filename: link_list.cc
* @Author: qeesung
* @Email: qeesung@qq.com
* @DateTime: 2015-06-04 03:37:28
* @Version: 1.0
* @Description: 实现链式链表的接口
**************************************************/
#include <iostream>
// 构造函数和析构函数
template <class Elem>
LinkList<Elem>::LinkList()
{
// 首先创建一个链表的表头
header = new ListNode<Elem>();
header->next = NULL;
}
/** 迭代的释放节点指针开始的所有节点 */
template <class Elem>
void LinkList<Elem>::freeList(ListNode<Elem> * startNode)
{
while(startNode != NULL)
{
ListNode<Elem> * tempNode = startNode->next;
delete startNode;
startNode = tempNode;
}
return;
}
template <class Elem>
LinkList<Elem>::~LinkList()
{
//递归的释放整个链表
freeList(header);
}
// 基本的操作函数
// 在链表头插入一个元素
template <class Elem>
bool LinkList<Elem>::insert(const Elem & ele)
{
ListNode<Elem> * newNode = new ListNode<Elem>();
if(newNode == NULL)
return false;
newNode->next=NULL;
newNode->data = ele;
ListNode<Elem> * tempNode = header->next;
header->next = newNode;
newNode->next = tempNode;
return true;
}
// 在链表尾插入一个元素
template <class Elem>
bool LinkList<Elem>::append(const Elem & ele)
{
// tempNode里面现在就指向最后一个元素
ListNode<Elem> * newNode = new ListNode<Elem>();
if(newNode == NULL)
return false;
newNode->next = NULL;
newNode->data = ele;
// 首先找到链表末尾
ListNode<Elem> * lastNode = header;
while(lastNode->next !=NULL)
{
lastNode = lastNode->next;
}
// 追加节点
lastNode->next = newNode;
return true;
}
// 移除链表里面的一个元素
template <class Elem>
bool LinkList<Elem>::remove(const Elem & ele)
{
// 在链表里面找到对应的元素
ListNode<Elem> * targetNode = header;
while(targetNode->next!=NULL && targetNode->next->data!=ele)
{
targetNode = targetNode->next;
}
if(targetNode->next == NULL)// 没有找到目标元素
return false;
ListNode<Elem> * tempNode = targetNode->next->next;
delete targetNode->next;
targetNode->next = tempNode;
return true;
}
// 清空链表里面额的所有元素
template <class Elem>
void LinkList<Elem>::clear()
{
freeList(header->next);
header->next = NULL;
}
// 打印整个链表
template <class Elem>
void LinkList<Elem>::print()
{
ListNode<Elem> * tempNode = header;
while(tempNode->next!=NULL)
{
std::cout<<tempNode->next->data<<"\t";
tempNode = tempNode->next;
}
std::cout<<std::endl;
}
template < class T >
LinkList<T>::LinkList (const LinkList<T> & list)
{
ListNode<T> * tempNode = list.header;
while(tempNode->next!=NULL)
{
this->append(tempNode->next->data);
tempNode = tempNode->next;
}
} /** ----- end of method LinkList<T>::LinkList ----- */
template < class T >
void LinkList<T>::printToVec (std::vector<T> & vec)
{
ListNode<T> * tempNode = header;
while(tempNode->next != NULL)
{
vec.push_back(tempNode->next->data);
tempNode = tempNode->next;
}
return ;
} /** ----- end of method LinkList<T>::printToVec ----- */
|
Java
|
GB18030
| 302
| 2.171875
| 2
|
[] |
no_license
|
package com.neuedu.action;
import java.awt.Graphics;
/**
* @ClassName: ActionAble
* @Description: Ϊӿ
* @author neuedu_sjm
* @date 2019819 1:00:23
*
*/
public interface ActionAble {
// ƶķ
void move();
//
void draw(Graphics g);
}
|
PHP
|
UTF-8
| 1,293
| 2.71875
| 3
|
[] |
no_license
|
<?php
require('function.php');
debug('================================');
debug('最大挙上重量ページ');
debug('================================');
debugLogStart();
//ログイン認証
require('auth.php');
//DB用変数
$user_id = $_SESSION['user_id'];
//DB接続開始
try{
$dbh = dbConnect();
$sql = 'SELECT item_name,MAX(weight) FROM post WHERE user_id=:user_id AND delete_flg=0 GROUP BY item_name';
$data = array(':user_id'=>$user_id);
$stmt = queryPost($dbh,$sql,$data);
$result = $stmt->fetchAll();
debug('クエリ結果の中身:'.print_r($result,true));
}catch(Exception $e){
error_log('エラー発生'.$e->getMessage());
$err_msg['common'] = MSG07;
}
debug('画面表示処理終了<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
?>
<?php require('head.php'); ?>
<body>
<?php require('header.php'); ?>
<main>
<h2 class="title">最大挙上重量</h2>
<?php foreach($result as $onerm): ?>
<article class="total-weight">
<div class="post-container">
<h4><?php echo $onerm['item_name']; ?></h4>
<p><i class="fas fa-medal"></i> <?php echo $onerm['MAX(weight)']."kg"; ?></p>
</div>
</article>
<?php endforeach; ?>
</main>
<?php require('footer.php'); ?>
|
Python
|
UTF-8
| 3,481
| 2.78125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 30 10:56:56 2017
@author: Eric
"""
import requests
import csv
from bs4 import BeautifulSoup as bsoup
from MALPageScrape import MALPageScrape as scrape
# this times 50 = top x shows to be considered
class MALTopScrape:
def __init__(self):
with open("animedata4.csv", "wb") as f:
writer = csv.writer(f)
#Put in a header row
writer.writerow(['Title', 'Type', 'Eps', 'Season', 'Year', 'Day', 'Timeslot', 'Source','Runtime', 'Rating',
'Score', 'Popularity', 'Sequel Score', 'Sequel Popularity', 'Source Url', 'Source Type',
'Source Score', 'Source Pop', 'Directors', 'Main VAs', 'Studio', 'Genres', 'Producers', 'Licensors'])
for z in range(0, 75):
print "working on page: " + str(z)
base_url = 'https://myanimelist.net/topanime.php?type=tv'
search_url = base_url + '&limit=' + str(z * 50)
response = requests.get(search_url).content
#parse the results
parsed_html = bsoup(response, "lxml")
prelim_list = parsed_html.find_all('a', attrs = {'class':'hoverinfo_trigger fl-l fs14 fw-b'})
url_list = []
#get the urls from the table, don't scrape anything with less than 10k members
#also not scraping from series that started before 2000
#arbitrary boundary to remember for what is notable.
for row in prelim_list:
check = row.find_parent()
check = check.find_next_sibling('div')
check = check.get_text()
check = check.split('\n')
target = check[2]
target = "".join(_ for _ in target if _ in "1234567890")
year = target[:4]
popularity = target [8:]
#print year
#print popularity
#old method that worked circa October 2017, but no longer does
#year = check[2]
#year = year.split('-')[0]
#year = year.strip(' ')
#year = year[4:]
#popularity = check[3]
#popularity = popularity.replace(' members', '')
#popularity = popularity.replace(',', '')
try:
if int(popularity) >= 3000 and year >= '1995':
url_list.append(row.get('href'))
except:
pass
#scrape each of the urls and write to file
for i in range(0, len(url_list)):
#print(url_list[i])
#print(type(url_list[i]))
x = scrape(url_list[i])
row = [s.encode('utf-8') for s in x.master_list]
if row != ['']:
writer.writerows([row])
f.close()
|
Python
|
UTF-8
| 25,818
| 2.5625
| 3
|
[] |
no_license
|
import json
from create_wf_model import change_and_xor_to_or, merge_split_join, change_and_to_multi_merge, \
change_loop_or_to_discriminator
from trace_validation import validate_multi_merge_in_trace, get_m_in_discriminator
from wf_graph import WF
class pattern_finder:
def __init__(self, log, wf_model, advanced_patterns=True):
self.log = log
self.wf_model = wf_model
self.patterns = {}
self.discover_patterns()
self.make_ors()
if advanced_patterns:
self.make_multi_merges()
self.rediscover_patterns()
self.check_patterns_for_discriminator()
if advanced_patterns:
self.make_discr()
self.rediscover_patterns()
def rediscover_patterns(self):
"""
Rediscovers patterns after something has changed
Returns
-------
object
"""
multi_merges = self.get_multi_merges()
self.patterns = {}
self.discover_patterns()
self.mark_discriminators()
for pattern in self.patterns:
pattern = self.patterns[pattern]
if pattern['partner'] in multi_merges:
pattern['is_multi_merge'] = True
def create_pattern(self, name, incoming_nodes, outgoing_nodes, partner, inner_nodes, is_loop=False, is_or=False):
"""This function creates a pattern object that can then be easily uses as JSON object
Parameters:
name (String): Name of the pattern (e.G, XOR-Split),
incoming_nodes (List<String>): List of ids of incoming nodes into the pattern node
outgoing_nodes (List<String>): List of ids of outgoing nodes into the pattern node
inner_nodes (List<String>): List of ids of nodes inside the pattern (between split and merge e.G)
partner (String): Partner node id (e.G for a split this would be the join or vice versa)
Returns:
{
"name": name,
"incoming_nodes": incoming_nodes,
"outgoing_nodes": outgoing_nodes,
"partner": partner,
"inner_nodes": inner_nodes
}
"""
pattern = {
"name": name,
"incoming_nodes": incoming_nodes,
"outgoing_nodes": outgoing_nodes,
"partner": partner,
"inner_nodes": inner_nodes,
"isLoop": is_loop,
"is_or": is_or,
"is_multi_merge": False,
"post_merge": None,
"is_discriminator": False,
"post_discriminator": None,
"discriminator_name": None
}
self.patterns[name] = pattern
return pattern
def find_split_join_pattern(self, node, end):
"""
Finds split_join pattern that starts at node
Parameters
----------
node : pattern start
end : pattern end
Returns
-------
"""
out_arcs = node.get_out_arcs()
if isinstance(node, WF.ExclusiveGateway):
if node.get_name() in self.patterns:
return [node.get_name()]
if node.get_name().endswith('split'):
seen = set()
join_node, isLoop = self.find_join_for_XOR_Split(node, node.get_name(), seen)
inner_patterns = []
for arc in out_arcs:
target = arc.get_target()
inner_pattern = self.find_split_join_pattern(target, join_node.get_name())
inner_patterns.extend(inner_pattern)
self.create_pattern(node.get_name(), [], [], join_node.get_name(), inner_patterns, isLoop)
return [node.get_name()]
if isinstance(node, WF.ParallelGateway):
if node.get_name() in self.patterns:
return [node.get_name()]
if node.get_name().endswith('split'):
join_node = self.find_join_for_And_Split(node, 0)
inner_patterns = []
for arc in out_arcs:
target = arc.get_target()
inner_pattern = self.find_split_join_pattern(target, join_node.get_name())
inner_patterns.extend(inner_pattern)
self.create_pattern(node.get_name(), [], [], join_node.get_name(), inner_patterns)
return [node.get_name()]
if isinstance(node, WF.InclusiveGateway):
if node.get_name() in self.patterns:
return [node.get_name()]
if node.get_name().endswith('split'):
join_node = self.find_join_for_Or_Split(node, 0)
inner_patterns = []
for arc in out_arcs:
target = arc.get_target()
inner_pattern = self.find_split_join_pattern(target, join_node.get_name())
inner_patterns.extend(inner_pattern)
self.create_pattern(node.get_name(), [], [], join_node.get_name(), inner_patterns)
return [node.get_name()]
if node.get_name() != end:
inner_patterns = [node.get_name()]
for arc in out_arcs:
target = arc.get_target()
inner_patterns.extend(self.find_split_join_pattern(target, end))
return inner_patterns
return []
def find_join_for_XOR_Split(self, node, split_name, seen):
"""
Finds Join for XOR Split
Returns join node name
-------
object
"""
if node in seen:
if node.get_name() == split_name:
return None, True
return None, False
out_arcs = node.get_out_arcs()
seen.add(node)
if isinstance(node, WF.ExclusiveGateway):
if node.get_name().endswith('join') and split_name[:6] == node.get_name()[:6]:
seen.remove(node)
return node, False
join_node = None
isLoop = False
if len(node.get_out_arcs()) == 0:
return None, True
for arc in out_arcs:
arc_node = arc.get_target()
x_join, is_loop = self.find_join_for_XOR_Split(arc_node, split_name, seen)
if is_loop:
isLoop = True
if x_join is not None:
join_node = x_join # TODO: This probably is a loop
return join_node, isLoop
def find_join_for_And_Split(self, node, openSplits):
"""
Finds Join for AND Split
Returns join node name
-------
object
"""
out_arcs = node.get_out_arcs()
if isinstance(node, WF.ParallelGateway):
if node.get_name().endswith('split'):
openSplits += 1
else:
openSplits -= 1
if openSplits == 0:
return node
for arc in out_arcs:
arc_node = arc.get_target()
x_join = self.find_join_for_And_Split(arc_node, openSplits)
return x_join
return None
def find_join_for_Or_Split(self, node, openSplits):
"""
Finds Join for Or Split
Returns join node name
-------
object
"""
out_arcs = node.get_out_arcs()
if isinstance(node, WF.InclusiveGateway):
if node.get_name().endswith('split'):
openSplits += 1
else:
openSplits -= 1
if openSplits == 0:
return node
for arc in out_arcs:
arc_node = arc.get_target()
x_join = self.find_join_for_Or_Split(arc_node, openSplits)
return x_join
return None
def check_patterns_for_or(self):
"""
Checks if patterns for or and marks them
Returns
-------
"""
for pattern in self.patterns:
pattern = self.patterns[pattern]
if pattern['name'].startswith('parallel'):
is_or = True
for node in pattern['inner_nodes']:
if node in self.patterns:
node = self.patterns[node]
targets = [arc.get_target() for arc in self.get_node_by_name(node['partner']).get_out_arcs()]
if not node['name'].startswith('xor') or len(node['inner_nodes']) > 1 or targets [0].get_name() != pattern['partner']:
is_or = False
break
else:
is_or = False
break
pattern['is_or'] = is_or
def check_patterns_for_multi_merge(self):
"""
Checks if patterns for multi merges and marks them
Returns
-------
"""
for pattern in self.patterns:
pattern = self.patterns[pattern]
if pattern['name'].startswith('parallel'):
partner_node = self.get_node_by_name(pattern['partner'])
if not len(partner_node.get_out_arcs()) == 1: # Cant be Multi Merge
continue
node = self.get_node_by_name(pattern['name'])
post_merge = None
for arc in node.get_out_arcs():
out_node_join = arc.get_target()
out_name_split = out_node_join.get_name()[:-4] + 'split'
found_one = True
if out_name_split in self.patterns and self.patterns[out_name_split]['isLoop']:
out_node_split = self.get_node_by_name(out_name_split)
if len(out_node_split.get_out_arcs()) == 2:
for out_arc in out_node_split.get_out_arcs():
if out_arc.get_target() == partner_node:
if post_merge is None:
post_merge = out_name_split
else:
found_one = False
if found_one and post_merge is not None:
outgoing_nodes = []
incoming_nodes = []
for flow in self.wf_model.get_flows():
if flow.get_source() == out_node_join:
if (flow.get_target().get_name().endswith('split')):
outgoing_nodes.extend(self.expand_inner_nodes(flow.get_target().get_name()))
else:
outgoing_nodes.append(flow.get_target().get_name())
if flow.get_target() == partner_node and flow.get_source() != out_node_split:
incoming_nodes.append(flow.get_source().get_name())
print(incoming_nodes, outgoing_nodes)
if validate_multi_merge_in_trace(self.log, incoming_nodes, outgoing_nodes):
pattern['is_multi_merge'] = True
pattern['post_merge'] = post_merge
def check_patterns_for_discriminator(self):
"""
Checks if patterns for Discriminators and marks them
Returns
-------
"""
for pattern in self.patterns:
pattern = self.patterns[pattern]
if pattern['name'].startswith('xor') and pattern['isLoop']:
partner_node = self.get_node_by_name(pattern['partner'])
node = self.get_node_by_name(pattern['name'])
counter = 0
if len(node.get_out_arcs()) == 2:
for arc in partner_node.get_out_arcs():
out_node_split = arc.get_target()
out_name_split = out_node_split.get_name()
out_name_join = out_node_split.get_name()[:-5] + 'join'
if out_name_split in self.patterns and out_name_split.startswith('or'):
out_node_join = self.get_node_by_name(out_name_join)
if len(out_node_join.get_out_arcs()) == 1:
if out_node_join.get_out_arcs()[0].get_target() == node:
outgoing_nodes = []
incoming_nodes = []
_, loop_redo_nodes = self.get_loop_redo_nodes(node, partner_node,
node)
with_xor = False
for flow in self.wf_model.get_flows():
if flow.get_source() == node and flow.get_target() in loop_redo_nodes:
if (flow.get_target().get_name().endswith('split')):
if flow.get_target().get_name().startswith('xor'):
with_xor = True
outgoing_nodes.extend(
self.expand_inner_nodes(flow.get_target().get_name()))
else:
outgoing_nodes.append(flow.get_target().get_name())
if flow.get_target() == out_node_join:
incoming_nodes.append(flow.get_source().get_name())
print(incoming_nodes, outgoing_nodes, with_xor)
m = get_m_in_discriminator(self.log, incoming_nodes, outgoing_nodes, with_xor)
if m != 'F':
pattern['is_discriminator'] = True
pattern['discriminator_name'] = str(m) + '_of_' + str(len(incoming_nodes))
pattern['post_discriminator'] = partner_node.get_out_arcs()[
0].get_target().get_name()
def recreate_sequences(self, node, seen):
if (node not in seen):
sequence = self.find_split_join_pattern(node, None)
seen.add(node)
if sequence[-1] != 'end':
pattern = self.patterns[sequence[-1]]
partner = pattern['partner']
if pattern['isLoop']:
# print('Found Loop')
for node_2 in self.wf_model.get_nodes():
if node_2.get_name() == pattern['inner_nodes'][1]:
sequence.append(self.recreate_sequences(node_2, seen))
if node_2.get_name() == pattern['inner_nodes'][0]:
sequence.append(self.recreate_sequences(node_2, seen))
else:
for node_2 in self.wf_model.get_nodes():
if node_2.get_name() == partner:
for target in node_2.get_out_arcs():
sequence.extend(self.recreate_sequences(target.get_target(), seen))
return sequence
return []
def expand_inner_nodes(self, pattern):
"""
Returns all inner nodes of a pattern (Nodes between join and split)
Parameters
----------
pattern : name of split node of pattern
Returns
-------
"""
found = True
seen = []
nodes = []
currentNodes = [self.get_node_by_name(pattern)]
while found:
found = False
c2 = currentNodes[:]
for node in c2:
if node not in seen:
currentNodes.remove(node)
if node.get_name() != self.patterns[pattern]['partner']:
for arc in node.get_out_arcs():
currentNodes.append(arc.get_target())
seen.append(node)
nodes.append(node)
found = True
nodes.remove(self.get_node_by_name(pattern))
nnames = []
for node in nodes:
nnames.append(node.get_name())
return nnames
def get_node_by_name(self, name):
"""
Returns
-------
Node with given name
"""
for node in self.wf_model.get_nodes():
if node.get_name() == name:
return node
return None
def make_ors(self):
"""
Rewires And and Xor to or in wf_model
"""
or_count = 1
for pattern in self.patterns:
pattern = self.patterns[pattern]
if pattern['is_or']:
and_split_node = self.get_node_by_name(pattern['name'])
and_join_node = self.get_node_by_name(pattern['partner'])
xors = []
for node in and_split_node.get_out_arcs():
node = node.get_target()
xors.append((node, self.get_node_by_name(self.patterns[node.get_name()]['partner'])))
change_and_xor_to_or(self.wf_model, and_split_node, and_join_node, xors, or_count)
or_count += 1
def make_multi_merges(self):
"""
Rewires the multi merges in wf_model
"""
for pattern in self.patterns:
pattern = self.patterns[pattern]
if pattern['is_multi_merge']:
and_split_node = self.get_node_by_name(pattern['name'])
and_join_node = self.get_node_by_name(pattern['partner'])
loop_split_node = self.get_node_by_name(pattern['post_merge'])
loop_join_node = self.get_node_by_name(self.patterns[pattern['post_merge']]['partner'])
change_and_to_multi_merge(self.wf_model, and_split_node, and_join_node, loop_split_node, loop_join_node)
def make_discr(self):
"""
Rewires the multi merges in wf_model
"""
for pattern in self.patterns:
counter = 1
pattern = self.patterns[pattern]
if pattern['is_discriminator']:
discriminator_name = pattern['discriminator_name']
loop_split_node = self.get_node_by_name(pattern['name'])
loop_join_node = self.get_node_by_name(pattern['partner'])
or_split_node = self.get_node_by_name(pattern['post_discriminator'])
or_join_node = self.get_node_by_name(self.patterns[pattern['post_discriminator']]['partner'])
_, loop_redo_nodes = self.get_loop_redo_nodes(loop_split_node, loop_join_node, loop_split_node)
change_loop_or_to_discriminator(self.wf_model, or_split_node, or_join_node, loop_split_node,
loop_join_node, loop_redo_nodes, discriminator_name, counter)
counter += 1
def discover_patterns(self):
"""
Discovers patterns and finds or and multi merges
"""
for node in self.wf_model.get_nodes():
self.find_split_join_pattern(node, None)
self.check_patterns_for_or()
self.check_patterns_for_multi_merge()
# print(self.patterns)
def merge_join(self, pattern_name):
"""
Merges join with pattern_name as split node
Parameters
----------
pattern_name : Split node name of pattern to merge
"""
if pattern_name in self.patterns:
merge_split_join(self.wf_model, self.get_node_by_name(pattern_name),
self.get_node_by_name(self.patterns[pattern_name]['partner']),
self.expand_inner_nodes(pattern_name))
self.patterns = {}
self.discover_patterns()
def get_loops(self):
"""
Returns node names of split and join xors that are indedd loops
-------
"""
loop_nodes = []
for pattern_name in self.patterns:
pattern = self.patterns[pattern_name]
if pattern['isLoop']:
loop_nodes.extend([pattern_name, pattern['partner']])
return loop_nodes
def get_multi_merges(self):
"""
Returns List of And Join node names, which are multi merges
-------
"""
multi_merges = []
for pattern_name in self.patterns:
pattern = self.patterns[pattern_name]
if pattern['is_multi_merge']:
multi_merges.append(pattern['partner'])
return multi_merges
def mark_discriminators(self):
for pattern_name in self.patterns:
pattern = self.patterns[pattern_name]
if pattern_name.startswith('parallel_discr_'):
pattern['is_discriminator'] = True
pattern['discriminator_name'] = pattern_name[15:21]
def get_discriminators(self):
discriminators = []
for pattern_name in self.patterns:
pattern = self.patterns[pattern_name]
if pattern['is_discriminator']:
discriminators.append(pattern['partner'])
return discriminators
def get_loop_redo_nodes(self, loop_split_node, loop_join_node, current_node):
for arc in current_node.get_out_arcs():
if arc.get_target() == loop_join_node:
x = set()
x.add(current_node)
return True, x
inner_nodes = set()
is_right_path = False
for arc in current_node.get_out_arcs():
if arc.get_target() != loop_join_node:
is_right_path_2, inner_nodes_2 = self.get_loop_redo_nodes(loop_split_node, loop_join_node,
arc.get_target())
if is_right_path_2:
is_right_path = True
for inner_node in inner_nodes_2:
inner_nodes.add(inner_node)
if (current_node != loop_split_node):
inner_nodes.add(current_node)
return is_right_path, inner_nodes
def patterns_to_json(self):
"""
Returns JSON Representation of Patterns
-------
"""
patterns_list = []
seen = set()
for pattern_name in self.patterns:
for pattern in [pattern_name, self.patterns[pattern_name]['partner']]:
is_multi_merge = self.patterns[pattern_name]['is_multi_merge']
is_discriminator = self.patterns[pattern_name]['is_discriminator']
incoming_nodes = []
outgoing_nodes = []
seen.add(pattern)
node = self.get_node_by_name(pattern)
for arc in node.get_in_arcs():
incoming_nodes.append(arc.get_source().get_name())
for arc in node.get_out_arcs():
outgoing_nodes.append(arc.get_target().get_name())
pattern_type = 'None'
if pattern.startswith('xor') and pattern.endswith('split'):
pattern_type = 'XOR Split'
elif pattern.startswith('xor') and pattern.endswith('join'):
pattern_type = 'XOR Join'
elif pattern.startswith('or') and pattern.endswith('split'):
pattern_type = 'OR Split'
elif pattern.startswith('or') and pattern.endswith('join'):
pattern_type = 'OR Join'
elif pattern.startswith('parallel') and pattern.endswith('split'):
pattern_type = 'AND Split'
elif pattern.startswith('parallel') and pattern.endswith('join'):
pattern_type = 'AND Join'
if is_multi_merge:
pattern_type = 'Multi Merge'
if is_discriminator:
pattern_type = 'Discriminator ' + self.patterns[pattern_name]['discriminator_name']
if self.patterns[pattern_name]['isLoop'] and pattern.endswith('join'):
pattern_type = 'Loop Start'
elif self.patterns[pattern_name]['isLoop'] and pattern.endswith('split'):
pattern_type = 'Loop End'
pattern_as_json = {
'pattern_node': pattern,
'incoming_nodes': incoming_nodes,
'outgoing_nodes': outgoing_nodes,
'pattern_type': pattern_type
}
patterns_list.append(pattern_as_json)
for node in self.wf_model.get_nodes():
if node.get_name() not in seen:
incoming_nodes = []
outgoing_nodes = []
for arc in node.get_in_arcs():
if arc.get_source().get_name() not in seen:
incoming_nodes.append(arc.get_source().get_name())
for arc in node.get_out_arcs():
if arc.get_target().get_name() not in seen:
outgoing_nodes.append(arc.get_target().get_name())
if len(outgoing_nodes) > 0:
pattern_as_json = {
'pattern_node': node.get_name(),
'incoming_nodes': incoming_nodes,
'outgoing_nodes': outgoing_nodes,
'pattern_type': 'Sequence'
}
patterns_list.append(pattern_as_json)
return json.dumps(patterns_list)
|
SQL
|
UTF-8
| 7,093
| 3.421875
| 3
|
[] |
no_license
|
#erstellen der evaluation_type und der evaluation_value Tabellen
CREATE TABLE evaluation_type (id INT NOT NULL, evaluation_type VARCHAR(100),
PRIMARY KEY (id), UNIQUE (evaluation_type));
CREATE TABLE evaluation_value (id INT NOT NULL, evaluation_value VARCHAR(100),
evaluation_type_id INT, FOREIGN KEY (evaluation_type_id) REFERENCES evaluation_type (id),
PRIMARY KEY (id), UNIQUE (evaluation_value));
#befüllen der evaluation_type Tabelle
INSERT INTO evaluation_type (id, evaluation_type) VALUES (1,'ActivityType');
INSERT INTO evaluation_type (id, evaluation_type) VALUES (2,'Genre');
INSERT INTO evaluation_type (id, evaluation_type) VALUES (3,'Setting');
INSERT INTO evaluation_type (id, evaluation_type) VALUES (4,'Dauer');
#befüllen der evaluation_value Tabelle
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (1,'ruhig', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (2,'actionreich', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (3,'gruselig', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (4,'dramatisch', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (5,'humorvoll', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (6,'spannend', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (7,'lehrreich', 1);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (8,'Horror', 2);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (9,'Action', 2);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (10,'Abenteuer', 2);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (11,'Fantasy', 2);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (12,'Krimi', 2);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (13,'Comedy', 2);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (14,'Fantasy_Setting', 3);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (15,'Zukunft', 3);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (16,'Gegenwart', 3);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (17,'Vergangenheit', 3);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (18,'sehr kurz', 4);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (19,'kurz', 4);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (20,'mittel', 4);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (21,'lang', 4);
INSERT INTO evaluation_value (id, evaluation_value, evaluation_type_id) VALUES (22,'unbegrenzt', 4);
# befüllen der question_type Tabelle
INSERT INTO question_type (id, question_type) VALUES (1, 'Einfachauswahl');
INSERT INTO question_type (id, question_type) VALUES (2, 'Mehrfachauswahl');
INSERT INTO question_type (id, question_type) VALUES (3, 'Slider');
# befüllen der question Tabelle
INSERT INTO question (id, question, question_type_id) VALUES (1, 'Welche Genres interessieren dich?', 2);
INSERT INTO question (id, question, question_type_id) VALUES (2, 'Wie soll der Abend verlaufen?', 1);
INSERT INTO question (id, question, question_type_id) VALUES (3, 'Wie lange willst du maximal beschäftigt sein?', 1);
INSERT INTO question (id, question, question_type_id) VALUES (4, 'Welche Settings sprechen dich an?', 2);
INSERT INTO question (id, question, question_type_id) VALUES (5, 'Was sind deine Lieblings Creator', 2);
INSERT INTO question (id, question, question_type_id) VALUES (6, 'Würdest du vom Auenland nach Mordor gehen?', 1);
INSERT INTO question (id, question, question_type_id) VALUES (7, 'Was sind die besten Pizzatoppings?', 2);
#Spalte für weight und evaluation_value_id hinzüfügen
ALTER TABLE choice ADD evaluation_value_id INT;
ALTER TABLE choice ADD FOREIGN KEY (evaluation_value_id) REFERENCES evaluation_value (id);
ALTER TABLE choice ADD weight DECIMAL (5,2);
ALTER TABLE choice CHANGE COLUMN choice choice VARCHAR(100);
ALTER TABLE choice ADD CONSTRAINT uqx_chc UNIQUE (choice);
# befüllen der choice und der question2choice Tabellen
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (1,'Horror', 8, 1), (2,'Action',9,1), (3,'Abenteuer',10,1),
(4,'Fantasy',11,1), (5,'Krimi',12,1), (6,'Comedy',13,1);
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (7,'ruhig',1,1), (8,'actionreich',2,1), (9,'gruselig',3,1),
(10,'dramatisch',4,1),(11,'humorvoll',5,1), (12,'spannend',6,1),
(13,'lehrreich',7,1);
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (14,'sehr kurz',18,1), (15,'kurz',19,1), (16,'mittel',20,1), (17,'lang',21,1),
(18,'unbegrenzt',22,1);
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (19,'Fantasie Welt',14,1), (20,'Zukunft',15,1), (21,'Gegenwart',16,1),
(22,'Vergangenheit',17,1);
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (23,'Astrid Lindgren',5,0.5), (24,'Stephen King', 3,0.5),
(25,'J. R. R. Tolkien', 6,0.5),(26,'Steven Spielberg', 4,0.5),
(27,'Michael Moore', 7,0.5), (28,'Hayao Miyazaki', 1,0.5),
(29,'Michael Bay', 2,0.5);
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (30,'Ja', 6, 1), (31,'Nein',6,0), (32,'Häh?', 11,0);
INSERT INTO choice (id, choice, evaluation_value_id, weight) VALUES (33,'Hollandaise',8,0.3), (34,'Jalapenos',9,0.3 ), (35,'Pasta',10,0.3),
(36,'Gummibärsaft',11,0.3), (37,'Nur Tomatensauce',12,0.3),
(38,'Ananas', 13,0.3);
INSERT INTO question2choice (question_id, choice_id) VALUES (1, 1), (1,2), (1,3), (1,4), (1,5), (1,6);
INSERT INTO question2choice (question_id, choice_id) VALUES (2,7), (2,8), (2,9), (2,10), (2,11), (2,12), (2,13);
INSERT INTO question2choice (question_id, choice_id) VALUES (3,14), (3,15), (3,16), (3,17), (3,18);
INSERT INTO question2choice (question_id, choice_id) VALUES (4, 19), (4, 22), (4,20), (4,21);
INSERT INTO question2choice (question_id, choice_id) VALUES (5, 29), (5,23), (5,24), (5,25), (5,26), (5,27), (5,28);
INSERT INTO question2choice (question_id, choice_id) VALUES (6, 32), (6,30), (6,31);
INSERT INTO question2choice (question_id, choice_id) VALUES (7,38), (7,33), (7,34), (7,35), (7,36), (7,37);
|
Python
|
UTF-8
| 7,263
| 3.484375
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 18:37:17 2020
Requires the spacy library to be installed.
Needed to reformat the data from the data set to match the
data set format from the previous chat bot prototype.
Converts the tsv file to the desired list of tuples. Each index of the
tuple consists of a list of the words in the intent, question and answer.
Also the script splits the data into training data and test data if necessary,
and saves each relevant piece of data in files. Including all data, test data, train data,
indexed answers and text versions of each for reference.
@author: tpvan
"""
"""
--------------------------------------------------------------------------------------------------------
Imports
--------------------------------------------------------------------------------------------------------
"""
import pandas as pd
import pickle
import spacy
nlp = spacy.load('en_core_web_sm')
"""
--------------------------------------------------------------------------------------------------------
Read file - tsv
--------------------------------------------------------------------------------------------------------
"""
# Method for returning file as a string. Not required.
def read_file(filepath):
with open(filepath) as f:
text = f.read()
return text
# Returns pandas DataFrame
data_frame = pd.read_csv('chat_data.tsv', sep='\t')
"""
--------------------------------------------------------------------------------------------------
'Clean' data
--------------------------------------------------------------------------------------------------
"""
if(input("Clean Data? (Y / N)") in "y"):
print('\n')
print('Before Cleaning NULL data ...')
# check for missing data - I saw a fair few NULLS in original file.
print(data_frame.isnull().sum())
print('\n')
# remove missing data
data_frame.dropna(inplace=True)
print('After Cleaning NULL data ...')
print(data_frame.isnull().sum())
print('\n')
# remove blank lines -- isspace method.
blanks=[]
for index, article, question, answer in data_frame.itertuples():
if article.isspace():
blanks.append(index)
if question.isspace():
blanks.append(index)
if answer.isspace():
blanks.append(index)
print('Number of Blank Lines before:')
print(len(data_frame))
# drop the blank lines
data_frame.drop(blanks, inplace=True)
print('Number of Blank Lines after:')
print(len(data_frame))
print('\n')
"""
--------------------------------------------------------------------------------------------------
Process Data into desired structure
--------------------------------------------------------------------------------------------------
"""
# Converts to a list of lists
df_list = [list(x) for x in data_frame.to_records(index=True)]
# Used to remove all the punctuation and turn every string into a list of words.
def seperate_punct_doc(doc):
return [token.text for token in doc if token.text not in '\n\n \n\n\n--"#$%&()*+,-/:;<=>@[\\]^_`{|}~\t\n']
print("Loading ... ")
# Ensure data is a string, then tokenize, then remove punctuation, returns a list.
for i in range(len(df_list)):
idx = df_list[i][0]
df_list[i][0] = [word.lower() for word in seperate_punct_doc(nlp(str(df_list[i][0])))]
df_list[i][1] = [word.lower() for word in seperate_punct_doc(nlp(str(df_list[i][1])))]
df_list[i][2] = [word.lower() for word in seperate_punct_doc(nlp(str(df_list[i][2])))]
df_list[i][3] = [str(idx)] + [word.lower() for word in seperate_punct_doc(nlp(str(df_list[i][3])))]
# Convert the lists consisting of [Article, Question, Asnwer] to a tuple
df_tuple = [tuple(x) for x in df_list]
# Serialize object.
with open('qa_df.txt', 'wb') as fp:
pickle.dump(df_tuple, fp, protocol=4)
# Ensure output is as desired.
with open('qa_df.txt', 'rb') as f:
df_loaded = pickle.load(f)
print(df_loaded)
"""
--------------------------------------------------------------------------------------------------------
Train Test Split
Note that the current bot does not use a train test split.
We could try an implement a proper test split and all that considering this dialogue data set is more
suitable for trying a proper test, but it does not matter. The validation/test data for the fitting does
not affect the training of the model.
--------------------------------------------------------------------------------------------------------
"""
from sklearn.model_selection import train_test_split
# X is articles and questions
X=[]
# y is answers
y=[]
indexed_answers = []
# append articles, questions and answers to X or y respectively -- X always represents 'features' and y is 'targets'
for i in range(len(df_list)):
X.append([df_list[i][0], df_list[i][1], df_list[i][2]])
y.append([df_list[i][3]])
indexed_answers.append([df_list[i][0], df_list[i][3]])
#print(indexed_answers)
# Use the sklean train_test_split method - and shuffles if include 'randomstate = 42'
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Copy the appropriate answers from y_train to X_train to create train data portion
# This will likely need refactoring -
for i in range(len(X_train)):
X_train[i].append(y_train[i][0])
# Same thing for the test split
for i in range(len(X_test)):
X_test[i].append(y_test[i][0])
# for clarity
train_data = X_train
test_data = X_test
indexed_train_answers =[]
# append articles, questions and answers to X or y respectively -- X always represents 'features' and y is 'targets'
for i in range(len(train_data)):
indexed_train_answers.append([train_data[i][2][0], ' '.join(train_data[i][2][1:])])
# Convert the lists consisting of [Article, Question, Asnwer] to a tuple.
df_train = [tuple(x) for x in train_data]
df_test = [tuple(x) for x in test_data]
print(df_train)
# Serialize objects / write actual text to file.
# training data
with open('qa_train_df_v2.txt', 'wb') as fp:
pickle.dump(df_train, fp, protocol=4)
# print to Ensure output is as desired.
with open('qa_train_df_v2.txt', 'rb') as f:
df_train_loaded = pickle.load(f)
# test data
with open('qa_test_df_v2.txt', 'wb') as fp:
pickle.dump(df_test, fp, protocol=4)
with open('qa_test_df_v2.txt', 'rb') as f:
df_test_loaded = pickle.load(f)
# indexed answers
with open('qa_indexed_ans_v2.txt', 'wb') as fp:
pickle.dump(indexed_answers, fp, protocol=4)
with open('qa_indexed_ans_v2.txt', 'rb') as f:
df_idx_ans = pickle.load(f)
# indexed answers - train data
with open('qa_train_indexed_ans_v2.txt', 'wb') as fp:
pickle.dump(indexed_train_answers, fp, protocol=4)
# indexed train answers text representation
with open('qa_train_indexed_ans_text_v2.txt', 'w') as f:
for i in range(len(indexed_train_answers)):
f.write("index : " + ' '.join(df_train[i][0]) +", Intent: "+ ' '.join(df_train[i][1]) + ", Question: " + ' '.join(df_train[i][2]) + ", Answer: " + ' '.join(df_train[i][3]) + '\n')
|
C
|
UTF-8
| 7,340
| 4.0625
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "linked_list.h"
struct list
{
cell_t *first;
cell_t *last;
int length;
};
struct cell
{
int key;
void *value;
cell_t *prev;
cell_t *next;
};
union elem
{
int i;
unsigned int u;
bool b;
float f;
void *p;
/// BYT UT VOID VALUE I CELL TILL EN ELEM
};
/// @brief Creates a new empty list
/// @return an empty linked list
ioopm_list_t *ioopm_linked_list_create()
{
// Allocate memory for the list head.
ioopm_list_t *l = calloc(1, sizeof(ioopm_list_t));
l->last = calloc(1, sizeof(cell_t));
l->first = calloc(1, sizeof(cell_t));
l->first->next = l->last;
l->last->prev = l->first->next;
l->length = 0;
return l;
}
/// @brief Tear down the linked list and return all its memory (but not the memory of the elements)
/// @param list the list to be destroyed
void ioopm_linked_list_destroy(ioopm_list_t *list);
/// @brief Insert at the end of a linked list in O(1) time
/// @param list the linked list that will be appended
/// @param value the value to be appended
void ioopm_linked_list_append(ioopm_list_t *list, int value)
{
cell_t *new = calloc(1, sizeof(cell_t));
new->value = value;
list->first->next->prev = new;
new->next = list->first->next;
list->first->next = new;
new->prev = list->first;
list->length++;
}
/// @brief Insert at the front of a linked list in O(1) time
/// @param list the linked list that will be prepended
/// @param value the value to be appended
void ioopm_linked_list_prepend(ioopm_list_t *list, int value)
{
cell_t *new = calloc(1, sizeof(cell_t));
new->value = value;
list->last->prev->next = new;
new->prev = list->last->prev;
list->last->prev = new;
new->next = list->last;
list->length++;
}
/// @brief Insert an element into a linked list in O(n) time.
/// The valid values of index are [0,n] for a list of n elements,
/// where 0 means before the first element and n means after
/// the last element.
/// @param list the linked list that will be extended
/// @param index the position in the list
/// @param value the value to be appended
void ioopm_linked_list_insert(ioopm_list_t *list, int index, int value)
{
cell_t *next = ioopm_linked_list_get(list, index);
cell_t *prev = next->prev;
cell_t *new = calloc(1, sizeof(cell_t));
prev->next = new;
new->prev = prev;
new->next = next;
next->prev = new;
list->length++;
}
/// @brief Remove an element from a linked list in O(n) time.
/// The valid values of index are [0,n-1] for a list of n elements,
/// where 0 means the first element and n-1 means the last element.
/// @param list the linked list that will be extended
/// @param index the position in the list
/// @param value the value to be appended
/// @return the value returned (*)
int ioopm_linked_list_remove(ioopm_list_t *list, int index)
{
cell_t *entry = ioopm_linked_list_get(list, index + 1);
if (entry == NULL)
{
return NULL;
}
entry->prev->next = entry->next;
entry->next->prev = entry->prev;
free(entry);
list->length--;
}
/// @brief Retrieve an element from a linked list in O(n) time.
/// The valid values of index are [0,n-1] for a list of n elements,
/// where 0 means the first element and n-1 means the last element.
/// @param list the linked list that will be extended
/// @param index the position in the list
/// @return the value at the given position
int ioopm_linked_list_get(ioopm_list_t *list, int index)
{
if (index > list->length && index < 0)
{
fprintf(stderr, "index %d exceeds list length %d", index, list->length);
return NULL;
}
cell_t *entry = linked_list_lookup(list, index);
return entry->value;
}
/// @brief Retrieve an element from a linked list in O(n) time.
/// The valid values of index are [0,n-1] for a list of n elements,
/// where 0 means the first element and n-1 means the last element.
/// @param list the linked list that will be extended
/// @param index the position in the list
/// @return the entry at the given position
static void *linked_list_lookup(ioopm_list_t *list, int index)
{
cell_t *entry = list->first;
int i = 0;
for (int i = 0; i <= index; i++)
{
entry = entry->next;
}
return entry;
}
/// @brief Test if an element is in the list
/// @param list the linked list
/// @param element the element sought
/// @return true if element is in the list, else false
bool ioopm_linked_list_contains(ioopm_list_t *list, int element)
{
cell_t *entry = list->first->next;
for (int i = 0; i < list->length; i++)
{
if (entry->value == element)
{
return true;
}
entry = entry->next;
}
return false;
}
/// @brief Lookup the number of elements in the linked list in O(1) time
/// @param list the linked list
/// @return the number of elements in the list
int ioopm_linked_list_size(ioopm_list_t *list)
{
return list->length;
}
/// @brief Test whether a list is empty or not
/// @param list the linked list
/// @return true if the number of elements int the list is 0, else false
bool ioopm_linked_list_is_empty(ioopm_list_t *list)
{
return list->first->next == list->last;
}
/// @brief Remove all elements from a linked list
/// @param list the linked list
void ioopm_linked_list_clear(ioopm_list_t *list)
{
while (list->first->next != list->last)
{
ioopm_linked_list_remove(list, 0);
}
}
/// @brief Test if a supplied property holds for all elements in a list.
/// The function returns as soon as the return value can be determined.
/// @param list the linked list
/// @param prop the property to be tested (function pointer)
/// @param extra an additional argument (may be NULL) that will be passed to all internal calls of prop
/// @return true if prop holds for all elements in the list, else false
bool ioopm_linked_list_all(ioopm_list_t *list, ioopm_char_predicate prop, void *extra)
{
cell_t *entry = list->first;
while (entry != NULL)
{
if (!rop(entry->key, entry->value, extra))
{
return false;
}
entry = entry->next;
}
return true;
}
/// @brief Test if a supplied property holds for any element in a list.
/// The function returns as soon as the return value can be determined.
/// @param list the linked list
/// @param prop the property to be tested
/// @param extra an additional argument (may be NULL) that will be passed to all internal calls of prop
/// @return true if prop holds for any elements in the list, else false
bool ioopm_linked_list_any(ioopm_list_t *list, ioopm_char_predicate prop, void *extra)
{
cell_t *entry = list->first;
while (entry != NULL)
{
if (prop(entry->key, entry->value, extra))
{
return true;
}
entry = entry->next;
}
return false;
}
/// @brief Apply a supplied function to all elements in a list.
/// @param list the linked list
/// @param fun the function to be applied
/// @param extra an additional argument (may be NULL) that will be passed to all internal calls of fun
void ioopm_linked_apply_to_all(ioopm_list_t *list, ioopm_apply_char_function fun, void *extra)
{
fun(0, list_(list), extra);
}
|
C#
|
UTF-8
| 7,207
| 2.640625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.SpreadSheet;
using System.IO;
namespace WindowsFormsApp1
{
public partial class reportsForm : Form
{
string connstring = "datasource=localhost;port=3307;user=root;password=toor";
MySqlConnection conn;
DataTable dt;
public reportsForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i;
dt = new DataTable();
dt.Columns.Add("srno");
dt.Columns.Add("jtitle");
dt.Columns.Add("volno");
dt.Columns.Add("issueno");
dt.Columns.Add("stdname");
dt.Columns.Add("_class");
dt.Columns.Add("issuedate");
dt.Columns.Add("returndate");
int choice = 0;
if (radioButton1.Checked) choice = 3; else if (radioButton2.Checked) choice = 4;
string fromDate = fromDatePicker.Value.ToString("dd-MM-yyyy");
string toDate = toDatePicker.Value.ToString("dd-MM-yyyy");
int count = 1;
string allStudents = "";
string allNames = "";
string allClasses = "";
try
{
conn = new MySqlConnection(connstring);
conn.Open();
string query = "SELECT reg_no,first_name, last_name, surname, class FROM journals.students;";
MySqlCommand cmd1 = new MySqlCommand(query, conn);
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
allStudents += (reader1.GetString(0) + "~");
allNames += (reader1.GetString(1)+" "+reader1.GetString(2)+" "+reader1.GetString(3) +"~");
allClasses += (reader1.GetString(4)+"~");
}
reader1.Close();
string[] studentList = allStudents.Split('~');
string[] studentNameList = allNames.Split('~');
string[] studentClassList = allClasses.Split('~');
/*for (int i=0;i<studentList.Count()-1;i++)
{
MessageBox.Show("Student is"+studentList[i]);
}*/
for (i=0;i<studentList.Count()-1;i++)
{
//MessageBox.Show(studentList[i]);
query = "SELECT * FROM journals._"+studentList[i]+";";
//MessageBox.Show(query);
MySqlCommand cmd2 = new MySqlCommand(query, conn);
MySqlDataReader reader2 = cmd2.ExecuteReader();
while (reader2.Read())
{
if (tellDate(fromDate, reader2.GetString(choice), toDate)){
DataRow dr = dt.NewRow();
dr["srno"] = count;
dr["jtitle"] = reader2.GetString(0);
dr["volno"] = reader2.GetString(1);
dr["issueno"] = reader2.GetString(2);
dr["stdname"] = studentNameList[i];
dr["_class"] = studentClassList[i];
dr["issuedate"] = reader2.GetString(3);
dr["returndate"] = reader2.GetString(4);
dt.Rows.Add(dr);
count++;
}
}
reader2.Close();
}
//reader1.Close();
conn.Close();
dataGridView1.DataSource = dt;
panel2.Hide();
panel3.Hide();
dataGridView1.Show();
/*foreach(DataRow ddd in dt.Select())
{
MessageBox.Show(ddd["stdname"].ToString());
}*/
foreach(DataRow ddd in dt.Select())
{
//MessageBox.Show(ddd["srno"].ToString());
}
button3.Show();
button4.Show();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void reportsForm_Load(object sender, EventArgs e)
{
dataGridView1.Hide();
button3.Hide();
button4.Hide();
}
private bool tellDate(string startDate, string gotDate, string endDate)
{
if (DateTime.Parse(gotDate) >= DateTime.Parse(startDate) && DateTime.Parse(gotDate) <= DateTime.Parse(endDate))
{
return true;
}
else return false;
}
private void button3_Click(object sender, EventArgs e)
{
int i = 2, j = 1;
string filename = "";
SaveFileDialog sv1 = new SaveFileDialog();
sv1.DefaultExt = "xls";
if(sv1.ShowDialog() == DialogResult.OK)
{
//MessageBox.Show(sv1.FileName);
filename = sv1.FileName;
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("abcdname");
worksheet.Cells[1, 1] = new Cell("Sr No");
worksheet.Cells[1, 2] = new Cell("Journal Title");
worksheet.Cells[1, 3] = new Cell("Volume No");
worksheet.Cells[1, 4] = new Cell("Issue No");
worksheet.Cells[1, 5] = new Cell("Student Name");
worksheet.Cells[1, 6] = new Cell("Class");
worksheet.Cells[1, 7] = new Cell("Issue Date");
worksheet.Cells[1, 8] = new Cell("Return Date");
foreach(DataRow dr in dt.Select())
{
worksheet.Cells[i, j] = new Cell(dr["srno"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["jtitle"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["volno"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["issueno"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["stdname"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["_class"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["issuedate"]);
j++;
worksheet.Cells[i, j] = new Cell(dr["returndate"]);
i++;
j = 1;
}
worksheet.Cells.ColumnWidth[2,2] = 10000;
worksheet.Cells.ColumnWidth[5, 5] = 6000;
workbook.Worksheets.Add(worksheet);
workbook.Save(filename);
}
}
}
}
|
PHP
|
UTF-8
| 1,221
| 3
| 3
|
[] |
no_license
|
<?php
class Users {
// deklasrasi objek/variabel
private $mysqli;
// fungsi yang otomatis diload pertama kali oleh kelas
function __construct($conn) {
$this->mysqli = $conn;
}
// fungsi tampil data users
public function tampil($id = null) {
$db = $this->mysqli->conn;
$sql = "SELECT * FROM tb_users";
if($id != null) {
$sql .= " WHERE id_users = $id";
}
$query = $db->query($sql) or die ($db->error);
return $query;
}
// fungsi tambah data users
public function tambah($nama_users, $username, $password, $role) {
$db = $this->mysqli->conn;
$db->query("INSERT INTO tb_users VALUES('', '$nama_users', '$username', '$password', '$role')") or die ($db_error);
}
// fungsi edit data users
public function edit($sql) {
$db = $this->mysqli->conn;
$db->query($sql) or die ($db_error);
}
// fungsi hapus data users
public function hapus($id) {
$db = $this->mysqli->conn;
$db->query("DELETE FROM tb_users WHERE id_users = '$id'") or die ($db_error);
}
// fungsi yang otomatis dipanggil terakhir kali setelah semua fungsi dalam kelas dijalankan / penutup koneksi
function __destruct() {
$db = $this->mysqli->conn;
$db->close();
}
}
?>
|
SQL
|
UTF-8
| 380
| 2.546875
| 3
|
[] |
no_license
|
/*
Creator: Mats J Svensson, CAnMove
*/
create table r_ori_sensor_type
(
sensor_type_id serial primary key,
sensor_type varchar(50) not null unique,
remark text
);
insert into x_table (name) select distinct 'r_ori_sensor_type' from x_table
where not exists (select 1 from x_table where name='r_ori_sensor_type');
update x_table set version='1.0' where name='r_ori_sensor_type';
|
Markdown
|
UTF-8
| 2,277
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
Dyn API hook for Dehydrated
===========================
`host.rb` is a hook, driven by `hook.sh`, for [Dehydrated](https://dehydrated.de/) to get certificates from [Let's Encrypt](https://letsencrypt.org/) using the `dns-01` challenge-response method, for [Dyn](https://dyn.com/) Managed DNS.
It uses the official `dyn-rb` gem to access the Dyn REST API, configured using Dehydrated's config file.
The `dns-01` challenge-response is useful because it lets you get all of your certs from one ACME client, to save you littering clients on every host in your infrastructure that needs a cert. That's especially useful for hosts where you can't install and operate a client, like routers, where certificates can still be installed.
It's a much more sensible method than the HTTP challenge-response method for that reason.
Basic Usage
-----------
0. Clone Dehydrated
0. Clone this hook
0. Configure Dehydrated (`config` file) to tell it where the hook is, provide your Dyn account details, and provide a path to `hook.rb` for `hook.sh` to call
0. Setup your ``domains.txt``
0. Run Dehydrated and get certificates
Example Dehydrated Configuration
--------------------------------
Here's an example `config` for Dehydrated. Set it up to your own liking.
```
CA="https://acme-staging.api.letsencrypt.org/directory"
HOOK=/path/to/hook.sh
CHALLENGETYPE="dns-01"
CERTDIR="${BASEDIR}/certs"
ACCOUNTDIR="${BASEDIR}/accounts"
CONTACT_EMAIL="your.email@address.com"
# config for hook.sh and host.rb
export DYN_ACCOUNTNAME="yourdynaccountname"
export DYN_USERNAME="yourdynapiusername"
export DYN_PASSWORD="yourdynapipassword"
export HOST_RB=/path/to/host.rb
```
Notes
-----
* In the `config` above, I'm using the staging Let's Encrypt directory. Please test against that yourself before making live requests.
* It doesn't handle Dehydrated's calls to `unchanged_cert` or `deploy_cert` in `hook.sh`. You might want to fill those in to do something useful on your setup, after Dehydrated gets your certs.
* If it wasn't obvious, `host.rb` is Ruby code, so you'll need a functioning Ruby and the `dyn-rb` gem for the hook to execute properly.
* The 5 second sleeps in `host.rb` might not be necessary, they just helped me debug the order of interaction between Dehydrated and how it calls a configured hook.
|
PHP
|
UTF-8
| 1,100
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Xsanisty\UserManager\Command;
use SilexStarter\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class PermissionRemoveCommand extends Command
{
protected function configure()
{
$this
->setName('permission:remove')
->setDescription('Remove permission from database')
->addArgument(
'permission-name',
InputArgument::REQUIRED,
'The permission name'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getSilexStarter();
$permName = $input->getArgument('permission-name');
$perm = $app['Xsanisty\UserManager\Repository\PermissionRepository']->findByName($permName);
$app['Xsanisty\UserManager\Repository\PermissionRepository']->delete($perm->id);
$output->writeln('<info>Permission "'.$perm->name.'" is now removed</info>');
}
}
|
Java
|
UTF-8
| 1,038
| 2.515625
| 3
|
[] |
no_license
|
package Classes;
import java.sql.PreparedStatement;
public class PessoaDao {
public boolean inserir(Pessoa p) {
Conexao con = new Conexao();
Boolean resultado = false;
try {
String SQL = "INSERT INTO vestibulando(nome, endereco, cidade, estado, cpf, rg, telresidencia, telcelular, email, titeleitor, pai, mae) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prep = con.getConexao().prepareStatement(SQL);
prep.setString(1, p.getNome());
prep.setString(2, p.getEndereco());
prep.setString(3, p.getCidade());
prep.setString(4, p.getEstado());
prep.setString(5, p.getCpf());
prep.setString(6, p.getRg());
prep.setString(7, p.getTelresidencia());
prep.setString(8, p.getTelcelular());
prep.setString(9, p.getEmail());
prep.setString(10, p.getTiteleitor());
prep.setString(11, p.getPai());
prep.setString(12, p.getMae());
prep.execute();
resultado = true;
} catch (Exception e) {
e.printStackTrace();
resultado = false;
}
con.desconecta();
return resultado;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.