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 | 6,787 | 2.53125 | 3 | [] | no_license | import os
import csv
import platform
import re
from collections import Counter
# data set dir
if platform.system() == "Darwin":
root_dir = '/Users/lee/Desktop/大四/毕业设计/GP_data'
elif platform.system() == "Linux":
root_dir = '/home/lee/Desktop/GP/linux'
ndpi_label_filename = 'ndpi_result.txt'
single_packet_length = 1568
# return sub dirs in the root dic
def sub_dir_list():
for root, dirs, files in os.walk(root_dir):
if root == root_dir:
return dirs
# read from the raw data file and return a joint payload
# @return: [return payload, payload_length, process, success]
def read_raw_data(file_name):
payload = ""
process = "NULL"
p_count = 0
try:
with open(file_name) as f:
content = f.readlines()
except IOError:
print("file= ", file_name, "is not found")
return '', process, p_count, False
else:
content = [x.strip() for x in content]
read_type = 0
for line in content:
if read_type == 1:
# joint the payload as one str
payload += ',' + line.strip()
read_type = 0
continue
if read_type == 2:
# save the process info
process = line[:line.find(' ')]
read_type = 0
continue
if not line.find('src:'):
read_type = 1
p_count += 1
# count the total length of the flow
# payload_length += int(line[line.find("payload length:") + len("payload length:"):])
continue
if not line.find('COMMAND'):
read_type = 2
continue
return payload, process, p_count, True
# read from the ndpi result data
# @return: list of tuples: flow name, Ms_protocol, app_protocol
def read_ndpi_result(ndpi_file_name):
with open(ndpi_file_name) as f:
content = f.readlines()
# get rid of the \n
content = [x.strip() for x in content]
container = []
# split into tuple
for item in content:
container.append(item.split('\t'))
return container
def write_payload_to_csv(date_info, flow_name, payload, payload_count):
csv_file_name = os.path.join(root_dir, 'payload_info.csv')
pl = [tok for tok in re.split(',', payload) if len(tok) > 0]
# print(pl)
data = []
# # cut the packet into single_packet_length
# for pp in pl:
# # get the distribution to the payload length
# lene = len(pp)
# lene = int(lene / 10)
# payload_count[lene] += 1
#
# if len(pp) >= single_packet_length:
# info_tuple = (str(date_info + ':' + flow_name), pp[:single_packet_length])
# else:
# info_tuple = (str(date_info + ':' + flow_name), pp)
# data.append(info_tuple)
for i in range(len(pl)):
pp = pl[i]
lene = len(pp)
lene = int(lene / 10)
payload_count[lene] += 1
if len(pp) >= single_packet_length:
info_tuple = (str(date_info + ':' + flow_name), pp[:single_packet_length])
else:
j = i + 1
while j < len(pl):
pp += pl[j]
if len(pp) >= single_packet_length:
info_tuple = (str(date_info + ':' + flow_name), pp[:single_packet_length])
break
j += 1
if len(pp) < single_packet_length:
info_tuple = (str(date_info + ':' + flow_name), pp[:single_packet_length])
data.append(info_tuple)
# # just concat
# pp = payload.replace(',', '')
# while True:
# info_tuple = (str(date_info + ':' + flow_name), pp[:single_packet_length])
# data.append(info_tuple)
# if len(pp) < single_packet_length:
# break
# else:
# pp = pp[single_packet_length:]
#
with open(csv_file_name, "a") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for info in data:
writer.writerow(info)
return payload_count
def write_date_ndpi_to_csv(date, ndpi_result_list):
csv_file_name = os.path.join(root_dir, 'ndpi_result.csv')
with open(csv_file_name, "a") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for flow_name, ms_pro, app_pro, process in ndpi_result_list:
writer.writerow((str(date + ':' + flow_name), ms_pro, app_pro, process))
if __name__ == '__main__':
print("start to format data")
for sub_dir in sub_dir_list():
print("entering dir: ", sub_dir)
file_dir = os.path.join(root_dir, sub_dir)
ndpi_file = os.path.join(file_dir, ndpi_label_filename)
ndpi_result = read_ndpi_result(ndpi_file)
print("ndpi_result read")
error_file = []
com_result = []
pro_result = []
count_result = Counter()
packet_length_counter = Counter()
payload_length = 0
packet_count = 0
for flow, ms_p, app_p in ndpi_result:
loads, process_name, count, result = read_raw_data(os.path.join(file_dir, flow))
if result:
packet_length_counter = write_payload_to_csv(sub_dir, flow, loads, packet_length_counter)
payload_length += len(loads)
packet_count += count
com_result.append((flow, ms_p, app_p, process_name))
if (ms_p, app_p) not in pro_result:
pro_result.append((ms_p, app_p))
print("add new protocol: ", (ms_p, app_p))
if (ms_p, app_p) in pro_result:
count_result[(ms_p, app_p)] += 1
else:
# mark the file-missing item
error_file.append(flow)
print("date ", sub_dir, ": payload data writing finished")
write_date_ndpi_to_csv(sub_dir, com_result)
print("date ", sub_dir, ": label writing finished")
print("\t total packet: ", packet_count, ", total bytes:", payload_length, "bytes")
print("\t total session counted: ", len(com_result))
print("\t total protocol counted: ", len(count_result))
print("\t ", count_result)
print("\t packet length distribute: ", packet_length_counter)
print("\t missing total ", len(error_file), " files:")
# with open(os.path.join(root_dir, 'length_dis.csv'), 'w') as csvfile:
# writer = csv.writer(csvfile)
# for key, value in packet_length_counter.items():
# writer.writerow(list(key) + [value])
# for err_info in error_file:
# print("\t\t", err_info)
print("---------------------------------------------------------")
|
Java | UTF-8 | 10,257 | 1.9375 | 2 | [] | no_license | package com.itel.monitor.p2pview.register;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.surveillancecamera.R;
import com.itel.monitor.entity.User;
import com.itel.monitor.p2pview.login.LoginActivity;
import com.itel.monitor.util.S;
import com.itel.monitor.util.ToastUtil;
import com.itel.monitor.view.BaseActivity;
public class VerificationPhoneCodeActivity extends BaseActivity {
private TextView verification_phone_code_next;
private Button verification_phone_code_get_again;
private TextView verification_phone_code_timer;
private TextView verification_phone_code_phonenumber;
private EditText verification_phone_code_edit;
private ImageView verification_phone_code_back;
private String phone_number="";
private Handler handler;
private Timer timer;
private String text;
private String flag="";
//private Thread timer_thread;
private User register_user;
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_phone_code);
flag=getIntent().getStringExtra("flag");
if("VerificationByPhoneActivity".equals(flag)){
phone_number=getIntent().getStringExtra("phone_number");
}else if("PersonalRegisterActivity".equals(flag)){
register_user=(User)getIntent().getSerializableExtra("register_user");
}else if("EnterpriseRegisterActivity".equals(flag)){
register_user=(User)getIntent().getSerializableExtra("register_user");
}
setupView();
setListener();
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.obj!=null)
//S.o("msg.what="+msg.what+",msg.obj="+msg.obj);
switch(msg.what){
case 0:
verification_phone_code_timer.setText((String)msg.obj+"秒后");
break;
case 1:
timer.cancel();
verification_phone_code_get_again.setTextColor(Color.BLACK);
verification_phone_code_get_again.setEnabled(true);
break;
default:break;
}
}
};
setConfig();
}
class myTimerTask extends TimerTask{
int i = 60;
//定义一个消息传过去
// TimerTask 是个抽象类,实现的是Runable类
@Override
public void run() {
Message msg = new Message();
if(i>=0){
msg.what = 0;
msg.obj=i--+"";
handler.sendMessage(msg);
}else{
msg.what = 1;
msg.obj="";
handler.sendMessage(msg);
}
}
}
private void setConfig() {
if("VerificationByPhoneActivity".equals(flag)){
}else if("PersonalRegisterActivity".equals(flag)){
phone_number=register_user.getMobilePhone();
}else if("EnterpriseRegisterActivity".equals(flag)){
phone_number=register_user.getMobilePhone();
}
text="请输入手机号"+phone_number.substring(0, 3)+"****"+phone_number.substring(7)+"接收到的验证码";
if(!"".equals(phone_number)){
verification_phone_code_phonenumber.setText(text);
}
try {
timer = new Timer();
// 定义计划任务,根据参数的不同可以完成以下种类的工作:在固定时间执行某任务,在固定时间开始重复执行某任务,重复时间间隔可控,在延迟多久后执行某任务,在延迟多久后重复执行某任务,重复时间间隔可控
timer.schedule(new myTimerTask(), 0, 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setupView() {
verification_phone_code_back=(ImageView)findViewById(R.id.verification_phone_code_back);
verification_phone_code_edit=(EditText)findViewById(R.id.verification_phone_code_edit);
verification_phone_code_phonenumber=(TextView)findViewById(R.id.verification_phone_code_phonenumber);
verification_phone_code_timer=(TextView)findViewById(R.id.verification_phone_code_timer);
verification_phone_code_get_again=(Button)findViewById(R.id.verification_phone_code_get_again);
verification_phone_code_next=(TextView)findViewById(R.id.verification_phone_code_next);
}
private void setListener() {
//返回
verification_phone_code_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if("VerificationByPhoneActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,VerificationByPhoneActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}else if("PersonalRegisterActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,PersonalRegisterActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}else if("EnterpriseRegisterActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,EnterpriseRegisterActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}
}
});
//重新获取验证码
verification_phone_code_get_again.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(verification_phone_code_get_again.isEnabled()){
verification_phone_code_get_again.setTextColor(Color.GRAY);
sendEms();
ToastUtil.show(VerificationPhoneCodeActivity.this, "重新获取验证码", Toast.LENGTH_SHORT);
timer=new Timer();
timer.schedule(new myTimerTask(), 0, 1000);
}
}
});
//验证码验证成功,下一步
verification_phone_code_next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if("VerificationByPhoneActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,ModifyPasswordActivity.class);
intent.putExtra("phone_number", text);
intent.putExtra("flag", "VerificationPhoneCodeActivity");
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}else if("PersonalRegisterActivity".equals(flag)){
//注册业务
ToastUtil.show(VerificationPhoneCodeActivity.this, "个人版账号注册成功!", Toast.LENGTH_LONG);
Intent intent=new Intent(VerificationPhoneCodeActivity.this,LoginActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}else if("EnterpriseRegisterActivity".equals(flag)){
//注册业务
Toast.makeText(VerificationPhoneCodeActivity.this, "企业版账号注册成功!", Toast.LENGTH_LONG).show();
Intent intent=new Intent(VerificationPhoneCodeActivity.this,LoginActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}
}
});
}
private void sendEms() {
/*ContentValues values = new ContentValues();
values.put("address", "13168728859");
values.put("type", "1");
values.put("read", "1");
values.put("body", "您的验证码是123456");
values.put("date", new Date().getTime());
values.put("person", "test");
values.put("protocol", "0");
Uri uri = this.getApplicationContext().getContentResolver()
.insert(Uri.parse("content://mms-sms/"), values);*/
/*ContentValues values = new ContentValues();
try
{
//发送时间
values.put("date", System.currentTimeMillis());
//阅读状态
values.put("read", 0);
//1为收,2为发
values.put("type", 2);
//送达号码
values.put("address", "13168728859");
//送达内容
values.put("body", "您的验证码是123456");
//插入短信库
getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
}catch (Exception e)
{
e.printStackTrace();
}finally
{
values = null;
}*/
//发送通知
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.add_camera, "您的短信验证码是123456", System.currentTimeMillis());
n.flags = Notification.FLAG_AUTO_CANCEL;
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setType("vnd.android-dir/mms-sms");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
//PendingIntent
PendingIntent contentIntent = PendingIntent.getActivity(
this,
R.string.app_name,
i,
PendingIntent.FLAG_UPDATE_CURRENT);
n.setLatestEventInfo(
this,
"短信验证码",
"您的短信验证码是123456",
contentIntent);
nm.notify(R.string.app_name, n);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.verification_phone_code, menu);
return true;
}
@Override
protected void onDestroy() {
//timer_thread.stop();
super.onDestroy();
}
@Override
public void onBackPressed() {
if("VerificationByPhoneActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,VerificationByPhoneActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}else if("PersonalRegisterActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,PersonalRegisterActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}else if("EnterpriseRegisterActivity".equals(flag)){
Intent intent=new Intent(VerificationPhoneCodeActivity.this,EnterpriseRegisterActivity.class);
startActivity(intent);
VerificationPhoneCodeActivity.this.finish();
}
}
}
|
C# | UTF-8 | 705 | 3.3125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[4] { 6, 4, 2, 1 };
Console.WriteLine("逆序前的数组:");
Console.Write(a[0].ToString() + " " + a[1].ToString() + " " + a[2].ToString() + " " + a[3].ToString());
Array.Reverse(a);
Console.WriteLine();
Console.WriteLine("逆序后的数组:");
Console.Write(a[0].ToString() + " " + a[1].ToString() + " " + a[2].ToString() + " " + a[3].ToString());
Console.Read();
}
}
}
|
PHP | UTF-8 | 2,236 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
namespace Application;
use Application\Contract\Command as CommandInterface;
use Application\Contract\EventDispatcher;
use Application\Contract\UseCase;
use Application\Contract\User;
use Application\Contract\Validator;
use Application\Event\Events;
use Application\Event\PostCommandEvent;
use Application\Event\PreCommandEvent;
use Application\Exception\BadRequestException;
use Application\Result\Result;
class CommandHandler
{
private $validator;
private $eventDispatcher;
private $user;
/**
* @var UseCase[]
*/
private $useCases;
public function __construct(
Validator $validator,
EventDispatcher $eventDispatcher,
User $user
) {
$this->validator = $validator;
$this->eventDispatcher = $eventDispatcher;
$this->user = $user;
}
public function registerCommands(array $useCases)
{
foreach ($useCases as $useCase) {
if ($useCase instanceof UseCase) {
$this->useCases[$useCase->getManagedCommand()] = $useCase;
} else {
throw new \LogicException('CommandHandler::registerCommands UseCase must be array');
}
}
}
public function execute(CommandInterface $command)
{
$this->exceptionIfCommandNotManaged($command);
$this->eventDispatcher->notify(Events::PRE_COMMAND, new PreCommandEvent($command));
if ($command->isValidated()) {
$errors = $this->validator->validate($command, $command->getValidationGroups());
if (!$errors->isEmpty()) {
throw new BadRequestException('Data validation errors', $errors);
}
}
$result = $this->useCases[get_class($command)]->run($command, $this->user);
$this->eventDispatcher->notify(Events::POST_COMMAND, new PostCommandEvent($command, $result));
return new Result($result);
}
private function exceptionIfCommandNotManaged(CommandInterface $command)
{
$commandClass = get_class($command);
if (!array_key_exists($commandClass, $this->useCases)) {
throw new \LogicException($commandClass . ' is not registered command');
}
}
}
|
Python | UTF-8 | 632 | 2.78125 | 3 | [] | no_license | import subprocess
import json
import rl_training
from time import time
import numpy as np
trainer = rl_training.TrainAgent()
count = 0
rewards = []
while True:
count += 1
try:
now = time()
proc_output = subprocess.getoutput('run_game.bat')
stats = json.loads(proc_output[proc_output.find('{'):])['stats']['0']
bot_reward = stats['score']
bot_rank = stats['rank']
rewards.append(bot_reward)
trainer.train()
print("Iteration took {:.0f} seconds".format(time() - now))
if count % 20 == 0:
print("Mean reward over past 20 games: {}".format(np.mean(rewards)))
rewards = []
except KeyboardInterrupt:
break
|
C++ | UTF-8 | 2,023 | 3.5625 | 4 | [] | no_license | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// arr[]: Input Array
// N : Size of the Array arr[]
// Function to count inversions in the array.
long long int inversionCount(long long arr[], long long N)
{
long long temp[N];
return mergesort(arr, temp, 0, N-1);
}
long long int mergesort(long long arr[], long long temp[], long long start, long long end)
{
long long int inv_count = 0;
long long mid = start + (end - start)/2;
if(start < end)
{
inv_count += mergesort(arr, temp, start, mid);
inv_count += mergesort(arr, temp, mid+1, end);
inv_count += merge(arr, temp, start, mid, end);
}
return inv_count;
}
long long int merge(long long arr[], long long temp[], long long start, long long mid, long long end)
{
long long i, j, k;
long long int inv_count = 0;
i = start;
j = mid + 1;
k = start;
while(i<=mid && j<=end)
{
if(arr[i] > arr[j])
{
temp[k++] = arr[j++];
inv_count += (mid - i + 1);
}
else
{
temp[k++] = arr[i++];
}
}
while(i<=mid)
{
temp[k++] = arr[i++];
}
while(j<=end)
{
temp[k++] = arr[j++];
}
for(i = start; i<=end; i++)
{
arr[i] = temp[i];
}
return inv_count;
}
};
// { Driver Code Starts.
int main() {
long long T;
cin >> T;
while(T--){
long long N;
cin >> N;
long long A[N];
for(long long i = 0;i<N;i++){
cin >> A[i];
}
Solution obj;
cout << obj.inversionCount(A,N) << endl;
}
return 0;
}
// } Driver Code Ends |
C | UTF-8 | 167 | 3.421875 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int a=28;
int b=2;
//Swapping...
int temp=a;
a=b;
b=temp;
printf("After swapping , a is %d , b is %d",a,b);
return 0;
}
|
Python | UTF-8 | 793 | 3.390625 | 3 | [] | no_license | import sys
sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos')
from mensagem import ler_cabecalho
from numeros import ler_num_nat, ler_num_float
from time import sleep
def pa():
ler_cabecalho('progressão aritmética')
A1 = ler_num_float('Primeiro termo: ')
r = ler_num_float('Razão: ')
i = 1
An = A1
termo = 10
total_termos = 10
while termo != 0:
while termo > 0:
print(f'{An:.2f}', end=' -> ', flush=True)
An = A1 + i*r
i += 1
termo -= 1
sleep(0.5)
print('pausa')
print('Digite 0 para encerrar.')
termo = ler_num_nat('Quantos termos deseja mostrar? ')
total_termos += termo
print(f'Total de termos mostrados: {total_termos}\n')
|
C# | UTF-8 | 2,281 | 2.875 | 3 | [
"MIT"
] | permissive | //By Ronny Berglihn Reinertsen <ronny@reinertsen.net> 05.11.2019
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace FSKristiansandWebLib.Prime
{
public static class ProfileDataParser
{
/// <summary>
/// Convert from uploaded profile to object
/// </summary>
/// <param name="data">Uploaded profile data</param>
/// <returns>AgentStatsModel object</returns>
public static AgentStatsModel ParseData(string data)
{
var retVal = new AgentStatsModel();
if (data.IndexOf((char)0x0a) == -1)
return retVal;
string[] dataLines = data.Split(new char[] { (char)0x0a });
string[] columns = dataLines[0].Split('\t');
if (dataLines.Length > 1)
{
string[] rows = dataLines[1].Split('\t');
for (int i = 0; i < columns.Length; ++i)
{
if (!string.IsNullOrEmpty(columns[i]))
SetField(ref retVal, columns[i], rows[i]);
}
}
return retVal;
}
/// <summary>
/// Set data on variables using reflection to get attribute name
/// </summary>
/// <param name="model">AgentStatsModel</param>
/// <param name="propName">Property name</param>
/// <param name="value">Property value</param>
public static void SetField(ref AgentStatsModel model, string propName, object value)
{
if (string.IsNullOrWhiteSpace(propName)) return;
var propertiesWithAttribute = typeof(AgentStatsModel).GetProperties()
.Select(pi => new { Property = pi, Attribute = pi.GetCustomAttributes(typeof(DataMemberAttribute), true).FirstOrDefault() as DataMemberAttribute })
.Where(x => x.Attribute != null)
.ToList();
PropertyInfo findProperty = null;
try
{
findProperty = propertiesWithAttribute.Where(p => p.Attribute.Name == propName).FirstOrDefault().Property;
} catch
{
LogHelper.Warn($"Failed to get property with name: '{propName}' and value: {value}");
//ex.Log();
return;
}
if (findProperty != null)
{
findProperty.SetValue(model, Convert.ChangeType(value, findProperty.PropertyType));
return;
}
else
{
//Log item not found... We need to add support for it in our AgentStatsModel class
LogHelper.Warn($"ProfileDataParser>SetField>Missing data column property for '{propName}' with value {value}");
}
}
}
}
|
Markdown | UTF-8 | 2,447 | 3.1875 | 3 | [
"MIT"
] | permissive | ---
title: „Ég er Jósef, bróðir ykkar“
date: 16/06/2022
---
`Lestu 1Mós 45. Hvað getum við lært um kærleika, trú og von í þessari frásögn?`
Það var einmitt þegar Júda talaði um þá „óhamingju“ sem koma mundi yfir föður sinn (1Mós 44.34) að Jósef gat „ekki lengur haft stjórn á tilfinningum sínum,“ „brast í grát“ og „opinberaði sig“ fyrir bræðrum sínum (1Mós 45.1, 2). Þetta orðalag sem oft er notað um opinberun Guðs (2Mós 6.3; Esk 20.9) bendir til þess að Guð sé einnig að opinbera sig hér. Það er að segja Drottinn hefur sýnt fram á að forsjón hans hafi völdin þrátt fyrir veikleika mannsins.
Bræður Jósefs trúa ekki eigin eyrum og augum. Því verður Jósef að endurtaka: „Ég er Jósef, bróðir ykkar“ (1Mós 45.4) og það er fyrst við endurtekningu orðanna „sem þið selduð til Egyptalands“ (1Mós 45.4) að þeir trúa því.
Jósef bætir síðan við: „Það var Guð sem sendi mig hingað“ (1Mós 45.5). Tilvísun hans til Guðs gegnir tvennu hlutverki. Það var ekki einungis til að fullvissa bræður sína um að hann bæri ekki neitt kal í brjósti til þeirra heldur er það einnig djúp trúarjátning og yfirlýsing um von þar sem það sem þeir gerðu var nauðsynlegt til þess að „bjarga lífi“ og „halda við kyni ykkar“ (1Mós 45.5, 7).
Jósef hvetur síðan bræður sína til að fara tilbaka til föður hans og búa hann undir að koma til Egyptalands. Síðan bætir hann við lýsingu á staðnum þar sem þeir muni dvelja, Gósenlandi, sem var þekkt fyrir að vera frjósamt og „það besta sem Egyptaland hefur upp á að bjóða“ (1Mós 45.18, 20). Hann sér einnig fyrir vögnum sem farkosti en þeir sannfæra Jakob að lokum um að synir hans séu ekki að ljúga að honum um reynslur sínar (1Mós 45.27). Jakob lítur þetta sem sýnilega vísbendingu um að Jósef sé á lífi og það nægir til þess að það lifnaði yfir honum (sbr. 1Mós 37.35; 1Mós 44.29).
Allt er nú komið í lag. Allir tólf synir Jakobs eru á lífi. Jakob er nefndur „Ísrael“ (1Mós 45.28) og forsjón Guðs hefur birst á áhrifamikinn hátt.
`Jósef var miskunnsamur í garð bræðra sinna. Hann hafði líka efni á því. Hvernig getum við lært að vera miskunnsöm í garð þeirra sem hafa gert eitthvað gegn okkur sem þó hefur ekki snúist til góðs eins og í lífi Jósefs?` |
Markdown | UTF-8 | 4,519 | 3.796875 | 4 | [] | no_license | # Analysis
## Test Set 1
For the small test set, one can generate all possible conversions recursively and select the one with the smallest number of rule violations as the answer. Since each note can be converted to four possible notes in the alien scale, this results into 4<sup>**K**</sup> combinations to be tested and O(4</sup>**K**</sup>) time complexity.
## Test Set 2
### Dynamic Programming Solution
Let DP[i, j] be the minimum number of rule violations required to convert the first i notes **A<sub>1</sub>**, **A<sub>2</sub>**, ..., **A<sub>i</sub>** such that the i-th note **A<sub>i</sub>** is converted to note j of the alien piano (1 ≤ j ≤ 4). Then the answer is the minimum DP[**K**, j] over all j, 1 ≤ j ≤ 4.
The table DP[i, j] can be computed using dynamic programming as follows.<br>
(1) DP[1, j] = 0 for all j.<br>
(2) For i > 1, DP[i, j] = min{ DP[i - 1, j'] + P(i, j', j) | 1 ≤ j' ≤ 4 }. Here P(i, j', j) is a binary penalty term accounting for a rule violation between the notes **A<sub>i-1</sub>** and **A<sub>i</sub>**. For example, if **A<sub>i-1</sub>** > **A<sub>i</sub>**, then P(i, j', j) = 1 whenever j' ≤ j and P(i, j', j) = 0 otherwise.<br>
Since each entry of the table is calculated using a constant number of operations, the overall time complexity of the algorithm is O(**K**), which is okay to pass the large test set.
### Greedy Solution
Let us say that a sequence of pitches is _playable_ if it can be converted to the alien piano notes without violating any rules. Our goal here is to split the given sequence of pitches into as few playable fragments as possible.
We can take the longest playable prefix of the sequence as the first fragment of the split. In this way, the remainder of the sequence is as short as possible, and therefore requires potentially fewer rule violations.
Now let us characterise the playable sequences. Note that repeated notes of the same pitch do not affect the playability of the sequence, therefore, without loss of generality, suppose that any two consecutive notes are at a different pitch. Let us say that two consecutive notes form an _upward step_ if the second note has a higher pitch than the first. Otherwise, we call it a _downward step_.
Clearly, a sequence of notes is not playable if it contains more than three consecutive upward or downward steps, as we would run out of the alien scale. Otherwise, the sequence is playable and we can convert it using this simple strategy (assuming the note names A, B, C, and D of the alien piano from the lowest to the highest note):<br>
(1) If the first step is upward, convert the first note to A.<br>
(2) If the first step is downward, convert the first note to D.<br>
(3) If three consecutive notes form an upward step followed by a downward step, convert the second note to D.<br>
(4) If three consecutive notes form a downward step followed by an upward step, convert the second note to A.<br>
(5) In all other cases, convert a note one step higher or lower than the note before depending on whether they form an upward or downward step.<br>
Since any maximal sequence of upward steps starts at A and has no more than three steps (and similarly for any maximal sequence of downward steps), we will never leave the alien scale.
The following diagram illustrates the process of splitting the sequence (1, 8, 9, 7, 6, 5, 4, 3, 2, 1, 3, 2, 1, 3, 5, 7) into two playable fragments. Since the subsequence (9, 7, 6, 5, 4) consists of four downward steps, the sequence needs to be split between notes 5 and 4.

According to the analysis above, a single pass through the given sequence of notes maintaining the current number of consecutive upward and downward steps results in an O(**K**) solution, where **K** is the number of notes in the sequence. As soon as the number of upward or downward steps exceeds 3, we have to split the sequence by violating the rules and start a new fragment. A Python code snippet is included below for clarity.
```
def solve():
k = input()
a = map(int, raw_input().split())
# Filter out repeated notes.
a = [a[i] for i in xrange(0, k) if i == 0 or a[i - 1] != a[i]]
upCount = 0
downCount = 0
violations = 0
for i in xrange(1, len(a)):
if a[i] > a[i - 1]:
upCount += 1
downCount = 0
else:
downCount += 1
upCount = 0
if upCount > 3 or downCount > 3:
violations += 1
upCount = downCount = 0
return violations
```
|
C# | UTF-8 | 914 | 2.640625 | 3 | [] | no_license | using log4net;
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Octopus.Standlone.Webapp
{
public class StreamReadingDelegatingHandler : DelegatingHandler
{
private static ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
Stream strea = new MemoryStream();
await request.Content.CopyToAsync(strea);
strea.Position = 0;
StreamReader reader = new StreamReader(strea);
String res = reader.ReadToEnd();
Log.Info("request content: " + res);
return response;
}
}
}
|
Java | UTF-8 | 1,623 | 2.125 | 2 | [] | no_license | package com.jumper.bluetoothdevicelib.device.bloodpressure;
import com.jumper.bluetoothdevicelib.config.DeviceConfig;
import com.jumper.bluetoothdevicelib.core.ADBlueTooth;
import static com.jumper.bluetoothdevicelib.device.bloodpressure.BloodPressureResult.TESTING;
import static com.jumper.bluetoothdevicelib.device.bloodpressure.BloodPressureResult.TEST_FINISH;
/**
* Created by Terry on 2016/7/20.
*/
public class BroadcastDeviceBloodPressure extends DeviceConfig {
public static final String BROADCAST_DEVICE_BLOODPRESSURE = "JPP";
public BroadcastDeviceBloodPressure() {
super(new String[]{BROADCAST_DEVICE_BLOODPRESSURE});
}
private boolean isNeedShowData;
@Override
public BloodPressureResult parseData(byte[] scanRecord, ADBlueTooth adBlueTooth) {
if (scanRecord == null || scanRecord.length <= 13) return null;
int d1 = scanRecord[11] & 0xff;//收缩压 106
int d2 = scanRecord[12] & 0xff;//舒张压 68
int d3 = scanRecord[13] & 0xff;//心率 62
if (d1 == 0 && d2 == 0 && d3 == 0) {
isNeedShowData = true;
return new BloodPressureResult(TESTING, "-1");
}
if (isNeedShowData) {
isNeedShowData = false;
return new BloodPressureResult(TEST_FINISH, d2 + "", d1 + "", d3 + "");
}
return null;
}
@Override
public boolean isRealData(byte[] datas) {
return datas != null && datas.length > 13;
}
@Override
public boolean isConnnectedJudgeByData(byte[] datas) {
return super.isConnnectedJudgeByData(datas);
}
}
|
Python | UTF-8 | 364 | 3.609375 | 4 | [] | no_license | # def my_function(food):
# for x in food:
# print(x)
#
# livros = ['a','b']
#
# def frutas():
# fruits = ["apple", "banana", "cherry"]
# return fruits
#
# frutas()
#
# a = frutas()
#
# my_function(a)
# my_function(livros)
def criar ():
lista = []
nome = input('Digite o nome: ')
idade = int('Digite a idade: ')
lista.append(nome)
|
Python | UTF-8 | 1,202 | 4.28125 | 4 | [] | no_license | # 230.py -- Kth Smallest Element in a tree
'''
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
'''
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def kthSmallest(root, k):
'''
Use BFS,
however it is not good
as we may modify the tree frequently
'''
queue = [(root, root.val)]
for node, val in queue:
if node.left:
queue.append((node.left, node.left.val))
if node.right:
queue.append((node.right, node.right.val))
queue.sort(key = lambda x: x[1])
return queue[k-1][1]
'''
Remember it is a BST,
the left child is less than father
the right child is bigger than father
Try Inorder
'''
self.cnt = 0
self.val = 0
def inorder(node, k):
if not node:
return
inorder(node.left, k)
self.cnt += 1
if self.cnt == k:
self.val = node.val
inorder(node.right, k)
inorder(root, k)
return self.val |
JavaScript | UTF-8 | 2,520 | 2.53125 | 3 | [] | no_license | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var TS = require('text-statistics');
var ts = TS();
var n = require('natural');
var micro = require('micro');
var dotenv = require('dotenv');
function service() {
var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
//Call service on object
if ((typeof text === 'undefined' ? 'undefined' : _typeof(text)) === 'object') {
var data = parse(text);
text = data.text;
context = data.context;
}
//shortcut response
if (text === '') {
return Promise.resolve({});
}
var analysis = {
textLength: ts.textLength(text) - 1,
letterCount: ts.letterCount(text),
wordCount: ts.wordCount(text),
sentenceCount: ts.sentenceCount(text),
syllableCount: ts.syllableCount(text),
averageSyllablesPerWord: ts.averageSyllablesPerWord(text),
percentageWordsWithThreeSyllables: ts.percentageWordsWithThreeSyllables(text),
averageWordsPerSentence: ts.averageWordsPerSentence(text),
fleschKincaidReadingEase: ts.fleschKincaidReadingEase(text),
fleschKincaidGradeLevel: ts.fleschKincaidGradeLevel(text),
gunningFogScore: ts.gunningFogScore(text),
colemanLiauIndex: ts.colemanLiauIndex(text),
smogIndex: ts.smogIndex(text),
automatedReadabilityIndex: ts.automatedReadabilityIndex(text)
};
//console.log(context)
if (context !== '') {
analysis.jaroWinkler = n.JaroWinklerDistance(text, context);
analysis.levenshteinDistance = n.LevenshteinDistance(text, context);
analysis.diceCoefficient = n.DiceCoefficient(text, context);
analysis.indexStart = context.toLowerCase().indexOf(text.toLowerCase());
}
return Promise.resolve(analysis);
}
function parse(data) {
var text = data.text || '';
var context = data.context || '';
return { text: text, context: context };
}
function handler(event, context, callback) {
try {
var data = parse(event);
var analysis = service(data);
callback(null, {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: analysis
});
} catch (err) {
callback(err);
}
}
module.exports = { service: service, handler: handler, parse: parse }; |
Shell | UTF-8 | 340 | 3 | 3 | [] | no_license | #! /bin/sh
HOME=/var/apps/up1/WEB-APP
cd $HOME
case "$1" in
start)
uwsgi -x $HOME/bin/http-config.xml
;;
stop)
uwsgi --stop /tmp/cmo-http.pid
;;
restart)
echo Stoping service
uwsgi --stop /tmp/cmo-http.pid
sleep 3
uwsgi -x $HOME/bin/http-config.xml
;;
*)
echo "Usage:$0{start|stop|status}"
;;
esac
exit 0 |
C++ | UTF-8 | 926 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <cmath>
#include <map>
#include <algorithm>
#include <queue>
#include <climits>
#include <fstream>
#include <iomanip>
using namespace std;
struct Student
{
string name;
string id;
int grade;
bool operator<(const Student &s) const
{
return grade > s.grade;
}
};
int main()
{
ifstream in("in.in");
int stu_num;
in >> stu_num;
vector<Student> student(stu_num);
for(int i = 0; i < stu_num; i++)
{
in >> student[i].name >> student[i].id >> student[i].grade;
}
sort(student.begin(), student.end());
int left;
int right;
in >> left >> right;
bool flag = false;
for(int i =0; i < stu_num; i++)
{
if(student[i].grade >= left && student[i].grade <= right)
{
cout << student[i].name << " " << student[i].id << endl;
flag = true;
}
}
if(!flag)
{
cout << "NONE" << endl;
}
system("pause");
return 0;
} |
C# | UTF-8 | 698 | 2.734375 | 3 | [] | no_license | var doc = new HtmlDocument
{
OptionOutputAsXml = true,
OptionCheckSyntax = true,
OptionFixNestedTags = true,
OptionAutoCloseOnEnd = true,
OptionDefaultStreamEncoding = Encoding.UTF8
};
doc.LoadHtml(htmlContent);
var results = new List<string[]>();
foreach (var node in doc.DocumentNode.SelectNodes("//div"))
{
var divContent = node.InnerText;
if (string.IsNullOrWhiteSpace(divContent))
continue;
var lines = divContent.Trim().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
results.Add(lines);
}
|
JavaScript | UTF-8 | 1,197 | 4.09375 | 4 | [] | no_license | //[]{}() valid
//[{()}] valid
//[{]} invalid
function braces(values) {
var stack = [];
var hash = {'(' : ')', '[' : ']', '{' : '}'};
var current = null;
var stackPop = null;
var str = null;
var flag = false;
var result = [];
for(var j = 0; j < values.length; j++){
str = values[j];
for(var i = 0; i < str.length; i++){
current = str[i];
if(current in hash){
stack.push(current);
}else{
if(stack.length == 0){
result.push('NO');
flag = true;
break;
}else{
stackPop = stack.pop();
if(hash[stackPop] !== current){
result.push('NO');
flag = true;
break;
}
}
}
}
if(!flag){
if(stack.length === 0){
result.push('YES');
}else{
result.push('NO');
}
}
stack = [];
flag = false;
} //Fin for
return result;
}
test = ['{}[]()','{[}]', '{{{}}}', '[{]}', '({)]'];
console.log(braces(test));
|
Java | UTF-8 | 1,192 | 2.125 | 2 | [] | no_license | package com.revenat.jcart.core.customers;
import com.revenat.jcart.core.entities.Customer;
import com.revenat.jcart.core.entities.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
@Profile("!test")
public class JCartCustomerService implements CustomerService {
@Autowired
private CustomerRepository customerRepository;
@Override
public Customer getCustomerByEmail(String email) {
return customerRepository.findByEmail(email);
}
@Override
public Customer createCustomer(Customer customer) {
return customerRepository.save(customer);
}
@Override
public Customer getCustomerById(Integer id) {
return customerRepository.findOne(id);
}
@Override
public List<Customer> getAllCustomers() {
return customerRepository.findAll();
}
@Override
public List<Order> getCustomerOrders(String email) {
return customerRepository.getCustomerOrders(email);
}
}
|
Markdown | UTF-8 | 2,608 | 2.53125 | 3 | [] | no_license | # 2018年 12月 20日
## 分享
### 这,就是飞冰物料
<daily-item
note="如果你使用过飞冰开发项目,可能已经知道飞冰是什么,但如果你是初次了解飞冰,可能还是茫然的;那这便是这篇文章存在的意义,借着这篇文章,可以带着以下三个问题去了解飞冰物料:物料是什么?解决了什么问题?未来的规划是什么?"
url="https://juejin.im/post/5c1c6237e51d454aae0046ec"/>
### GitHub GraphQL API 使用介绍
<daily-item
note="面向未来的API — 知乎"
url="https://zhuanlan.zhihu.com/p/28077095"/>
### Node.js 服务端实践之 GraphQL 初探
<daily-item
note="Taobao FED | 淘宝前端团队"
url="http://taobaofed.org/blog/2015/11/26/graphql-basics-server-implementation/"/>
## 开源项目
### open-source-mac-os-apps
<daily-item
note="Mac 的一大烦恼,就是各种软件都要钱。所以有人整理出了一份 Mac 系统免费软件清单"
url="https://github.com/serhii-londar/open-source-mac-os-apps/blob/master/README.md"/>
### rhysd/vim.wasm
<daily-item
note="有人把 Vim 编译成了 WebAssembly,从而可以在浏览器里面使用 Vim 了"
url="https://github.com/rhysd/vim.wasm"/>
### Clock Shop
<daily-item
note="收集各种时钟的CSS代码"
url="https://a-jie.github.io/clock-shop/"/>
### filamentgroup/select-css
<daily-item
note="简单的美化 select 的 css 库,没有其它功能"
url="https://github.com/filamentgroup/select-css"/>
### d33tah/strokes
<daily-item
note="输入常用汉字,自动生成笔画学习卡片"
url="https://github.com/d33tah/strokes"/>
### pwxcoo/chinese-xinhua
<daily-item
note="新华字典数据库和 API,收录 14032 条歇后语,16142 个汉字,264434 个词语,31648 个成语"
url="https://github.com/pwxcoo/chinese-xinhua"/>
### gka/chroma.js
<daily-item
note="处理颜色的 JS 库"
url="https://github.com/gka/chroma.js"/>
### GetPublii/Publii
<daily-item
note="一个生成静态网站的内容管理系统,所有管理都在本地进行,生成静态网页之后推送到服务器"
url="https://github.com/GetPublii/Publii"/>
## 网站
### FastPNG
<daily-item
note="PNG 在线压缩工具"
url="https://fastpng.com/"/>
### VReadTech
<daily-item
note="在网页上关注和浏览微信公众号"
url="http://www.vreadtech.com/#"/>
## 教程
### 八大步骤解决90%的NLP问题
<daily-item
note="机器学习 - 知乎"
url="https://zhuanlan.zhihu.com/p/36736328"/>
<daily-footer/> |
Java | UTF-8 | 81 | 1.875 | 2 | [] | no_license | package task2;
public interface InputInformation {
void makeStudentBase();
} |
Java | UTF-8 | 932 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package com.minminaya.setting.debug;
import android.graphics.Color;
import android.os.Bundle;
import com.minminaya.aau.utils.BarsHelper;
import com.minminaya.base.componet.BaseActivity;
import com.minminaya.setting.R;
/**
* <p> </p>
* <p>
* <p>Created by LGM on 2018/4/24 20:57</p>
* <p>Email:minminaya@gmail.com</p>
*/
public class MainActivity extends BaseActivity {
@Override
public int setContentViewLayout_1() {
return R.layout.module_setting_activity_login;
}
@Override
protected void initView_2(Bundle savedInstanceState) {
}
@Override
protected void setListeners_4() {
}
@Override
protected void bindLogic_3() {
}
@Override
protected void excuteOthers_5() {
BarsHelper.setStatusTransparentAndColor(this, Color.TRANSPARENT, 0.0f);
BarsHelper.setNavBarVisibility(this, false);
}
@Override
protected void unBindLogic() {
}
}
|
C# | UTF-8 | 688 | 2.609375 | 3 | [] | no_license | //mzxrules 2017
using System;
namespace ZeldaRand
{
class Program
{
static void Main(string[] args)
{
var result = TruthSpinner.Solve();
Console.WriteLine("Results: ");
Console.WriteLine($"{result[0]}, {result[1]}, {result[2]})");
Console.ReadLine();
}
void RandClassTest()
{
Rand r = new Rand();
Console.WriteLine($"{r.Next():X8}, {r.Next():X8}, {r.Next():X8}");
r.SetSeed(0);
for (int i = 0; i < 4; i++)
Console.WriteLine(r.NextFloat());
Console.ReadLine();
Console.ReadLine();
}
}
}
|
Markdown | UTF-8 | 695 | 2.515625 | 3 | [] | no_license | # project Photo Bay NodeJS_Express_Mongo
https://photo-bay.herokuapp.com/
This is a small web app for reviewing pictures submitted by people.
It is written in NOdeJS/ExpressJS and as database, I used MongoDB. Its hosted for free at Heroku.Any uploaded photos heroku deletes
them next day
It has basic CRUD for adding, deleting photos submitted by users.
Basic authentication system works using passportJS. After you signup you have to login for adding your pictures or reviewing them.
All pictures are of my authoring.You can not use them for ad, commercial or any profit. You can use them for teaching, practicing or all
other use that is not commercial. No restriction for using the code.
|
Python | UTF-8 | 1,448 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Custom wrappers for Uber API
"""
from uber_rides.session import Session
from uber_rides.client import UberRidesClient
class UberWrapper(object):
def __init__(self, token):
self.session = Session(server_token=token)
self.client = UberRidesClient(self.session)
def getPrices(self, origin, destination, seats=1):
''' origin, destination: tuples of (longtitude, latitude)
response contains a bunch of dict objects, each for an Uber product
The low_estimate, high_estimate keys give the price
'duration' key gives estimated time in secs
'''
response = self.client.get_price_estimates(start_latitude=origin[0],
start_longitude=origin[1],
end_latitude=destination[0],
end_longitude=destination[1],
seat_count=seats)
estimate = response.json.get('prices')
return estimate
def getWaitTime(self, origin, seats = 1):
''' origin, destination: tuples of (longtitude, latitude) '''
response = self.client.get_pickup_time_estimates(origin[0], origin[1]).json
waitTime = [product['estimate'] for product in response['times']]
return waitTime |
Java | UTF-8 | 850 | 2.75 | 3 | [] | no_license | package com.hand.javasamples.DesignPatterns.action.responsbility.frame.multi_function;
public class LogInterceptorThree implements Interceptor {
@Override
public boolean preDoAction(Request request, Response response) {
request.setRequest("LogInterceptorThree request");
System.out.println("LogInterceptorThree拦截请求request:"+request.getRequest());
return true;
}
@Override
public void postDoAction(Request request, Response response) {
response.setResponse("LogInterceptorThree response");
System.out.println("LogInterceptorThree拦截响应response:"+response.getResponse());
}
@Override
public void onComplete(Request request, Response response) {
System.out.println("LogInterceptorThree完成:"+request.getRequest()+"---"+response.getResponse());
}
}
|
JavaScript | UTF-8 | 1,083 | 3 | 3 | [
"MIT"
] | permissive | const {toString} = Object.prototype
export const isArray =
Array.isArray || (obj => toString.call(obj) === '[object Array]')
export const isFunction = obj => toString.call(obj) === '[object Function]'
export const mapValues = callback => obj => {
const ret = {}
for (let key in obj) {
const val = obj[key]
ret[key] = callback(val)
}
return ret
}
export const mapWithKey = callback => obj => {
const ret = []
for (let key in obj) {
const val = obj[key]
ret.push(callback(val, key))
}
return ret
}
export const get = path => {
const pathParts = path.split('.')
return obj => {
let val = obj
for (let i = 0; i < pathParts.length; i++) {
const pathPart = pathParts[i]
if (val == null) return
val = val[pathPart]
}
return val
}
}
export const shallowEqualArray = (a, b) => {
if (!(a && a.length != null && b && b.length != null)) return false
if (!(a.length === b.length)) return false
for (let index = 0; index < a.length; index++) {
if (!(a[index] === b[index])) return false
}
return true
}
|
C# | UTF-8 | 1,981 | 2.53125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
namespace Preston.Media
{
[Serializable]
public class MediaAttribute
{
private string attributeName;
private bool isReadOnly;
private bool includeInBackup;
private bool includeInXlst;
private int sortOrder;
public MediaAttribute()
{
}
public MediaAttribute(string attributeName, bool isReadOnly)
{
this.attributeName = attributeName;
this.isReadOnly = isReadOnly;
}
#region Properties
public string AttributeName
{
get { return attributeName; }
set { attributeName = value; }
}
public string AttributeNodeName
{
get { return attributeName.Replace("WM/", "WM_"); }
}
public bool IsReadOnly
{
get { return isReadOnly; }
set { isReadOnly = value; }
}
public bool IncludeInBackup
{
get { return includeInBackup; }
set { includeInBackup = value; }
}
public bool IncludeInXslt
{
get { return includeInXlst; }
set { includeInXlst = value; }
}
public int SortOrder
{
get { return sortOrder; }
set { sortOrder = value; }
}
#endregion Properties
internal static ListViewItem ToListViewItem(MediaAttribute attribute)
{
return ToListViewItem(attribute, false);
}
internal static ListViewItem ToListViewItem(MediaAttribute attribute, bool itemIsChecked)
{
ListViewItem item = new ListViewItem(attribute.AttributeName);
item.Tag = attribute;
item.SubItems.Add(attribute.IsReadOnly.ToString());
item.Checked = itemIsChecked;
return item;
}
}
}
|
Shell | UTF-8 | 307 | 3.09375 | 3 | [] | no_license | #!/bin/bash
var1="complete"
var2="partial"
if [ $var1 = "complete" ]; then
echo "var1 = complete!"
echo "$var1"
else
echo "var2 = complete!"
echo "$var2"
fi
if [ $var1 = "partial" ]; then
echo "var1 = partial!"
echo "$var1"
else
echo "var2 = partial!"
echo "$var2"
fi
|
Java | UTF-8 | 755 | 2.375 | 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 q4tht3;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
/*
* @author User
*/
public class calculateServer {
public static void main(String[] args) throws RemoteException, NotBoundException {
try {
Registry reg = java.rmi.registry.LocateRegistry.createRegistry(1090);
reg.rebind("calculateClient", new calculateClient());
System.out.println("Server is running");
} catch (RemoteException e) {
System.out.println(e);
}
}
}
|
C | UTF-8 | 2,069 | 2.5625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_app_taille_cham_w.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: macuguen <macuguen@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/27 21:49:18 by macuguen #+# #+# */
/* Updated: 2018/04/07 18:43:00 by macuguen ### ########.fr */
/* */
/* ************************************************************************** */
#include "../libft/includes/libft.h"
#include "../includes/ft_printf.h"
static wchar_t *ft_app_taille_cham_w_one(t_printf *list, wchar_t *tmp, t_count *env)
{
while (env->i < env->k)
{
if (list->zero == 1)
tmp[env->i] = '0';
else
tmp[env->i] = ' ';
env->i++;
}
env->k = 0;
while (env->i < env->j)
{
tmp[env->i] = list->unico[env->k];
env->i++;
env->k++;
}
env->k = list->entier;
return (tmp);
}
static wchar_t *ft_app_taille_cham_w_two(t_printf *list, wchar_t *tmp, t_count *env)
{
env->k = 0;
while (env->i < env->j)
{
tmp[env->i] = list->unico[env->k];
env->i++;
env->k++;
}
return (tmp);
}
wchar_t *ft_app_taille_cham_w(t_printf *list)
{
t_count env;
wchar_t *tmp;
ft_bzero(&env, sizeof(t_count));
tmp = NULL;
env.j = ft_strlen_w(list->unico);
env.k = list->taille_cham;
if (env.j > env.k)
env.t = env.j;
else
env.t = env.k;
if (!(tmp = (wchar_t*)malloc((sizeof(wchar_t) * (env.t + 1)))))
return (0);
ft_bzero(tmp, sizeof(wchar_t) * (env.t + 1));
env.k = list->taille_cham - env.j;
if (env.j < env.t)
tmp = ft_app_taille_cham_w_one(list, tmp, &env);
else
tmp = ft_app_taille_cham_w_two(list, tmp, &env);
return (tmp);
}
|
Go | UTF-8 | 932 | 3.28125 | 3 | [] | no_license | package pkcs7
import "errors"
var BadPadding = errors.New("bad padding")
func Pad(in []byte, blockSize int) []byte {
padding := blockSize - len(in)%blockSize
for i := 0; i < padding; i++ {
in = append(in, byte(padding))
}
return in
}
func Unpad(in []byte, blockSize int) ([]byte, error) {
N := len(in)
// The padded length must be a multiple of block size, but never 0:
// PKCS7 requires a full block of padding in case input is block-aligned.
if N == 0 || N%blockSize != 0 {
return nil, BadPadding
}
// The last byte is certainly padding.
// Each padding byte equals the padding length.
padLength := in[N-1]
// Padding defined to be between 1 and blockSize bytes.
if padLength == 0 || int(padLength) > blockSize {
return nil, BadPadding
}
inputLength := N - int(padLength)
for i := inputLength; i < N; i++ {
if in[i] != padLength {
return nil, BadPadding
}
}
return in[:inputLength], nil
}
|
C# | UTF-8 | 609 | 2.71875 | 3 | [
"MIT"
] | permissive | using System;
namespace Decorator.IO.Core
{
/// <summary>
/// A field for the item.
/// </summary>
public class DecoratorField
{
/// <summary>
/// The name of the field.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The type of the field.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// The modifier.
/// </summary>
public Modifier Modifier { get; set; }
/// <summary>
/// The index of a field.
/// </summary>
public int Index { get; set; }
public override string ToString() => $@"@{Index}: {Modifier} {Type} ""{Name}""";
}
} |
C | UTF-8 | 5,430 | 2.953125 | 3 | [] | no_license | #include <signal.h> /* signal */
#include <stdio.h> /* perror */
#include <stdlib.h> /* exit */
#include <string.h> /* memset */
#include <unistd.h> /* read, close */
#include <sys/socket.h> /* socket, setsockopt */
#include <sys/stat.h> /* stat */
#include <fcntl.h> /* open */
#include <netinet/in.h> /* struct sockaddr_in */
#include <arpa/inet.h> /* inet_ntoa */
#define PORT 80
#define BACKLOG 128
void process_connection(int socket_fd, struct sockaddr_in *client_addr);
void send_response(int socket_fd, unsigned char *buffer, int chars_to_send);
void get_request(int socket_fd, unsigned char *buffer);
int main(int argc, char **argv)
{
int reuseaddr = 1;
socklen_t sin_size;
int listening_socket_fd, accepting_socket_fd;
struct sockaddr_in server_addr, client_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(server_addr.sin_zero), 0, 8);
if((listening_socket_fd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Cannot create socket");
exit(1);
}
/* SOL_REUSEADDR allows you to bind to an address in TIME_WAIT */
if(setsockopt(listening_socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) == -1)
{
perror("Cannot setsocketopt");
exit(1);
}
if(bind(listening_socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
perror("Cannot bind");
exit(1);
}
/*
* backlog just set to /proc/sys/net/core/somaxconn
* i.e. default value for max in connection queue
*/
if(listen(listening_socket_fd, BACKLOG) == -1)
{
perror("Cannot listen");
exit(1);
}
/*
* Ignore "broken pipe" errors
* These can occur if the client (e.g. the browser) closes the connection
* with the server, but the server is not aware and attempts to send data.
*/
signal(SIGPIPE, SIG_IGN);
printf("Accepting connection on port %d\n", PORT);
while(1)
{
sin_size = sizeof(client_addr);
if((accepting_socket_fd = accept(listening_socket_fd, (struct sockaddr *)&client_addr, &sin_size)) == -1)
{
perror("Cannot accept connection");
exit(1);
}
process_connection(accepting_socket_fd, &client_addr);
}
return 0;
}
void process_connection(int socket_fd, struct sockaddr_in *client_addr)
{
/*
* Shitty Web Server does not care about your request. You get index.html
* no matter what you want.
*/
unsigned char request[500];
unsigned const char *response_filename = "./index.html";
unsigned const char *response_header = "HTTP/1.1 200 OK\r\nServer: Shitty Web Server\r\n\r\n";
unsigned char *response_data;
int response_fd, response_file_size;
int header_size = strlen(response_header);
struct stat file_stat;
/*
* If I was to inline get_request here then the local variables (cr and request_ptr) would probably
* get overwritten when the stack is overflowed, completely fucking with the getting of the request.
*/
get_request(socket_fd, request);
printf("%s\t%s:%d\n", request, inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
/* If the request is anything other than "GET /" then fuck off. */
if(strncmp(request, "GET / ", 6) == 0)
{
if((response_fd = open(response_filename, O_RDONLY, 0)) == -1)
{
perror("Cannot open file");
exit(1);
}
if((fstat(response_fd, &file_stat)) == -1)
{
perror("Cannot stat file");
exit(1);
}
response_file_size = file_stat.st_size;
if((response_data = (unsigned char *)malloc(response_file_size + header_size)) == NULL)
{
perror("Cannot allocate data for file");
exit(1);
}
if(read(response_fd, response_data + header_size, response_file_size) == -1)
{
perror("Cannot read");
exit(1);
}
memcpy(response_data, response_header, header_size);
send_response(socket_fd, response_data, response_file_size + header_size);
free(response_data);
close(response_fd);
}
else
{
unsigned char *error_response = "HTTP/1.1 404 NOT FOUND\r\nServer: Shitty Web Server\r\n\r\nGTFO\r\n";
send_response(socket_fd, error_response, strlen(error_response));
}
shutdown(socket_fd, SHUT_RDWR);
}
void get_request(int socket_fd, unsigned char *buffer)
{
int cr = 0;
while(recv(socket_fd, buffer, 1, 0) == 1)
{
if(*buffer == '\r')
{
cr = 1;
}
else if((cr == 1) && (*buffer == '\n'))
{
/* go back to \r and terminate the string */
*(buffer - 1) = '\0';
break;
}
buffer++;
}
}
void send_response(int socket_fd, unsigned char *buffer, int chars_to_send)
{
int chars_sent;
while(chars_to_send > 0)
{
if((chars_sent = send(socket_fd, buffer, chars_to_send, 0)) == -1)
{
perror("Cannot send");
break;
}
chars_to_send -= chars_sent;
buffer += chars_sent;
}
}
|
Python | UTF-8 | 1,073 | 3.375 | 3 | [] | no_license | import sys
import humansize
s = '深入 Python'
print(len(s))
print(s[0])
print(s + '3')
username = 'mark'
password = 'PapayaWhip'
print("{0}'s password is {1}".format(username, password))
si_suffixes = humansize.SUFFIXES[1000]
print(si_suffixes)
print('1000{0[0]} = 1{0[1]}'.format(si_suffixes))
print('1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}'.format(sys))
s = '''Finished files are the re-
sult of years of scientif-
ic study combined with the
experience of years.'''
print(s.splitlines())
print(s.lower())
print(s.lower().count('f'))
query = 'user=pilgrim&database=master&password=PapayaWhip'
a_list = query.split('&')
print(a_list)
a_list_of_lists = [v.split('=', 1) for v in a_list if '=' in v]
print(a_list_of_lists)
a_dict = dict(a_list_of_lists)
print(a_dict)
a_string = 'My alphabet starts where your alphabet ends.'
print(a_string[3:11])
print(a_string[3:-3])
print(a_string[0:2])
print(a_string[:18])
print(a_string[18:])
by = b'abcd\x65'
print(by)
print(type(by))
a_string = '深入 Python'
by = a_string.encode('utf-8')
print(by) |
C# | UTF-8 | 11,672 | 2.53125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace MELM
{
class cMusteriler
{
cGenel gnl = new cGenel();
#region Fields
private int MusteriID;
private string MusteriAdı;
private string MusteriSoyadı;
private string Telefon;
private string Adres;
private string Email;
#endregion
#region Properties
public int MusteriID1 { get => MusteriID; set => MusteriID = value; }
public string MusteriAdı1 { get => MusteriAdı; set => MusteriAdı = value; }
public string MusteriSoyadı1 { get => MusteriSoyadı; set => MusteriSoyadı = value; }
public string Telefon1 { get => Telefon; set => Telefon = value; }
public string Adres1 { get => Adres; set => Adres = value; }
public string Email1 { get => Email; set => Email = value; }
#endregion
public bool MusteriVarmı(string tlf)
{
bool sonuc = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "MusteriVarmı";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Telefon", SqlDbType.VarChar).Value = tlf;
cmd.Parameters.Add("@sonuc", SqlDbType.Int);
cmd.Parameters["@sonuc"].Direction = ParameterDirection.Output;
if(con.State == ConnectionState.Closed)
{
con.Open();
try
{
cmd.ExecuteNonQuery();
sonuc = Convert.ToBoolean(cmd.Parameters["@sonuc"].Value);
}
catch(SqlException ex)
{
string hata = ex.Message;
}
finally
{
con.Close();
}
}
return sonuc;
}
public int MusteriEkle(cMusteriler m)
{
int sonuc = 0;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Insert Into Müsteriler(Adı, Soyadı, Adres, Telefon, Email) values (@Adı, @Soyadı, @Adres, @Telefon, @Email); select SCOPE_IDENTITY()", con);
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.Parameters.Add("@Adı", SqlDbType.VarChar).Value = m.MusteriAdı;
cmd.Parameters.Add("@Soyadı", SqlDbType.VarChar).Value = m.MusteriSoyadı;
cmd.Parameters.Add("@Adres", SqlDbType.VarChar).Value = m.Adres;
cmd.Parameters.Add("@Telefon", SqlDbType.VarChar).Value = m.Telefon;
cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = m.Email;
sonuc = Convert.ToInt32(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
string hata = ex.Message;
}
finally
{
con.Dispose();
con.Close();
}
return sonuc;
}
public bool MusteriBilgileriGuncelle(cMusteriler m)
{
bool sonuc = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Update Müsteriler set Adı=@Adı, Soyadı=@Soyadı, Adres=@Adres, Telefon=@Telefon, Email=@Email where ID=@MusteriID", con);
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.Parameters.Add("@Adı", SqlDbType.VarChar).Value = m.MusteriAdı;
cmd.Parameters.Add("@Soyadı", SqlDbType.VarChar).Value = m.MusteriSoyadı;
cmd.Parameters.Add("@Adres", SqlDbType.VarChar).Value = m.Adres;
cmd.Parameters.Add("@Telefon", SqlDbType.VarChar).Value = m.Telefon;
cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = m.Email;
cmd.Parameters.Add("@MusteriID", SqlDbType.VarChar).Value = m.MusteriID;
sonuc = Convert.ToBoolean(cmd.ExecuteNonQuery());
}
catch (SqlException ex)
{
string hata = ex.Message;
}
finally
{
con.Dispose();
con.Close();
}
return sonuc;
}
public void MusterileriGetir(ListView lv)
{
lv.Items.Clear();
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Müsteriler", con);
SqlDataReader dr = null;
try
{
if(con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
int sayac = 0;
while(dr.Read())
{
lv.Items.Add(dr["ID"].ToString());
lv.Items[sayac].SubItems.Add(dr["Adı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Soyadı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Telefon"].ToString());
lv.Items[sayac].SubItems.Add(dr["Adres"].ToString());
lv.Items[sayac].SubItems.Add(dr["Email"].ToString());
sayac++;
}
}
}
catch(SqlException ex)
{
string hata = ex.Message;
}
finally
{
dr.Close();
con.Dispose();
con.Close();
}
}
//Müşterileri ID'ye gröe getirme.
public void MusterileriGetirID(int MusteriID, TextBox Adı, TextBox Soyadı, TextBox tlf, TextBox Adres, TextBox Email)
{
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Müsteriler where ID=@MusteriID", con);
SqlDataReader dr = null;
cmd.Parameters.Add("MusteriID", SqlDbType.Int).Value = MusteriID;
try
{
if(con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
Adı.Text = dr["Adı"].ToString();
Soyadı.Text = dr["Soyadı"].ToString();
tlf.Text = dr["Telefon"].ToString();
Adres.Text = dr["Adres"].ToString();
Email.Text = dr["Email"].ToString();
}
}
}
catch(SqlException ex)
{
string hata = ex.Message;
}
dr.Close();
con.Dispose();
con.Close();
}
public void MusteriGetirAd(ListView lv, string MusteriAdı)
{
lv.Items.Clear();
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Müsteriler where Adı like @MusteriAdı + '%' ", con);
SqlDataReader dr = null;
cmd.Parameters.Add("MusteriAdı", SqlDbType.VarChar).Value = MusteriAdı;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
int sayac = 0;
while (dr.Read())
{
lv.Items.Add(Convert.ToInt32(dr["ID"]).ToString());
lv.Items[sayac].SubItems.Add(dr["Adı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Soyadı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Telefon"].ToString());
lv.Items[sayac].SubItems.Add(dr["Adres"].ToString());
lv.Items[sayac].SubItems.Add(dr["Email"].ToString());
sayac++;
}
}
}
catch (SqlException ex)
{
string hata = ex.Message;
}
dr.Close();
con.Dispose();
con.Close();
}
public void MusteriGetirSoyadı(ListView lv, string MusteriSoyadı)
{
lv.Items.Clear();
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Müsteriler where Soyadı like @MusteriSoyadı + '%' ", con);
SqlDataReader dr = null;
cmd.Parameters.Add("MusteriSoyadı", SqlDbType.VarChar).Value = MusteriSoyadı;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
int sayac = 0;
while (dr.Read())
{
lv.Items.Add(Convert.ToInt32(dr["ID"]).ToString());
lv.Items[sayac].SubItems.Add(dr["Adı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Soyadı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Telefon"].ToString());
lv.Items[sayac].SubItems.Add(dr["Adres"].ToString());
lv.Items[sayac].SubItems.Add(dr["Email"].ToString());
sayac++;
}
}
}
catch (SqlException ex)
{
string hata = ex.Message;
}
dr.Close();
con.Dispose();
con.Close();
}
public void MusteriGetirTlf(ListView lv, string Telefon)
{
lv.Items.Clear();
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Müsteriler where Telefon like @Tlf + '%' ", con);
SqlDataReader dr = null;
cmd.Parameters.Add("Tlf", SqlDbType.VarChar).Value = Telefon;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
int sayac = 0;
while (dr.Read())
{
lv.Items.Add(Convert.ToInt32(dr["ID"]).ToString());
lv.Items[sayac].SubItems.Add(dr["Adı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Soyadı"].ToString());
lv.Items[sayac].SubItems.Add(dr["Telefon"].ToString());
lv.Items[sayac].SubItems.Add(dr["Adres"].ToString());
lv.Items[sayac].SubItems.Add(dr["Email"].ToString());
sayac++;
}
}
}
catch (SqlException ex)
{
string hata = ex.Message;
}
dr.Close();
con.Dispose();
con.Close();
}
}
}
|
Python | UTF-8 | 1,291 | 2.765625 | 3 | [] | no_license | import os
import json
import glob
import sys
HIGH_FREQUENCY = 30
MEDIUM_FREQUENCY = 20
def parseData(filename):
data = {}
with open(filename, 'r') as f:
data = json.load(f)
bydate = {}
total_pushes = 0
for date in data['oranges']:
if data['oranges'][date]['testruns'] == 0:
continue
bydate[date] = {'pushes': data['oranges'][date]['testruns'],
'failures': len(data['oranges'][date]['oranges']),
'orangefactor': 0}
bydate[date]['orangefactor'] = bydate[date]['failures']*1.0 / bydate[date]['pushes']
return bydate
files = ['0109.json', '0116.json', '0123.json', '0130.json',
'0206.json', '0213.json', '0220.json', '0227.json',
'0306.json', '0313.json', '0320.json', '0327.json']
counter = []
moving_average = 0
for file in list(glob.glob('2017/*.json')):
data = parseData(file)
dates = data.keys()
dates.sort()
for item in dates:
counter.append(data[item]['orangefactor'])
if len(counter) == 7:
moving_average = sum(counter) / 7.0
counter.remove(counter[0])
print "%s,%s,%s,%.2f,%.2f" % (item, data[item]['pushes'], data[item]['failures'], data[item]['orangefactor'], moving_average)
|
Java | UTF-8 | 1,073 | 1.742188 | 2 | [
"Apache-2.0"
] | permissive | package org.estatio.capex.dom.invoice.approval.tasks;
import org.apache.isis.applib.annotation.Mixin;
import org.estatio.capex.dom.invoice.IncomingInvoice;
import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalState;
import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalStateTransition;
import org.estatio.capex.dom.invoice.approval.IncomingInvoiceApprovalStateTransitionType;
import org.estatio.capex.dom.task.DomainObject_reasonGuardNotSatisfiedAbstract;
@Mixin(method="prop")
public class IncomingInvoice_reasonApprovalTaskBlocked
extends DomainObject_reasonGuardNotSatisfiedAbstract<
IncomingInvoice,
IncomingInvoiceApprovalStateTransition,
IncomingInvoiceApprovalStateTransitionType,
IncomingInvoiceApprovalState> {
public IncomingInvoice_reasonApprovalTaskBlocked(final IncomingInvoice incomingInvoice) {
super(incomingInvoice, IncomingInvoiceApprovalStateTransition.class);
}
}
|
TypeScript | UTF-8 | 913 | 2.828125 | 3 | [] | no_license | import actionTypes from "./action-types";
import { FluxStandardAction } from "flux-standard-action";
/**
*
* @param storeKey
*/
export default function(storeKey: string) {
const { SET_STATE, SET_VALUE, RESET,VALIDATE } = actionTypes(storeKey);
/** */
const setState: (
payload: {}
) => FluxStandardAction<Partial<{}>, undefined> = payload => ({
type: SET_STATE,
payload,
meta: undefined
});
const setValue = (
key: string,
value: any
): FluxStandardAction<Partial<{}>> => ({
type: SET_VALUE,
payload: { key, value },
meta: undefined
});
const reset = (): FluxStandardAction<undefined> => ({
type: RESET,
payload: undefined,
meta: undefined
});
const validate = (): FluxStandardAction<undefined> => ({
type: VALIDATE,
payload: undefined,
meta: undefined
})
return {
setState,
setValue,
reset,
validate
};
}
|
JavaScript | UTF-8 | 599 | 2.640625 | 3 | [] | no_license | $(function () {
$('.chkDisallowed').on('click', function () {
let disallowedPages = [];
$('.pagename').each(function () {
let $this = $(this);
if ($this.find('.chkDisallowed').is(':checked'))
disallowedPages.push($this.find('label').text());
});
$('.disallowedPages').val(disallowedPages.join(","));
});
$('.selectrobotType').on('change', function () {
let selected = $(this).val();
alert(selected)
$('.selectedType').hide();
$('[data-type=' + selected + ']').show();
});
}); |
JavaScript | UTF-8 | 1,752 | 2.515625 | 3 | [] | no_license | const express = require('express');
var router = express.Router();
var { Candidate } = require('../models/candidate');
var ObjectId = require('mongoose').Types.ObjectId;
// Get all candidates => localhost:3000/candidates
router.get('/candidates', (req,res) => {
Candidate.find((err,docs) => {
if (!err) { res.send(docs); }
else ( res.send('Data not found') )
});
});
// Add candidates details
router.post('/candidates',(req,res) => {
var can = new Candidate({
name: req.body.name,
party: req.body.party
});
can.save((err, doc)=>{
if(!err) {res.send(doc);}
else(res.send('Data insertion failed'))
});
});
// Get candidates by id
router.get('/candidates/:id',(req,res) => {
if(!ObjectId.isValid(req.params.id))
return res.send('not a valid ID');
Candidate.findById(req.params.id,(err,doc) => {
if(!err) {res.send(doc);}
else {res.send('no record found')}
});
});
// Update candidates details by id
router.put('/candidates/:id', (req,res) => {
if(!ObjectId.isValid(req.params.id))
return res.send('not a valid ID found to update')
var can = {
name: req.body.name,
party: req.body.party
};
Candidate.findByIdAndUpdate(req.params.id, {$set: can}, {new: true}, (err,doc)=>{
if(!err) {res.send(doc);}
else {res.send('Data updation failed')}
});
});
// Delete candidate data by id
router.delete('/candidates/:id',(req,res) => {
if(!ObjectId.isValid(req.params.id))
return res.send('id not found to delete');
Candidate.findByIdAndRemove(req.params.id, (err,doc) => {
if(!err) {res.send(doc);}
else {res.send('data deleted');}
});
});
module.exports = router; |
C++ | UTF-8 | 1,863 | 2.78125 | 3 | [] | no_license | #ifndef ASTEROIDS_UI_CLIENTTEXTUI_DISPLAYGRID_H
#define ASTEROIDS_UI_CLIENTTEXTUI_DISPLAYGRID_H
//
#include "Asteroids/ForwardDeclarations.h"
//
#include <vector>
#include <string>
#include <memory>
//
namespace Asteroids
{
//
namespace UI
{
//
namespace ClientTextUI
{
//
using std::string;
/// Class to help translate and render actors and stuff from the virtual game board, to actual ASCII graphics that can be seen
class DisplayGrid
{
//
public:
//
DisplayGrid(
double source_width, double source_height,
int grid_width, int grid_height
);
//
void reset();
void clear();
//
void set_header_text(string s);
void set_footer_text(string s);
//
void draw_filled_polygon(
double offset_x, double offset_y,
const std::vector<std::pair<double, double>>& points
);
//
void draw_polygon(
double offset_x, double offset_y,
const std::vector<std::pair<double, double>>& points
);
//
void set_pixel(double x, double y);
void set_grid_pixel(int x, int y);
//
string render();
void print();
//
private:
//
int
_width,
_height,
_unused_width,
_unused_height
;
double
_source_width,
_source_height,
_unused_source_width,
_unused_source_height
;
double _translation_ratio;
std::vector<std::vector<bool>> grid;
//
string
_header_text,
_footer_text
;
//
void init();
//
void calculate_translation();
//
void clear_grid();
void add_border();
//
std::pair<int, int> translate_source_point(double x, double y);
};
}
}
}
#endif
|
TypeScript | UTF-8 | 5,821 | 2.609375 | 3 | [] | no_license | import * as util from "gulp-util";
import * as _ from "underscore";
import * as path from "path";
import * as fs from "fs";
import * as childProcess from "child_process";
import * as semver from "semver";
import {Logger} from "./Logging";
/**
* Provides context for a Gulp plugin that works with 'npm'.
*
* @typeparam TOptions The options type that will be associated with the plugin implementation.
*/
export class NpmPluginBinding<TOptions> {
/**
* Initialises the new binding object.
*
* @param options The options that are to be associated with the running plugin implementation.
*/
constructor(public options: TOptions) {
}
/**
* Converts a semver version to a semver range that is compatible with the 'npm install' command.
*
* @param version A semver version (i.e., ~1.2.3).
*
* @returns A string that represents a semver range that is equivilant to the provided version
* (i.e., ~1.2.x).
*/
public toSemverRange(version: string): string {
let matches = /^(\^|~)?(?:(\d+)\.?)(?:(\d+)\.?)?(?:(\d+)\.?)?/g.exec(version);
if (!matches || !matches[1]) return version;
if (matches[1] === "^") {
return `^${matches[2]}.x.x`;
}
else {
return `~${matches[2]}.${matches[3] ? matches[3] : "x"}.x`;
}
}
/**
* Creates a symbolic link to a folder representing a package. If the package name represents a scoped
* package name then this method delegates to {NpmPluginBinding#createScopedPackageSymLink}.
*
* @param sourcePath The path of the souce package (its node_modules folder will be updated).
* @param packageName The name of the package being symbolically linked.
* @param targetPath The path of the folder that is being linked.
*/
public createPackageSymLink(sourcePath: string, packageName: string, targetPath: string): void {
let packageInfo = /(@.*)\/(.*)+|(.*)+/.exec(packageName);
let scopeName = packageInfo[1];
packageName = scopeName !== undefined ? packageInfo[2] : packageInfo[3];
if (scopeName) return this.createScopedPackageSymLink(sourcePath, scopeName, packageName, targetPath);
sourcePath = path.resolve(sourcePath, "node_modules");
if (fs.existsSync(path.resolve(sourcePath, packageName))) return;
if (!fs.existsSync(sourcePath)) fs.mkdirSync(sourcePath);
fs.symlinkSync(targetPath, path.join(sourcePath, packageName), "dir");
}
/**
* Creates a symbolic link to a folder representing a scoped package.
*
* @param sourcePath The path of the souce package (its node_modules folder will be updated).
* @param scopeName The name of the scope to use when creating the smbolic link.
* @param packageName The name of the package being symbolically linked.
* @param targetPath The path of the folder that is being linked.
*/
public createScopedPackageSymLink(sourcePath: string, scopeName: string, packageName: string, targetPath: string): void {
sourcePath = path.resolve(sourcePath, "node_modules");
if (!fs.existsSync(sourcePath)) fs.mkdirSync(sourcePath);
sourcePath = path.resolve(sourcePath, scopeName);
if (!fs.existsSync(sourcePath)) fs.mkdirSync(sourcePath);
if (fs.existsSync(path.resolve(sourcePath, packageName))) return;
fs.symlinkSync(targetPath, path.join(sourcePath, packageName), "dir");
}
/**
* Executes the 'npm install' command for the packages specified in the registry package map.
*
* @param packagePath The folder of the package that is to be installed.
* @param registryMap The map of registry and packages that should be installed.
*/
public shellExecuteNpmInstall(packagePath: string, registryMap: IDictionary<Array<string>>): void {
const INSTALLABLE_PACKAGE_CHUNKSIZE: number = 50;
for (let registry in registryMap) {
let packages = registryMap[registry];
if (!packages || packages.length === 0) continue;
// Install packages in bundles because command line lengths aren't infinite. Windows for example has
// a command line limit of 8192 characters. It's variable on *nix and OSX but will in the 100,000s
let installablePackages = _.first(packages, INSTALLABLE_PACKAGE_CHUNKSIZE);
packages = _.rest(packages, INSTALLABLE_PACKAGE_CHUNKSIZE);
while (installablePackages && installablePackages.length > 0) {
var installArgs = ["install"].concat(installablePackages);
if (packagePath === process.cwd()) {
installArgs.push("--ignore-scripts");
}
if (registry !== "*") {
installArgs.push("--registry");
installArgs.push(registry);
}
this.shellExecuteNpm(packagePath, installArgs);
installablePackages = _.first(packages, INSTALLABLE_PACKAGE_CHUNKSIZE);
packages = _.rest(packages, INSTALLABLE_PACKAGE_CHUNKSIZE);
}
}
}
/**
* Executes the 'npm' command on the platform.
*
* @param packagePath The folder in which to execute the npm command.
* @param cmdArgs An array of arguments to pass to npm.
*/
public shellExecuteNpm(packagePath: string, cmdArgs: Array<string>): void {
var result = childProcess.spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", cmdArgs, { cwd: packagePath });
if (result.status !== 0) {
Logger.verbose((logger) => {
logger(`npm ${cmdArgs.join(" ")}`);
});
throw new Error(result.stderr.toString());
}
}
}
|
Java | UTF-8 | 1,166 | 3.328125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package selftestanswerscap02;
/**
*
* @author Rafael
*/
public class Ejercicio05 {
public static void main(String[] args) {
System.out.println("Which statement(s) are true? (Choose all that apply.)\n" +
" \n" +
" A. Cohesion is the OO principle most closely associated with hiding implementation details\n" +
" \n" +
" B. Cohesion is the OO principle most closely associated with making sure that classes know\n" +
"about other classes only through their APIs\n" +
" \n" +
" \n" +
" C. Cohesion is the OO principle most closely associated with making sure that a class is\n" +
"designed with a single, well-focused purpose\n" +
" \n" +
" D. Cohesion is the OO principle most closely associated with allowing a single object to be\n" +
"seen as having many types\n" +
" \n" +
" R= A. La cohesión es el principio OO más estrechamente asociado con asegurarse de que una clase es\n" +
"diseñado con un único propósito bien enfocado");
}
}
|
Java | UTF-8 | 874 | 2.796875 | 3 | [] | no_license | package ru.bona.fileindex.model.range;
import java.nio.ByteBuffer;
/**
* ShortRange
*
* @author Kontsur Alex (bona)
* @since 23.09.14
*/
public class ShortRange extends Range<Short> {
/*===========================================[ INTERFACE METHODS ]============*/
@Override
public ByteBuffer dumpRange() {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putShort(start);
buffer.putShort(stop);
return buffer;
}
@Override
public void readRange(ByteBuffer buffer) {
start = buffer.getShort();
stop = buffer.getShort();
}
@Override
public void setStart(Number start) {
this.start = start.shortValue();
}
@Override
public void setStop(Number stop) {
this.stop = stop.shortValue();
}
@Override
public int getSize() {
return 4;
}
}
|
JavaScript | UTF-8 | 1,044 | 2.703125 | 3 | [] | no_license | // Reducers
const claimsHistory = (oldListOfClaims = [], action) => {
if(action.type == 'CREATE_CLAIM') {
return [...oldListOfClaims, action.payload];
}
return oldListOfClaims;
};
const accounting = (currentBagOfMoney = 100, action) => {
if(action.type == 'CREATE_CLAIM') {
return currentBagOfMoney - action.payload.amountofMoneyToCollect;
} else if(action.type == 'CREATE_POLICY') {
return currentBagOfMoney + action.payload.amount;
}
return currentBagOfMoney;
};
const policies = (listOfPolicies = [], action) => {
if(action.type == 'CREATE_POLICY') {
return [...listOfPolicies, action.payload.name];
} else if(action.type == 'DETETE_POLICY') {
return listOfPolicies.filter(theName => theName !== action.payload.name);
}
return listOfPolicies;
};
const { createStore, combineReducers } = Redux;
const ourDepartments = combineReducers({
accounting: accounting,
claimsHistory: claimsHistory,
policies: policies
});
const store = createStore(ourDepartments);
|
Java | UTF-8 | 1,719 | 2.265625 | 2 | [] | no_license | package org.sqli.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.sqli.entities.Admin;
import org.sqli.entities.Collaborateur;
import org.sqli.entities.Encadrant;
import org.sqli.entities.HbSessionManager;
import org.sqli.entities.ManagerRH;
import org.sqli.entities.Projet;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Collaborateur coll1=new Collaborateur();
coll1.setNomColl("coll1");
coll1.setPrenomColl("coll11");
Collaborateur coll2=new Collaborateur();
coll1.setNomColl("coll2");
coll1.setPrenomColl("coll22");
Collaborateur coll3=new Collaborateur();
coll1.setNomColl("coll3");
coll1.setPrenomColl("coll33");
ManagerRH man=new ManagerRH();
man.getColls().add(coll1);
man.getColls().add(coll2);
man.getColls().add(coll3);
coll1.setManager(man);
coll2.setManager(man);
coll3.setManager(man);
HbSessionManager manager = new HbSessionManager();
Session session = manager.factory.openSession();
Transaction tr = session.beginTransaction();
Projet pr1=new Projet();
Projet pr2=new Projet();
Projet pr3=new Projet();
Projet pr4=new Projet();
Encadrant enc=new Encadrant();
pr1.getColls().add(coll1);
pr1.getColls().add(coll3);
pr1.getColls().add(coll2);
pr1.getEncadrants().add(enc);
pr1.setStatut("active");
pr2.setStatut("active");
pr3.setStatut("active");
pr4.setStatut("active");
session.save(man);
session.save(coll1);
session.save(coll3);
session.save(coll2);
session.save(enc);
session.save(pr4);
session.save(pr3);
session.save(pr2);
session.save(pr1);
tr.commit();
}
}
|
TypeScript | UTF-8 | 1,183 | 2.796875 | 3 | [] | no_license | import { AuthorizationCheck, CredentialTypes } from '../models/types/verification';
import { User, UserType, UserRoles } from '../models/types/user';
export class AuthorizationService {
isAuthorized = (requestUser: User, identityId: string): AuthorizationCheck => {
const isAuthorizedUser = this.isAuthorizedUser(requestUser.identityId, identityId);
if (!isAuthorizedUser) {
const isAuthorizedAdmin = this.isAuthorizedAdmin(requestUser);
if (!isAuthorizedAdmin) {
return { isAuthorized: false, error: new Error('not allowed!') };
}
}
return { isAuthorized: true, error: null };
};
isAuthorizedUser = (requestUserId: string, identityId: string): boolean => {
return requestUserId === identityId;
};
isAuthorizedAdmin = (requestUser: User): boolean => {
const role = requestUser?.role;
if (role === UserRoles.Admin) {
return true;
}
return false;
};
hasAuthorizedUserType(type: string): boolean {
return type === UserType.Person || type === UserType.Service || type === UserType.Organization;
}
hasVerificationCredentialType(type: string[]): boolean {
return type.some((t) => t === CredentialTypes.VerifiedIdentityCredential);
}
}
|
Java | UTF-8 | 1,966 | 2.25 | 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 com.aviara.bean;
import java.sql.Date;
/**
*
* @author comp2
*/
public class PaymentDetails {
private int id;
private String emp_id;
private String emp_type;
private Double basicSal;
private String duration;
private Double hra;
private Double other;
private Double total;
private Date nextPay;
private Date incDate;
public void setId(int id) {
this.id = id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
public void setEmp_type(String emp_type) {
this.emp_type = emp_type;
}
public void setBasicSal(Double basicSal) {
this.basicSal = basicSal;
}
public void setDuration(String duration) {
this.duration = duration;
}
public void setHra(Double hra) {
this.hra = hra;
}
public void setOther(Double other) {
this.other = other;
}
public void setTotal(Double total) {
this.total = total;
}
public void setNextPay(Date nextPay) {
this.nextPay = nextPay;
}
public void setIncDate(Date incDate) {
this.incDate = incDate;
}
public int getId() {
return id;
}
public String getEmp_id() {
return emp_id;
}
public String getEmp_type() {
return emp_type;
}
public Double getBasicSal() {
return basicSal;
}
public String getDuration() {
return duration;
}
public Double getHra() {
return hra;
}
public Double getOther() {
return other;
}
public Double getTotal() {
return total;
}
public Date getNextPay() {
return nextPay;
}
public Date getIncDate() {
return incDate;
}
}
|
Markdown | UTF-8 | 793 | 3.203125 | 3 | [] | no_license | # Walsh and Haar approximations
Input function samples and approximate the function as a linear
combination of Walsh or Haar functions. These are in the form of
square waves, and therefore go well with sampling.\
In the file input.txt, in the same directory as the project,
input the desired basic interval (the domain of the function or
a period) and the number of samples of the functions in the first
row. In the second row, input the values of the samples of the
functions. In the third row put the desired number of approximating
Walsh/Haar functions.\
For implementation reasons, the number of samples and number of
approximating functions need to be powers of two, and the latter
has to be less than or equal to the former. The code uses the
matplotlib package to plot the functions.
|
Java | UTF-8 | 4,331 | 2.46875 | 2 | [] | no_license | package com.shop.dao;
//55555666666666665
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.shop.db.DateSourseUtil;
import com.shop.entity.Product;
//12138
//��Ʒ��Ϣ����
public class ProductDao {
//��ѯȫ����Ʒ
public static List<Product> selectAllProduct() throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
List<Product> products = runner.query("select * from Product;", new BeanListHandler<Product>(Product.class));
return products;
}
//��ѯ��������Ʒ
public static List<Product> selectOneProduct(String type) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
List<Product> products = runner.query("select * from Product where type = ?;", new BeanListHandler<Product>(Product.class),type);
return products;
}
//ģ����ѯ��Ʒ
public static List<Product> vagueSelectProduct(String name) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
name = "%" + name + "%";
List<Product> products = runner.query("select * from Product where productName like ?;", new BeanListHandler<Product>(Product.class),name);
return products;
}
//�жϹ���������Ƿ���ڿ���
public static Product isEnoughQuanty(String productId,int productQuanty) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
Product product = runner.query("select * from Product where productId = ? ;", new BeanHandler<Product>(Product.class), productId);
//��������������ڿ������������ʵ��������null
if(productQuanty <= product.getQuanty()){
return product;
}
return null;
}
//ͨ����Ʒ��ź�������������¿�������
public static void updateProduct(String productId,int productQuanty) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
runner.update("update product set quanty = quanty - ? where productId = ? ;", productQuanty,productId);
}
//ͨ����Ʒ����ID�����ۣ������������±�����Ʒ
public static void saveProduct(Product Products) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
runner.update("update product set productPrice=?,quanty=? where productId = ? ;",Products.getProductPrice(),Products.getQuanty(),Products.getProductId());
}
//ͨ����Ʒ����ID�����ƣ����ۣ�������������µ���Ʒ
public static void addProduct(Product Product) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
runner.update("insert into product values(?,?,?,?,?);",Product.getProductId(),Product.getProductName(),Product.getProductPrice(),Product.getQuanty(),Product.getType());
}
//ͨ����Ʒ����ID����ɾ����Ʒ
public static void deleteProduct(Product Product) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
runner.update("update product set quanty = 0 where productId = ? ;",Product.getProductId());
}
//ͨ����Ʒ����ID�����ۣ�������Ʒ����
public static void adjustProductPrice(String productId,String produPrice) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
runner.update("update product set productPrice = ? where productId = ? ;",Double.valueOf(produPrice),productId);
}
//ͨ����Ʒ����ID����棩������Ʒ����
public static void adjustProductQuanty(String productId,String quanty) throws SQLException{
QueryRunner runner = new QueryRunner(DateSourseUtil.getDataSource());
runner.update("update product set quanty = ? where productId = ? ;",Integer.valueOf(quanty),productId);
}
}
|
JavaScript | UTF-8 | 645 | 3.5625 | 4 | [] | no_license | // getElemenyByID()
console.log(window);
// console.log(document);
// console.dir(document);
// alert('hello');
// select the element or group of elements that we want
// decide the effect that we want to apply to the selection
// getElementByID();
// assign to a variable
const h1 = document.getElementById('title');
h1.style.color = 'red';
// not assigning a varibale
// document.getElementById('btn').style.backgroundColor = 'blue';
// document.getElementById('btn').style.color = 'white';
const btn = document.getElementById('btn');
btn.style.backgroundColor = 'blue'
btn.style.color = 'white';
|
JavaScript | UTF-8 | 397 | 3.3125 | 3 | [] | no_license | let largest = 127289373913828309127381263;
let largest2 = 111333321
function findProduct (input){
let bucket = []
input = input.toString().split('').sort().reverse()
// let input2 = input.sort().reverse()
// console.log(input);
for (var i = 0; i < 5; i++) {
bucket.push(input[i])
}
return bucket.reduce(function(a,b){
return a * b
})
}
console.log(findProduct(largest2))
|
JavaScript | UTF-8 | 291 | 3.28125 | 3 | [] | no_license | // Задача №2
export function secondTask(){
let num = []
while(num.length < 50)
{
let n = Math.round(Math.random()*100)
if (!num.includes(n)){
num.push(n)
}
}
return num.sort((a,b) => a - b)
}
|
C# | UTF-8 | 6,799 | 2.78125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using ElasticSearchGetAllIds.Response;
using ElasticSearchGetAllIds.Request;
namespace ElasticSearchGetAllIds
{
public class Program
{
public static void Main(string[] args)
{
try
{
Execute().Wait();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("processed all the endpoints: press enter to close the window");
Console.ReadLine();
}
public static async Task Execute()
{
//get all the appsettings
var settings = GetConfig();
var esEndPointsToScan = settings
.GetSection("elasticsearch:endpoints")
.GetChildren()
.Select(x => x.Value);
//loop through all the end points found in configuration - dev and prod
foreach (var endpoint in esEndPointsToScan)
{
//create a base payload to generate scroll id - once the scroll id is generated use the same scrollId until the ids are exhausted
var basePayload = new RootObject
{
_source = new List<string> {"UniversalId"},
size = Convert.ToInt32(settings["batchSize"]),
sort = "UniversalId",
query = new Query {match_all = new MatchAll()}
};
//setting below will keep the scroll live for how many ever seconds which are set here
string keepScrollactiveFor = settings["keepScrollactiveFor"];
var baseHttpContent = new StringContent(JsonConvert.SerializeObject(basePayload), Encoding.UTF8, "application/json");
//use the string builder below to store all the universalids - which will later be saved into a textfile
var allids = new StringBuilder();
//counter to maintain count for showing the status on console
int statusCounter = 0;
using (var httpClient = new HttpClient())
{
// Do the actual request and await the response with post
var baseHttpResponse = await httpClient.PostAsync(endpoint + "_search?scroll=" + keepScrollactiveFor, baseHttpContent);
//if any errors will exit
if (baseHttpResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Error Processing " + endpoint + ": " + baseHttpResponse.ReasonPhrase);
continue;
}
// If the response contains content we want to read it!
var baseResponseContentString = await baseHttpResponse.Content.ReadAsStringAsync();
var baseResponse = JsonConvert.DeserializeObject<ScrollBase.RootObject>(baseResponseContentString);
if (baseResponse.hits.hits.Count > 0)
{
//add all the matches only if they are integers which will be universalids - there are some tagids also part if same index which are not ints and will be excluded in the statement below
foreach (var hit in baseResponse.hits.hits)
{
if (hit._id.All(Char.IsDigit))
{
allids.Append(hit._id + ",");
}
}
statusCounter += Convert.ToInt32(settings["batchSize"]);
Console.WriteLine("Processed " + endpoint + " count: " + statusCounter);
//hit the same url using scroll api until the matches het exhausted
var httpResponse = await httpClient.GetAsync(endpoint + "_search/scroll?&scroll="+ keepScrollactiveFor + "&scroll_id=" + baseResponse._scroll_id);
if (baseHttpResponse.StatusCode != HttpStatusCode.OK)
return;
var responseContentString = await httpResponse.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<ScrollBase.RootObject>(responseContentString);
//loop will be run until all the matches are exhausted
while (response.hits.hits.Count > 0)
{
foreach (var hit in response.hits.hits)
{
if (hit._id.All(Char.IsDigit))
{
allids.Append(hit._id + ",");
}
}
statusCounter += Convert.ToInt32(settings["batchSize"]);
Console.WriteLine("Processed " + endpoint + " count: " + statusCounter);
httpResponse = await httpClient.GetAsync(endpoint + "_search/scroll?&scroll=" + keepScrollactiveFor + "&scroll_id=" + baseResponse._scroll_id);
if (baseHttpResponse.StatusCode != HttpStatusCode.OK)
return;
responseContentString = await httpResponse.Content.ReadAsStringAsync();
response = JsonConvert.DeserializeObject<ScrollBase.RootObject>(responseContentString);
}
}
allids.Remove(allids.Length - 1, 1);
//save the ids to file
var file = settings["savePathFolder"] + endpoint.Replace("/", "").Replace(":", "") + ".txt";
using (StreamWriter sw = new StreamWriter(new FileStream(file, FileMode.Create)))
{
sw.WriteLine(allids.ToString().Remove(allids.ToString().Length - 1, 1));
}
}
}
}
public static IConfiguration GetConfig()
{
var builder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json",
optional: true,
reloadOnChange: true);
return builder.Build();
}
}
public class Endpoints
{
public string baseEndPoint { get; set; }
public string endPointWithIndex { get; set; }
}
}
|
C++ | UTF-8 | 1,067 | 3.28125 | 3 | [] | no_license | #include "ball.h"
Ball::~Ball()
{
SDL_FreeSurface(image);
}
Ball::Ball(SDL_Surface *field, SDL_Surface *image, int x, int y, int x_v, int y_v)
{
this->field = field;
this->image = image;
box.x = x;
box.y = y;
box.h = 16;
box.w = 16;
y_vect = y_v;
x_vect = x_v;
right = false;
down = false;
}
void Ball::update()
{
if (down)
{
box.y = box.y + y_vect;
}
else
{
box.y = box.y - y_vect;
}
if (right)
{
box.x = box.x + x_vect;
}
else
{
box.x = box.x - x_vect;
}
if (!right && box.x < 0)
{
box.x = 0;
right = !right;
}
if (right && box.x > field->w - 16)
{
right = !right;
box.x = field->w - 16;
}
if (down && box.y > field->h-16)
{
down = !down;
box.y = field->h - 16;
}
if (!down && box.y < 0)
{
down = !down;
box.y = 0;
}
draw();
}
void Ball::draw()
{
SDL_BlitSurface(image, NULL, field, &box);
}
void Ball::speedUp(int xInc, int yInc)
{
y_vect += yInc;
x_vect += xInc;
}
void Ball::bounce()
{
right = !right;
}
int Ball::getXPos()
{
return box.x;
}
int Ball::getYPos()
{
return box.y;
}
|
Python | UTF-8 | 561 | 3.328125 | 3 | [] | no_license | from collections import defaultdict
import typing as t
def create() -> t.Tuple[t.Callable[[t.List[int], int], int], int, int]:
return action, 10, 20
def action(xs: t.List[int], y: int) -> int:
n = 0
for i, x in enumerate(xs):
n += x ** i
return n
def run0() -> None:
d = defaultdict(list) # type: t.DefaultDict[t.Callable[[t.List[int], int], int], t.List[int]]
ac, x, y = create()
d[ac].append(x)
ac, x, y = create()
d[ac].append(x)
ac, x, y = create()
d[ac].append(x)
print(ac(d[ac], y))
run0()
|
C# | UTF-8 | 631 | 3.671875 | 4 | [] | no_license | using System;
namespace Sum
{
class Program
{
static void Main(string[] args)
{
// - Write a function called `sum` that sum all the numbers
// until the given parameter
int number = 7;
Console.WriteLine(Sum(number));
Console.ReadLine();
}
static int Sum (int input)
{
if (input % 2 == 0)
{
return (input + 1) * input / 2;
}
else
{
return (input + 1) * (input - 1) / 2 + (input + 1) / 2;
}
}
}
} |
Java | UTF-8 | 1,818 | 1.992188 | 2 | [] | no_license | package wang.ismy.shopa.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* @author MY
* @date 2020/3/28 8:21
*/
@Data
@ApiModel(value = "用户信息")
public class UserEntity {
/**
* userid
*/
@ApiModelProperty(value = "用户id")
private Long user_id;
/**
* 手机号码
*/
@ApiModelProperty(value = "手机号码")
private String mobile;
/**
* 邮箱
*/
@ApiModelProperty(value = "邮箱")
private String email;
/**
* 密码
*/
@ApiModelProperty(value = "密码")
private String password;
/**
* 用户名称
*/
@ApiModelProperty(value = "用户名称")
private String userName;
/**
* 性别 0 男 1女
*/
@ApiModelProperty(value = "用户性别")
private Integer sex;
/**
* 年龄
*/
@ApiModelProperty(value = "用户年龄")
private Long age;
/**
* 注册时间
*/
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
/**
* 修改时间
*
*/
@ApiModelProperty(value = "修改时间")
private LocalDateTime updateTime;
/**
* 账号是否可以用 1 正常 0冻结
*/
@ApiModelProperty(value = "账号是否可以用 1 正常 0冻结")
private Integer is_avalible;
/**
* 用户头像
*/
@ApiModelProperty(value = " 用户头像")
private String pic_img;
/**
* 用户关联 QQ 开放ID
*/
@ApiModelProperty(value = "用户关联 QQ 开放ID")
private String qq_openid;
/**
* 用户关联 微信 开放ID
*/
@ApiModelProperty(value = "用户关联 微信 开放ID")
private String WX_OPENID;
}
|
Markdown | UTF-8 | 1,491 | 2.546875 | 3 | [
"MIT"
] | permissive | # Local and Global MOT Memory<a name="EN-US_TOPIC_0260488147"></a>
SILO manages both a local memory and a global memory, as shown in.
- **Global** memory is long-term shared memory is shared by all cores and is used primarily to store all the table data and indexes
- **Local** memory is short-term memory that is used primarily by sessions for handling transactions and store data changes in a primate to transaction memory until the commit phase.
When a transaction change is required, SILO handles the copying of all that transaction's data from the global memory into the local memory. Minimal locks are placed on the global memory according to the OCC approach, so that the contention time in the global shared memory is extremely minimal. After the transaction’ change has been completed, this data is pushed back from the local memory to the global memory.
The basic interactive transactional flow with our SILO-enhanced concurrency control is shown in the figure below
**Figure 1** Private \(Local\) Memory \(for each transaction\) and a Global Memory \(for all the transactions of all the cores\)<a name="fig1610715616384"></a>
-memory-(for-each-transaction)-and-a-global-memory-(for-all-the-transactions-of-all-t.png "private-(local)-memory-(for-each-transaction)-and-a-global-memory-(for-all-the-transactions-of-all-t")
For more details, refer to the Industrial-Strength OLTP Using Main Memory and Many-cores document[\[6\]](#_ftn6).
|
TypeScript | UTF-8 | 1,501 | 2.515625 | 3 | [] | no_license | import { validationResult } from "express-validator";
import queries from "../DAL/queries";
import { Request, Response } from "express";
import { User } from "../model/User";
import { CustomRequest } from "../model/Request";
const roomsWithSpaceForPatients = async (req: Request, res: Response) => {
console.log("llego a rooms with space for patients", req.query);
const user: User = (req as CustomRequest).user;
if (user) {
const systemName = req.query.systemName as string;
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log("invalid params", errors);
return res.sendStatus(400);
}
try {
console.log(systemName);
const system = await queries.findSystemForName(systemName);
if (!system) {
console.log("the system was not found");
return res.sendStatus(404);
}
const rooms = await queries.returnRoomsWithSpaceOfSystemForSystemId(
system.id
);
console.log(rooms);
if (!rooms) {
console.log("the rooms was not found, the system dont have free beds");
return res.sendStatus(404);
}
console.log("rooms with space", rooms);
let validRooms = true;
if (rooms.length === 0) {
validRooms = false;
}
res.json({ rooms, validRooms });
} catch (error) {
console.log("user invalid");
return res.sendStatus(403);
}
} else {
res.sendStatus(404);
}
};
export default roomsWithSpaceForPatients;
|
C++ | UTF-8 | 7,819 | 3.109375 | 3 | [] | no_license | #include "Orange.h"
#include <QBrush>
namespace
{
Directions m_movementDirection = Directions::Unknown;
Directions m_oldMoveDirection = Directions::Unknown;
bool m_onScatteringLoop = false;
int m_scatteringStep = 0;
int m_frightenedCounter = 0;
}
Orange::Orange(Ghost *parent): Ghost(parent)
{
InitDefaultSettings();
}
void Orange::InitDefaultSettings()
{
setRect(0,0,DEFAULT_BLOCK_SIZE,DEFAULT_BLOCK_SIZE);
QPixmap pixmapItem(":/Orange/Images/Orange/OrangeEnemyDown.png");
pixmapItem = pixmapItem.scaled(DEFAULT_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
setBrush(QBrush(pixmapItem));
this->setPos(9 * DEFAULT_BLOCK_SIZE, 10 * DEFAULT_BLOCK_SIZE);
SetPositions();
m_state = GhostsStates::Chase;
m_counter = 5;
}
void Orange::SetPositions()
{
m_coordinates.x = this->pos().x() / DEFAULT_BLOCK_SIZE; // DEFAULT_BLOCK_SIZE means block size
m_coordinates.y = this->pos().y() / DEFAULT_BLOCK_SIZE;
}
void Orange::DoMove(Directions targetDirection)
{
if(m_counter == 0)
{
if(m_state == GhostsStates::Chase)
{
DisableScatteBlueLoop();
Coords targetCords;
ChooseBottomPointOfTarget(targetDirection, targetCords);
m_movementDirection = GetShortestWay(targetCords.x, targetCords.y, m_coordinates);
}
else if(m_state == GhostsStates::Scattered)
{
qDebug() << "pos . x == " << m_coordinates.x << " y == " << m_coordinates.y;
if(m_coordinates.x == 17 && m_coordinates.y == 20)
m_onScatteringLoop = true;
if(m_onScatteringLoop)
ScatteringLoop();
else
{
m_movementDirection = GetShortestWay(17, 20, m_coordinates);
}
}
else if(m_state == GhostsStates::Frightend)
{
DisableScatteBlueLoop();
m_movementDirection = ChooseFrightendWay(m_coordinates);
}
if(m_movementDirection == Directions::Unknown)
m_movementDirection = MoveToAvilablePoint(m_coordinates);
m_counter = 5;
}
if(m_frightenedCounter == FRIGHTENED_MODE_STEPS)
{
m_state = GhostsStates::Chase;
m_frightenedCounter = 0;
}
if(m_state == GhostsStates::Frightend || m_state == GhostsStates::Scattered)
{
if(m_state == GhostsStates::Frightend)
{
QPixmap pixmapItem(":/images/Images/Frightened.png");
pixmapItem = pixmapItem.scaled(DEFAULT_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
setBrush(QBrush(pixmapItem));
m_oldMoveDirection = m_movementDirection;
}
m_frightenedCounter++;
}
switch (m_movementDirection)
{
case Directions::Up: MoveUp(); break;
case Directions::Down: MoveDown(); break;
case Directions::Right: MoveRight(); break;
case Directions::Left: MoveLeft(); break;
default: qDebug() << "Direction is uncnown"; m_counter--; break;
}
m_oldMoveDirection = m_movementDirection;
}
void Orange::MoveUp()
{
setPos(pos().x(), pos().y() - DEFAULT_BLOCK_SIZE / 5);
SetPositions();
m_counter--;
if(m_oldMoveDirection == m_movementDirection)
return;
QPixmap pixmapItem(":/Orange/Images/Orange/OrangeEnemyUp.png");
pixmapItem = pixmapItem.scaled(DEFAULT_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
setBrush(QBrush(pixmapItem));
}
void Orange::MoveDown()
{
setPos(pos().x(), pos().y() + DEFAULT_BLOCK_SIZE / 5);
SetPositions();
m_counter--;
if(m_oldMoveDirection == m_movementDirection)
return;
QPixmap pixmapItem(":/Orange/Images/Orange/OrangeEnemyDown.png");
pixmapItem = pixmapItem.scaled(DEFAULT_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
setBrush(QBrush(pixmapItem));
}
void Orange::MoveRight()
{
setPos(pos().x() + DEFAULT_BLOCK_SIZE / 5, pos().y());
SetPositions();
m_counter--;
if(m_oldMoveDirection == m_movementDirection)
return;
QPixmap pixmapItem(":/Orange/Images/Orange/OrangeEnemyRight.png");
pixmapItem = pixmapItem.scaled(DEFAULT_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
setBrush(QBrush(pixmapItem));
}
void Orange::MoveLeft()
{
setPos(pos().x() - DEFAULT_BLOCK_SIZE / 5, pos().y());
SetPositions();
m_counter--;
if(m_oldMoveDirection == m_movementDirection)
return;
QPixmap pixmapItem(":/Orange/Images/Orange/OrangeEnemyLeft.png");
pixmapItem = pixmapItem.scaled(DEFAULT_BLOCK_SIZE, DEFAULT_BLOCK_SIZE);
setBrush(QBrush(pixmapItem));
}
// Scattered mode
void Orange::ScatteringLoop()
{
DEBUG_LOG;
switch (m_scatteringStep)
{
case 0: m_movementDirection = Directions::Up; ++m_scatteringStep; break;
case 1: m_movementDirection = Directions::Up; ++m_scatteringStep; break;
case 2: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 3: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 4: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 5: m_movementDirection = Directions::Up; ++m_scatteringStep; break;
case 6: m_movementDirection = Directions::Up; ++m_scatteringStep; break;
case 7: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 8: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 9: m_movementDirection = Directions::Down; ++m_scatteringStep; break;
case 10: m_movementDirection = Directions::Down; ++m_scatteringStep; break;
case 11: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 12: m_movementDirection = Directions::Left; ++m_scatteringStep; break;
case 13: m_movementDirection = Directions::Down; ++m_scatteringStep; break;
case 14: m_movementDirection = Directions::Down; ++m_scatteringStep; break;
case 15: m_movementDirection = Directions::Right; ++m_scatteringStep; break;
case 16: m_movementDirection = Directions::Right; ++m_scatteringStep; break;
case 17: m_movementDirection = Directions::Right; ++m_scatteringStep; break;
case 18: m_movementDirection = Directions::Right; ++m_scatteringStep; break;
case 19: m_movementDirection = Directions::Right; ++m_scatteringStep; break;
case 20: m_movementDirection = Directions::Right; ++m_scatteringStep; break;
default: m_scatteringStep = 0; break;
}
}
void Orange::ChooseBottomPointOfTarget(Directions targetDirection, Coords &targetCoords)
{
targetCoords = CoreGlobals::playersCoords;
if(targetDirection == Directions::Up)
{
targetCoords.y = targetCoords.y + 1;
return;
}
else if(targetDirection == Directions::Down)
{
targetCoords.y = targetCoords.y - 1;
return;
}
else if(targetDirection == Directions::Right)
{
targetCoords.x = targetCoords.x - 1;
return;
}
else if(targetDirection == Directions::Left)
{
targetCoords.x = targetCoords.x + 1;
return;
}
}
void Orange::DisableScatteBlueLoop()
{
m_onScatteringLoop = false;
m_scatteringStep = 0;
}
void Orange::ChangeStates()
{
int x = m_state;
x++;
if(x == 3)
x = 0;
m_state = (GhostsStates)x;
}
void Orange::SetState(GhostsStates state)
{
m_state = state;
}
GhostsStates Orange::GetState()
{
return m_state;
}
void Orange::SetCounter(int count)
{
m_counter = count;
}
void Orange::Reset()
{
m_state = GhostsStates::Chase;
m_movementDirection = Directions::Unknown;
m_oldMoveDirection = Directions::Unknown;
m_counter = 5; // start movement from first step
m_frightenedCounter = 0;
setPos(9 * DEFAULT_BLOCK_SIZE, 10 * DEFAULT_BLOCK_SIZE);
}
|
C# | UTF-8 | 11,566 | 3.265625 | 3 | [
"MIT"
] | permissive | /*
Copyright (c) 2017 Denis Zykov
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.
License: https://opensource.org/licenses/MIT
*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
// ReSharper disable once CheckNamespace
namespace System
{
/// <summary>
/// Dictionary of command line arguments. Provides parsing/formatting features and by name access to parsed arguments.
/// </summary>
#if !NETSTANDARD1_3
[Serializable]
#endif
public class CommandLineArguments : Dictionary<string, object>
{
private class IntAsStringComparer : IComparer<string>
{
public static readonly IntAsStringComparer Default = new IntAsStringComparer();
public int Compare(string x, string y)
{
int xInt = 0, yInt = 0;
bool xIsInt = false, yIsInt = false;
if (x != null && x.All(char.IsDigit) && int.TryParse(x, out xInt))
xIsInt = true;
if (y != null && y.All(char.IsDigit) && int.TryParse(y, out yInt))
yIsInt = true;
if (xIsInt && yIsInt)
return xInt.CompareTo(yInt);
else if (xIsInt)
return -1;
else if (yIsInt)
return 1;
else
return StringComparer.Ordinal.Compare(x ?? string.Empty, y ?? string.Empty);
}
}
/// <summary>
/// Get positional argument.
/// </summary>
/// <param name="position">Zero-based position of argument.</param>
/// <returns>Value of positional argument.</returns>
public string this[int position]
{
get
{
return TypeConvert.ToString(this.GetValueOrDefault(position.ToString()));
}
set
{
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Value can't be empty or null.", "value");
this[position.ToString()] = value;
}
}
/// <summary>
/// Creates new empty instance of <see cref="CommandLineArguments"/>.
/// </summary>
public CommandLineArguments()
: base(StringComparer.Ordinal)
{
}
/// <summary>
/// Creates new instance of <see cref="CommandLineArguments"/> with <paramref name="arguments"/>.
/// </summary>
public CommandLineArguments(params string[] arguments)
: this((IEnumerable<string>)arguments)
{
}
/// <summary>
/// Creates new instance of <see cref="CommandLineArguments"/> with <paramref name="arguments"/>.
/// </summary>
public CommandLineArguments(IEnumerable<string> arguments)
: this()
{
if (arguments == null) throw new ArgumentException("arguments");
foreach (var kv in ParseArguments(arguments))
{
var currentValue = default(object);
if (this.TryGetValue(kv.Key, out currentValue))
{
if (kv.Value == null)
continue;
// try to combine with existing value
if (currentValue == null)
this[kv.Key] = currentValue = new List<string>();
else if (currentValue is List<string> == false)
this[kv.Key] = currentValue = new List<string> { TypeConvert.ToString(currentValue) };
var currentList = (List<string>)currentValue;
if (kv.Value is List<string>)
currentList.AddRange((List<string>)kv.Value);
else
currentList.Add(TypeConvert.ToString(kv.Value));
}
else
{
this.Add(kv.Key, kv.Value);
}
}
}
/// <summary>
/// Creates new instance of <see cref="CommandLineArguments"/> with <paramref name="argumentsDictionary"/>.
/// </summary>
public CommandLineArguments(IDictionary<string, object> argumentsDictionary)
: base(argumentsDictionary, StringComparer.Ordinal)
{
if (argumentsDictionary == null) throw new ArgumentException("argumentsDictionary");
}
#if !NETSTANDARD1_3
/// <summary>
/// Creates new instance of <see cref="CommandLineArguments"/> for <see cref="System.Runtime.Serialization.Formatter"/>.
/// </summary>
protected CommandLineArguments(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Add new positional argument.
/// </summary>
public void Add(int position, string value)
{
if (position < 0) throw new ArgumentOutOfRangeException("position");
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Value can't be empty or null.", "value");
this.Add(position.ToString(), value);
}
/// <summary>
/// Insert new positional argument and "push" other positional argument forward.
/// </summary>
public void InsertAt(int position, string value)
{
if (position < 0) throw new ArgumentOutOfRangeException("position");
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Value can't be empty or null.", "value");
var currentValue = default(object);
var positionKey = position.ToString();
var hasCurrent = this.TryGetValue(positionKey, out currentValue) && string.IsNullOrEmpty(TypeConvert.ToString(currentValue)) == false;
this[positionKey] = value;
while (hasCurrent)
{
value = TypeConvert.ToString(currentValue);
positionKey = (++position).ToString();
hasCurrent = this.TryGetValue(positionKey, out currentValue) && string.IsNullOrEmpty(TypeConvert.ToString(currentValue)) == false;
this[positionKey] = value;
}
}
/// <summary>
/// Remove positional argument and "pull" other positional arguments backward.
/// </summary>
public void RemoveAt(int position)
{
if (position < 0) throw new ArgumentOutOfRangeException("position");
var positionKey = position.ToString();
this.Remove(positionKey);
for (var i = position + 1; ; i++)
{
var value = default(object);
positionKey = i.ToString();
if (this.TryGetValue(positionKey, out value) == false)
break;
this[(i - 1).ToString()] = value;
this.Remove(positionKey);
}
}
/// <summary>
/// Get value of positional argument by name or null if it is missing.
/// </summary>
public object GetValueOrDefault(string key)
{
var value = default(object);
return this.TryGetValue(key, out value) == false ? null : value;
}
/// <summary>
/// Get value of positional argument by name or <paramref name="defaultValue"/> if it is missing.
/// </summary>
public object GetValueOrDefault(string key, object defaultValue)
{
var value = defaultValue;
return this.TryGetValue(key, out value) == false ? defaultValue : value;
}
/// <summary>
/// Transform <see cref="CommandLineArguments"/> to list of string chunks. Chunks should be escaped(quoted) before combining them into one string.
/// </summary>
public string[] ToArray()
{
var count = 0;
var position = 0;
foreach (var kv in this)
{
if (!int.TryParse(kv.Key, out position))
{
if (kv.Value == null)
count++; // only parameter name
else if (kv.Value is IList<string>)
count += 1 + ((IList<string>)kv.Value).Count; // parameter name + values
else
count += 2; // parameter name + value
}
else
{
if (kv.Value is IList<string>)
count += ((IList<string>)kv.Value).Count; // only values
else if (kv.Value != null)
count += 1; // only value
}
}
var array = new string[count];
var index = 0;
foreach (var kv in this.OrderBy(kv => kv.Key, IntAsStringComparer.Default))
{
var valuesList = kv.Value as IList<string>;
if (!int.TryParse(kv.Key, out position))
array[index++] = string.Concat(CommandLine.ArgumentNamePrefix, kv.Key);
if (valuesList != null)
{
valuesList.CopyTo(array, index);
index += valuesList.Count;
}
else if (kv.Value != null)
{
array[index++] = TypeConvert.ToString(kv.Value);
}
}
return array;
}
/// <summary>
/// Parse list of arguments into <see cref="CommandLineArguments"/>. Chunks should be un-escaped(un-quoted).
/// </summary>
private static IEnumerable<KeyValuePair<string, object>> ParseArguments(IEnumerable<string> arguments)
{
if (arguments == null) throw new ArgumentException("arguments");
var positional = true;
var forcePositional = false;
var noHyphenParameters = false;
var position = -1;
var argumentName = default(string);
var argumentValue = default(List<string>);
foreach (var argument in arguments)
{
if (forcePositional || IsArgumentName(argument, noHyphenParameters) == false)
{
if (positional || forcePositional)
yield return new KeyValuePair<string, object>((++position).ToString(), argument);
else if (argumentValue == null)
argumentValue = new List<string> { argument };
else
argumentValue.Add(argument);
continue;
}
// save previous argument
if (argumentName != null)
yield return new KeyValuePair<string, object>(argumentName, GetNullOrFirstOrAll(argumentValue));
argumentValue = null;
argumentName = null;
if (argument == CommandLine.ArgumentNamePrefix)
{
forcePositional = true;
continue;
}
else if (argument == CommandLine.ArgumentNamePrefixShort)
{
noHyphenParameters = !noHyphenParameters;
continue;
}
if (argument.StartsWith(CommandLine.ArgumentNamePrefix, StringComparison.Ordinal))
argumentName = argument.Substring(CommandLine.ArgumentNamePrefix.Length);
else if (argument.StartsWith(CommandLine.ArgumentNamePrefixShort))
argumentName = argument.Substring(CommandLine.ArgumentNamePrefixShort.Length);
else
throw new InvalidOperationException(string.Format("Argument name should start with '{0}' or '{1}' symbols. " +
"This is arguments parser error and should be reported to application developer.", CommandLine.ArgumentNamePrefix, CommandLine.ArgumentNamePrefixShort));
positional = false;
}
if (!string.IsNullOrEmpty(argumentName))
yield return new KeyValuePair<string, object>(argumentName, GetNullOrFirstOrAll(argumentValue));
}
private static object GetNullOrFirstOrAll(List<string> argumentValue)
{
if (argumentValue == null)
return null;
if (argumentValue.Count == 1)
return argumentValue[0];
return argumentValue.ToArray();
}
private static bool IsStartsAsNumber(string value)
{
if (string.IsNullOrEmpty(value))
return false;
if (value.Length > 1 && value[0] == '-' && char.IsDigit(value[1]))
return true;
else if (value.Length > 0)
return char.IsDigit(value[0]);
else
return false;
}
private static bool IsArgumentName(string value, bool noHyphenParameters)
{
if (string.IsNullOrEmpty(value))
return false;
if (IsStartsAsNumber(value))
return false;
return value.StartsWith(CommandLine.ArgumentNamePrefix, StringComparison.Ordinal) ||
(noHyphenParameters == false && value.StartsWith(CommandLine.ArgumentNamePrefixShort, StringComparison.Ordinal));
}
/// <summary>
/// Transform <see cref="CommandLineArguments"/> via <see cref="ToArray"/> into string chunks and apply basic escaping and joining with SPACE character.
/// </summary>
public override string ToString()
{
var arguments = this.ToArray();
var length = arguments.Sum(a => a.Length) + arguments.Length * 3;
var sb = new StringBuilder(length);
foreach (var value in arguments)
{
var start = sb.Length;
sb.Append(value);
sb.Replace("\\", "\\\\", start, sb.Length - start);
sb.Replace("\"", "\\\"", start, sb.Length - start);
if (value != null && value.IndexOf(' ') != -1)
sb.Insert('"', start).Append('"');
sb.Append(' ');
}
if (sb.Length > 0)
sb.Length--;
return sb.ToString();
}
}
}
|
PHP | UTF-8 | 791 | 3.25 | 3 | [] | no_license | <?php
namespace info\domain;
require_once("DomainObject.php");
class Document extends DomainObject {
private $description;
private $date;
private $src;
private $format;
function __construct($id, $title, $text, $description, $date, $src) {
parent::__construct($id, $title, $text);
$this->description = $description;
$this->date = $date;
$this->src = $src;
$this->format = $this->generateFormat($src);
}
private function generateFormat($src) {
$formatIndex = strrpos($src, ".");
return substr($src, $formatIndex + 1);
}
public function getDescription() {
return $this->description;
}
public function getDate() {
return $this->date;
}
public function getSrc() {
return $this->src;
}
public function getFormat() {
return $this->format;
}
}
?> |
C# | UTF-8 | 865 | 2.859375 | 3 | [] | no_license | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace ConsoleApp3
{
public class SensetiveJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return existingValue;
}
public override void WriteJson(JsonWriter writer, object existingValue, JsonSerializer serializer)
{
var value = existingValue?.ToString();
writer.WriteValue(value != null ? $"{value[0]}***{value[value.Length - 1]}" : null);
//https://www.newtonsoft.com/json/help/html/ContractResolver.htm
}
}
}
|
Shell | UTF-8 | 794 | 3.578125 | 4 | [] | no_license | #!/bin/bash
BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CONF_FILE_PATH=${BASE_DIR%%/}/settings.conf
echo "Reading config from: $CONF_FILE_PATH" >&2
. $CONF_FILE_PATH
echo "Config for the proxy port: $POLIPO_PROXY_PORT" >&2
#Start the shadowsocks proxy
$SS_DAEMON -s $SS_SERVER_IP -p $SS_SERVER_PORT -k $SS_SERVER_PASS -m $SS_SERVER_METHOD -d restart --pid-file=$SS_PID_FILE --log-file=$SS_LOG_FILE
#Try to kill running polipo && remove the PID file as well.
killall polipo
if [ -f $POLIPO_PID_FILE ] ; then
rm $POLIPO_PID_FILE
fi
#Start the polipo http proxy
polipo daemonise=true pidFile=$POLIPO_PID_FILE logFile=$POLIPO_LOG_FILE socksParentProxy=$POLIPO_SOCKS_IP:$POLIPO_SOCKS_PORT socksProxyType=socks5 proxyPort=$POLIPO_PROXY_PORT proxyAddress=$POLIPO_PROXY_IP
|
Java | UTF-8 | 2,023 | 2.4375 | 2 | [] | no_license | package com.app.tGolachowski.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
private BigDecimal price;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Set<CustomerOrder> customerOrders = new HashSet<>();
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "producer_id")
private Producer producer;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Set<Stock> stocks;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "category_id")
private Category category;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(
name = "GuaranteeComponent",
joinColumns = @JoinColumn(name = "product_id")
)
@Column(name = "guarantee_component")
private Set<GuaranteeComponent> guaranteeComponentSet = new HashSet<>();
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product)) return false;
Product product = (Product) o;
if (getId() != null ? !getId().equals(product.getId()) : product.getId() != null) return false;
if (getName() != null ? !getName().equals(product.getName()) : product.getName() != null) return false;
return getPrice() != null ? getPrice().equals(product.getPrice()) : product.getPrice() == null;
}
@Override
public int hashCode() {
int result = getId() != null ? getId().hashCode() : 0;
result = 31 * result + (getName() != null ? getName().hashCode() : 0);
result = 31 * result + (getPrice() != null ? getPrice().hashCode() : 0);
return result;
}
}
|
C++ | UTF-8 | 805 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <assert.h>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
const int len = s.length();
if (numRows == 1 || len == 1)
return s;
const int circle = numRows * 2 - 2; // 周期
string r = "";
for (int i = 0; i < numRows; i++) {
for (int j = i; j < len; j += circle) {
r += s[j];
if (i > 0 && i < numRows - 1) {
int dist = circle - 2 * i;
if ((j + dist) < len)
r += s[j + dist];
}
}
}
return r;
}
};
int main()
{
string s = "AB";
Solution so;
cout << so.convert(s, 3) << endl;
return 0;
}
|
Java | UTF-8 | 1,805 | 2.34375 | 2 | [] | no_license | package org.srinadh.exception;
import java.util.Date;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
@RestController
public class CustomeResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleallExceptios(Exception e, WebRequest request){
ExceptionStudent exception = new ExceptionStudent(new Date(), e.getMessage(), request.getDescription(false));
return new ResponseEntity(exception, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(StudentNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(StudentNotFoundException s, WebRequest request){
ExceptionStudent exception=new ExceptionStudent(new Date(), s.getMessage(), request.getDescription(false));
return new ResponseEntity(exception, HttpStatus.NOT_FOUND);
}
//@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException e,
HttpHeaders header, HttpStatus status, WebRequest requst){
ExceptionStudent exception=new ExceptionStudent(new Date(), "Validation Failed", e.getBindingResult().toString());
return new ResponseEntity(exception, HttpStatus.BAD_REQUEST);
}
}
|
C++ | UTF-8 | 11,058 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstring>
struct book
{
int Id_b = 0;
char Name_b[25] = {};
int Flag_b = 0;
};
struct reader
{
int Id_r;
char Name_r[20];
book library[3];
char Hist_book[100][25];
int Flag_r;
};
void add_book_read ()
{
int count_b;
std::fstream count_r_b ("count_b.txt");
count_r_b >> count_b;
count_r_b.close();
book arr_b[count_b-1];
int count;
std::fstream count_r ("count.txt");
count_r >> count;
count_r.close();
reader arr_r[count-1];
std::fstream book_r ("Book.bin"); // открываем файл с книгами
if (book_r)
{
for (int i = 0; book_r; i++)
{
book_r.read(reinterpret_cast<char*>(&arr_b),sizeof(arr_b));
}
book_r.close();
for (int i = 0; i < count_b-1; i++)
{
if (arr_b[i].Flag_b == 1)
{
std::cout << arr_b[i].Id_b << ' ' << arr_b[i].Name_b << std::endl;
}
}
}
int numb_r; //выбор номера читателя
int numb_b; //выбор номера книги которую выдать чителю
std::cout << "Input number reader: ";
std::cin >> numb_r;
std::fstream read_book ("Reader.bin"); //нужно, чтобы перезаписать файл с читателями
for (int i = 0; read_book; i++)
{
read_book.read(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
}
read_book.open("Reader.bin", std::ios::trunc); // очистил файл
read_book.close();
if (arr_r[numb_r-1].Flag_r == 1) // если пользователь есть, открой его и запиши ему книгу
{
std::cout << "input number Book: ";
std::cin >> numb_b;
for (int i = 0; i < 3; i++)
{
if (arr_r[numb_r-1].library[i].Flag_b == 0)
{
arr_r[numb_r-1].library[i] = arr_b[numb_b-1]; // записали книгу в 1 ячейку читателя
arr_b[numb_b-1].Flag_b = 0;
//std::cerr << "Break\n";
break;
}
else
{
std::cout << "Return book";
break;
}
}
}
else
{
std::cout << "Reader not found. Maybe removed.";
}
std::ofstream book_add_read ("Reader.bin");
book_add_read.write(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
book_add_read.close();
std::ofstream flag_book ("Book.bin");
flag_book.write(reinterpret_cast<char*>(&arr_b),sizeof(arr_b));
flag_book.close();
}
void reader_book_rw()
{
int count;
std::fstream count_r ("count.txt"); // создай переменную для работы с файлом, открой файл
if (count_r) //если файл есть и не пустой
{
count_r >> count; //запомни в переменную значение из файла
count_r.close(); // закрой переменную и файл
reader arr_r[count]; // создай массив, размера как указано в файле
std::fstream read_book ("Reader.bin"); //создай переменную для работы с файлом
if (read_book) // если файл не пустой
{
for (int i = 0; read_book; i++) // читай пока файл не закончится
{
read_book.read(reinterpret_cast<char*>(&arr_r),sizeof(arr_r)); // запомни в массив все, что прочитал
}
read_book.open("Reader.bin", std::ios::trunc); //очисти файл
read_book.close(); // закрой переменную и файл
arr_r[count-1].Id_r = count;
std::cout << "input Name reader: ";
std::cin.getline(arr_r[count-1].Name_r, 20);
/*for (int j=0; j<2; j ++)
{
std::cout << "input Name Book: ";
std::cin.getline(arr_r[count-1].library[j].Name_b, 25);
}*/
arr_r[count-1].Flag_r = 1;
count++;
std::ofstream count_r ("count.txt");
count_r << count;
count_r.close();
std::ofstream read_book ("Reader.bin");
read_book.write(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
read_book.close();
}
}
else // если файла нет
{
std::ofstream count_r ("count.txt");
count = 1;
count_r << count;
count_r.close();
reader arr_r[1];
arr_r[0].Id_r = count;
std::cout << "input Name reader: ";
std::cin.getline(arr_r[0].Name_r, 20);
/*for (int j=0; j<2; j ++)
{
std::cout << "input Name Book: ";
std::cin.getline(arr_r[0].Book_r[j], 25);
}*/
arr_r[0].Flag_r = 1;
count++;
std::ofstream count_rw ("count.txt");
count_rw << count;
count_rw.close();
std::ofstream read_book ("Reader.bin");
read_book.write(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
read_book.close();
}
}
void reader_book_r()
{
int count;
int choice;
std::cout << "Full listing reader, imput value 1: " << std::endl;
std::cout << "Selecyive listing reader, imput value 2: " << std::endl;
std::cin >> choice;
std::fstream count_r ("count.txt");
count_r >> count;
count_r.close();
reader arr_r[count-1];
std::fstream read_book ("Reader.bin");
if (read_book)
{
if (choice == 1)
{
for (int i = 0; read_book; i++)
{
read_book.read(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
}
read_book.close();
for (int i = 0; i < count-1; i++)
{
if (arr_r[i].Flag_r == 1)
{
std::cout << arr_r[i].Id_r << ' ' << arr_r[i].Name_r << std::endl;
for (int j = 0; j<3; j++)
{
std::cout << "#"<< j+1 << ':' << arr_r[i].library[j].Name_b << ' ' << "ID_Book: " << arr_r[i].library[j].Id_b << std::endl;
}
std::cout << std::endl;
}
}
}
if (choice ==2)
{
int numb_r;
std::cout << "Input number reader: ";
std::cin >> numb_r;
for (int i = 0; read_book; i++)
{
read_book.read(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
}
read_book.close();
if (arr_r[numb_r-1].Flag_r == 1)
{
std::cout << arr_r[numb_r-1].Id_r << ' ' << arr_r[numb_r-1].Name_r << std::endl;
/*for (int j = 0; j<2; j++)
{
std::cout << "#"<< j+1 << ':' << arr_r[numb_r-1].Book_r[j] << ' ';
}
std::cout << std::endl;*/
}
else
{
std::cout << "Reader not found. Maybe removed.";
}
}
}
else
{
std::cout << "File readers is Empty" << std::endl;
}
}
void reader_removed()
{
int count;
int choice_rem;
std::fstream count_r ("count.txt");
count_r >> count;
count_r.close();
reader arr_r[count-1];
std::fstream read_book ("Reader.bin");
if (read_book)
{
for (int i = 0; read_book; i++)
{
read_book.read(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
}
read_book.close();
for (int i = 0; i < count-1; i++)
{
if (arr_r[i].Flag_r == 1)
{
std::cout << arr_r[i].Id_r << ' ' << arr_r[i].Name_r << std::endl;
for (int j = 0; j<3; j++)
{
std::cout << "#"<< j+1 << ':' << arr_r[i].library[j].Name_b << ' ' << "ID_Book: " << arr_r[i].library[j].Id_b << std::endl;
}
std::cout << std::endl;
}
}
std::cout << "Imput number reader for removed: " << std::endl;
std::cin >> choice_rem;
arr_r[choice_rem-1].Flag_r = 0;
std::ofstream read_book ("Reader.bin");
read_book.write(reinterpret_cast<char*>(&arr_r),sizeof(arr_r));
read_book.close();
}
}
void book_rw()
{
int count_b;
std::fstream count_r_b ("count_b.txt"); // создай переменную для работы с файлом, открой файл
if (count_r_b) //если файл есть и не пустой
{
count_r_b >> count_b; //запомни в переменную значение из файла
count_r_b.close(); // закрой переменную и файл
book arr_b[count_b]; // создай массив, размера как указано в файле
std::fstream book_r ("Book.bin"); //создай переменную для работы с файлом
if (book_r) // если файл не пустой
{
for (int i = 0; book_r; i++) // читай пока файл не закончится
{
book_r.read(reinterpret_cast<char*>(&arr_b),sizeof(arr_b)); // запомни в массив все, что прочитал
}
book_r.open("Book.bin", std::ios::trunc); //очисти файл
book_r.close(); // закрой переменную и файл
arr_b[count_b-1].Id_b = count_b;
std::cout << "input Name a Book: ";
std::cin.getline(arr_b[count_b-1].Name_b, 25);
arr_b[count_b-1].Flag_b = 1;
count_b++;
std::ofstream count_r_b ("count_b.txt");
count_r_b << count_b;
count_r_b.close();
std::ofstream book_r ("Book.bin");
book_r.write(reinterpret_cast<char*>(&arr_b),sizeof(arr_b));
book_r.close();
}
}
else // если файла нет
{
std::ofstream count_r_b ("count_b.txt");
count_b = 1;
count_r_b << count_b;
count_r_b.close();
book arr_b[1];
arr_b[0].Id_b = count_b;
std::cout << "input Name a Book: ";
std::cin.getline(arr_b[0].Name_b, 25);
arr_b[0].Flag_b = 1;
count_b++;
std::ofstream count_rw ("count_b.txt");
count_rw << count_b;
count_rw.close();
std::ofstream book_r ("Book.bin");
book_r.write(reinterpret_cast<char*>(&arr_b),sizeof(arr_b));
book_r.close();
}
}
void book_r()
{
int count_b;
int choice;
std::cout << "Full listing a book, imput value 1: " << std::endl;
std::cout << "Selecyive listing book, imput value 2: " << std::endl;
std::cin >> choice;
std::fstream count_r_b ("count_b.txt");
count_r_b >> count_b;
count_r_b.close();
book arr_b[count_b-1];
std::fstream book_r ("Book.bin");
if (book_r)
{
if (choice == 1)
{
for (int i = 0; book_r; i++)
{
book_r.read(reinterpret_cast<char*>(&arr_b),sizeof(arr_b));
}
book_r.close();
for (int i = 0; i < count_b-1; i++)
{
if (arr_b[i].Flag_b == 1)
{
std::cout << arr_b[i].Id_b << ' ' << arr_b[i].Name_b << ' ' << arr_b[i].Flag_b<< std::endl;
}
}
}
if (choice ==2)
{
int numb_b;
std::cout << "Input numb a book: ";
std::cin >> numb_b;
for (int i = 0; book_r; i++)
{
book_r.read(reinterpret_cast<char*>(&arr_b),sizeof(arr_b));
}
book_r.close();
if (arr_b[numb_b-1].Flag_b == 1)
{
std::cout << arr_b[numb_b-1].Id_b << ' ' << arr_b[numb_b-1].Name_b << ' ' << arr_b[numb_b-1].Flag_b<< std::endl;
}
else
{
std::cout << "Book not found. Maybe removed.";
}
}
}
else
{
std::cout << "File book is Empty" << std::endl;
}
}
int main ()
{
//reader_book_rw();
//reader_book_r();
//reader_removed();
//rw_read();
//book_rw();
//add_book_read();
//book_r();
}
|
Shell | UTF-8 | 206 | 3.109375 | 3 | [] | no_license | #!/bin/bash
# for i in 1 2 3 4 5
#OR
# for i in {0..50..2}
# {start..end..increment}
for (( i=0; i<10; i++ ))
do
if [ $i -eq 3 ] || [ $i -eq 7 ]
then
continue
fi
echo $i
done
|
C | UTF-8 | 1,030 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/rmat_graph_generator.hpp>
#include <boost/random/linear_congruential.hpp>
typedef boost::adjacency_list<> Graph;
typedef boost::rmat_iterator<boost::minstd_rand, Graph> RMATGen;
int main(int argc, char* argv[])
{
int verts = 10;
if(argc > 1){
verts = atoi(argv[1]);
}
boost::minstd_rand gen;
// Create graph with 100 nodes and 400 edges
Graph g(RMATGen(gen, verts, 4*verts, 0.57, 0.19, 0.19, 0.05), RMATGen(), verts);
typedef boost::property_map<Graph, boost::vertex_index_t>::type IndexMap;
IndexMap index = get(boost::vertex_index, g);
std::ofstream outfile("rmat_graph.gv");
outfile << "digraph my_rmat_graph {" << std::endl;
boost::graph_traits<Graph>::edge_iterator e_i, e_end;
for(tie(e_i, e_end) = edges(g); e_i != e_end; ++e_i){
outfile << index[source(*e_i, g)] << " -> " << index[target(*e_i, g)] << ";" << std::endl;
}
outfile << "}" << std::endl;
outfile.close();
return 0;
}
|
PHP | UTF-8 | 1,964 | 2.609375 | 3 | [] | no_license | <?php
namespace App\Document;
use App\Repository\CsvFileRepository;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document(repositoryClass=CsvFileRepository::class)
*/
class CsvFile
{
public const STATUS_NEW = 'new';
public const STATUS_PARSE = 'parse';
public const STATUS_COMPLETE = 'complete';
public const STATUS_FAIL = 'fail';
/**
* @MongoDB\Id
*/
private $id;
/**
* @MongoDB\Field(type="string")
*/
private $file_name;
/**
* @MongoDB\Field(type="timestamp")
*/
private $date_created;
/**
* @MongoDB\Field(type="string")
*/
private $file_path;
/**
* @MongoDB\Field(type="string")
*/
private $status;
public function getId(): ?string
{
return $this->id;
}
public function getFileName(): ?string
{
return $this->file_name;
}
public function setFileName(string $file_name): self
{
$this->file_name = $file_name;
return $this;
}
public function getDateCreated()
{
return $this->date_created->getTimestamp();
}
public function setDateCreated($date_created): self
{
$this->date_created = $date_created;
return $this;
}
public function getFilePath(): ?string
{
return $this->file_path;
}
public function setFilePath(string $file_path): self
{
$this->file_path = $file_path;
return $this;
}
public function getStatus(): ?string
{
return $this->status;
}
public function setStatus(string $status): self
{
$this->status = $status;
return $this;
}
public function toArray()
{
return [
'id' => $this->getId(),
'fileName' => $this->getFileName(),
'dateCreated' => $this->getDateCreated(),
'status' => $this->getStatus(),
];
}
}
|
Java | UTF-8 | 1,923 | 2.46875 | 2 | [] | no_license | package main.data;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
public class Login {
private String username;
@JsonUnwrapped
private Password password;
private String website;
private Folder folder;
private String notes;
private List<SecurityQuestion> securityQuestions;
// ONLY FOR JSON SERIALIZATION/DESERIALIZATION
public Login() { }
public Login(String u, String p, String site) {
this.username = u;
this.password = new Password(p);
this.website = site;
this.securityQuestions = new ArrayList<SecurityQuestion>();
}
public Login(String u, String p, String site, Folder f, String n, List<SecurityQuestion> questions) {
this.username = u;
this.password = new Password(p);
this.website = site;
this.folder = f;
this.notes = n;
if (questions != null)
this.securityQuestions = new ArrayList<SecurityQuestion>();
else
this.securityQuestions = questions;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String retrieveHiddenPassword() {
return Password.getHiddenPassword();
}
public String retrieveRealPassword() {
return password.retrieveRealPassword();
}
public void setPassword(String password) {
this.password = new Password(password);
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<SecurityQuestion> getSecurityQuestions() {
return securityQuestions;
}
public void addSecurityQuestion(SecurityQuestion securityQuestion) {
this.securityQuestions.add(securityQuestion);
}
}
|
Java | UTF-8 | 4,213 | 2.109375 | 2 | [] | no_license | package com.aml.propaganda.model;
import com.aml.sys.entity.Dict;
import java.util.Date;
/**
* Created by hb on 2017/10/24.
*/
public class CmsNewsAndDictModel {
/**
* 标识ID
*/
private Integer id;
/**
* 栏目ID
*/
private String channelId;
/**
* 标题
*/
private String title;
/**
* 内容
*/
private String content;
/**
* 是否发布
*/
private String isPublish;
/**
* 发布人
*/
private String publisher;
/**
* 发布时间
*/
private Date publishTime;
/**
* 是否新
*/
private String isNew;
/**
* 访问次数
*/
private String visitCount;
/**
* 是否滚动
*/
private String isScorll;
/**
* 是否显示
*/
private String isDisplay;
/**
* 审核人
*/
private String auditer;
/**
* 审核时间
*/
private Date auditTime;
/**
* 关键词
*/
private String keyword;
/**
* 发布类型
*/
private String publishType;
/**
* 开始时间
*/
private Date begDate;
/**
* 截至时间
*/
private Date endDate;
/**
* 作者
*/
private String author;
/**
* 栏目名称
*/
private Dict dict;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getIsPublish() {
return isPublish;
}
public void setIsPublish(String isPublish) {
this.isPublish = isPublish;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Date getPublishTime() {
return publishTime;
}
public void setPublishTime(Date publishTime) {
this.publishTime = publishTime;
}
public String getIsNew() {
return isNew;
}
public void setIsNew(String isNew) {
this.isNew = isNew;
}
public String getVisitCount() {
return visitCount;
}
public void setVisitCount(String visitCount) {
this.visitCount = visitCount;
}
public String getIsScorll() {
return isScorll;
}
public void setIsScorll(String isScorll) {
this.isScorll = isScorll;
}
public String getIsDisplay() {
return isDisplay;
}
public void setIsDisplay(String isDisplay) {
this.isDisplay = isDisplay;
}
public String getAuditer() {
return auditer;
}
public void setAuditer(String auditer) {
this.auditer = auditer;
}
public Date getAuditTime() {
return auditTime;
}
public void setAuditTime(Date auditTime) {
this.auditTime = auditTime;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getPublishType() {
return publishType;
}
public void setPublishType(String publishType) {
this.publishType = publishType;
}
public Date getBegDate() {
return begDate;
}
public void setBegDate(Date begDate) {
this.begDate = begDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Dict getDict() {
return dict;
}
public void setDict(Dict dict) {
this.dict = dict;
}
}
|
Python | UTF-8 | 7,950 | 2.765625 | 3 | [
"MIT"
] | permissive | """Integration tests for signup template
The signup view extends uses a custom template. The tests in this file
verify that the custom templates contains all of the necessary
elements including error messages and mark-up.
Tests in this file include:
+ form elements
+ form success
+ missing first_name
+ missing last_name
+ missing email
+ missing password1
+ missing password2
+ passwords do not match
+ passwords too short
+ username exists
+ email exists
"""
import pytest
from django.urls import reverse
from django.utils.html import escape
from pytest_django.asserts import assertContains
from myusers.tests.fixtures import joe_user
def test_form_elements(client):
"""verify that the signup form contains the expected elements."""
response = client.get(reverse("signup"))
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
print(content)
assert "Sign-Up" in content
assert "First name:" in content
assert "Last name:" in content
assert "Email address:" in content
assert "Password:" in content
assert "Password confirmation:" in content
@pytest.mark.django_db
def test_form_success(client):
"""Verify that we can sign up a new user with our form."""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": "bart@simpsons.com",
"password1": "Django123",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "registration/login.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
@pytest.mark.django_db
def test_form_missing_lastname(client):
"""If we submit the form without a last name, we should see an
bmo appropriate error messages."""
data = {
"first_name": "bart",
"email": "bart@simpsons.com",
"password1": "Django123",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "This field is required." in content
@pytest.mark.django_db
def test_form_missing_firstname(client):
"""If we submit the form without a firstname, we should see an
bmo appropriate error messages."""
data = {
"last_name": "simpson",
"email": "bart@simpsons.com",
"password1": "Django123",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "This field is required." in content
@pytest.mark.django_db
def test_form_missing_email(client):
"""If we submit the form without an email, we should see an
appropriate error messages."""
data = {
"first_name": "bart",
"last_name": "simpson",
"password1": "Django123",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "This field is required." in content
@pytest.mark.django_db
def test_form_malformed_email(client):
"""If we submit the form with an email that is malformed, we should
see an appropriate error messages.
"""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": "bartsimpson",
"password1": "Django123",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "Enter a valid email address." in content
@pytest.mark.django_db
def test_form_missing_password1(client):
"""If we submit the form missing password1, we should
see an appropriate error messages.
"""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": "bart@simpsons.com",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "This field is required." in content
@pytest.mark.django_db
def test_form_missing_password2(client):
"""If we submit the form missing password2, we should
see an appropriate error messages.
"""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": "bart@simpsons.com",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "This field is required." in content
@pytest.mark.django_db
def test_form_password_mismatch(client):
"""If we submit the form with mis-matched passwords, we should
see an appropriate error messages.
"""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": "bart@simpsons.com",
"password1": "123Django",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
assertContains(response, "Please fix the errors in the form below")
# msg = "The two password fields didn't match"
msg = "The two password fields didn"
assertContains(response, escape(msg))
@pytest.mark.django_db
def test_form_short_password(client):
"""If we submit the form with a password that is too short, we should
see an appropriate error messages.
"""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": "bart@simpsons.com",
"password1": "2short",
"password2": "2short",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "This password is too short." in content
assert "This password is too common." in content
@pytest.mark.django_db
def test_form_existing_email(client, joe_user):
"""If we submit the form with a email that already exists, we should
see an appropriate error messages.
"""
data = {
"first_name": "bart",
"last_name": "simpson",
"email": joe_user.email,
"password1": "Django123",
"password2": "Django123",
}
response = client.post(reverse("signup"), data=data, follow=True)
assert "signup.html" in [t.name for t in response.templates]
assert response.status_code == 200
content = response.content.decode("utf-8")
assert "Please fix the errors in the form below" in content
assert "User with this Email address already exists." in content
|
Python | UTF-8 | 2,535 | 3.8125 | 4 | [] | no_license | intento = 1
contrasena = 1234
acceso = False
diaSemanaSeleccionada = False
mSeleccionada = False
hSeleccionado = False
contrasennaAcceso = input("Ingrese la contraseña :")
def diaSemana():
return ['Lunes','Martes','Miercoles','Jueves','Viernes']
def materias():
return ['quimica','fisica','matematica','sociales']
def horario():
return ['vespertino','diurno','nocturno']
while contrasena != int(contrasennaAcceso):
contrasennaAcceso = input("Contrasena Incorrecota, ingrese nuevamente la contraseña :")
intento+=1
if intento == 3:
print("Lo sentimos ha intentado ingresar tres veces sin exito, espere 3 minutos para intentar volver a accesar")
break
if contrasena == int(contrasennaAcceso):
acceso = True
if acceso:
print("Bienvenido, a continuación se muestran las opciones disponibles para escoger sus materias y horarios")
print("Dias: ")
for i in diaSemana():
print(i,end=" ")
print('\n'+"Materias: ")
for j in materias():
print(j,end=" ")
print('\n'+"Horarios: ")
for k in horario():
print(k,end=" ")
diaSeleccionado =input('\n'+"Escriba uno de los dias de la semana expuesto: ")
while diaSemanaSeleccionada == False:
print("El dia seleccionado no se encuentra en la lista expuesta")
diaSeleccionado =input('\n'+"Escriba uno de los dias de la semana expuesto: ")
if diaSeleccionado in diaSemana():
diaSemanaSeleccionada = diaSeleccionado
print('\n'+"Día seleccionado " + diaSemanaSeleccionada)
materiaSeleccionada = input('\n'+"Escriba la materia que desea cursa del listado expuesto: ")
if materiaSeleccionada in materias():
mSeleccionada = materiaSeleccionada
while mSeleccionada == False:
print("La materia seleccionada no se encuentra en la lista expuesta")
materiaSeleccionada = input('\n'+"Escriba la materia que desea cursa del listado expuesto: ")
if materiaSeleccionada in materias():
mSeleccionada = materiaSeleccionada
print('\n'+"Materia seleccionada : " + mSeleccionada)
horarioSelecionado = input("Seleccione su horario del listado expuesto: ")
if horarioSelecionado in horario():
hSeleccionado = horarioSelecionado
while hSeleccionado == False:
print("El horario seleccionado no se encuentra en la lista expuesta")
horarioSelecionado = input("Seleccione su horario del listado expuesto: ")
if horarioSelecionado in horario():
hSeleccionado = horarioSelecionado
print('\n'+"Felicitaciones a seleccionado la materia : " + mSeleccionada + " los dias: " + diaSemanaSeleccionada + " en el horaio: " +hSeleccionado)
|
JavaScript | UTF-8 | 809 | 2.640625 | 3 | [
"MIT"
] | permissive |
var analyzer = require('../lib/analyzer');
var cases = [
[ 'value11', 'value21', 'class1' ],
[ 'value12', 'value22', 'class1' ],
[ 'value13', 'value21', 'class2' ],
[ 'value14', 'value22', 'class2' ],
[ 'value15', 'value23', 'class3' ]
];
exports['no frequencies'] = function (test) {
var freqs = analyzer.frequencies([], 2);
test.ok(freqs);
test.equal(typeof freqs, 'object');
test.equal(Object.keys(freqs).length, 0);
};
exports['cases frequencies'] = function (test) {
var freqs = analyzer.frequencies(cases, 2);
test.ok(freqs);
test.equal(typeof freqs, 'object');
test.equal(Object.keys(freqs).length, 3);
test.equal(freqs.class1, 2);
test.equal(freqs.class2, 2);
test.equal(freqs.class3, 1);
};
|
C++ | UTF-8 | 5,721 | 2.515625 | 3 | [] | no_license | #include "Headers.cpp"
/* 用例
#include <iostream>
signed main()
{
int n, m, s, t;
std::cin >> n >> m >> s >> t;
auto MMP = MCMF<LL>(n);
MMP.s = s;
MMP.t = t;
for (auto i : range(m))
{
int u, v;
LL flow, cost;
std::cin >> u >> v >> flow >> cost;
MMP.add(u, v, flow, cost);
}
MMP.Dinic();
std::cout << MMP.maxflow << ' ' << MMP.mincost << std::endl;
return 0;
}*/
/* 除非卡时不然别用的预流推进桶排序优化黑魔法,用例如下
signed main()
{
qr(HLPP::n);
// qr(HLPP::m);
qr(HLPP::src);
qr(HLPP::dst);
while (HLPP::m--)
{
LL t1, t2, t3;
qr(t1);
qr(t2);
qr(t3);
HLPP::add(t1, t2, t3);
}
cout << HLPP::hlpp(HLPP::n + 1, HLPP::src, HLPP::dst) << endl;
return 0;
}
*/
namespace HLPP
{
const LL INF = 0x3f3f3f3f3f3f;
const LL MXn = 1203;
const LL maxm = 520010;
vector<LL> gap;
LL n, src, dst, now_height, src_height;
struct NODEINFO
{
LL height = MXn, traffic;
LL getIndex();
NODEINFO(LL h = 0) : height(h) {}
bool operator<(const NODEINFO &a) const { return height < a.height; }
} node[MXn];
LL NODEINFO::getIndex() { return this - node; }
struct EDGEINFO
{
LL to;
LL flow;
LL opposite;
EDGEINFO(LL a, LL b, LL c) : to(a), flow(b), opposite(c) {}
};
std::list<NODEINFO *> dlist[MXn];
vector<std::list<NODEINFO *>::iterator> iter;
vector<NODEINFO *> list[MXn];
vector<EDGEINFO> edge[MXn];
inline void add(LL u, LL v, LL w = 0)
{
edge[u].push_back(EDGEINFO(v, w, (LL)edge[v].size()));
edge[v].push_back(EDGEINFO(u, 0, (LL)edge[u].size() - 1));
}
priority_queue<NODEINFO> PQ;
inline bool prework_bfs(NODEINFO &src, NODEINFO &dst, LL &n)
{
gap.assign(n, 0);
for (auto i = 0; i <= n; i++)
node[i].height = n;
dst.height = 0;
queue<NODEINFO *> q;
q.push(&dst);
while (!q.empty())
{
NODEINFO &top = *(q.front());
for (auto i : edge[&top - node])
{
if (node[i.to].height == n and edge[i.to][i.opposite].flow > 0)
{
gap[node[i.to].height = top.height + 1]++;
q.push(&node[i.to]);
}
}
q.pop();
}
return src.height == n;
}
inline void relabel(NODEINFO &src, NODEINFO &dst, LL &n)
{
prework_bfs(src, dst, n);
for (auto i = 0; i <= n; i++)
list[i].clear(), dlist[i].clear();
for (auto i = 0; i <= n; i++)
{
NODEINFO &u = node[i];
if (u.height < n)
{
iter[i] = dlist[u.height].insert(dlist[u.height].begin(), &u);
if (u.traffic > 0)
list[u.height].push_back(&u);
}
}
now_height = src_height = src.height;
}
inline bool push(NODEINFO &u, EDGEINFO &dst) // 从x到y尽可能推流,p是边的编号
{
NODEINFO &v = node[dst.to];
LL w = min(u.traffic, dst.flow);
dst.flow -= w;
edge[dst.to][dst.opposite].flow += w;
u.traffic -= w;
v.traffic += w;
if (v.traffic > 0 and v.traffic <= w)
list[v.height].push_back(&v);
return u.traffic;
}
inline void push(LL n, LL ui)
{
auto new_height = n;
NODEINFO &u = node[ui];
for (auto &i : edge[ui])
{
if (i.flow)
{
if (u.height == node[i.to].height + 1)
{
if (!push(u, i))
return;
}
else
new_height = min(new_height, node[i.to].height + 1); // 抬到正好流入下一个点
}
}
auto height = u.height;
if (gap[height] == 1)
{
for (auto i = height; i <= src_height; i++)
{
for (auto it : dlist[i])
{
gap[(*it).height]--;
(*it).height = n;
}
dlist[i].clear();
}
src_height = height - 1;
}
else
{
gap[height]--;
iter[ui] = dlist[height].erase(iter[ui]);
u.height = new_height;
if (new_height == n)
return;
gap[new_height]++;
iter[ui] = dlist[new_height].insert(dlist[new_height].begin(), &u);
src_height = max(src_height, now_height = new_height);
list[new_height].push_back(&u);
}
}
inline LL hlpp(LL n, LL s, LL t)
{
if (s == t)
return 0;
now_height = src_height = 0;
NODEINFO &src = node[s];
NODEINFO &dst = node[t];
iter.resize(n);
for (auto i = 0; i < n; i++)
if (i != s)
iter[i] = dlist[node[i].height].insert(dlist[node[i].height].begin(), &node[i]);
gap.assign(n, 0);
gap[0] = n - 1;
src.traffic = INF;
dst.traffic = -INF; // 上负是为了防止来自汇点的推流
for (auto &i : edge[s])
push(src, i);
src.traffic = 0;
relabel(src, dst, n);
for (LL ui; now_height >= 0;)
{
if (list[now_height].empty())
{
now_height--;
continue;
}
NODEINFO &u = *(list[now_height].back());
list[now_height].pop_back();
push(n, &u - node);
}
return dst.traffic + INF;
}
} |
JavaScript | UTF-8 | 542 | 4.1875 | 4 | [] | no_license | // 28. Implement strStr()
// Implement strStr().
// Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if(needle == '') return 0;
for(var i = 0 ; i < haystack.length - needle.length+1; i++){
if(haystack[i] == needle[0]) {
var tmp = haystack.substr(i,needle.length);
if(tmp == needle ) return i;
}
}
return -1;
}; |
Java | UTF-8 | 570 | 2.28125 | 2 | [] | no_license | package com.sda.thox.zdautpol1;
import org.junit.Before;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class My_First_JUnit_Test {
@BeforeEach
public void setUp() {
System.out.println("wykon przed kazdym test");
}
@AfterAll
public void setUp2(){
}
// beforeall aftereach
@Test
public void myTest1(){
System.out.println("wykon testu 1");
}
@Test
public void myTest2(){
System.out.println("wykon testu 2");
}
}
|
Java | UTF-8 | 1,210 | 3.328125 | 3 | [] | no_license | package repeticioRepte1;
import java.util.Scanner;
public class repeticioRepte1 {
public static void main (String [] args) {
/////////////////////////////////////////////////////////////
//Bloc de variables i subvariables pel tractament de dades//
///////////////////////////////////////////////////////////
boolean respostaOK = false;
lector = new Scanner(System.in);
//variable que conte la resposta de l'usuari
int car = 0;
//variable que conté el contador
int contador = 0;
////////////////////////////////////////
//Bloc de preguntes i gestió d'errors//
//////////////////////////////////////
//Pregunta a l'usuari quants caracters '-' vol que és repeteixi
System.out.println("Cuants càracters "-" vols que és mostri per pantalla? (1-100)");
respostaOK = lector.hasNextInt();
if (repostaOK) {
car = lector.nextInt();
lector.nextLine();
//fer un while, compara contador amb car, si és true continua el programa
while (car <= 100) {
System.out.print(-);
car = car + 1;
}
}
else {
System.out.println("Les dades introduides no són correctes");
}
}
}
|
Shell | UTF-8 | 893 | 3.671875 | 4 | [] | no_license | #!/bin/sh
GITHUB_KEY="${1:-$GITHUB_KEY}"
GITHUB_ORG="${2:-$GITHUB_ORG}"
if [[ -z "$GITHUB_KEY" || -z "$GITHUB_ORG" ]]; then
echo "GITHUB_KEY and GITHUB_ORG must be set"
exit 1
fi
curl -H "Authorization: Bearer $GITHUB_KEY" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/orgs/$GITHUB_ORG/members?per_page=100 > members.json
for username in $(jq -r '.[].login' members.json); do
home_dir="/home/$username"
random_password=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
# Users must have a password to login so set a secure random one
yes $random_password | adduser --shell /bin/false $username
mkdir $home_dir/.ssh
curl https://github.com/$username.keys 2> /dev/null > $home_dir/.ssh/authorized_keys
chmod 600 $home_dir/.ssh/authorized_keys
chmod 700 $home_dir/.ssh
chown -R $username:$username $home_dir/.ssh
done
|
C++ | UTF-8 | 814 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
int main(){
int n;
printf("Nhap ngay: ");
scanf("%d",&n);
int k;
printf("Nhap thang: ");
scanf("%d",&k);
int a;// ngay thu .. trong nam
switch(k){
case 1: a = n;break;
case 2: a = 31+n;break;
case 3: a = 31+28+n;break;
case 4: a = 31+28+31+n;break;
case 5: a = 31+28+31+30+n;break;
case 6: a = 31+28+31+30+31+n;break;
case 7: a = 31+28+31+30+31+30+n;break;
case 8: a = 31+28+31+30+31+30+31+n;break;
case 9: a = 31+28+31+30+31+30+31+31+n;break;
case 10: a = 31+28+31+30+31+30+31+31+30+n;break;
case 11: a = 31+28+31+30+31+30+31+31+30+31+n;break;
case 12: a = 31+28+31+30+31+30+31+31+30+31+30+n;break;
}
if(a%7==0){
printf(" %d/%d la chu nhat ngay %d",n,k,a);
}else{
int b=a%7+1;
printf(" %d/%d la thu %d ngay %d",n,k,b,a);
}
}
|
C++ | UTF-8 | 22,950 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <vector>
#include "classes/headers/Sistema.h"
#include "datatypes/headers/DtUsuario.h"
using namespace std;
//Encabezados de funciones auxiliares
void DatosTesteo();
bool DeseaContinuar(string msg);
void OpcionCrearReserva(DtUsuario* usuarioActual);
void OpcionVerInfoPelicula();
void OpcionPuntuarPelicula(DtUsuario* usuarioActual);
void OpcionComentarPelicula(DtUsuario* usuarioActual);
void OpcionVerComentariosyPuntajes();
void OpcionesAdministrativas();
void OpcionAltaCine();
void OpcionAltaPelicula();
void OpcionAltaFuncion();
void OpcionEliminarPelicula();
void OpcionVerReservas(DtUsuario* usuarioActual);
int main() {
ISistema* sistema = Sistema::getInstance();
DtUsuario* usuarioActual = NULL;
DatosTesteo();
while (true) {
int op;
//Menu Inicio de Sesion
cout << "\tBienvenido, por favor inicie sesion\n" << endl;
cout << "1 - Iniciar Sesion" << endl;
cout << "2 - Registrarse" << endl;
cout << "0 - Salir" << endl;
cin >> op;
try {
switch (op) {
case 0:
return 0;
break;
case 1: {
string user, pass;
cout << "Ingrese su nombre de usuario: ";
cin.ignore();
getline(cin, user);
cout << "Ingrese su contrasenia: ";
getline(cin, pass);
usuarioActual = sistema->iniciarSesion(user, pass);
cout << "\nHa iniciado sesion con exito" << endl;
break;
}
case 2: {
string user, img, pass;
cout << "Ingrese su nombre de usuario: ";
cin.ignore();
getline(cin, user);
cout << "Ingrese su contrasenia: ";
getline(cin, pass);
cout << "Agregue una imagen de perfil (URL): ";
getline(cin, img);
sistema->AltaUsuario(user, img, pass, false);
break;
}
default:
throw std::invalid_argument("La opcion ingresada no es valida");
}
}
catch (std::invalid_argument& e) {
cout << "\nError: " << e.what() << endl;
}
if (usuarioActual != NULL) //Prohibe la entrada sin iniciar sesion
{
while (op != 0) {
//Menu de opciones
cout << "\n\tMenu\n" << endl;
cout << "1 - Hacer una reserva" << endl;
cout << "2 - Ver la informacion de una pelicula" << endl;
cout << "3 - Puntuar una Pelicula" << endl;
cout << "4 - Comentar pelicula" << endl;
cout << "5 - Ver comentarios y puntajes" << endl;
cout << "6 - Ver mis reservas" << endl;
cout << "7 - Opciones Administrativas" << endl;
cout << "0 - Cerrar Sesion" << endl;
cin >> op;
//Switch de opciones
//Agregar posibles errores con stdexcept en cada case
try {
switch (op)
{
case 0:
usuarioActual = NULL;
break;
case 1:
OpcionCrearReserva(usuarioActual);
break;
case 2:
OpcionVerInfoPelicula();
break;
case 3:
OpcionPuntuarPelicula(usuarioActual);
break;
case 4:
OpcionComentarPelicula(usuarioActual);
break;
case 5:
OpcionVerComentariosyPuntajes();
break;
case 6:
OpcionVerReservas(usuarioActual);
break;
case 7:
if (usuarioActual->getAdmin()) OpcionesAdministrativas();
else {
cin.ignore();
throw std::invalid_argument("No tiene permitido el acceso");
}
break;
default:
throw std::invalid_argument("La opcion ingresada no es valida");
}
}
catch (std::invalid_argument& e) {
cout << "\nError: " << e.what() << endl;
}
if (op != 0) {
//cin.ignore();
cout << "\nPresione ENTER para continuar...";
cin.get();
cout << endl;
}
}
}
}
}
//Funciones auxiliares
void DatosTesteo() {
ISistema* s = Sistema::getInstance();
//Usuarios
s->AltaUsuario("admin", "www.perfiles.com/admin.jpg", "admin123", true);
s->AltaUsuario("user1", "www.perfiles.com/user1.jpg", "contra1", false);
s->AltaUsuario("user2", "www.perfiles.com/user2.jpg", "contra2", false);
s->AltaUsuario("user3", "www.perfiles.com/user3.jpg", "contra3", false);
//Peliculas
s->AltaPelicula("Avengers: Endgame", "www.posters.com/endgame.jpg", "Thanos 2");
s->AltaPelicula("Jhon Whick 1", "www.posters.com/jw1.jpg", "Primera entrega de la saga de Jhon Whick, tu asesino favorito");
s->AltaPelicula("Jhon Whick 2", "www.posters.com/jw2.jpg", "Segunda entrega de la saga de Jhon Whick, tu asesino favorito");
s->AltaPelicula("Jhon Whick 3", "www.posters.com/jw3.jpg", "Tercera entrega de la saga de Jhon Whick, tu asesino favorito");
//Puntajes
s->AltaPuntaje(5, "Avengers: Endgame", "user1");
s->AltaPuntaje(3, "Avengers: Endgame", "user2");
s->AltaPuntaje(4, "Avengers: Endgame", "user3");
s->AltaPuntaje(1, "Jhon Whick 3", "user1");
s->AltaPuntaje(5, "Jhon Whick 3", "admin");
s->AltaPuntaje(4, "Jhon Whick 3", "user1"); //Solo modifica no crea otra
s->AltaPuntaje(5, "Jhon Whick 3", "user3");
//Comentarios
vector<int> padresComentarios;
s->AltaComentario(padresComentarios, "10/10", "Avengers: Endgame", "user1");
s->AltaComentario(padresComentarios, "10/10 x2", "Avengers: Endgame", "user1");
s->AltaComentario(padresComentarios, "Yo hice la pusieran en el cine by El Admin", "Jhon Whick 3", "admin");
s->AltaComentario(padresComentarios, "Ni la vi", "Jhon Whick 3", "user2");
//Respuestas de comentarios
padresComentarios.push_back(1);
s->AltaComentario(padresComentarios, "Gracias admin", "Jhon Whick 3", "user1");
padresComentarios.push_back(1);
s->AltaComentario(padresComentarios, "Denada user1, me voy a asegurar este la 4", "Jhon Whick 3", "admin");
//Cines
s->AltaCine("Calle 1 Nro. 1");
s->AltaCine("Calle 2 Nro. 2");
s->AltaCine("Calle 3 Nro. 3");
//Salas
s->AltaSala(1, 100);
s->AltaSala(1, 150);
s->AltaSala(1, 50);
s->AltaSala(2, 100);
s->AltaSala(2, 100);
s->AltaSala(3, 200);
//Funciones que no deberian verse
s->AltaFuncion("Avengers: Endgame", "2019/06/10 18:30:00", 1, 1);
s->AltaFuncion("Jhon Whick 1", "2019/06/12 18:30:00", 2, 1);
s->AltaFuncion("Jhon Whick 2", "2019/06/12 20:30:00", 2, 2);
s->AltaFuncion("Jhon Whick 3", "2019/06/12 22:30:00", 2, 1);
//Funciones que deberian verse
s->AltaFuncion("Avengers: Endgame", "2019/07/12 19:30:00", 1, 1);
s->AltaFuncion("Jhon Whick 1", "2019/07/10 18:30:00", 1, 3);
s->AltaFuncion("Jhon Whick 2", "2019/07/10 20:30:00", 2, 2);
s->AltaFuncion("Jhon Whick 3", "2019/07/10 22:30:00", 3, 1);
s->AltaFuncion("Jhon Whick 3", "2019/07/11 19:30:00", 1, 3);
//Reservas
s->CrearReserva(4, (float) 959.97, "Jhon Whick 1", 1, "admin", "", "Bacacay", 20); //El admin es re fan de Jhon Whick
s->CrearReserva(4, (float) 959.97, "Jhon Whick 2", 1, "admin", "", "Bacacay", 20);
s->CrearReserva(4, (float) 959.97, "Jhon Whick 3", 1, "admin", "", "Bacacay", 20);
}
bool DeseaContinuar(string msg) {
string elegir;
while (true) {
cout << endl;
cout << msg;
cin >> elegir;
cout << endl;
if (elegir == "Si" || elegir == "si") {
//El usuario continuara con lo que sea este despues de esta funcion
return true;
}
else {
if (elegir == "No" || elegir == "no") {
//El usuario saldra de la operacion actual
//cout << "Se cancela la operacion" << endl;
return false;
}
else {
//El usuario seguira en el loop hasta dar una opcion valida
cout << "Error: La opcion ingresada no es valida" << endl;
}
}
}
}
void OpcionCrearReserva(DtUsuario* usuarioActual) {
ISistema* sistema = Sistema::getInstance(); //Obtengo la instancia de Sistema
string titulo, elegir, banco = "", financiera = "";
int cantAsientos, idFuncion, idCine;
float costo;
float descuento = 0;
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = sistema->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
if (DeseaContinuar("Continuar con la reserva? (Si/No): ") == false) return;
cout << "Ingrese el titulo de la pelicula que desee: ";
cin.ignore();
getline(cin, titulo);
sistema->VerInfoPelicula(titulo);
if (DeseaContinuar("Desea ver informacion adicional? (Si/No): ") == false) return;
cout << "\n\tCines" << endl << endl;
ICollection* c = sistema->ListarCinesPorTitulo(titulo);
it = c->getIterator();
if (c->isEmpty()) throw invalid_argument("No hay cines que den esta pelicula");
while (it->hasCurrent()) {
DtCine* c = dynamic_cast<DtCine*>(it->getCurrent());
cout << "Cine " + std::to_string(c->getIdCine()) << endl;
cout << "Direccion: "+c->getDireccion() << endl;
it->next();
}
if (DeseaContinuar("Desea elegir un cine? (Si/No): ") == false) return;
cout << "Ingrese el numero del cine que desee: ";
cin >> idCine;
cout << "\n\tFunciones" << endl << endl;
ICollection* f = sistema->ListarFunciones(idCine, titulo);
it = f->getIterator();
if (f->isEmpty()) throw std::invalid_argument("No hay funciones para esta pelicula actualmente");
while (it->hasCurrent()) {
DtFuncion* f = dynamic_cast<DtFuncion*>(it->getCurrent());
cout << "Funcion " + std::to_string(f->getIdFuncion()) << endl;
time_t h = f->getHorario();
cout << "Horario :" << ctime(&h) << endl;
it->next();
}
if (DeseaContinuar("Desea elegir una funcion? (Si/No): ") == false) return;
cout << "Elija una funcion: ";
cin >> idFuncion;
cout << "\nIngrese la cantidad de asientos que desea reservar: ";
cin >> cantAsientos;
do {
cout << "\nElija su tipo de pago (Debito/Credito): ";
cin.ignore();
getline(cin, elegir);
if (elegir == "Debito") {
cout << "Ingrese su banco: ";
getline(cin, banco);
}
else {
if (elegir == "Credito") {
cout << "Ingrese su financiera: ";
getline(cin, financiera);
descuento = (float) sistema->ObtenerDescuentoFinanciera(financiera);
if (descuento != 0) cout << "\nDescuento por financiera: " << std::to_string(descuento*100) << "%" << endl;
}
else cout << "Error: La opcion ingresada no es valida";
}
}
while (elegir != "Debito" && elegir != "Credito");
costo = (float) ((cantAsientos * 299.99) * (1 - descuento));
cout << "Usted pagara: " << std::to_string(costo) << endl;
if (DeseaContinuar("Continuar con la reserva? (Si/No): ") == false) return;
sistema->CrearReserva(cantAsientos, costo, titulo, idFuncion, usuarioActual->getNickName(), banco, financiera, descuento);
cout << "La reserva se ha realizado con exito" << endl;
cin.ignore();
}
void OpcionVerInfoPelicula()
{
ISistema* sistema = Sistema::getInstance();
string titulo;
int idCine;
bool seguir = true;
while (seguir) {
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = sistema->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
if (DeseaContinuar("Desea seleccionar una pelicula? (Si/No): ") == false) return;
cout << "Ingrese el titulo de la pelicula que desee: ";
cin.ignore();
getline(cin, titulo);
sistema->VerInfoPelicula(titulo);
if (DeseaContinuar("Desea ver informacion adicional? (Si/No): ") == false) return;
cout << "\n\tCines" << endl << endl;
ICollection* c = sistema->ListarCinesPorTitulo(titulo);
it = c->getIterator();
if (c->isEmpty()) cout << "No hay cines que den esta pelicula" << endl;
else {
while (it->hasCurrent()) {
DtCine* c = dynamic_cast<DtCine*>(it->getCurrent());
cout << "Cine " + std::to_string(c->getIdCine()) << endl;
cout << "Direccion :" + c->getDireccion() << endl;
it->next();
}
if (DeseaContinuar("Desea elegir un cine? (Si/No): ") == false) return;
cout << "Ingrese el numero del cine que desee: ";
cin >> idCine;
cout << "\n\tFunciones" << endl << endl;
ICollection* f = sistema->ListarFunciones(idCine, titulo);
it = f->getIterator();
if (f->isEmpty()) cout << "Actualmente no hay funciones en este cine para esta pelicula" << endl;
while (it->hasCurrent()) {
DtFuncion* f = dynamic_cast<DtFuncion*>(it->getCurrent());
cout << "Funcion " + std::to_string(f->getIdFuncion()) << endl;
time_t h = f->getHorario();
cout << "Horario :" << ctime(&h) << endl;
it->next();
}
}
seguir = DeseaContinuar("Desea ver informacion de otra pelicula? (Si/No): ");
cin.ignore();
}
}
void OpcionPuntuarPelicula(DtUsuario* usuarioActual) {
ISistema* sistema = Sistema::getInstance();
string _nombre;
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = sistema->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
if (DeseaContinuar("Desea seleccionar una pelicula? (Si/No): ") == false) return;
cout << "\nIngrese el nombre de pelicula: " << endl;
cin.ignore();
getline(cin, _nombre);
int puntajeAnterior = sistema->YaPuntuo(_nombre, usuarioActual->getNickName());
int _puntuacion;
if (puntajeAnterior == 0) {
cout << "Puntuacion Anterior: " << std::to_string(puntajeAnterior) << endl << endl;
cout << "Desea modificarla? (Si/No): ";
string elegir;
bool seguir = true;
while (seguir) {
cin >> elegir;
if (elegir == "Si" || elegir == "si") {
seguir = false;
}
else {
if (elegir == "No" || elegir == "no") {
cout << "Se cancela la operacion" << endl;
return;
}
else {
cout << "Error: La opcion ingresada no es valida" << endl;
}
}
}
}
cout << "Puntuacion (1/5): " << endl;
cin >> _puntuacion;
if (_puntuacion < 1 || _puntuacion > 5) throw std::invalid_argument("Puntuacion incorrecta.");
sistema->AltaPuntaje(_puntuacion, _nombre, usuarioActual->getNickName());
}
void OpcionComentarPelicula(DtUsuario* usuarioActual)
{
ISistema* sistema = Sistema::getInstance();
string _nombre;
string _comentario;
vector<int> padres;
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = sistema->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
cout << "\nIngrese el nombre de una pelicula: ";
cin.ignore();
getline(cin, _nombre);
//Listar comentarios de la pelicula
sistema->ListarComentarios(_nombre);
while (DeseaContinuar("Desea ingresar un comentario? (Si/No): "))
{
if(DeseaContinuar("Desea comentar un comentario ya existente? (Si/No): ")) {
int id_comentario;
bool seguir = true;
while (seguir) {
cout << "Ingrese la id del comentario que desea responder \n(Si es respuesta de otro, ingrese primero la id de ese): ";
cin >> id_comentario;
padres.push_back(id_comentario);
seguir = DeseaContinuar("Desea ingresar otra id (Si/No): ");
}
cout << "Ingrese su comentario: ";
cin.ignore();
getline(cin, _comentario);
}
else {
cout << "Ingrese su comentario: ";
cin.ignore();
getline(cin, _comentario);
}
sistema->AltaComentario(padres, _comentario, _nombre, usuarioActual->getNickName());
cout << "\nComentario guardado" << endl;
}
cin.ignore(); //Para evitar que el enter del while salte la pausa del main
}
void OpcionVerComentariosyPuntajes()
{
ISistema* sistema = Sistema::getInstance(); //Obtengo la instancia de Sistema
string titulo;
//Lista Films
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = sistema->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
//Selecciona Films
cout << "\nIngrese el titulo de la pelicula que desee: ";
cin.ignore();
getline(cin, titulo);
sistema->VerInfoPelicula(titulo);
cout << endl;
sistema->VerComentariosyPuntajes(titulo);
}
void OpcionesAdministrativas() {
ISistema* s = Sistema::getInstance();
int op = -1;
while (op != 0) {
//Menu Admin.
cout << "\n\tMenu de Administracion\n" << endl;
cout << "1 - Alta Cine" << endl;
cout << "2 - Alta Pelicula" << endl;
cout << "3 - Alta Funcion" << endl;
cout << "4 - Eliminar Pelicula" << endl;
cout << "0 - Volver al menu anterior" << endl;
cin >> op;
switch (op) {
case 0:
break;
case 1:
OpcionAltaCine();
break;
case 2:
OpcionAltaPelicula();
break;
case 3:
OpcionAltaFuncion();
break;
case 4:
OpcionEliminarPelicula();
break;
default:
throw std::invalid_argument("La opcion ingresada no es valida");
}
if (op != 0) {
//cin.ignore();
cout << "\nPresione ENTER para continuar...";
cin.get();
cout << endl;
}
}
}
void OpcionAltaCine() {
ISistema* s = Sistema::getInstance();
string dir;
int cantaux, idCine;
vector<int> cantAsientos;
cout << "Ingrese la direccion del cine: ";
cin.ignore();
getline(cin, dir);
while (DeseaContinuar("Desea ingresar una sala? (Si/No): ")) {
cout << "Ingrese la capacidad de la sala: ";
cin >> cantaux;
cantAsientos.push_back(cantaux);
}
if (DeseaContinuar("Desea completar la operacion? (Si/No): ") == false) return;
s->AltaCine(dir);
idCine = s->DarUltimoCine();
for (auto i = cantAsientos.begin(); i != cantAsientos.end(); i++) {
s->AltaSala(idCine, *i);
}
cin.ignore();
}
void OpcionAltaPelicula()
{
ISistema* s = Sistema::getInstance();
string titulo, img, sinopsis;
cout << "Ingrese el titulo: ";
cin.ignore();
getline(cin, titulo);
cout << "Ingrese el url del poster: ";
getline(cin, img);
cout << "Ingrese la sinopsis: ";
getline(cin, sinopsis);
s->AltaPelicula(titulo, img, sinopsis);
}
void OpcionAltaFuncion(){
ISistema* sistema = Sistema::getInstance(); //Obtengo la instancia de Sistema
string titulo, fechaFun;
vector<int> SalasOcupadas;
bool deseaIngresar = true;
while (deseaIngresar) {
//Lista Films
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = sistema->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
//Selecciona Films
cout << "\nIngrese el titulo de la pelicula que desee: ";
cin.ignore();
getline(cin, titulo);
//Listar Cines
cout << "\n\tCines" << endl << endl;
ICollection* c = sistema->ListarCines();
it = c->getIterator();
while (it->hasCurrent()) {
DtCine* c = dynamic_cast<DtCine*>(it->getCurrent());
cout << "Cine " + std::to_string(c->getIdCine()) << endl;
cout << "Direccion :"+c->getDireccion() << endl;
it->next();
}
//Selecciona Cine
int idCine;
cout << "\nIngrese el numero del cine que desee: ";
cin >> idCine;
cout << "Ingrese Fecha y hora de la funcion (Ej: 2019/05/18 13:10:00): ";
cin.ignore();
getline(cin, fechaFun);
//Conversion de string a time_t
time_t horario;
int yy, month, dd, hh, mm, ss;
struct tm horariotm = { 0 };
sscanf(fechaFun.c_str(), "%d/%d/%d %d:%d:%d", &yy, &month, &dd, &hh, &mm, &ss);
horariotm.tm_year = yy - 1900;
horariotm.tm_mon = month - 1;
horariotm.tm_mday = dd;
horariotm.tm_hour = hh;
horariotm.tm_min = mm;
horariotm.tm_sec = ss;
horariotm.tm_isdst = -1;
horario = mktime(&horariotm);
//
//Lista Salas - Mostrar Ocupadas y Disponibles
//Voy por todas las pelis
t = sistema->ListarTitulos();
it = t->getIterator();
while (it->hasCurrent()) {
//Voy por todas las funciones de todas las pelis de el cine seleccionado por el user
ICollection* f = sistema->ListarFunciones(idCine, dynamic_cast<KeyString*>(it->getCurrent())->getValue());
IIterator* it2 = f->getIterator();
while (it2->hasCurrent()) {
DtFuncion* f = dynamic_cast<DtFuncion*>(it2->getCurrent());
time_t h = f->getHorario();
//Me fijo si dicha funcion + 3 horas esta en el rango de la hora y fecha que el user puso
//No me salio ese if xD
double DiffSeconds = difftime(horario, h);
if (DiffSeconds < 10800) {
//En el caso de ser asi, es porque esta ocupada esa sala entonces la pusheo dentro del vector dinamico
SalasOcupadas.push_back(f->getIdSala()); //Crear getIdSala
}
it2->next();
}
it->next();
}
//Mostramos las salas
cout << "\n\tSalas" << endl << endl;
ICollection* s = sistema->ListarSalas(idCine);
it = s->getIterator();
while (it->hasCurrent()) {
DtSala* s = dynamic_cast<DtSala*>(it->getCurrent());
cout << "Sala " + std::to_string(s->getIdSala()) << endl;
cout << "Cantidad de asientos: " + std::to_string(s->getCantAsientos()) << endl;
//Comparamos si esta en la lista de no disponibles para este cine a esa hora
if (find(SalasOcupadas.begin(), SalasOcupadas.end(), s->getIdSala()) != SalasOcupadas.end()) {
cout << "Ocupada" << endl;
}
else {
cout << "Disponible" << endl;
}
it->next();
}
//Selecionar Sala
int idSala;
bool existeSala = false;
cout << "\nIngrese el numero de sala que desee: ";
cin >> idSala;
//Ahora veremos si esta ocupada o no
if (std::find(SalasOcupadas.begin(), SalasOcupadas.end(), idSala) != SalasOcupadas.end()) {
cout << "Esta seleccionando una sala que esta ocupada" << endl;
}
else {
//Todo bien, hagamos el alta.
sistema->AltaFuncion(titulo, fechaFun, idCine, idSala);
}
deseaIngresar = DeseaContinuar("Desea ingresar otra funcion para esta pelicula? (Si/No): ");
}
cin.ignore();
}
void OpcionEliminarPelicula()
{
ISistema* s = Sistema::getInstance();
string titulo;
cout << "\n\tCatalogo de Peliculas" << endl << endl;
ICollection* t = s->ListarTitulos();
IIterator* it = t->getIterator();
while (it->hasCurrent()) {
cout << dynamic_cast<KeyString*>(it->getCurrent())->getValue() << endl;
it->next();
}
cout << "Ingrese el titulo de la pelicula a eliminar: ";
cin.ignore();
getline(cin, titulo);
if (!DeseaContinuar("Enserio desea eliminar dicha pelicula? (Si/No): ")) return;
s->EliminarPelicula(titulo);
cout << "La pelicula " << titulo << " ha sido eliminada" << endl;
}
void OpcionVerReservas(DtUsuario* usuarioActual)
{
ISistema* sistema = Sistema::getInstance();
cout << "\tReservas" << endl << endl;
sistema->VerReservasPorUsuario(usuarioActual->getNickName());
cin.ignore();
}
|
Python | UTF-8 | 1,180 | 3.484375 | 3 | [] | no_license | import string
STOP_WORDS = [
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were',
'will', 'with'
]
def print_word_freq(file):
"""Read in `file` and print out the frequency of words in that file."""
with open(file) as file:
lines = ' '.join(file.readlines())
print(lines)
l_words = lines.lower()
words = l_words.split(' ')
just_words = [s.translate(string.punctuation) for s in words]
word_count = {}
for word in just_words:
x = l_words.count(word)
y = word
# if y in word_count == False:
word_count[word] = x + 1
print(word_count.items())
if __name__ == "__main__":
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(
description='Get the word frequency in a text file.')
parser.add_argument('file', help='file to read')
args = parser.parse_args()
file = Path(args.file)
if file.is_file():
print_word_freq(file)
else:
print(f"{file} does not exist!")
exit(1)
|
Java | UTF-8 | 511 | 2.0625 | 2 | [] | no_license | package com.study.orderproducer.controller;
import com.study.orderproducer.producer.OrderProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController {
@Autowired
private OrderProducer orderProducer;
@RequestMapping("/sendOrder")
public String sendOrder() {
return orderProducer.sendOrder();
}
}
|
Shell | UTF-8 | 653 | 2.984375 | 3 | [] | no_license | #!/bin/bash
set -exuo pipefail
MY_DIR=$(dirname "${BASH_SOURCE[0]}")
source $MY_DIR/build-common.sh
filename=$(echo "$package" | tr '-' '_')
source /io/preinstall-rust.sh
# Compile wheels
for PYBIN in /opt/python/*/bin; do
"${PYBIN}/pip" download --no-binary="$package" "$package==$version"
"${PYBIN}/pip" wheel "$package-$version.tar.gz" -w /io/wheelhouse/
done
mv /io/wheelhouse/$filename-$version-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl /io/wheelhouse/$filename-$version-nogil39-nogil_39_x86_64_linux_gnu-linux_x86_64.whl
repair_wheel /io/wheelhouse/$filename-$version-nogil39-nogil_39_x86_64_linux_gnu-linux_x86_64.whl
|
C | UTF-8 | 658 | 3.84375 | 4 | [] | no_license | /* Programma per il calcolo del numero di giorni a partire da un numero di ore */
/* #define _CRT_SECURE_NO_WARNINGS */ /* Utilizzare questa direttiva se non si vuole utilizzare la scanf_s */
#include <stdio.h>
int main()
{
int oreTotali; /*Primo numero*/
int giorni; /*Secondo numero*/
int oreResidue; /*Variabile per contenere il prodotto*/
printf("Inserire il numero di ore: ");
scanf_s("%d", &oreTotali);
giorni = oreTotali / 24;
oreResidue = oreTotali % 24;
printf("Numero totale di ore inserite: %d\n\n", oreTotali);
printf("Numero di giorni corrispondenti: %d\n", giorni);
printf("Numero di ore residue: %d\n", oreResidue);
return 0;
} |
Swift | UTF-8 | 12,405 | 2.765625 | 3 | [] | no_license | //
// AppDelegate.swift
// MVVMCSample
//
// Created by Ranjeet Singh on 20/05/20.
// Copyright © 2020 Ranjeet Singh. All rights reserved.
//
import UIKit
extension String {
subscript(i: Int) -> String {
return String(self[index(startIndex, offsetBy: i)])
}
subscript(i: Range<UInt>) -> String {
let lower = Int(i.lowerBound)
let upper = Int(i.upperBound)
let sIndex = lower > self.count ? self.endIndex : index(startIndex, offsetBy: lower)
let eIndex = upper > count ? self.endIndex : index(startIndex, offsetBy: upper)
return String(self[sIndex..<eIndex])
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
debugPrint("Text"[2..<3])
// let a = [5, 5, 5, 5, 5]
// debugPrint("first dublicate \(firstDuplicate(a: a))")
// // Override point for customization after application launch.
//
// let arr = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
// debugPrint(arr)
// debugPrint(rotateImage(a: arr))
// debugPrint(checkPalindrome(inputString: "hlbeeykoqqqqokyeeblh"))
//
//
// let romanNumber = "XLX" // 2015
let romanNumber = "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMCDLXXVI" // 53476
// let romanNumber = "MMMMDCCCLXXXVIII"
let grid: [[Character]] =
[[".",".",".","2",".",".","6",".","."],
[".",".",".","1",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".","5",".","1",".",".","8"],
[".","3",".",".",".",".",".",".","."],
[".",".",".","9",".",".",".",".","3"],
["4",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".","3","8","."],
[".",".",".",".",".",".",".",".","4"]]
debugPrint("sudexo = \(sudoku2(grid: grid))")
debugPrint(integerValueOfRomanNumeral(s: romanNumber))
//
// let crypt =
// ["TEN",
// "TWO",
// "ONE"]
// let solution: [[Character]] =
// [["O","1"],
// ["T","0"],
// ["W","9"],
// ["E","5"],
// ["N","4"]]
let crypt =
["AA",
"AA",
"AA"]
let solution: [[Character]] = [["A","0"]]
debugPrint("Crypto = \(isCryptSolution(crypt: crypt, solution: solution))")
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func firstDuplicate(a: [Int]) -> Int {
var dict = [Int:Int]()
for (i,v) in a.enumerated() {
if let x = dict[v] {
if x == -1 {
dict[v] = i
}
} else {
dict[v] = -1
}
}
var myKey = -1
var repetedValue = Int.max
for (key, value) in dict {
if value == -1 {
continue
} else {
if repetedValue > value {
repetedValue = value
myKey = key
}
}
debugPrint(key, value)
}
return myKey
}
func firstNotRepeatingCharacter(s: String) -> Character {
var nonRepeatingChar: Character = "_"
var dict = [Character: Int]()
for ch in s {
if let count = dict[ch] {
dict[ch] = count + 1
} else {
dict[ch] = 1
}
}
for ch in s {
if dict[ch] == 1 {
nonRepeatingChar = ch
break
}
}
return nonRepeatingChar
}
func rotateImage(a: [[Int]]) -> [[Int]] {
var a = a
var i = 0
var j = 0
let c = a.count
for _ in i..<c {
j = i
for _ in j..<c {
let temp = a[i][j]
a[i][j] = a[j][i]
a[j][i] = temp
j += 1
}
i += 1
}
i = 0
for _ in i..<c {
j = 0
for _ in j..<c/2 {
let temp = a[i][j]
a[i][j] = a[i][c - 1 - j]
a[i][c-1-j] = temp
j += 1
}
i += 1
}
return a
}
func checkPalindrome(inputString: String) -> Bool {
let inputString = inputString.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if inputString.isEmpty {
return false
}
guard inputString.count >= 2 else {
return true
}
let count = inputString.count
let firstHalfIndex = inputString.index(inputString.startIndex, offsetBy: count/2)
let firstSubStr = String(inputString[..<firstHalfIndex])
var index = count/2 + (count % 2 == 0 ? 0 : 1)
let lastHalfIndex = inputString.index(inputString.startIndex, offsetBy: index)
let lastSubStr = String(inputString[lastHalfIndex..<inputString.endIndex].reversed())
return firstSubStr == lastSubStr
while (index < count/2) {
let firstChar = inputString[index]
let lastChar = inputString[count - 1 - index]
if firstChar != lastChar {
return false
}
index += 1
}
return true
}
}
enum RomanNumber: String {
case I, V, X, L, C, D, M, none
var intValue: Int {
switch self {
case .I: return 1
case .V: return 5
case .X: return 10
case .L: return 50
case .C: return 100
case .D: return 500
case .M: return 1000
case .none: return -1
}
}
}
func validation(number: RomanNumber, pv1: RomanNumber, pv2: RomanNumber, pv3: RomanNumber) -> Bool {
if pv1 == pv2, pv2 == pv3, pv3 == .none {
return true
}
else if pv1 == pv2, pv2 == pv3, pv3 == number, number != .M {
return false
} else if pv1.intValue < number.intValue, pv2 != .none, pv2.intValue < number.intValue {
return false
} else if (pv1 == .V) || (pv1 == .L) || (pv1 == .D), pv1.intValue < number.intValue {
return false
} else if (pv1 == .V) || (pv1 == .L) || (pv1 == .D), pv1 == number {
return false
} else if pv2 != .none, pv1 != pv2, pv2 == number, !((pv1 == .I) || (pv1 == .X) || (pv1 == .C) || (pv1 == .M)) {
return false
} else {
return true
}
}
func integerValueOfRomanNumeral(s: String) -> Int {
var sum = 0
var previousNum1: RomanNumber = .none
var previousNum2: RomanNumber = .none
var previousNum3: RomanNumber = .none
let s = s.uppercased()
for ch in s {
let str = String(ch)
guard let romanNumber = RomanNumber(rawValue: str) else { return -1}
if validation(number: romanNumber, pv1: previousNum1, pv2: previousNum2, pv3: previousNum3) {
let number = romanNumber.intValue
if previousNum1 != .none, number > previousNum1.intValue {
sum -= (previousNum1.intValue * 2)
}
sum += number
previousNum3 = previousNum2
previousNum2 = previousNum1
previousNum1 = romanNumber
} else {
return -1
}
}
return sum
}
/*
var a: [[Character]] = [[".", ".", ".", ".", "2", ".", ".", "9", "."],
[".", ".", ".", ".", "6", ".", ".", ".", "."],
["7", "1", ".", ".", "7", "5", ".", ".", "."],
[".", "7", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", "8", "3", ".", ".", "."],
[".", ".", "8", ".", ".", "7", ".", "6", "."],
[".", ".", ".", ".", ".", "2", ".", ".", "."],
[".", "1", ".", "2", ".", ".", ".", ".", "."],
[".", "2", ".", ".", "3", ".", ".", ".", "."]]
[[".",".",".","2",".",".","6",".","."],
[".",".",".","1",".",".",".",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".","5",".","1",".",".","8"],
[".","3",".",".",".",".",".",".","."],
[".",".",".","9",".",".",".",".","3"],
["4",".",".",".",".",".",".",".","."],
[".",".",".",".",".",".","3","8","."],
[".",".",".",".",".",".",".",".","4"]]
*/
func sudoku2(grid: [[Character]]) -> Bool {
//check for each colom
for i in 0..<grid.count {
var charDict: [Character: Bool] = ["1": false, "2": false, "3": false,
"4": false, "5": false, "6": false,
"7": false, "8": false, "9": false]
for j in 0..<grid.count {
let ch: Character = grid[i][j]
if ch == "." {
continue
} else {
if charDict[ch] == false {
charDict[ch] = true
} else {
return false
}
}
}
}
//check for each row
for i in 0..<grid.count {
var charDict: [Character: Bool] = ["1": false, "2": false, "3": false,
"4": false, "5": false, "6": false,
"7": false, "8": false, "9": false]
for j in 0..<grid.count {
let ch: Character = grid[j][i]
if ch == "." {
continue
} else {
if charDict[ch] == false {
charDict[ch] = true
} else {
return false
}
}
}
}
//Check for each 3X3 matrix
var i = 0
while i < grid.count {
var j = 0
while j < grid.count {
var charDict: [Character: Bool] = ["1": false, "2": false, "3": false,
"4": false, "5": false, "6": false,
"7": false, "8": false, "9": false]
for k in 0..<3 {
let arr = grid[i+k]
for l in 0..<3 {
let ch: Character = arr[j+l]
if ch == "." {
continue
} else {
if charDict[ch] == false {
charDict[ch] = true
} else {
return false
}
}
}
}
j += 3
}
i += 3
}
return true
}
func isCryptSolution(crypt: [String], solution: [[Character]]) -> Bool {
var solutionDict = [Character: String]()
for mapArray in solution {
guard let char = mapArray.first, let num = mapArray.last else { return false }
solutionDict[char] = String(num)
}
var numbers = [String]()
for word in crypt {
var numStr = ""
for ch in word {
guard let number = solutionDict[ch] else { return false }
numStr += number
}
numbers.append(numStr)
}
var sum: UInt64 = 0
for i in 0..<numbers.count - 1 {
let number = numbers[i]
if number.count > 1, number[0] == "0" {
return false
}
guard let num = UInt64(number) else { return false }
sum += num
}
guard let lastValue = numbers.last, let total = UInt64(lastValue) else { return false }
return sum == total
}
|
Java | UTF-8 | 722 | 2.5 | 2 | [
"MIT"
] | permissive | package com.himank.activitiwithspring.servicetasks;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
public class SendEmailServiceTask implements JavaDelegate {
public void execute(DelegateExecution execution) {
//logic to sent email confirmation
System.out.println("sent email To :-> "+ execution.getVariable("employeeName")+ "\n subject :-> "+
" Vacation Leave Approved \n body :-> Hello "+ execution.getVariable("employeeName")
+"!! Your "+ execution.getVariable("numberOfDays") + " days vacation leave is approved !!"
+ " Manager's Comment :-> "+execution.getVariable("comments"));
}
}
|
Python | UTF-8 | 2,574 | 2.609375 | 3 | [] | no_license | import wget
import os
import zipfile
import shutil
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(CURRENT_DIR)
class DataLoader:
original_ud = 'https://github.com/olexandryermilov/ukrdata/raw/master/original_embedding_original_ud.zip'
fast_text = 'https://github.com/olexandryermilov/ukrdata/raw/master/fasttext_embedding_augmented_ud.zip'
glove = 'https://github.com/olexandryermilov/ukrdata/raw/master/glove_embedding_augmented_ud.zip'
def __load(self):
print('Beginning to download models')
os.mkdir(f'{ROOT_DIR}/models')
print("Downloading original_ud")
wget.download(self.original_ud, f'{ROOT_DIR}/models/')
print("\nDownloading fast_text")
wget.download(self.fast_text, f'{ROOT_DIR}/models/')
print("\nDownloading glove")
wget.download(self.glove, f'{ROOT_DIR}/models/')
print("\nModels have been downloaded.")
def __extract(self):
print("\nExtracting data")
try:
with zipfile.ZipFile(f'{ROOT_DIR}/models/original_embedding_original_ud.zip', 'r') as zip_ref:
zip_ref.extractall(f'{ROOT_DIR}/models/')
with zipfile.ZipFile(f'{ROOT_DIR}/models/fasttext_embedding_augmented_ud.zip', 'r') as zip_ref:
zip_ref.extractall(f'{ROOT_DIR}/models/')
with zipfile.ZipFile(f'{ROOT_DIR}/models/glove_embedding_augmented_ud.zip', 'r') as zip_ref:
zip_ref.extractall(f'{ROOT_DIR}/models/')
except:
pass
print('\nRemoving unnecessary files')
try:
shutil.rmtree(f'{ROOT_DIR}/models/__MACOSX')
except:
pass
try:
os.remove(f'{ROOT_DIR}/models/original_embedding_original_ud.zip')
os.remove(f'{ROOT_DIR}/models/fasttext_embedding_augmented_ud.zip')
os.remove(f'{ROOT_DIR}/models/glove_embedding_augmented_ud.zip')
except:
pass
try:
os.rename(f'{ROOT_DIR}/models/glove_embedding_augmented_ud', f'{ROOT_DIR}/models/glove')
os.rename(f'{ROOT_DIR}/models/model', f'{ROOT_DIR}/models/fast-text')
os.rename(f'{ROOT_DIR}/models/original_embedding_original_ud', f'{ROOT_DIR}/models/original')
except:
pass
def init_data(self):
if os.path.isdir(f'{ROOT_DIR}/models'):
return
self.__load()
self.__extract()
if __name__ == "__main__":
data_loader = DataLoader()
data_loader.init_data()
|
Shell | UTF-8 | 151 | 2.53125 | 3 | [] | no_license | #!/bin/bash
IMG=`find /extra/Photos -iname "*jpg" -type f | shuf -n 1`
convert "$IMG" -auto-orient /tmp/bg.jpg
DISPLAY=:0 feh --bg-fill /tmp/bg.jpg
|
Java | UTF-8 | 2,700 | 2.015625 | 2 | [] | no_license | package com.mashreq.app.viewmodel;
import android.content.Context;
import android.util.Log;
import android.view.View;
import androidx.hilt.lifecycle.ViewModelInject;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.JsonObject;
import com.mashreq.app.R;
import com.mashreq.app.RealTimeActions.ISignUpServices;
import com.mashreq.app.model.modeldb.Signup.SignUpModel;
import com.mashreq.app.network.Constanturl;
import com.mashreq.app.network.RetrofitInterfaces;
import com.mashreq.app.repository.Repository;
import com.valdesekamdem.library.mdtoast.MDToast;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SignUpViewModel extends ViewModel {
MutableLiveData<SignUpModel>signUpModelMutableLiveData=new MutableLiveData<>();
private Repository repository;
@ViewModelInject
public SignUpViewModel(Repository repository) {
this.repository = repository;
}
public MutableLiveData<SignUpModel> getSignUpModelMutableLiveData() {
return signUpModelMutableLiveData;
}
ISignUpServices iSignUpServices;
public void getResponse(String username, String email, String password, String mobile,String firebaseToken,
Context ctx
,SpinKitView spinKitView){
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("name",username);
jsonObject.addProperty("email",email);
jsonObject.addProperty("password",password);
jsonObject.addProperty("mobile",mobile);
jsonObject.addProperty("fire_base",firebaseToken);
iSignUpServices=(ISignUpServices)ctx;
repository.signUp(jsonObject).subscribeOn(Schedulers.io())
.subscribe(signUpModel -> {
if(!signUpModel.getStatus().equals("error"))
if (signUpModel.getData() == null) {
MDToast mdToastt = MDToast.makeText(ctx, signUpModel.getMessage(), MDToast.LENGTH_LONG, MDToast.TYPE_ERROR);
mdToastt.show();
iSignUpServices.onLoadingFailed();
}
else
signUpModelMutableLiveData.setValue(signUpModel);
else{
spinKitView.setVisibility(View.GONE);
MDToast mdToastt = MDToast.makeText(ctx,ctx.getString(R.string.login_error),MDToast.LENGTH_LONG,MDToast.TYPE_ERROR);
mdToastt.show();
}
},error->Log.e("error",error.getMessage()));
}
}
|
PHP | UTF-8 | 1,776 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/5/21
* Time: 10:28
*/
namespace app\api\controller;
use think\Db;
/**
* 用户接口类
* Class User
* @package app\api\controller
*/
class User extends Base
{
/**
* 访问白名单
* @var array
*/
protected $actionWhite = [
];
/**
* 当前请求参数信息
* @var
*/
public $param;
/**
* 当前用户id
* @var int
*/
public $uid;
/**
* 当前用户数据
* @var array
*/
public $user;
/**
* 初始化
* Base constructor.
*/
public function initialize()
{
parent::initialize(); // TODO: Change the autogenerated stub
//登录访问过滤
if (!empty($this->param['token']) || session('userinfo') || !$this->checknode($this->actionWhite,$this->request->module(),$this->request->controller(),$this->request->action())) {
}
}
/**
* 权限过滤
* @param $white_list 白名单
* @param $module
* @param $controller
* @param $action
* @return bool
*/
protected function checknode($white_list,$module,$controller,$action)
{
foreach ($white_list as &$v){
$v = strtolower($v);
}
$module = strtolower($module);
$controller = strtolower($controller);
$action = strtolower($action);
if (in_array($module,$white_list))
{
return true;
}
if (in_array($module.'/'.$controller,$white_list))
{
return true;
}
if (in_array($module.'/'.$controller.'/'.$action,$white_list))
{
return true;
}
return false;
}
} |
JavaScript | UTF-8 | 1,089 | 2.703125 | 3 | [] | no_license | import Image3 from "../../img/avatarka.jpg";
import Image4 from "../../img/avatarka2.jpg";
import profileReducer from "./profile-reducer";
import {addPostActionCreator, deletePost} from "../Actions/profile-actions";
let initialState = {
posts: [
{id: 1, post: 'Hey, why nobody love me?', likesCount: 1, img: Image3},
{id: 2, post: 'It\'s our new program! Hey!', likesCount: 2, img: Image4}
]
};
test('length of posts should be incremented', () => {
let action = addPostActionCreator("it-kamasutra.com");
let newState = profileReducer(initialState, action);
expect(newState.posts.length).toBe(3);
});
test('message of new post should be correct', () => {
let action = addPostActionCreator("it-kamasutra.com");
let newState = profileReducer(initialState, action);
expect(newState.posts[2].post).toBe("it-kamasutra.com");
});
test('after deleting length of message should be decremented', () => {
let action = deletePost(1);
let newState = profileReducer(initialState, action);
expect(newState.posts.length).toBe(1);
});
|
PHP | UTF-8 | 3,425 | 2.703125 | 3 | [] | no_license | <?php
session_start();
//importar o banco de dados
require("../database/conexao.php");
//declarar o sql de select
$sql = " SELECT * FROM tbl_categoria ";
//executar o sql
$resultado = mysqli_query($conexao, $sql) or die(mysqli_error($conexao));
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../styles-global.css" />
<link rel="stylesheet" href="./categorias.css" />
<title>Administrar Categorias</title>
</head>
<body>
<?php
include("../componentes/header/header.php");
?>
<div class="content">
<section class="categorias-container">
<main>
<form class="form-categoria" method="POST" action="./acoes.php">
<input type="hidden" name="acao" value="inserir" />
<h1 class="span2">Adicionar Categorias</h1>
<ul>
<?php
//verifica se existe erros na sessão do usuário
if (isset($_SESSION["erros"])) {
//se existir percorre os erros exbindo na tela
foreach ($_SESSION["erros"] as $erro) {
?>
<li><?= $erro ?></li>
<?php
}
//eliminar da sessão os erros já mostrados
unset($_SESSION["erros"]);
}
?>
</ul>
<div class="input-group span2">
<label for="descricao">Descrição</label>
<input type="text" name="descricao" id="descricao"/>
</div>
<button type="button" onclick="javascript:window.location.href = '../produtos/'">Cancelar</button>
<button>Salvar</button>
</form>
<h1>Lista de Categorias</h1>
<?php
//percorrer os resultados da consulta
//mostrando um card para cada categoria
if (mysqli_num_rows($resultado) == 0) {
echo "<p style='text-align: center'>Nenhuma categoria cadastrada.</p>";
}
while ($categoria = mysqli_fetch_array($resultado)) {
?>
<div class="card-categorias">
<?= $categoria["descricao"] ?>
<img onclick="deletar(<?= $categoria['id'] ?>)" src="https://icons.veryicon.com/png/o/construction-tools/coca-design/delete-189.png" />
</div>
<?php
}
?>
<form id="form-deletar" method="POST" action="./acoes.php">
<input type="hidden" name="acao" value="deletar" />
<input type="hidden" id="categoriaId" name="categoriaId" value="" />
</form>
</main>
</section>
</div>
<script lang="javascript">
function deletar(categoriaId){
document.querySelector("#categoriaId").value = categoriaId;
document.querySelector("#form-deletar").submit();
}
</script>
</body>
</html> |
C++ | UTF-8 | 1,093 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include<fstream>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<set>
#include<list>
#include<algorithm>
#include<math.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctime>
#include<iomanip>
#define MAXN 50
#define MOD 10000000000
#define LL long long
#define eps 1e-8
#define inf 0x3f3f3f3f
using namespace std;
//a quite efficient way to make it: https://projecteuler.net/thread=91;page=8
int main()
{
clock_t start = clock();
int res = MAXN * MAXN; //the vertex of the right angle is at the origin
for(short x1 = 0; x1 <= MAXN; x1++)
for(short y1 = 0; y1 <= MAXN; y1++)
for(short x2 = 0; x2 <= MAXN; x2++)
for(short y2 = 0; y2 <= MAXN; y2++)
{
if(x1 * y2 - x2 * y1 != 0 && x1 * (x2 - x1) + y1 * (y2 - y1) == 0)//The three points are not on a line or coincide && right angle
res++;
}
printf("%d\n", res);
printf("Time cost: %f s.\n", (double)((clock() - start) / CLOCKS_PER_SEC));
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.