language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
TypeScript
|
UTF-8
| 1,264 | 2.515625 | 3 |
[] |
no_license
|
import 'winston-daily-rotate-file';
import * as fs from 'fs';
import * as path from 'path';
import * as winston from 'winston';
// make a logs directory if it does not exists
const logsDir = path.resolve('.', 'logs');
if (!fs.existsSync(logsDir)) fs.mkdirSync(logsDir);
// set max log level
const level = process.env.LOG_LEVEL || 'debug';
// configure daily log rotation options
const dailyRotateCommonOpts = { datePattern: 'yyyy-MM-dd.', prepend: true };
// define logger transports
const logToConsole = [
new winston.transports.Console({
colorize: true,
prettyPrint: true,
timestamp: true
})
];
const logToFiles = [
new winston.transports.DailyRotateFile({
filename: logsDir + '/info.log',
level: 'info',
name: 'info',
...dailyRotateCommonOpts
}),
new winston.transports.DailyRotateFile({
filename: logsDir + '/debug.log',
level: 'debug',
name: 'debug',
tailable: true,
...dailyRotateCommonOpts
}),
new winston.transports.DailyRotateFile({
filename: logsDir + '/error.log',
level: 'error',
name: 'error',
tailable: true,
...dailyRotateCommonOpts
})
];
// create logger
export const logger = new winston.Logger({
level,
transports: [...logToConsole, ...logToFiles]
});
|
PHP
|
UTF-8
| 694 | 2.796875 | 3 |
[] |
no_license
|
<?php
/**
* Account.php
* Date: 13.01.2017
* Time: 10:14
* Author: Maksim Klimenko
* Email: mavsan@gmail.com
*/
namespace AmoCRM;
class Account
{
protected static $_accountInfo;
/**
* Получение информации о учетной записи в AmoCRM
*
* @param \AmoCRM\Handler $handler инициализированный ранее экземпляр
*
* @return \AmoCRM\Account
*/
public static function getAccountInfo(Handler $handler)
{
if (is_null(self::$_accountInfo)) {
self::$_accountInfo = $handler->request(new Request(Request::INFO))->result;
}
return self::$_accountInfo;
}
}
|
C++
|
UTF-8
| 812 | 2.703125 | 3 |
[] |
no_license
|
#ifndef TREEITEM_H
#define TREEITEM_H
#include <QList>
#include <QVariant>
#include <QStringList>
#include <QModelIndex>
class TreeItem
{
public:
explicit TreeItem(TreeItem *parent = nullptr);
TreeItem(const QVariantList& data,TreeItem *parent = nullptr);
~TreeItem();
void appendChild(TreeItem *child);
TreeItem * removeChild(TreeItem *item);
void deleteAllChild();
TreeItem *child(int row);
int index(TreeItem *child);
int childCount() const;
int columnCount() const;
int row() const;
QVariant data(int column) const;
bool setData(QVariant data,int column);
TreeItem *parent();
void setParent(TreeItem *parent);
private:
TreeItem *m_parentItem;
QList<TreeItem*> m_childItems;
QList<QVariant> m_itemData;
};
#endif // TREEITEM_H
|
C++
|
UTF-8
| 207 | 2.578125 | 3 |
[] |
no_license
|
#include <cstdio>
#include <cassert>
#include <cstdlib>
int main (int argc, char **argv) {
assert (argc == 2);
int n = atoll (argv[1]);
printf ("square of %d is %d\n", n, n * n);
return 0;
}
|
Shell
|
UTF-8
| 1,979 | 2.921875 | 3 |
[
"BSD-3-Clause",
"GPL-2.0-or-later"
] |
permissive
|
#!/bin/bash
export LD_LIBRARY_PATH="$PREFIX/lib:$LD_LIBRARY_PATH"
export CFLAGS="-w $CFLAGS"
export CXXFLAGS="-w $CXXFLAGS"
export CPPFLAGS="$CPPFLAGS -I$PREFIX/include"
#export SAGE_FAT_BINARY=yes
export SAGE_LOCAL="$PREFIX"
export SAGE_PKGS=`pwd`/build/pkgs
export SAGE_CYTHONIZED=`pwd`/build/cythonized
export SAGE_ETC="$SAGE_LOCAL/etc"
export SAGE_SHARE="$SAGE_LOCAL/share"
export SAGE_EXTCODE="$SAGE_SHARE/sage/ext"
export SAGE_SPKG_INST="$SAGE_LOCAL/var/lib/sage/installed"
export SAGE_DOC="$SAGE_SHARE/doc/sage"
export SAGE_ROOT=`pwd`
export MATHJAX_DIR="$SAGE_LOCAL/lib/python$PY_VER/site-packages/notebook/static/components/MathJax"
ln -s "$PREFIX/bin/python" "$PREFIX/bin/sage-system-python"
ln -s "$PREFIX" local
export SAGE_NUM_THREADS=$CPU_COUNT
make configure
./configure --prefix="$PREFIX" --with-python="$CONDA_PY"
cd src
# move the scripts
cp bin/* "$SAGE_LOCAL/bin/"
# move the extcode
mkdir -p "$SAGE_SHARE/sage"
cp -r ext "$SAGE_SHARE/sage/ext"
mkdir -p "$SAGE_SPKG_INST"
mkdir -p "$SAGE_DOC"
python -u setup.py build
# With the output of the install target we often exceeds Travis' limit of 4MB logs.
# Usually this contains nothing interesting, so just remove it completely.
python -u setup.py install >/dev/null 2>&1
# TODO: Add these in corresponding packages
rm "$PREFIX/share/jupyter/kernels/sagemath/doc"
mkdir -p "$PREFIX/etc/conda/activate.d"
mkdir -p "$PREFIX/etc/conda/deactivate.d"
cp "$RECIPE_DIR/activate/activate.sh" "$PREFIX/etc/conda/activate.d/sage-activate.sh"
cp "$RECIPE_DIR/activate/deactivate.sh" "$PREFIX/etc/conda/deactivate.d/sage-deactivate.sh"
echo 'export MATHJAX_DIR="$SAGE_LOCAL/lib/python'$PY_VER'/site-packages/notebook/static/components/MathJax"' >> "$PREFIX/etc/conda/activate.d/sage-activate.sh"
ln -s $PREFIX/bin/python $PREFIX/bin/sage-python23
rm $PREFIX/lib64
echo "$PREFIX" > "$PREFIX/lib/sage-current-location.txt"
mkdir -p "$PREFIX/var/lib/sage/installed"
touch "$PREFIX/var/lib/sage/installed/.conda"
|
Java
|
UTF-8
| 1,099 | 1.953125 | 2 |
[] |
no_license
|
package me.znzn.tools.module.blog.service;
import me.znzn.tools.module.blog.entity.form.SubscribeManageForm;
import me.znzn.tools.module.blog.entity.po.Eid;
import me.znzn.tools.module.blog.entity.po.Subscribe;
import java.util.List;
/**
* @author zhuzening
* @version 1.0
* @since 2021/8/5
*/
public interface SubscribeService {
/**
* 订阅
* @param subscribe
*/
void subscribe(Subscribe subscribe);
/**
* 修改订阅状态
* @param eid
* @return String 邮箱地址
*/
String enableSubscribe(String eid);
/**
* 根据eid取消订阅
* @param eid
* @return String 邮箱地址
*/
String disableSubscribe(String eid);
/**
* 管理订阅
* @param subscribeManageForm
*/
void manageSubscribe(SubscribeManageForm subscribeManageForm);
/**
* 获取订阅列表
* @param mailAddress
* @return
*/
List<Integer> getSubscribeList(String mailAddress);
/**
* 获取eid记录
* @param eid
* @return
*/
Eid getEidBeanByEid(String eid);
}
|
C
|
UTF-8
| 2,567 | 3.046875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define LEN 64
void sendMessageSocket(char* hostname, char* str, int port)
{
struct hostent *hp;
int s, rc, len;
struct sockaddr_in sin;
printf("TP1");
fflush(stdout);
hp = gethostbyname(hostname);
if ( hp == NULL ) {
fprintf(stderr, "%s: host not found\n", hostname);
exit(1);
}
printf("TP1");
fflush(stdout);
s = socket(AF_INET, SOCK_STREAM, 0);
if ( s < 0 ) {
perror("socket:");
exit(s);
}
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
printf("TP1");
fflush(stdout);
rc = connect(s, (struct sockaddr *)&sin, sizeof(sin));
if ( rc < 0 ) {
perror("connect:");
exit(rc);
}
len = send(s, str, strlen(str), 0);
if ( len != strlen(str) ) {
perror("send");
exit(1);
}
printf("TP1");
fflush(stdout);
close(s);
}
void receiveMessageSocket(char* str, int port)
{
char host[64];
struct hostent *hp, *ihp;
int s, rc, len, p;
struct sockaddr_in sin, incoming;
printf("TP1");
fflush(stdout);
gethostname(host, sizeof host);
printf("TP1");
fflush(stdout);
hp = gethostbyname(host);
if ( hp == NULL ) {
fprintf(stderr, "%s: host not found\n", host);
exit(1);
}
s = socket(AF_INET, SOCK_STREAM, 0);
if ( s < 0 ) {
perror("socket:");
exit(s);
}
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
/* bind socket s to address sin */
rc = bind(s, (struct sockaddr *)&sin, sizeof(sin));
if ( rc < 0 ) {
perror("bind:");
exit(rc);
}
rc = listen(s, 1);
if ( rc < 0 ) {
perror("listen:");
exit(rc);
}
p = accept(s, (struct sockaddr *)&incoming, &len);
if ( p < 0 ) {
perror("bind:");
exit(rc);
}
ihp = gethostbyaddr((char *)&incoming.sin_addr,
sizeof(struct in_addr), AF_INET);
printf(">> Connected to %s\n", ihp->h_name);
hp = gethostbyaddr((char *)&incoming.sin_addr,
sizeof(struct in_addr), AF_INET);
len = recv(p, str, 32, 0);
printf("%s\n", str);
close(s);
printf(">> Connection closed\n");
}
void main()
{
char str[64] = "Hey! How are you!";
int port = 8888;
printf("message sending");
fflush(stdout);
sendMessageSocket("localhost", str, port);
printf("message sent");
fflush(stdout);
return;
}
|
Java
|
UTF-8
| 1,943 | 2.71875 | 3 |
[] |
no_license
|
package com.ogresolutions.kaogire.smarthouse.objects;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Njuguna on 4/26/2016.
*/
public class Notice {
int id;
String houseNo;
String title;
String body;
Date timeUp;
boolean seen;
// int counter;
public Notice (){}
public Notice(int id, String houseNo, String title, String body, String timeUp){
this.body = body;
this.id = id;
this.houseNo = houseNo;
this.title = title;
this.timeUp = stringToDate(timeUp);
}
public Date getTimeUp() {
return timeUp;
}
public String getBody() {
return body;
}
public String getHouseNo() {
return houseNo;
}
public String getTitle() {
return title;
}
public void setBody(String body) {
this.body = body;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setTimeUp(Date timeUp) {
this.timeUp = timeUp;
}
public void setTimeUp(String timeUp) {
this.timeUp = stringToDate(timeUp);
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSeen() {
return seen;
}
public void setSeen(boolean seen) {
this.seen = seen;
}
// public int getCounter() {
// return counter;
// }
// public void setCounter(int counter) {
// this.counter = counter;
// }
public Date stringToDate(String date){
if(date == null)
return null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date myDate = sdf.parse(date, pos);
return myDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
C++
|
UTF-8
| 577 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
#include "header.hpp"
class Solution
{
public:
vector<int> sortedSquares(vector<int> &A)
{
int l = 0;
int r = A.size() - 1;
vector<int> res(r + 1);
int i = r;
while (l <= r)
{
int l_square = A[l] * A[l];
int r_square = A[r] * A[r];
if (l_square >= r_square)
{
res[i--] = l_square;
l++;
}
else
{
res[i--] = r_square;
r--;
}
}
return res;
}
};
|
C#
|
UTF-8
| 3,850 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace NotificationLamishtaken
{
internal class Program
{
private static void Main(string[] args)
{ }
/* private static IWebDriver m_chromeInstance;
private const string SiteUrl = "https://www.dira.moch.gov.il/ProjectsList";
private static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var fileName = Path.Combine(currentDirectory, "chromedriver.exe");
try
{
try
{
Console.WriteLine("Loading chrome driver from {0}", fileName);
using (var w = new BinaryWriter(new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)))
{
w.Write(Resources.chromedriver);
}
m_chromeInstance = new ChromeDriver(currentDirectory);
}
catch (Exception ex)
{
Console.WriteLine("Chrome driver does not exist! Exception: {0}", ex);
throw;
}
m_chromeInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
// Open URL
Console.WriteLine("Go to target URL: {0}", SiteUrl);
m_chromeInstance.Navigate().GoToUrl(SiteUrl);
// Get relevant element
var selectionLayout =
m_chromeInstance.FindElement(By.CssSelector("div.row.col-lg-12.col-md-12.col-xs-12.dark-blue-box"));
// var projectStateSelectionLayout = selectionLayout.FindElement(By.CssSelector("div.col-lg-3.col-md-3.col-xs-12"));
var selector = selectionLayout.FindElement(By.Id("slctStatus"));
var selectElement = new SelectElement(selector);
// Select relevant topic
selectElement.SelectByText("פתוח להרשמה לציבור");
// Go
var wait = new WebDriverWait(m_chromeInstance, TimeSpan.FromSeconds(10));
var button =
wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("a.btn.btn-success.btn-green")));
// TODO: find a better way to wait for the button to be clickable
Thread.Sleep((int) TimeSpan.FromSeconds(5).TotalMilliseconds);
button.Click();
// TODO: find a better way to wait for the button to be clickable
Thread.Sleep((int) TimeSpan.FromSeconds(5).TotalMilliseconds);
// Now we have the table with relevant data
var table = m_chromeInstance.FindElement(By.ClassName("table-responsive"));
// Gets table rows
IWebElement tableBody = table.FindElement(By.TagName("tbody"));
ICollection<IWebElement> rows = tableBody.FindElements(By.TagName("tr"));
foreach (var row in rows)
{
ICollection<IWebElement> columns = row.FindElements(By.TagName("td"));
IEnumerable<string> texts = columns.Select(col => col.Text);
Console.WriteLine(string.Join(", ", texts));
}
}
catch (Exception)
{
throw;
}
finally
{
m_chromeInstance.Quit();
File.Delete(fileName);
}
}*/
}
}
|
C++
|
UTF-8
| 1,795 | 3.53125 | 4 |
[] |
no_license
|
//2020.09.20_#0_官方解法
//注意后期学会unordered_map的旧C遍历法
class Solution {
private:
string returnHash(string str) {
int counter[26] = {0};
string hashString;
for (int i = 0; i < str.size(); i++) {
counter[str[i] - 'a']++;
}
for (int i = 0; i < 26; i++) {
hashString += string(counter[i], i + 'a');
}
return hashString;
}
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> dict;
for (int i = 0; i < strs.size(); i++) {
dict[returnHash(strs[i])].push_back(strs[i]);
}
vector<vector<string>> ans;
//不会使用旧C的遍历来遍历Hash
//找大佬问一下
for (auto object : dict) {
ans.push_back(object.second);
}
return ans;
}
};
//BestVotes_Cpp
//实际上跟我的#-1的想法已经很类似了
/*
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for (string s : strs) {
mp[strSort(s)].push_back(s);
}
vector<vector<string>> anagrams;
for (auto p : mp) {
anagrams.push_back(p.second);
}
return anagrams;
}
private:
string strSort(string s) {
int counter[26] = {0};
for (char c : s) {
counter[c - 'a']++;
}
string t;
for (int c = 0; c < 26; c++) {
//string(counter[c], c + 'a');是string的构造函数
//string(n, c);构造一个n个c的string
//+是操作符重载
t += string(counter[c], c + 'a');
}
return t;
}
};
*/
|
Java
|
UTF-8
| 726 | 2.671875 | 3 |
[] |
no_license
|
package valiant.aop.springaspect;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import valiant.aop.Apology;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("valiant/aop/springaspect"
+ "/applicationcontext.xml");
GreetingImp greeting = (GreetingImp)applicationContext.getBean(GreetingImp.class);
try {
greeting.sayHello("Valiant");
greeting.goodMorning("Betty");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Apology apology = (Apology) greeting;
apology.saySorry("Betty");
}
}
|
JavaScript
|
UTF-8
| 10,492 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
/* MEDIA LIBRARY MODAL */
function MediaLibrary (getter, setter, token)
{
// Set up vars
this.filesToUpload = [];
// The URLs we need to get the media from and upload
this.getterURL = getter;
this.setterURL = setter;
// Laravel CSRF-token
this.token = token;
// Will be overwritten by the validate function
this.isReady = false;
// Dropzone object (will be filled in after constructor call)
this.dz = null;
// Currently unused
this.dzelement = '<div class="dz-preview dz-image-preview">\
<div class="dz-details">blablabla\
<div class="dz-filename"><span data-dz-name></span></div>\
<div class="dz-size" data-dz-size></div>\
<img data-dz-thumbnail />\
</div>\
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>\
<div class="dz-success-mark"><span>Ok</span></div>\
<div class="dz-error-mark"><span>Error</span></div>\
<div class="dz-error-message"><span data-dz-errormessage></span></div>\
</div>';
// The actual modal
this.modal = $('<div></div>', {
'id' : 'media-library',
'html' : ' <div id="tabs" style="height:100%;"> \
<h1>Media library</h1> \
<!-- Navigation --> \
<div class="tab-nav"> \
<ul> \
<li><a href="#media-library-content">Library</a></li> \
<li><a href="#media-library-upload">Upload files</a></li> \
</ul> \
</div> \
\
<div class="tab" id="media-library-content"> \
<img src="/img/loading_spinner.gif" class="loading-spinner" id="loading-spinner" alt="Loading …"> \
</div> \
\
<!-- Second tab: Uploader --> \
<div class="tab" id="media-library-upload"> \
<div id="dropzone"></div> \
</div> \
<div class="button-bar"><a class="button muted" id="media-library-upload-button">Upload files</a>\
<a class="button error" id="media-library-close">Close</a></div> \
</div>'
}).addClass("modal");
this.modal.style = 'display:none';
}
MediaLibrary.prototype.init = function() {
this.on("addedfile", function(file) {
titleElem = Dropzone.createElement('<input type="text" placeholder="Title" title="The file title" value="' + file.name + '" class="dz-img-info title-input-field" name="title[]">');
file.previewElement.appendChild(titleElem);
descElem = Dropzone.createElement('<input type="text" title="The file description" placeholder="Description" class="dz-img-info" name="description[]">');
file.previewElement.appendChild(descElem);
clearElem = Dropzone.createElement('<div style="clear:both;"></div>');
file.previewElement.appendChild(clearElem);
var current_dz_object = this;
titleElem.addEventListener("keypress", function(e) {
// Validate all fields. We assume all good, but if one field
// is empty, we change the assumption and disable the button
current_dz_object.isReady = true;
$('.title-input-field').each(function() {
if($(this).val() === "") {
current_dz_object.isReady = false;
}
});
// Now change the upload button accordingly
if(current_dz_object.isReady) {
$('#media-library-upload-button').removeClass("muted");
$('#media-library-upload-button').addClass("success");
}
else {
$('#media-library-upload-button').removeClass("success");
$('#media-library-upload-button').addClass("muted");
}
});
// Now manually fire the validation event to make sure it gets "pre"-validated
$('.title-input-field').trigger("keypress");
});
};
/**
* Displays the medialibrary modal by adding it to the document body and
* registering all necessary event handlers
*
* @return {void}
*/
MediaLibrary.prototype.show = function() {
// Add the dim class to the body and display the MediaLibrary
$('body').addClass('dim');
$('body').append(this.modal);
// Finally display the modal
$('#media-library').show();
// Want to quit the modal? Press escape ...
$(document).keydown($.proxy(function(e) {
if(e.which == 27) {
this.close(e);
}
}, this));
// ... or click the close button
$('#media-library-close').click($.proxy(this.close, this));
// Inject dropzone code into the page
$('head').append('<script src="js/dropzone.js" id="dzjs"></script>');
// Activate dropzone
this.dz = new Dropzone('div#dropzone', {
url: this.setterURL, // Where to upload files to
paramName: "file", // The $request-index
maxFilesize: 8, // remember to make automatically depending on the wiki settings
uploadMultiple: true, // More than one media file in one batch
addRemoveLinks: true, // To cancel upload or remove element
clickable: true, // Make the DZ-element clickable for non-d&d
acceptedFiles: 'image/jpg,image/jpeg,image/png,image/gif,image/svg,image/bmp', // Only accept image files
autoProcessQueue: false, // Don't let dropzone upload immediately, for information is needed
previewElement: this.dzelement, // The preview container
// Overwrite the init function to for every file add fields like title etc.
init: this.init,
});
// Event handler for tracking changes on the file inputs for validation
// $('#media-library media-library-file-list').on('change', 'input', $.proxy(this.validate, this));
// Tabbify
$('#media-library').tabs();
// Initially hide the upload button as at first the library itself will be
// shown, not the upload form
$('#media-library-upload-button').hide();
// Hook into tab selection to hide/show the upload button
$('.tab-nav').bind("click", function(e) {
if($('#media-library').tabs("option", "active") == 1) { // Second tab
$('#media-library-upload-button').show();
}
else {
$('#media-library-upload-button').hide();
}
});
// Trigger the upload button
var current_medialibrary_object = this;
$('#media-library-upload-button').click(function(e) {
// First determine if we are all set
if($(this).is(':visible') && current_medialibrary_object.dz.isReady) {
// Commence upload
current_medialibrary_object.dz.processQueue();
}
});
// Append title and description to file on upload
this.dz.on('sending', function(file, xhr, formData) {
// TODO
formData.append('userName', 'bob');
// file.previewElement;
});
};
/**
* Closes the media library by removing it from the document body
*
* @param {Event} e The event generated by the user to close
*
* @return {void}
*/
MediaLibrary.prototype.close = function(e) {
// Only close when element is visible
if($('#media-library').is(':visible')) {
// $('#media-library').hide();
$('body').removeClass('dim');
// Remove the modal alltogether, to be sure to leave no trace when the
// object gets destroyed and another one built after some time.
$('#media-library').remove();
// Also remove the script.
$('#dzjs').remove();
// Now every trace of the media library should be removed from the page
}
};
MediaLibrary.prototype.getMedia = function() {
// This function refills the tab with loaded images from the server
$.get( this.getterURL, function() { /* Do nothing */ })
.done(function(data) {
// On success display the media
for(var i = 0; i < data.responseJSON.length; i++)
{
// For now: Do nothing. First have to create uploading.
}
})
.fail(function(data) {
$('#media-library-content').html('<div class="alert primary">' + data.responseJSON.message + '</div>');
});
};
MediaLibrary.prototype.processSelection = function() {
// TODO when Dropzone works
if(this.validate) {
// Then we can safely call processQueue to start uploading
this.dz.processQueue();
}
};
/**
* Validates all inputs to make sure we are set to go uploading (i.e. activate
* the submit button)
*
* @param {Event} event The original event
*
* @return {bool} Returns false to make sure stopPropagation is called
*/
MediaLibrary.prototype.validate = function(event) {
// Basic functionality: go through all inputs, validate and either activate
// or deactivate the upload button
console.log("Validating ...");
// Set the trigger
disabled = true;
// Our three elements each have classes called media-library-file-title,
// -description and -copyright
$('.media-library-file').each(function() {
});
// Finally, after validation, disable or enable the upload button
if(disabled) {
$('#media-library-submit').attr('disabled', 'disabled');
}
else {
$('#media-library-submit').removeAttr('disabled');
}
return false;
};
// For uploading files using ajax, see http://blog.teamtreehouse.com/uploading-files-ajax
/* END MEDIA LIBRARY MODAL */
|
Python
|
UTF-8
| 2,028 | 4.0625 | 4 |
[] |
no_license
|
toDoList = []
# store dictionaries in a list
# make dictionary(ies) +
# delete something on a list
# add something to a list +
# view everything on the list
# have a way to quit
# can't stop won't stop until Q :check
# MAKE THEM IN FUNCTIONS check in progress
def introduction():
displayMessage = """\n
Welcome to my To Do Application!
Press 1 to Add Task
Press 2 to Delete Task
Press 3 to View Task List
Press q to Quit Program
\n"""
return print(displayMessage)
def addFunction():
toDoDictionary = {}
toDoList.append(toDoDictionary)
addTask = input("Enter a task to add: ")
addPriority = input("What priority is this task: ")
toDoDictionary["title"] = addTask
toDoDictionary["priority"] = addPriority
return print("I added * %s * to your list of things to do" % taskToAdd)
def viewFunction():
count = 1
print("Incompleted Tasks")
print("==========================")
for task in toDoList:
print(" %d. %s = %s " % (count, task["title"], task["priority"]))
count += 1
print("==========================")
def delFunction():
viewfunction()
taskToDelete = int(input(
"What task would you like to delete (choose the index)\n"))
# toDoList.pop(taskToDelete - 1)
taskToDeleteIndex = taskToDelete - 1
taskThatIsGettingDeleted = toDoList[taskToDeleteIndex]
del toDoList[taskToDeleteIndex]
return print("I deleted %s off your list" % taskThatIsGettingDeleted)
def determineTask(userChoice):
whatTheyChose = ""
if(userChoice == "1"):
whatTheyChose = addfunction()
elif(userChoice == "2"):
whatTheyChose = delfunction()
elif(userChoice == "3"):
whatTheyChose = viewfunction()
# elif(userChoice == "q"):
else:
print("Bad key ")
whatTheyChose = choice
return whatTheyChose
choice = ""
while(choice != "q"):
welcomeMessage()
userChoices = input("What would you like to do?")
outcome = determineTask(userChoices)
choice = outcome
|
Swift
|
UTF-8
| 1,097 | 2.921875 | 3 |
[] |
no_license
|
//
// PokemonAbility.swift
// PokeApi
//
// Created by Felipe Ramos on 13/03/21.
//
import Foundation
import Unrealm
struct PokemonAbility: Decodable, Realmable {
//Whether or not this is a hidden ability
var is_hidden: Bool = false
//The slot this ability occupies in this Pokémon species
var slot: Int = 0
//The ability the Pokémon may have
var ability: NamedAPIResource = NamedAPIResource()
}
struct PokemonDetailAbility: Decodable, Realmable {
//The identifier for this resource.
var id: Int = 0
//The name for this resource
var name: String = ""
//Whether or not this ability originated in the main series of the video games
//var is_main_series: Bool = false
//The generation this ability originated in
//var generation: NamedAPIResource = NamedAPIResource()
//The name of this resource listed in different languages
//var names: [Name] = []
//The effect of this ability listed in different languages
var effect_entries: [VerboseEffect] = []
static func primaryKey() -> String? {
return "id"
}
}
|
PHP
|
UTF-8
| 975 | 3.125 | 3 |
[] |
no_license
|
<?php
class Region
{
public $id = null;
public $name = null;
public $slug = null;
public function __construct($name, $slug)
{
$this->name = $name;
$this->slug = $slug;
}
// Setters
public function setName($param)
{
$this->name = $param;
}
public function setSlug($param)
{
$this->slug = $param;
}
// END
public function insert()
{
$query = "INSERT INTO `region` (`name`, `slug`) VALUES (?,?)";
insert($query, [$this->name, $this->slug]);
$this->id = last_insert_id();
}
public function update()
{
if (!$this->id) {
return false;
}
$query = "UPDATE `region` SET `name`=?, `slug`=? WHERE `id`=?";
update($query, [$this->name, $this->slug, $this->id]);
}
public function __destruct()
{
echo "A (new) region(Id: {$this->id}) has been inserted/modified!";
}
}
|
Python
|
UTF-8
| 1,038 | 2.859375 | 3 |
[] |
no_license
|
import urllib2
import json
import time
def get_minute_avg_query(uuid, starttime, endtime, width=1):
# def dont call this (or any of these functions) with more than a
# couple hour difference between start time and end time. Smap will
# only look at about 10,000 samples.
return get_smap_query(uuid, "minute", starttime, endtime, width)
def get_second_avg_query(uuid, starttime, endtime, width=3):
return get_smap_query(uuid, "second", starttime, endtime, width)
def get_smap_query(uuid, field, starttime, endtime, width=1):
base_url = "http://128.97.93.240:8079/api/query?"
q = "apply window(mean, field='%s', width=%d, skip_empty='True') to data in (%d, %d) where uuid = '%s'" % (field, int(width), starttime, endtime, uuid)
fp = urllib2.urlopen(base_url, data = q)
return json.loads(fp.read())[0]["Readings"]
if __name__ == "__main__":
ct = int(time.time() * 1000)
pt = ct - 3600000
print "starttime:", pt
print "endttime:", ct
uuid = "6a6e1be3-2315-f849-f02c-adea4fe29099"
print get_minute_avg_query(uuid, pt, ct)
|
Java
|
UTF-8
| 989 | 2.265625 | 2 |
[] |
no_license
|
package poc.rabbitmq.service;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import poc.rabbitmq.model.Payment;
import static java.util.Objects.*;
@Service
public class PaymentPublisherService {
@Value("${message-queuing.queue}")
private String queue;
@Value("${message-queuing.exchange}")
private String exchange;
@Value("${message-queuing.routing-key}")
private String routingKey;
private RabbitTemplate rabbitTemplate;
public PaymentPublisherService(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
public boolean schedulePayment(Payment payment) {
boolean paymentScheduled = false;
if (nonNull(payment)) {
rabbitTemplate.convertAndSend(exchange, routingKey, payment);
paymentScheduled = true;
}
return paymentScheduled;
}
}
|
Java
|
UTF-8
| 151 | 2.140625 | 2 |
[] |
no_license
|
package abstractFactory;
public class City extends Auto {
public City (AutoParts autoParts) {
this.autoParts = autoParts;
}
}
|
C
|
UTF-8
| 609 | 2.5625 | 3 |
[] |
no_license
|
// SAMIP JASANI 2015A7PS0127P
#ifndef TREE_H
#define TREE_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct node node;
extern const char keys1[][30];
extern const char keys2[][15];
typedef node *Node;
struct node
{
bool isterminal;
void *data;
Node child;
Node parent;
Node sibling;
};
Node new_node(void *ptr, bool isterminal);
Node add_sibling(Node n, void *ptr, bool isterminal);
Node add_child(Node n, void *ptr, bool isterminal);
Node nextNT(Node n);
void PrintInorderTree(Node n);
void FileInorderTree(Node n, FILE *fp);
void PrintInorderASTree(Node n);
#endif
|
PHP
|
UTF-8
| 1,026 | 2.765625 | 3 |
[] |
no_license
|
<?php
$hostname = "localhost";
$username = "root";
$password = "0000";
$dbname = "margo";
$output;
$error;
$conn = mysqli_connect($hostname, $username, $password, $dbname);
$username = $_POST['username'];
$event_action = $_POST['event_action'];
$statement = "practice001.exe " . $username . " " . $event_action;
// exec 명령어 알고리즘 실행시키는 부분
exec($statement, $output, $error);
$arr = explode(',', $output[0]);
$query = "select url from music where id in (";
// Query를 만들어주는 부분
for($i=0; $i<count($arr); $i++) {
if($i == count($arr)-1) {
$query = $query . $arr[$i] . ");";
}
else {
$query = $query . $arr[$i] . ",";
}
}
$myArr = array();
$result = mysqli_query($conn, $query);
$temp;
while($data=mysqli_fetch_array($result)) {
// ex - {abc.mp3, bac.mp3};
array_push($myArr, $data[0]);
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myArr);
?>
|
Java
|
UTF-8
| 1,553 | 2.9375 | 3 |
[] |
no_license
|
package utilities;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatorOfData {
private static final int PASSWORD_MIN_LENGTH = 6;
public static Boolean validateData(String data){
//TODO
return true;
}
public static Boolean validateEMail(String email){
// Input the string for validation
// String email = "xyz@.com";
// Set the email pattern string
Pattern p = Pattern.compile("[a-zA-Z0-9\\-_+.]+@[a-zA-Z0-9\\-_+.]+\\.[a-zA-Z]{2,3}");
// Match the given string with the pattern
Matcher m = p.matcher(email);
// check whether match is found
boolean matchFound = m.matches();
StringTokenizer st = new StringTokenizer(email, ".");
String lastToken = null;
while (st.hasMoreTokens()) {
lastToken = st.nextToken();
}
if (matchFound && lastToken.length() >= 2
&& email.length() - 1 != lastToken.length()) {
// validate the country code
return true;
} else
return false;
}
public static Boolean validatePhone(String phone){
Pattern pattern = Pattern.compile("(0|(00\\d{2})|(\\+\\d{2}))\\d{9}");
Matcher matcher = pattern.matcher(phone);
if (matcher.matches()) {
return true;
}
else{
return false;
}
}
public static Boolean validatePassWord(String password){
if(password.length() < ValidatorOfData.PASSWORD_MIN_LENGTH) {
return false;
}
return true;
}
}
|
Java
|
UTF-8
| 396 | 1.929688 | 2 |
[] |
no_license
|
package com.PJ.Shipping.Repository;
import com.PJ.Shipping.Entity.Operation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public
interface OperationRepository extends JpaRepository<Operation, Long> {
Operation findById(long Operation_id);
// Operation Isstock()
}
|
Java
|
UTF-8
| 7,550 | 1.945313 | 2 |
[] |
no_license
|
package org.fxp.android.market.worker.frame.master;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.fxp.android.apk.ApkBean;
import org.fxp.android.market.api.ApkDAO;
import org.fxp.crawler.bean.CertBean;
import org.fxp.mode.SingletonException;
import org.fxp.tools.FileUtilsExt;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class ApkManagerDao {
private static ApkManagerDao self = null;
private static boolean instance_flag = false;
// Database
private String DB_CLASS_NAME = "com.mysql.jdbc.Driver";
private String DB_URL = "jdbc:mysql://192.168.22.12:3306/apks";
private String DB_USER = "apkmanager";
private String DB_PASSWORD = "11q22w33e";
private Connection conn = null;
private String SQL_NEXT_CERT_ID = "SELECT max(id) FROM `apks`.`apk_cert`";
private String SQL_INSERT_APK = "INSERT INTO apk("
+ "package,version_code,apk_hash,market,cert_id,file_name,download_url,create_time,download_time,import_time,ref,apk_file) "
+ "VALUES(?,?,?,?,?,?,?,?,?,NOW(),?,?); ";
private String SQL_INSERT_CERT = "INSERT INTO apk_cert("
+ "id,public_key,issuer,public_key_algo,sign_algo,cert_body)"
+ "VALUES(?,?,?,?,?,?);";
private String SQL_GET_APK = "SELECT * FROM apk"
+ "WHERE package=?,version_code,apk_hash,market,cert_id,file_name,download_url,create_time,download_time,import_time,ref,apk_file";
private void init() {
try {
Class.forName(DB_CLASS_NAME);
String url = DB_URL;
conn = (Connection) DriverManager.getConnection(url, DB_USER,
DB_PASSWORD);
instance_flag = true;
} catch (Exception e) {
e.printStackTrace();
instance_flag = false;
}
}
public static ApkManagerDao GetInstance() {
if (self == null) {
self = new ApkManagerDao();
self.init();
if (!instance_flag)
self = null;
}
return self;
}
public static ApkManagerDao resetDb() {
instance_flag = false;
self = null;
return GetInstance();
}
public void fillApk(ApkBean apk) {
if (apk.packageName == null)
apk.packageName = "";
if (apk.marketBean.marketName == null)
apk.marketBean.marketName = "";
if (apk.apkLocalPath == null)
apk.apkLocalPath = "";
if (apk.apkFileChecksum == null)
apk.apkFileChecksum = "";
if (apk.marketBean.marketDownloadUrl == null)
apk.marketBean.marketDownloadUrl = "";
if (apk.marketBean.downloadTime == null)
apk.marketBean.downloadTime = new java.sql.Date(Calendar
.getInstance().getTime().getTime());
if (apk.apkCreateTime == null)
apk.apkCreateTime = new java.sql.Date(Calendar.getInstance()
.getTime().getTime());
if (apk.marketBean.ref == null)
apk.marketBean.ref = "";
}
// Clean up all database
public int clearDatabase() {
return 0;
}
public int getNextCertId() {
PreparedStatement pstmt;
ResultSet rs;
int nextId = -1;
try {
pstmt = (PreparedStatement) conn.prepareStatement(SQL_NEXT_CERT_ID);
rs = pstmt.executeQuery();
if (rs.next())
nextId = rs.getInt(1) + 1;
} catch (SQLException e) {
e.printStackTrace();
return nextId;
}
return nextId;
}
// Insert apk info into database
public int insertApk(ApkBean apk) {
fillApk(apk);
int ret = -1;
if (apk.marketBean.marketName.equals("") || apk.packageName.equals("")
|| apk.versionCode == 0 || apk.apkLocalPath.equals("")
|| apk.apkFileChecksum.equals(""))
return ret;
String insertQuery = SQL_INSERT_APK;
try {
PreparedStatement pstmt = (PreparedStatement) conn
.prepareStatement(insertQuery);
pstmt.setString(1, apk.packageName);
pstmt.setInt(2, Integer.valueOf(apk.versionCode));
pstmt.setString(3, new String(apk.apkFileChecksum));
pstmt.setString(4, apk.marketBean.marketName);
// apk.cert_id = getNextCertId();
// TODO
// Modify apk_id
pstmt.setInt(5, 0);
pstmt.setString(6, apk.apkLocalPath);
pstmt.setString(7, apk.marketBean.marketDownloadUrl);
pstmt.setDate(8, apk.apkCreateTime);
pstmt.setDate(9, apk.marketBean.downloadTime);
pstmt.setString(10, apk.marketBean.ref);
File file = new File(apk.apkLocalPath);
// pstmt.setBinaryStream(11, new FileInputStream(file),
// (int) file.length());
pstmt.setBytes(11, "".getBytes());
pstmt.execute();
ret = ApkManagerLog.SUCCESS;
} catch (SQLException e) {
if (e.getSQLState().equals("23000"))
System.out
.println("You may have inserted duplicated search history in a short time. Please be patient.");
else
e.printStackTrace();
ret = ApkManagerLog.INSERT_APK_FAILED;
}/*
* catch (FileNotFoundException e) { e.printStackTrace(); }
*/
return ret;
}
// Delete apk info into database
public int deleteApk(ApkBean apk) {
try {
String sql2 = "DELETE FROM apk WHERE package=? && version_code=? && market='unknown'";
PreparedStatement pstmt;
pstmt = (PreparedStatement) conn.prepareStatement(sql2);
ResultSet resultSet = pstmt.executeQuery();
while (resultSet.next()) {
int count = resultSet.getInt(1);
}
conn.close();
return ApkManagerLog.SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
}
return ApkManagerLog.DB_CONN_FAILED;
}
public FileOutputStream[] getApk() {
/*
* String sql2 = "SELECT name, description, image FROM pictures ";
* PreparedStatement stmt2 = conn.prepareStatement(sql2); ResultSet
* resultSet = stmt2.executeQuery(); while (resultSet.next()) { String
* name = resultSet.getString(1); String description =
* resultSet.getString(2); File image2 = new File("D:\\jason.jpg");
* FileOutputStream fos = new FileOutputStream(image2);
*
* byte[] buffer = new byte[1]; InputStream is =
* resultSet.getBinaryStream(3);
*
* while (is.read(buffer) > 0) { fos.write(buffer); } fos.close(); }
* conn.close();
*/return null;
}
// Insert certification info into database
public int insertCert(ApkBean apk) {
fillApk(apk);
int ret = -1;
if (apk.certs.size() == 0 || apk.apkLocalPath.equals(""))
return ret;
String insertQuery = SQL_INSERT_CERT;
for (CertBean cert : apk.certs) {
try {
PreparedStatement pstmt = (PreparedStatement) conn
.prepareStatement(insertQuery);
// TODO modify apk_id
// pstmt.setInt(1, apk.apk_id);
pstmt.setInt(1, 0);
pstmt.setBytes(2, cert.certificate.getPublicKey().getEncoded());
pstmt.setString(3, ((X509Certificate) cert.certificate)
.getIssuerX500Principal().getName());
pstmt.setString(4, cert.certificate.getPublicKey()
.getAlgorithm());
pstmt.setString(5,
((X509Certificate) cert.certificate).getSigAlgName());
pstmt.setBytes(6,
((X509Certificate) cert.certificate).getEncoded());
pstmt.execute();
ret = ApkManagerLog.SUCCESS;
} catch (SQLException e) {
System.out
.println("You may have inserted duplicated search history in a short time. Please be patient.");
e.printStackTrace();
ret = ApkManagerLog.INSERT_CERT_FAILED;
} catch (CertificateEncodingException e) {
e.printStackTrace();
}
return ret;
}
return ret;
}
// Delete certification info into database
public int deleteCert(ApkBean apk) {
return 0;
}
}
|
Shell
|
UTF-8
| 987 | 3.953125 | 4 |
[] |
no_license
|
#!/bin/bash
USAGE() {
echo USAGE:
echo "$0"
exit 1
}
if [ $# -lt 0 ];then
USAGE
fi
cd $(dirname $0)
number_of_tries=0
done=0
if ! sudo xm list > node_list; then
exit 1
fi
for (( i=0; i<100; i++ )); do
if [ "`grep -w "node-${i}" node_list`" == "" ]; then
echo node-$i is not running.
nodeno=$i
break
fi
done
while [ $done -eq "0" ]; do
number_of_running_nodes=0
number_of_started_nodes=0
echo Starting node-$nodeno
while [[ ! `./manage_node.sh start node-$nodeno` ]]; do
echo Starting node-$nodeno
done
echo "Waiting for nodes to start."
sleep 5
if [ "`ping -c 3 node-${nodeno} | grep " 0% packet loss"`" == "" ]; then
echo "node-$i is not answering to ping."
if [ "$number_of_tries" -eq "3" ]; then
echo Destroying node-$nodeno
sudo xm destroy node-$nodeno
number_of_tries=0
fi
else
done=1
fi
let number_of_tries=$number_of_tries+1
done
if ! sudo xm list > node_list; then
exit 1
fi
echo
echo Created node-$nodeno.
|
JavaScript
|
UTF-8
| 1,984 | 2.796875 | 3 |
[] |
no_license
|
// bookmark values
var chr = "chrome";
var dwy = "dewey";
// bookmark URLs
var chromeBM = "chrome://bookmarks";
var deweyBM = "chrome-extension://aahpfefkmihhdabllidnlipghcjgpkdm/app.html#/main";
// URL to use
var bmURL = " ";
// callback function
var setBM = function(bm) {
// set bookmarks URL to chrome or chosen extension
if (bm === chr)
{
bmURL = chromeBM;
}
if (bm === dwy)
{
bmURL = deweyBM;
}
// load bookmarks
chrome.tabs.update({ url: bmURL });
};
var getBM = function(callback) {
// create variable to store retrieved data
var bm = " ";
// retrieve from storage API
chrome.storage.sync.get({
myBmUse: 'chrome'
},
// store data in variable
function (obj) {
bm = obj.myBmUse;
// pass to callback function
callback(bm);
});
};
// loads bookmarks link on click
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('bookmarks').addEventListener('click', function() {
getBM(setBM);
});
});
// loads chrome://extensions
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('extensions').addEventListener('click', function() {
chrome.tabs.update({ url: 'chrome://extensions' });
});
});
// loads chrome://settings
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('settings').addEventListener('click', function() {
chrome.tabs.update({ url: 'chrome://settings' });
});
});
// loads chrome://history
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('history').addEventListener('click', function() {
chrome.tabs.update({ url: 'chrome://history' });
});
});
// loads chrome://downloads
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('downloads').addEventListener('click', function() {
chrome.tabs.update({ url: 'chrome://downloads' });
});
});
|
JavaScript
|
UTF-8
| 2,985 | 3.78125 | 4 |
[] |
no_license
|
// if ( condition ) {
// }
// var age = prompt("What is your age?");
// var cash = prompt("How much money do you have?");
// var drinks = prompt("How many drinks have you had already?");
// if (age >= 18) {
// if (drinks >= 5) {
// if (cash > 7) {
// console.log("You can drink!");
// }
// else if (cash > 5) {
// console.log("You can buy some crisps!");
// }
// else {
// console.log("Sorry, you don't have enough money. :(");
// }
// } else {
// console.log("You've had too many to drink!");
// }
// } else {
// console.log("You're underage!");
// }
// var name = "Timmy";
// switch(name) {
// case 'Tina':
// console.log("Hello Tina");
// break;
// case 'Bob':
// console.log("Hello Bob!")
// break;
// case 'Sammy':
// console.log("Hello Sammy!")
// break;
// default:
// console.log("Sorry, don't know who you are.")
// }
// var name = prompt("What is your name?") || "Captain no-name!";
// console.log(name);
// For Loop
// for (var i = 0; i < 10; i++) {
// console.log(i);
// }
// var people = ["Tina", "Bob", "Simon", "Jeff"];
// function greetPeople(listOfPeople) {
// for (var i = 0; i < listOfPeople.length; i++) {
// greet(listOfPeople[i]);
// }
// }
// function greet (name) {
// console.log("Hello " + name);
// }
// greetPeople(people);
// var people = ["Tina", "Bob", "Simon", "Jeff"];
// for (var i = 0; i < people.length; i++) {
// function greet (people[i]); {
// console.log("Hello " + name);
// }
// }
// while loop
// var i = 0;
// while (i < 5) {
// console.log("Conditions have been met.");
// console.log(i);
// i++
// }
// var isDrunk = false;
// var drinks = 0;
// while (!isDrunk) {
// console.log("There you go, enjoy your drink.")
// drinks++
// if (drinks === 5) {
// isDrunk = true;
// }
// }
// interate over a object
// var people = {
// "Niall": "Richmond",
// "Tim": "Newcastle",
// "Bob": "Birmingham"
// };
// for (var key in people) {
// greet(key, people[key]);
// }
// function greet(name, place) {
// console.log("Hello, " + name + ". You live in " + place)
// }
// function personGreet(people, place) {
// for (var key in people) {
// greet(people, place);
// }
// }
// function greet(name, home) {
// console.log("Hello, " + name + ". You live in " + home)
// }
// personGreet(people, place);
// for (var i=1; i <= 100; i++) {
// if (i % 3 === 0 && i % 5 === 0) {
// console.log("FizzBuzz");
// }
// else if (i % 5 === 0) {
// console.log("Buzz");
// }
// else if (i % 3 === 0) {
// console.log("Fizz");
// }
// else {
// console.log(i);
// }
// }
// for (var i=0; i<=100; i++) {
// i%15 === 0 ? console.log(“FizzBuzz”) : i%5===0 ? console.log(“Buzz”) : i%3 === 0 ? console.log(“Fizz”) : console.log(i)
// }
var age = 18;
var canDrink = (age >= 18) ?
("Yes, this person is over 18") :
(age <10 ? "No, this person isn't." : "You've got a couple of years to go")
console.log(canDrink);
|
Python
|
UTF-8
| 334 | 3.28125 | 3 |
[] |
no_license
|
import Stack
def convert2binary(num):
rem = Stack.Stack()
result = ''
while num > 0:
remainer = num % 2
num = num // 2
rem.push(remainer)
while rem.is_empty() != 1:
result += str(rem.peek())
rem.pop()
return result
print convert2binary(233)
|
JavaScript
|
UTF-8
| 645 | 4.09375 | 4 |
[] |
no_license
|
const palindrome = (str) => {
let loweredWord = str.toLowerCase();
let originalWord = loweredWord.replace(/[^0-9a-z]/gi, '')
console.log(originalWord)
let splitWord = originalWord.split("")
let reversedArr = splitWord.reverse()
let reversedWord = reversedArr.join("")
console.log(reversedWord)
if (originalWord == reversedWord){
return true;
} else {
return false
}
}
palindrome("1 eye for of 1 eye.");
/* 1. remove all non-abc chars from the string save it into a variable
2. reverse the string => save it into another variable
3. compare the variables
4. return boolean
*/
|
C++
|
UTF-8
| 925 | 2.75 | 3 |
[] |
no_license
|
/**
@author Nathan
*/
#ifndef RENDERER_H
#define RENDERER_H
#include <vector>
#include "RenderLayer.h"
#include "TextureList.h"
#include "ModelRemovalToken.h"
class Renderer
{
private:
bool m_bIsRendering;
TextureList* m_textureList;
ModelList* m_modelList;
std::vector<RenderLayer> m_renderLayers;
protected:
public:
Renderer();
Renderer(int iNumLayers);
~Renderer();
void setRendering(bool bRendering);
bool isRendering() const;
bool loadModelSet(std::string sFileName);
bool unloadModelSet(std::string sFileName);
bool reloadModelSet(std::string sFileName);
bool loadTextureSet(std::string sFileName);
bool unloadTextureSet(std::string sFileName);
bool reloadTextureSet(std::string sFileName);
ModelRemovalToken addActor(std::shared_ptr<Actor> actor, unsigned int iLayer);
bool removeActor(ModelRemovalToken token);
void render(sf::RenderWindow& window) const;
};
#endif
|
C++
|
UTF-8
| 998 | 2.875 | 3 |
[] |
no_license
|
// https://leetcode.com/problems/baseball-game/
// Easy
class Solution {
public:
stack<int>st;
int popData() {
int temp = 0;
if(!st.empty()) { temp = st.top(); st.pop(); }
return temp;
}
int calPoints(vector<string>& ops) {
int x, y;
for(string s : ops) {
if(s == "+") {
x = popData();
y = popData();
st.push(y); st.push(x); st.push(x+y);
}
else if(s == "C") popData();
else if(s == "D") {
if(!st.empty()){
x = popData();
st.push(x); st.push(2*x);
}
}
else {
st.push(stoi(s));
}
}
int total = 0;
while(!st.empty()) total += popData();
return total;
}
};
|
Python
|
UTF-8
| 406 | 3.484375 | 3 |
[] |
no_license
|
prime = [True] * 10000001 # 소수이면 True
def sieve():
prime[1] = False
for n in range(2, 10000001):
if prime[n]: # n 가 소수인경우
for m in range(n + n, 10000001, n):
prime[m] = False
sieve()
N = int(input())
for i in range(2, N+1):
if(N == 1):
break
if prime[i]:
while not N % i:
N /= i
print(i)
|
Java
|
UTF-8
| 2,386 | 3.03125 | 3 |
[] |
no_license
|
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class Notes extends Frame{
private static final long serialVersionUID = 1L;
private Choice user, platform;
private Button boton;
public Notes() {
super("Galarza Notes");
setLayout(new BorderLayout());
PanelyBotones panelnorte =new PanelyBotones(1);
PanelyBotones panelcentro=new PanelyBotones(2);
add("North", panelnorte);
add("Center",panelcentro);
setSize(400,200);
ManejadorVentana mv = new ManejadorVentana();
addWindowListener(mv);
ManejadorEvento me = new ManejadorEvento();
boton.addActionListener(me);
}
public static void main(String[] args) {
Notes n;
n=new Notes();
n.setVisible(true);
}
class PanelyBotones extends Panel{
private static final long serialVersionUID = 1L;
public PanelyBotones(int opcion){
switch(opcion){
case 1:
user=new Choice();
platform=new Choice();
user.add("jmedinax");
platform.add("");
platform.add("clf");
add(user);
add(platform);
break;
case 2:
boton=new Button("Enviar");
add(boton);
add(new Label("Powered by Galarza Engine"));
break;
}
}
}
class ManejadorEvento implements ActionListener{
public void actionPerformed(ActionEvent evento){
if(evento.getSource()==boton){
System.out.println(user.getSelectedItem()
+"_"+platform.getSelectedItem());
}
}
}
}
class ManejadorVentana implements WindowListener{
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}
|
Python
|
UTF-8
| 4,482 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# modificare.py
from pip._vendor.distlib.compat import raw_input
import dbConnection
def MeniuModificaCarte():
print("===============================")
print("Modificare inregistrare in baza de date:")
print("===============================")
titluCarte = raw_input("\n Introduceti titlul cartii pe care doriti sa o modificati: ")
querrySelectTitlu = "SELECT * FROM carte WHERE titlu = \"%s\"" % titluCarte
try:
db = dbConnection.CreeazaConexiune()
c = db.cursor()
c.execute(querrySelectTitlu)
rezultat = c.fetchall()
# if rezultat[0] == ():
# raise
except:
print("Eroare la accesarea inregistrarii in baza de date!")
raw_input("Apasati 'Enter' pentru a continua.")
return
try:
print("===============================")
print("Cartea care va fi modificata:")
print("===============================")
print("1 - Titlu:\t", rezultat[0][0])
print("2 - Autor:\t", rezultat[0][1])
print("3 - Editura:\t", rezultat[0][2])
print("4 - An:\t", rezultat[0][3])
print("5 - Pret:\t", rezultat[0][4])
print("6 - Gen:\t", rezultat[0][5])
print("===============================")
opt = raw_input("Introduceti numele campului pe care doriti sa-l modificati, si apasati 'Enter': ")
titluModificat = False
campModificat = ""
nouaValoare = ""
if opt == "1":
campModificat = "titlu"
nouaValoareTitlu = raw_input("Introduceti noul titlu: ")
nouaValoare = "\"%s\"" % nouaValoareTitlu
titluModificat = True
elif opt == "2":
campModificat = "autor"
nouaValoare = raw_input("Introduceti noul autor: ")
nouaValoare = "\"%s\"" % nouaValoare
elif opt == "3":
campModificat = "editura"
nouaValoare = raw_input("Introduceti editura noua: ")
nouaValoare = "\"%s\"" % nouaValoare
elif opt == "4":
campModificat = "an"
nouaValoare = raw_input("Introduceti anul nou: ")
nouaValoare = "\"%s\"" % nouaValoare
elif opt == "5":
campModificat = "pret"
nouaValoare = raw_input("Introduceti pretul nou: ")
nouaValoare = "\"%s\"" % nouaValoare
elif opt == "6":
campModificat = "gen"
print("===============================")
print("Alegeti genul pe care doriti sa-l modificati:")
print("1 - Beletristica")
print("2 - Stiinta")
print("3 - Comedie")
print("4 - Romantic")
print("5 - SF")
print("6 - Enciclopedie")
optiune = raw_input("Introduceti noua valoare pentru genul cartii: ")
if optiune == "1":
nouaValoare = "\"Beletristica\""
elif optiune == "2":
nouaValoare = "\"Stiinta\""
elif optiune == "3":
nouaValoare = "\"Comedie\""
elif optiune == "4":
nouaValoare = "\"Romantic\""
elif optiune == "5":
nouaValoare = "\"SF\""
elif optiune == "6":
nouaValoare = "\"Enciclopedie\""
querryUpdate = "UPDATE carte SET %s = %s WHERE titlu = \"%s\"" % (campModificat, nouaValoare, titluCarte)
db = dbConnection.CreeazaConexiune()
c = db.cursor()
c.execute(querryUpdate)
db.commit()
if titluModificat:
querrySelect = "SELECT * FROM carte WHERE titlu = \"%s\"" % nouaValoareTitlu
c = db.cursor()
c.execute(querrySelect)
rezultatModificare = c.fetchall()
c.close()
db.close()
except:
print("Eroare la modificarea inregistrarii!")
raw_input("Apasati 'Enter' pentru a continua.")
return
print("===============================")
print("Intregistrare modificata cu succes:")
print("===============================")
print("1 - Titlu:\t", rezultatModificare[0][0])
print("2 - Autor:\t", rezultatModificare[0][1])
print("3 - Editura:\t", rezultatModificare[0][2])
print("4 - An:\t", rezultatModificare[0][3])
print("5 - Pret:\t", rezultatModificare[0][4])
print("6 - Gen\t", rezultatModificare[0][5])
print("===============================")
raw_input("Apasati 'Enter' pentru a continua")
|
C++
|
UTF-8
| 400 | 2.734375 | 3 |
[] |
no_license
|
#include "Arduino.h"
#include "Raindrop.h"
#define NUM_LEDS 150
#define LOWER_HUE 140
#define UPPER_HUE 210
Raindrop::Raindrop() {
pos = random(0, NUM_LEDS - 1);
hue = random(LOWER_HUE, UPPER_HUE);
}
int Raindrop::updatePos() {
pos--;
if (pos < 0) {
pos = random(NUM_LEDS,NUM_LEDS*2);
hue = random(LOWER_HUE, UPPER_HUE);
}
return pos;
}
int Raindrop::getHue(){
return hue;
}
|
C#
|
UTF-8
| 3,938 | 3 | 3 |
[] |
no_license
|
using System;
using System.Linq;
namespace MvcJqGrid.Example.Models
{
public class Repository
{
private readonly AdventureWorksDataContext _dataContext = new AdventureWorksDataContext();
public int CountCustomers(GridSettings gridSettings)
{
var customers = _dataContext.Customers.AsQueryable();
if (gridSettings.IsSearch)
{
customers = gridSettings.Where.rules.Aggregate(customers, FilterCustomers);
}
return customers.Count();
}
public IQueryable<Customer> GetCustomers(GridSettings gridSettings)
{
var customers = orderCustomers(_dataContext.Customers.AsQueryable(), gridSettings.SortColumn, gridSettings.SortOrder);
if (gridSettings.IsSearch)
{
customers = gridSettings.Where.rules.Aggregate(customers, FilterCustomers);
}
return customers.Skip((gridSettings.PageIndex - 1) * gridSettings.PageSize).Take(gridSettings.PageSize);
}
public string[] GetCompanyNames()
{
return _dataContext.Customers.Select(c => c.CompanyName).Distinct().ToArray();
}
private static IQueryable<Customer> FilterCustomers(IQueryable<Customer> customers, Rule rule)
{
if (rule.field == "CustomerId")
{
int result;
if (!int.TryParse(rule.data, out result))
return customers;
return customers.Where(c => c.CustomerID == Convert.ToInt32(rule.data));
}
if (rule.field == "Name")
return from c in customers
where c.FirstName.Contains(rule.data) || c.LastName.Contains(rule.data)
select c;
if (rule.field == "Company")
return customers.Where(c => c.CompanyName.Contains(rule.data));
if (rule.field == "EmailAddress")
return customers.Where(c => c.EmailAddress.Contains(rule.data));
if (rule.field == "Last Modified")
{
DateTime result;
if (!DateTime.TryParse(rule.data, out result))
return customers;
if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
return customers;
return customers.Where(c => c.ModifiedDate.Date == Convert.ToDateTime(rule.data).Date);
}
if (rule.field == "Telephone")
return customers.Where(c => c.Phone.Contains(rule.data));
return customers;
}
private IQueryable<Customer> orderCustomers(IQueryable<Customer> customers, string sortColumn, string sortOrder)
{
if (sortColumn == "CustomerId")
return (sortOrder == "desc") ? customers.OrderByDescending(c => c.CustomerID) : customers.OrderBy(c => c.CustomerID);
if (sortColumn == "Name")
return (sortOrder == "desc") ? customers.OrderByDescending(c=>c.FirstName) : customers.OrderBy(c=>c.FirstName);
if (sortColumn == "Company")
return (sortOrder == "desc")? customers.OrderByDescending(c=>c.CompanyName) : customers.OrderBy(c=>c.CompanyName);
if (sortColumn == "EmailAddress")
return (sortOrder == "desc") ? customers.OrderByDescending(c => c.EmailAddress) : customers.OrderBy(c => c.EmailAddress);
if (sortColumn == "Last Modified")
return (sortOrder == "desc") ? customers.OrderByDescending(c => c.ModifiedDate) : customers.OrderBy(c => c.ModifiedDate);
if (sortColumn == "Telephone")
return (sortOrder == "desc") ? customers.OrderByDescending(c => c.Phone) : customers.OrderBy(c => c.Phone);
return customers;
}
}
}
|
Python
|
UTF-8
| 685 | 2.703125 | 3 |
[] |
no_license
|
from kivy.lang import Builder
from kivy.app import App
from kivy.clock import Clock
from plyer import camera
class MyApp(App):
count = 0
def build(self):
import pygame
print 'pygame version:', pygame.ver
print 'SDL version:', pygame.get_sdl_version()
def on_pause(self):
print 'on_pause'
return True
def on_resume(self):
print 'on_resume'
def tirar_foto(self):
print 'tirando foto...'
filename = '/sdcard/foo.jpg'
camera.take_picture(str(filename), self.foto_tirada)
def foto_tirada(self, filename):
print 'foto tirada', filename
if __name__ == '__main__':
MyApp().run()
|
Swift
|
UTF-8
| 2,023 | 2.984375 | 3 |
[] |
no_license
|
//
// PostViewModel.swift
// Parrot
//
// Created by administrador on 26/07/19.
// Copyright © 2019 Treinamento. All rights reserved.
//
import Foundation
import RealmSwift
struct PostView {
var id = 0
var likes = 0
var user = User()
var message = ""
}
class PostViewModel {
static func save(post: Post) {
try? uiRealm.write {
uiRealm.add(post, update: .all)
}
}
static func saveAll(posts: [Post]) {
try? uiRealm.write {
uiRealm.add(posts, update: .all)
}
}
static func update(post: Post) {
try? uiRealm.write {
uiRealm.add(post, update: .modified)
}
}
static func delete(post: Post) {
uiRealm.delete(post)
}
static func deleteAll() {
let results = uiRealm.objects(Post.self)
try? uiRealm.write {
uiRealm.delete(results)
}
}
static func get() -> [Post] {
let results = uiRealm.objects(Post.self)
var posts: [Post] = []
posts.append(contentsOf: results)
return posts
}
static func getPosts() -> [PostView] {
return self.getAsView(posts: self.get())
}
static func getAsView(post: Post?) -> PostView {
guard let post = post else {
return PostView()
}
var postView = PostView()
postView.id = post.id.value ?? 0
postView.likes = post.likes.value ?? 0
postView.user = post.user
postView.message = post.message ?? ""
return postView
}
static func getAsView(posts: [Post]) -> [PostView] {
var postView: [PostView] = []
posts.forEach { (post) in
postView.append(self.getAsView(post: post))
}
return postView
}
static func getAsModel(postView: PostView) -> Post {
let post = Post()
post.message = postView.message
return post
}
}
|
Markdown
|
UTF-8
| 9,874 | 2.953125 | 3 |
[
"Beerware"
] |
permissive
|
# Créer un formulaire de demande de devis avec l'API de son site Kiubi
## Introduction
Ce dépôt est un tutoriel qui explique comment utiliser l'API de son site [Kiubi](http://www.kiubi.com) pour créer un formulaire de demande de devis.
L'objectif étant d'intégrer de façon automatique le contenu du panier de l'internaute dans une réponse à un formulaire *dismoi?*. Ce formulaire pourra ainsi être utilisé comme un formulaire de demande de devis.

## Prérequis
Ce tutoriel suppose que vous avez un site Kiubi et qu'il est bien configuré :
- l'API est activée
- le catalogue est activé
- le site est en thème personnalisé, basé sur Shiroi
Il est préférable d'être à l'aise avec la manipulation des thèmes personnalisés. En cas de besoin, le [guide du designer](http://doc.kiubi.com) est là.
Ce tutoriel est applicable à tout thème graphique mais les exemples de codes donnés sont optimisés pour un rendu basé sur le thème Shiroi.
## Ajout d'un formulaire *dismoi?* dans la page de détail panier.
L'objectif est d'intégrer à la page de détail panier un formulaire dismoi?. Ce formulaire intégrera, dans un champ prévu à cet effet, un descriptif textuel du panier de l'utilisateur.
Pour y arriver, on utilise ici plusieurs composants :
- le framework jQuery pour les manipulations javascript de base
- le client Javascript API Front-office de Kiubi (qui est un plugin jQuery) pour récupérer les produits
Nous allons créer un fragment de template spécifique pour faciliter sa mise en place.
### Mise en place
Créer un formulaire *dismoi?*.
Ajouter un champ texte multi-lignes. Dans le champ Aide à la saisie, renseigner la valeur `%cart%`. Cette valeur permettra de retrouver le champ associé au contenu du panier et de pré-remplir sa valeur.

Ajouter d'autres champs si souhaité (civilité, coordonnées, message libre, ...) puis enregistrer le formulaire.
Dans l'onglet "Paramètres", repérer l'identifiant API du formulaire.

Copier les fichiers `theme/fr/templates/devis.css` et `theme/fr/templates/forms.js` de ce dépôt dans le dossier `fr/templates/` du thème personnalisé. Copier le fichier `theme/fr/includes/devis.html` de ce dépôt dans le dossier `fr/includes/` du thème personnalisé. Ouvrir ce même fichier et **renseigner la variable `form_id` avec l'identifiant API du formulaire**.
<pre lang="javascript">
<script type="text/javascript">
var form_id = 'X-XXXXXXXXXXXXXXX'; // identifiant API
</pre>
Dans le Back-office du site, éditer une mise en page de type "détail panier".
Placer le widget "Fragment de template" dans la page. Editer la configuration du widget et choisir le template "devis".
La page de détail d'un produit affiche désormais un bouton "demande de devis". Un clic sur ce bouton, affiche un formulaire de demande de devis. A la soumission du formulaire, un réponse au formulaire dismoi sera créé et apparaitra dans le Back-office du site. Elle contiendra le contenu du panier de l'internaute. Un confirmation par e-mail sera également envoyée à l'internaute et au propriétaire du site.
### Explications
Examinons en détail le code HTML du fragment de template `devis.html` :
<pre lang="html">
<link rel="stylesheet" href="{racine}/{theme}/{lg}/templates/devis.css" />
<input id="show_modal" type="submit" value="Demande de devis" />
<div id="overlay" style="display:none">
<div class="modal">
<h1>Demande de devis</h1>
<form method="post" onsubmit="return false;">
<div class="fields"><center>Chargement du formulaire...</center></div>
<input type="submit" value="Demande de devis" />
<input type="reset" value="Annuler" class="submit reset close">
<footer>Le contenu de votre panier sera joint à votre demande</footer>
</form>
</div>
</div>
</pre>
Cette première portion de code met en place le bouton "demande de devis". Ainsi que le bloc (masqué par défaut) permettant d'accueillir le formulaire dismoi?.
On inclut ensuite le client Javascript API Front-office de Kiubi ainsi que le fichier `forms.js` :
<pre lang="html">
<script type="text/javascript" src="{cdn}/js/kiubi.api.pfo.jquery-1.0.min.js"></script>
<script type="text/javascript" src="{racine}/{theme}/{lg}/templates/forms.min.js"></script>
</pre>
<pre lang="javascript">
<script type="text/javascript">
var form_id = 'X-XXXXXXXXXXXXXXX'; // identifiant API
var $form = $('.modal form');
var $container = $('.fields', $form);
</pre>
On initialise les variables `form_id`, `$form` et `$container` correspondant respectivement à l'identifiant unique du formulaire, l'objet jquery du formulaire HTML et enfin le conteneur destiné à accueillir les champs dudit formulaire.
##### Ouverture de la modal-box
<pre lang="javascript">
/**
* Ouverture de la modal
*/
$("#show_modal").click(function(){
$('#overlay').show();
$('#overlay .modal').addClass('scrolldown');
</pre>
Au clic sur le bouton "Demande de devis", on affiche le fond et on ajoute la classe `scrolldown` à la modal-box. On récupère ensuite la configuration du formulaire dismoi? à l'aide du client Javascript API Front-office de Kiubi :
<pre lang="javascript">
kiubi.forms.get(form_id).done(function(meta, APIForm){
</pre>
On vide puis remplit le conteneur à l'aide de la méthode `createForm()` définit dans le fichier `forms.js` précédemment inclus. Cette méthode accepte en premier argument une liste de champ issue d'une requête API et, en second argument, le noeud DOM dans lequel les champs seront ajoutés en HTML.
<pre lang="javascript">
$container.empty();
// on remplit le formulaire avec tous les champs
createForm(APIForm.fields, $container);
</pre>
On recherche ensuite le champ associé au panier :
<pre lang="javascript">
var cart_field = $('[placeholder=\\%cart\\%]', $container);
if(cart_field.length)
{
// on masque ce champ spécial, ainsi que son label
cart_field.hide();
$('label[for=' + cart_field.attr('id') +']').hide();
</pre>
Si le champ a été trouvé, on récupère le contenu du panier de l'internaute à l'aide du client Javascript API Front-office de Kiubi :
<pre lang="javascript">
// on récupère le contenu du panier
kiubi.cart.get().done(function(meta, data){
</pre>
On remplit enfin ce champ avec une version textuelle du contenu du panier :
<pre lang="javascript">
var text = data.items_count + " produit(s) \n\n";
data.items && $.each(data.items, function(num, item){
text += "- " + item.product_name + " (" + item.name + ")\n";
text += "\t quantité : " + item.quantity + "\n";
text += "\t référence : " + item.sku + "\n";
text += "\t URL : " + location.protocol + '//' + location.host + item.product_url + "\n";
text += "\n";
});
// on ajoute un descriptif textuel du panier au champ
cart_field.val(text);
});
}
});
});
</pre>
##### Soumission du formulaire
A la soumission du formulaire HTML, on utilise à nouveau l'API afin de stocker la demande de l'internaute.
<pre lang="javascript">
/**
* Soumission du formulaire
*/
$form.submit(function(){
var submit = kiubi.forms.submit(form_id, $form);
</pre>
En cas de succès, on remplace les champs du formulaire par le message de remerciement, on masque les erreurs éventuellement survenues lors d'une soumission antérieure, puis on renomme le bouton Annuler en Fermer :
<pre lang="javascript">
// Réussite
submit.done(function(meta, data){
$container.empty();
$container.append(data.message);
$('footer, input[type=submit]', $form).hide();
$('div.erreurs', $form).remove();
$('input.close', $form).val('Fermer');
});
</pre>

##### Gestion des erreurs
En cas d'échec (champ obligatoire non renseigné, valeur d'un champ incorrecte, …), on affiche un div qui contiendra l'erreur ayant occasionnée cet échec :
<pre lang="javascript">
// Echec
submit.fail(function(meta, error, data){
$('div.erreurs', $form).remove();
var info_box = $('<div>', {'class':'erreurs'});
info_box.insertBefore($container);
info_box.append(error.message);
</pre>
On ajoute une classe `erreur` aux champs ayant éventuellement occasionnés cette erreur :
<pre lang="javascript">
$('input, textarea, select', $form).removeClass('erreur');
$.each(error.fields, function(){
$('[name="'+this.field+'"]', $form).addClass('erreur');
info_box.append("<br>" + this.message);
});
</pre>
Si un nouveau captcha est à renseigner, on met à jour la question de ce dernier, puis on vide la réponse précédente :
<pre lang="javascript">
if(data && data.new_captcha) {
// un nouveau captcha à été généré pour ce formulaire
$('[name=captcha]', $form).val("");
$('label[for=captcha]', $form).html(data.new_captcha+' *');
}
});
return false; // empêche la soumission "normale" du formulaire.
});
</pre>

##### Fermeture de la modal-box
Pour finir, le code ci-dessous permet de fermer la modal-box au clic du bouton "Annuler/Fermer" :
<pre lang="javascript">
/**
* Fermeture de la modal
*/
$('input.close', $form).click(function(){
$('#overlay').hide();
$('div.erreurs', $form).remove();
$('#overlay .modal form *').show();
$container.empty();
$(this).val('Annuler'); // rétabli le nom du bouton
});
</script>
</pre>
La page affiche désormais un formulaire de demande de devis. Dans le back-office, les réponses à ce formulaire intègrent le contenu du panier :

|
PHP
|
UTF-8
| 329 | 2.78125 | 3 |
[] |
no_license
|
<?php
namespace sat8bit\RoombaSim\Roomba;
interface RoombaAIInterface
{
/**
* when hit.
*
* @param int $distance
* @return Motion
*/
public function hit($distance);
/**
* when ran.
*
* @param int $distance
* @return Motion
*/
public function ran($distance);
}
|
C++
|
UTF-8
| 2,890 | 3.15625 | 3 |
[] |
no_license
|
// BEGIN CUT HERE
/*
SRM 653 Div2 Medium (500)
問題
-N回じゃんけんする
-勝つと1ポイントもらえる
-ちょうどscoreポイント稼ぐ場合の数を求める
*/
// END CUT HERE
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
typedef long long LL;
#define COMBSZ 2048
#define MOD 1000000007LL
class RockPaperScissorsMagicEasy {
public:
int count(vector <int> card, int score) {
LL N = card.size();
if (score > N) {
return 0;
}
static LL C[COMBSZ][COMBSZ];
for (LL i = 0; i < COMBSZ; ++i) {
C[i][0] = 1;
for (LL j = 1; j <= i; ++j) {
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % MOD;
}
}
LL ans = C[N][score];
LL R = N - score;
for (LL i = 0; i < R; ++i) {
ans = (ans * 2) % MOD;
}
return (int)ans;
}
// BEGIN CUT HERE
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
public:
void run_test(int Case) {
int n = 0;
// test_case_0
if ((Case == -1) || (Case == n)){
int Arr0[] = {0,1,2};
int Arg1 = 2;
int Arg2 = 6;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg2, count(Arg0, Arg1));
}
n++;
// test_case_1
if ((Case == -1) || (Case == n)){
int Arr0[] = {1,2};
int Arg1 = 0;
int Arg2 = 4;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg2, count(Arg0, Arg1));
}
n++;
// test_case_2
if ((Case == -1) || (Case == n)){
int Arr0[] = {2,2,1,0,0};
int Arg1 = 10;
int Arg2 = 0;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg2, count(Arg0, Arg1));
}
n++;
// test_case_3
if ((Case == -1) || (Case == n)){
int Arr0[] = {0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2};
int Arg1 = 7;
int Arg2 = 286226628;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg2, count(Arg0, Arg1));
}
n++;
// test_case_4
if ((Case == -1) || (Case == n)){
int Arr0[] = {0,1,2,0,1,2,2,1,0};
int Arg1 = 8;
int Arg2 = 18;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg2, count(Arg0, Arg1));
}
n++;
}
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RockPaperScissorsMagicEasy ___test;
___test.run_test(-1);
}
// END CUT HERE
|
Java
|
UTF-8
| 270 | 1.742188 | 2 |
[
"MIT"
] |
permissive
|
package pl.tycm.fes.controller.service;
import pl.tycm.fes.model.ManualFileExchange;
public interface ManualFileExchangeService {
public void startManualFileExchange(ManualFileExchange manualFileExchange);
public void stopManualFileExchange(Long id);
}
|
PHP
|
UTF-8
| 2,384 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class StoreBookValidation extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|min:3',
'price' => 'required|numeric',
'quantity' => 'required|numeric',
'author_id' => 'required|numeric',
'category_id' => 'required|numeric',
'image' => 'required',
'introduce' => 'required',
];
}
public function messages(){
return [
'name.required' => 'Trường tên không được để trống',
'name.required' => 'Trường tên không được để trống',
'price.required' => 'Trường giá tiền không được để trống!',
'price.numeric' => 'Trường giá tiền phải là số!',
'quantity.required' => 'Trường số lượng không được để trống!',
'quantity.numeric' => 'Trường số lượng phải là số!',
'author_id.required' => 'Trường tác giả không được để trống!',
'author_id.numeric' => 'Trường tác giả phải là số!',
'category_id.required' => 'Trường danh mục không được để trống!',
'category_id.numeric' => 'Trường danh mục phải là số!',
'image.required' => 'Trường hình ảnh không được để trống!',
'image.image' => 'Hình ảnh không hợp lệ!',
'introduce.required' => 'Trường giới thiệu không được để trống!',
];
}
protected function failedValidation(Validator $validator)
{
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(response()->json(['errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}
|
Python
|
UTF-8
| 8,153 | 3.796875 | 4 |
[] |
no_license
|
# search.py
# ---------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
"""
In search.py, you will implement generic search algorithms which are called
by Pacman agents (in searchAgents.py).
"""
import util
import heapq
import searchAgents
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
You do not need to change anything in this class, ever.
"""
def getStartState(self):
"""
Returns the start state for the search problem
"""
util.raiseNotDefined()
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state
"""
util.raiseNotDefined()
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples,
(successor, action, stepCost), where 'successor' is a
successor to the current state, 'action' is the action
required to get there, and 'stepCost' is the incremental
cost of expanding to that successor
"""
util.raiseNotDefined()
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions. The sequence must
be composed of legal moves
"""
util.raiseNotDefined()
def tinyMazeSearch(problem):
"""
Returns a sequence of moves that solves tinyMaze. For any other
maze, the sequence of moves will be incorrect, so only use this for tinyMaze
"""
from game import Directions
s = Directions.SOUTH
w = Directions.WEST
return [s,s,w,s,w,w,s,w]
def depthFirstSearch(problem):
"""
Search the deepest nodes in the search tree first
[2nd Edition: p 75, 3rd Edition: p 87]
Your search algorithm needs to return a list of actions that reaches
the goal. Make sure to implement a graph search algorithm
[2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7].
To get started, you might want to try some of these simple commands to
understand the search problem that is being passed in:
print "Start:", problem.getStartState()
print "Is the start a goal?", problem.isGoalState(problem.getStartState())
print "Start's successors:", problem.getSuccessors(problem.getStartState())
"""
"*** YOUR CODE HERE ***"
fringe = util.Stack(); #create an empty fringe using a LIFO queue
root = (problem.getStartState(), [], 0); #make a (successor, action, stepCost) triple
fringe.push(root); #Initialize the fringe using the start with cost 0
visited = []; #create an empty set for visited nodes.
frontier = [] #create an empty set to store the positions in fringe
while not fringe.isEmpty():
state, direction, cost = fringe.pop(); #choose the deepest leaf node
if problem.isGoalState(state):
return direction #if the node contains a goal state then return the solution
visited.append(state); #if not, add the node to visited list
for node in fringe.list:
frontier.append(node[0]) #Take out the positions stored in fringe
for cstate, cdirection, ccost in problem.getSuccessors(state):
if (cstate not in frontier) and (cstate not in visited):
path = direction + [cdirection]; #store the directional path to each fringe node
fringe.push((cstate, path, ccost));
#expand the chosen node, and add the children nodes not in visited or fringe to fringe
return [];
util.raiseNotDefined()
def breadthFirstSearch(problem):
"""
Search the shallowest nodes in the search tree first.
[2nd Edition: p 73, 3rd Edition: p 82]
"""
"*** YOUR CODE HERE ***"
fringe = util.Queue(); #create an empty fringe using a FIFO queue
root = (problem.getStartState(), [], 0); #make a (successor, action, stepCost) triple
fringe.push(root); #Initialize the fringe using the start with cost 0
visited = []; #create an empty set for visited nodes.
frontier = [] #create an empty set to store the positions in fringe
while not fringe.isEmpty():
state, direction, cost = fringe.pop(); #choose the shallowest leaf node
if problem.isGoalState(state):
return direction #if the node contains a goal state then return the solution
visited.append(state); #if not, add the node to visited list
for node in fringe.list:
frontier.append(node[0]) #Take out the positions stored in fringe
for cstate, cdirection, ccost in problem.getSuccessors(state):
if (cstate not in frontier) and (cstate not in visited):
path = direction + [cdirection]; #store the directional path to each fringe node
fringe.push((cstate, path, ccost));
#expand the chosen node, and add the children nodes not in visited or fringe to fringe
return [];
util.raiseNotDefined()
def uniformCostSearch(problem):
"Search the node of least total cost first. "
"*** YOUR CODE HERE ***"
pathcost=0
node = (pathcost, problem.getStartState(), [])
frontier = [node]
visited = []
while len(frontier)>0:
pathcost, state, direction =heapq.heappop(frontier)
# print pathcost, state, direction
if problem.isGoalState(state):
return direction
visited.append(state)
for cstate,cdirection,ccost in problem.getSuccessors(state):
if (cstate not in frontier) and (cstate not in visited):
child_node =((pathcost + ccost),cstate,direction+[cdirection])
# print child_node
heapq.heappush(frontier, child_node)
elif cstate in frontier:
child_pathcost=pathcost+ccost
for i in range(len(frontier)) :
if (frontier[i][1][1]==cstate) and ( child_pathcost < frontier[i][1][0]):
frontier[i][1][0] = child_pathcost
util.raiseNotDefined()
def nullHeuristic(state, problem=None):
"""
A heuristic function estimates the cost from the current state to the nearest
goal in the provided SearchProblem. This heuristic is trivial.
"""
return 0
def aStarSearch(problem, heuristic=nullHeuristic):
"Search the node that has the lowest combined cost and heuristic first."
"*** YOUR CODE HERE ***"
pathcost=0
heur=heuristic(problem.getStartState(),problem)
node = (pathcost+heur, problem.getStartState(), [])
frontier = [node]
visited = []
while len(frontier)<>0:
cost, state, direction =heapq.heappop(frontier)
heur = heuristic(state,problem)
pathcost = cost - heur
if problem.isGoalState(state):
return direction
visited.append(state)
for cstate,cdirection,ccost in problem.getSuccessors(state):
if (cstate not in frontier) and (cstate not in visited):
child_pathcost=pathcost + ccost
child_heur=heuristic(cstate, problem)
child_cost=child_pathcost+child_heur
child_node =(child_cost, cstate,direction+[cdirection])
heapq.heappush(frontier, child_node)
elif cstate in frontier:
child_pathcost=pathcost+ccost
for i in range(len(frontier)) :
if (frontier[i][1]==cstate) and ( child_cost < frontier[i][0]):
frontier[i][0] = child_cost
# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch
|
Python
|
UTF-8
| 1,590 | 3.28125 | 3 |
[] |
no_license
|
import face_recognition
import os
pictures = [f for f in os.listdir() if f.endswith('jpg')]
# Load all the images of those people who are known to us and calculate their face encodings
image_known_1 = face_recognition.load_image_file('person_1.jpg')
image_known_2 =face_recognition.load_image_file('person_2.jpg')
image_known_3 =face_recognition.load_image_file('person_3.jpg')
encoding_person_1 = face_recognition.face_encodings(image_known_1)[0]
encoding_person_2 = face_recognition.face_encodings(image_known_2)[0]
encoding_person_3 = face_recognition.face_encodings(image_known_3)[0]
known_encodings = [encoding_person_1,encoding_person_2,encoding_person_3]
# Now load the images we want to check and calculate their encodings.
unknown_person = face_recognition.load_image_file('unknown_7.jpg')
known_face_location = face_recognition.face_locations(unknown_person , number_of_times_to_upsample=2) # Enlarge the image to better detect faces
unknown_encoding = face_recognition.face_encodings(unknown_person , known_face_locations=known_face_location)
# call the compare_face function of the face_recognition library
for face_encodings in unknown_encoding:
results = face_recognition.compare_faces(known_encodings , face_encodings) # only has True or False values based on the known encodings
if results[0].all():
print("Person 1 is detected")
elif results[1].all():
print("Person 2 is detected")
elif results[2].all():
print ("Person 3 is detected")
else:
print ("Unknown Person")
|
Java
|
UTF-8
| 1,922 | 2.265625 | 2 |
[] |
no_license
|
package com.example.paytusker.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.paytusker.R;
public class CryptoWalletAdapter extends RecyclerView.Adapter<CryptoWalletAdapter.ViewHolder> {
Context context;
Select select;
public interface Select{
void onclick(int position);
void onsendclick(int position);
}
public CryptoWalletAdapter(Context context, Select select) {
this.context = context;
this.select = select;
}
@NonNull
@Override
public CryptoWalletAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.crypto_wallet_list,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CryptoWalletAdapter.ViewHolder holder, int position) {
holder.receive_btn_crypto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
select.onclick(position);
}
});
holder.send_btn_crypto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
select.onsendclick(position);
}
});
}
@Override
public int getItemCount() {
return 2;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private Button receive_btn_crypto,send_btn_crypto;
public ViewHolder(@NonNull View itemView) {
super(itemView);
send_btn_crypto=itemView.findViewById(R.id.send_btn_crypto);
receive_btn_crypto=itemView.findViewById(R.id.receive_btn_crypto);
}
}
}
|
Python
|
UTF-8
| 616 | 4.0625 | 4 |
[] |
no_license
|
#递归式生成器:解决多层嵌套列表
"""
在生成器开头进行检查。要检查对象是否类似于字符串,简单、 快捷的方式是,尝
试将对象与一个字符串拼接起来,并检查这是否会引发TypeError异常
"""
def flatten(nested):
try:
# 不迭代类似于字符串的对象:
try: nested + ''
except TypeError: pass
else: raise TypeError
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
print( list(flatten(['foo', ['bar', ['baz']]])) )
|
Markdown
|
UTF-8
| 2,039 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
---
title: Logic Blocks
---
# Logic Blocks
MPF config files include the concept of "logic blocks" which let you
perform logic when certain events occur. Logic blocks can be thought of
as the "glue" that ties together all the different shows, shots,
achievements, and other parts of your game logic.
There are four types of logic blocks in MPF:
[Counter Logic Blocks](counters.md)
: Count the number of times an event happens, and when a certain
number is hit, a "complete" event is posted.
[Accrual Logic Blocks](accruals.md)
: Watch for several different events to occur, and once they all do
(no matter what order they happen in), a "complete" event is
posted.
[Sequence Logic Blocks](sequences.md)
: Watch for several different events that need to occur *in a specific
order*, and once they do, a "complete" event is posted.
[State Machine Logic Block](state_machines.md)
: A generic state machine with arbitrary state transitions and state.
Logic blocks can be configured to store their state in player variables,
meaning that each logic block will remember where it was from
ball-to-ball.
Logic blocks can be added to modes, and they can have events to enable,
disable, and reset them.
To help you understand how logic blocks might be used, here are some
real world examples from *Attack from Mars* (if we were building that
game in MPF):
* A counter logic block can count the number of times a pop bumper is
hit, and then when it hits a certain number, it posts an event to
start a "Super Jets" mode.
* A counter can be used to track the three hits to the force field
that are needed to lower it.
* A counter can be used (along with a timer) to track combos
* An accrual can be used in the Martian Attack mode to track all 4 of
the martians being hit
You should also read about
[integration of show and logic blocks](integrating_logic_blocks_and_shows.md).
* [Counters](counters.md)
* [Accruals](accruals.md)
* [Sequences](sequences.md)
* [State Machines](state_machines.md)
|
SQL
|
UTF-8
| 1,842 | 3.53125 | 4 |
[] |
no_license
|
CREATE TABLE hd_attr (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name char(10) NOT NULL DEFAULT '',
color char(10) NOT NULL DEFAULT '',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
CREATE TABLE hd_blog (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
title varchar(30) NOT NULL DEFAULT '',
content text,
summary varchar(255) NOT NULL DEFAULT '',
time int(10) unsigned NOT NULL DEFAULT '0',
click smallint(6) unsigned NOT NULL DEFAULT '0',
cid int(10) unsigned NOT NULL,
del tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (id),
KEY cid (cid)
) ENGINE=MyISAM AUTO_INCREMENT=72 DEFAULT CHARSET=utf8
CREATE TABLE hd_blog_attr (
bid int(10) unsigned NOT NULL,
aid int(10) unsigned NOT NULL,
KEY bid (bid),
KEY aid (aid)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
CREATE TABLE hd_cate (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name char(15) NOT NULL DEFAULT '',
pid int(10) unsigned NOT NULL DEFAULT '0',
sort smallint(6) NOT NULL DEFAULT '0',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8
CREATE TABLE hd_user (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
username char(20) NOT NULL DEFAULT '',
password char(32) NOT NULL DEFAULT '',
logintime int(10) unsigned NOT NULL DEFAULT '0',
loginip char(20) NOT NULL DEFAULT '',
PRIMARY KEY (id),
UNIQUE KEY username (username)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
CREATE TABLE hd_user_feedback (
id int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
name char(20) NOT NULL DEFAULT 'anonymity' COMMENT '姓名',
mobile char(11) NOT NULL DEFAULT 'empty' COMMENT '电话',
msg mediumtext COMMENT '留言信息',
create_time int(11) DEFAULT NULL COMMENT '留言时间',
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='用户反馈表'
|
Java
|
UTF-8
| 3,927 | 2.40625 | 2 |
[
"MIT"
] |
permissive
|
/*
* This file is part of jHDF. A pure Java library for accessing HDF5 files.
*
* http://jhdf.io
*
* Copyright (c) 2023 James Mudd
*
* MIT License see 'LICENSE' file
*/
package io.jhdf;
import io.jhdf.api.Group;
import io.jhdf.api.Node;
import io.jhdf.api.NodeType;
import io.jhdf.exceptions.HdfInvalidPathException;
import io.jhdf.storage.HdfBackingStorage;
import io.jhdf.storage.HdfFileChannel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GroupTest {
private static final String DATASETS_GROUP = "datasets_group";
private HdfBackingStorage hdfBackingStorage;
// Mock
private Group rootGroup;
@BeforeEach
void setUp() throws IOException {
final String testFileUrl = this.getClass().getResource("/hdf5/test_file.hdf5").getFile();
File file = new File(testFileUrl);
FileChannel fc = FileChannel.open(file.toPath(), StandardOpenOption.READ);
Superblock sb = Superblock.readSuperblock(fc, 0);
hdfBackingStorage = new HdfFileChannel(fc, sb);
rootGroup = mock(Group.class);
when(rootGroup.getPath()).thenReturn("/");
when(rootGroup.getFile()).thenReturn(file);
when(rootGroup.getFileAsPath()).thenReturn(file.toPath());
}
@AfterEach
void after() {
hdfBackingStorage.close();
}
@Test
void testGroup() {
Group group = GroupImpl.createGroup(hdfBackingStorage, 800, DATASETS_GROUP, rootGroup);
assertThat(group.getPath(), is(equalTo("/datasets_group/")));
assertThat(group.toString(), is(equalTo("Group [name=datasets_group, path=/datasets_group/, address=0x320]")));
assertThat(group.isGroup(), is(true));
assertThat(group.getChildren().keySet(), hasSize(2));
assertThat(group.getName(), is(equalTo(DATASETS_GROUP)));
assertThat(group.getType(), is(equalTo(NodeType.GROUP)));
assertThat(group.getParent(), is(rootGroup));
assertThat(group.getAddress(), is(equalTo(800L)));
}
@Test
void testGettingChildrenByName() {
Group group = GroupImpl.createGroup(hdfBackingStorage, 800, DATASETS_GROUP, rootGroup);
Node child = group.getChild("int");
assertThat(child, is(notNullValue()));
}
@Test
void testGettingMissingChildReturnsNull() {
Group group = GroupImpl.createGroup(hdfBackingStorage, 800, DATASETS_GROUP, rootGroup);
Node child = group.getChild("made_up_missing_child_name");
assertThat(child, is(nullValue()));
}
@Test
void testGetByPathWithInvalidPathReturnsNull() {
Group group = GroupImpl.createGroup(hdfBackingStorage, 800, DATASETS_GROUP, rootGroup);
assertThrows(HdfInvalidPathException.class, () -> group.getByPath("float/missing_node"));
}
@Test
void testGetByPathWithValidPathReturnsNode() {
Group group = GroupImpl.createGroup(hdfBackingStorage, 800, DATASETS_GROUP, rootGroup);
String path = "float/float32";
Node child = group.getByPath(path);
assertThat(child.getPath(), is(equalTo(group.getPath() + path)));
}
@Test
void testGetByPathThroughDatasetThrows() {
Group group = GroupImpl.createGroup(hdfBackingStorage, 800, DATASETS_GROUP, rootGroup);
// Try to keep resolving a path through a dataset 'float32' this should return
// null
String path = "float/float32/missing_node";
HdfInvalidPathException e = assertThrows(HdfInvalidPathException.class, () -> group.getByPath(path));
assertThat(e.getPath(), is(equalTo("/datasets_group/float/float32/missing_node")));
}
}
|
Shell
|
UTF-8
| 582 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
# vim: ft=sh
dot_edit() {
# init
if [ ! -e "${dotlink}" ]; then
echo "$(prmpt 1 empty)$(bd_ ${dotlink})"
if __confirm y "make dotlink file ? " ; then
echo "cp ${DOT_SCRIPT_ROOTDIR}/examples/dotlink ${dotlink}"
cp "${DOT_SCRIPT_ROOTDIR}/examples/dotlink" "${dotlink}"
else
echo "Aborted."; return 1
fi
fi
# open dotlink file
if [ -n "${dot_edit_default_editor}" ];then
eval ${dot_edit_default_editor} "${dotlink}"
elif hash "$EDITOR" 2>/dev/null; then
$EDITOR "${dotlink}"
else
xdg-open "${dotlink}"
fi
unset -f $0
}
|
Java
|
UTF-8
| 695 | 2.453125 | 2 |
[
"MIT"
] |
permissive
|
package org.sparky.model.builders;
import org.sparky.model.Filter;
import org.sparky.model.Rule;
import java.util.HashMap;
import java.util.Map;
/**
* Created by lloyd on 19/10/2015.
*/
public class FilterBuilder {
private VariableBuilder left;
private VariableBuilder right;
public FilterBuilder withLeft(VariableBuilder variableBuilder){
left = variableBuilder;
return this;
}
public FilterBuilder withRight(VariableBuilder variableBuilder){
right = variableBuilder;
return this;
}
public String columnName(){
return left.buildAsColumnName();
}
public Rule getRule() {
return right.build();
}
}
|
Java
|
UTF-8
| 761 | 2.28125 | 2 |
[
"MIT"
] |
permissive
|
package com.automation.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.automation.core.SeleniumPageBase;
import com.automation.elements.PageElement;
public class LoginPage extends PageElement{
public static PageElement UsernameTextField;
public static PageElement PasswordTextField;
public static PageElement loginButton;
public LoginPage(){}
public LoginPage(WebDriver webDriver)
{
By username=By.id("login-username");
By password=By.id("login-password");
By login=By.id("btn-login");
UsernameTextField = new PageElement(username, webDriver);
PasswordTextField= new PageElement(password, webDriver);
loginButton= new PageElement(login, webDriver);
}
}
|
Java
|
UTF-8
| 12,833 | 2.125 | 2 |
[] |
no_license
|
/*
2019-2학기 전자상거래 최종 프로젝트
@12163786 장현수
@12161652 정명현
@12162892 김지은
*/
/*
MainActivity -> 일반 소비자 계정으로 접속하였을 때 만나게 되는 페이지.
소비자는 사이트 별로 주문을 넣거나, 현재 우리 대학 사람들이 특정 사이트에 얼마 만큼의 주문을 넣었는지를 확인 할 수 있다.
또한 주문이 들어간 물품에 대해서는 결제를 진행할 수 있다.
*/
package com.example.ecommerce;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.security.acl.Group;
public class MainActivity extends AppCompatActivity {
FloatingActionButton FABtn = null;
String userID = null;
String userUniv = null;
TextView tvLogOut = null;
TextView tvHello = null;
TextView univ = null;
TextView tvMoney = null;
LinearLayout layout = null;
Context context;
ProgressBar progressBar1, progressBar2, progressBar3;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference dbr = db.getReference();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userID = intent.getStringExtra("user_id");
context = this;
findViewById(R.id.editText3).setEnabled(false);
tvLogOut = (TextView) findViewById(R.id.tvLogOut);
tvLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), LogIn.class);
startActivity(intent);
finish();
}
});
tvMoney = findViewById(R.id.tvMoney);
dbr.child("user_account").orderByChild("user_id").equalTo(userID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
tvMoney.setText(singleSnapshot.getValue(UserAccountDB.class).getAccount()+"원");
}}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
FABtn = (FloatingActionButton) findViewById(R.id.FABtn);
FABtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), orderPage.class);
intent.putExtra("user_id", userID);
startActivity(intent);
finish();
}
});
tvHello = (TextView) findViewById(R.id.tvHello);
tvHello.setText(userID + "님 안녕하세요");
univ = (TextView)findViewById(R.id.user_Univ);
progressBar1 = (ProgressBar)findViewById(R.id.progressBar1);
progressBar2 = (ProgressBar)findViewById(R.id.progressBar2);
progressBar3 = (ProgressBar)findViewById(R.id.progressBar3);
progressBar1.setMax(100000);
progressBar1.setProgress(0);
progressBar2.setMax(100000);
progressBar2.setProgress(0);
progressBar3.setMax(100000);
progressBar3.setProgress(0);
dbr.child("user").orderByChild("user_id").equalTo(userID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
UserDB user = singleSnapshot.getValue(UserDB.class);
userUniv = user.getUser_univ();
univ.setText(userUniv);
String g_key = "착한구두_" + userUniv;
Log.d("ID", g_key);
dbr.child("group_order").orderByChild("group_order_id").equalTo(g_key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
GroupOrderDB gorder = singleSnapshot.getValue(GroupOrderDB.class);
int price = gorder.getPrice();
int status = gorder.getStatus();
Log.d("DB", "firebase님 살려주세요");
if(status == 0)
progressBar2.setProgress(price);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
g_key = "텐바이텐_" + userUniv;
Log.d("ID", g_key);
dbr.child("group_order").orderByChild("group_order_id").equalTo(g_key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
GroupOrderDB gorder = singleSnapshot.getValue(GroupOrderDB.class);
int price = gorder.getPrice();
int status = gorder.getStatus();
Log.d("DB", "firebase님 살려주세요");
if(status == 0)
progressBar1.setProgress(price);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
g_key = "마켓컬리_" + userUniv;
Log.d("ID", g_key);
dbr.child("group_order").orderByChild("group_order_id").equalTo(g_key).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
GroupOrderDB gorder = singleSnapshot.getValue(GroupOrderDB.class);
int price = gorder.getPrice();
int status = gorder.getStatus();
Log.d("DB", "firebase님 살려주세요");
if(status == 0)
progressBar3.setProgress(price);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//userUniv 알아내는 과정
layout = (LinearLayout)findViewById(R.id.orderLinear);
dbr.child("order").orderByChild("user_id").equalTo(userID).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
//order 내역이 있으면 여기서부터 각각 linear Activity 한개씩 생성
LinearLayout parentLL = new LinearLayout(MainActivity.this);
parentLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parentLL.setOrientation(LinearLayout.HORIZONTAL);
OrderDB order = singleSnapshot.getValue(OrderDB.class);
String site = order.getSite();
int status = order.getStatus();
String model = order.getModel();
TextView topTV1 = new TextView(MainActivity.this);
topTV1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
topTV1.setBackgroundColor(Color.parseColor("#00FFFFFF"));
topTV1.setPadding(20, 10, 10, 10);
topTV1.setTextColor(Color.parseColor("#FF7200"));
topTV1.setTextSize(13);
topTV1.setText(site + "-" + model);
parentLL.addView(topTV1);
TextView topTV2 = new TextView(MainActivity.this);
topTV2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
topTV2.setBackgroundColor(Color.parseColor("#00FFFFFF"));
topTV2.setPadding(20, 10, 10, 10);
topTV2.setTextColor(Color.parseColor("#FF7200"));
topTV2.setTextSize(13);
if(status == 0)
topTV2.setText("아직 목표 주문량을 달성하지 못하였습니다");
else if(status == 1)
topTV2.setText("입금 대기 중 입니다.");
else if(status == 2)
topTV2.setText("배송 준비 중 입니다.");
parentLL.addView(topTV2);
if(status == 1){
final Button btn = new Button(context);
btn.setText("결제");
btn.setWidth(50);
btn.setHeight(50);
parentLL.addView(btn);
final String sModel = site+"-"+model;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PurchasePage.class);
intent.putExtra("user_id", userID);
intent.putExtra("model", sModel);
startActivity(intent);
finish();
}
});
}
layout.addView(parentLL);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
C
|
UTF-8
| 1,837 | 3.953125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <math.h>
int bestPrize(int N) {
int i;
int bp = 0;
for (i=0; i<N; i++) {
bp += pow(2, i);
}
return bp;
}
void binary(int N, char* bString) {
int i=0;
// Fill bString with a backward binary representation
while (N) {
if (N & 1) { // as long as the bitwise AND does not give '0000'
bString[i] = '1';
}
else {
bString[i] = '0';
}
N >>= 1;
i++;
}
// Mirror the binary string to get the correct binary
int k = 0;
int len = i;
for (k=0; k<len/2; k++) { // Swap
char temp = bString[k];
bString[k] = bString[len-k-1];
bString[len-k-1] = temp;
}
bString[len] = '\0';
}
int countWins(int n) {
int wins = 0;
int N = n;
while (N) {
if (N & 1) wins++;
N >>= 1;
}
char bString[100];
binary(n, bString);
// printf("%s has %d wins.\n", bString, wins);
return wins;
}
int easiestPrize(int bp, int wp) {
int ep = bp;
int wins = countWins(ep);
int i;
for (i=1; i<=bp-wp; i++) {
if (countWins(bp-i) < wins) {
ep = bp-i;
}
}
return ep;
}
int main(void) {
// PART ONE - Calculating the minimum wins needed to get a prize
int N = 3;
int P = 3;
int bp = bestPrize(N);
int wp = bp - P + 1;
int ep = easiestPrize(bp, wp); // find the easiest prize between the range bp and wp
char bp0b[100];
binary(bp, bp0b);
char wp0b[100];
binary(wp, wp0b);
char ep0b[100];
binary(ep, ep0b);
printf("Best: %s, Worst: %s, Easiest: %s\n", bp0b, wp0b, ep0b);
int minWins = countWins(ep);
printf("To win a prize, a minimum of %d wins is required.\n", minWins);
// PART TWO - Finding the larget-numbered team that is guaranteed to win a prize
// PART THREE - Finding the largest-numbered team that could win a prize
int z;
z = (pow(2,N) - 1) - (2*minWins - 1);
printf("The largest-numbered team that could win a prize is %d.\n", z);
return 0;
}
|
Markdown
|
UTF-8
| 357 | 2.6875 | 3 |
[] |
no_license
|
# ivanchiou.github.io
## This is my first personal website.
### The website structure:
- Home
- Team Members
- Projects
- More items
<p align="center">
<img src="images/website_preview.png" alt="website-preview">
</p>
### Git commands I used:
```
git clone https://github.com/username/repository-name
git add .
git commit -m "description"
git push
```
|
C++
|
UTF-8
| 5,431 | 2.84375 | 3 |
[] |
no_license
|
#pragma once
#include "graph.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <optional>
#include <unordered_map>
#include <utility>
#include <vector>
namespace Graph
{
template< typename Weight >
class Router
{
private:
using Graph = DirectedWeightedGraph< Weight >;
public:
Router( const Graph& graph );
using RouteId = uint64_t;
struct RouteInfo
{
RouteId id;
Weight weight;
size_t edge_count;
};
std::optional< RouteInfo > BuildRoute( VertexId from, VertexId to ) const;
EdgeId GetRouteEdge( RouteId route_id, size_t edge_idx ) const;
void ReleaseRoute( RouteId route_id );
private:
const Graph& graph_;
struct RouteInternalData
{
Weight weight;
std::optional< EdgeId > prev_edge;
};
using RoutesInternalData = std::vector< std::vector< std::optional< RouteInternalData>> >;
using ExpandedRoute = std::vector< EdgeId >;
mutable RouteId next_route_id_ = 0;
mutable std::unordered_map< RouteId, ExpandedRoute > expanded_routes_cache_;
void InitializeRoutesInternalData( const Graph& graph )
{
const size_t vertex_count = graph.GetVertexCount();
for( VertexId vertex = 0; vertex < vertex_count; ++vertex )
{
routes_internal_data_[ vertex ][ vertex ] = RouteInternalData { 0, std::nullopt };
for( const EdgeId edge_id : graph.GetIncidentEdges( vertex ) )
{
const auto& edge = graph.GetEdge( edge_id );
assert( edge.weight >= 0 );
auto& route_internal_data = routes_internal_data_[ vertex ][ edge.to ];
if( !route_internal_data || route_internal_data->weight > edge.weight )
{
route_internal_data = RouteInternalData { edge.weight, edge_id };
}
}
}
}
void RelaxRoute( VertexId vertex_from, VertexId vertex_to,
const RouteInternalData& route_from, const RouteInternalData& route_to )
{
auto& route_relaxing = routes_internal_data_[ vertex_from ][ vertex_to ];
const Weight candidate_weight = route_from.weight + route_to.weight;
if( !route_relaxing || candidate_weight < route_relaxing->weight )
{
route_relaxing = {
candidate_weight,
route_to.prev_edge
? route_to.prev_edge
: route_from.prev_edge
};
}
}
void RelaxRoutesInternalDataThroughVertex( size_t vertex_count, VertexId vertex_through )
{
for( VertexId vertex_from = 0; vertex_from < vertex_count; ++vertex_from )
{
if( const auto& route_from = routes_internal_data_[ vertex_from ][ vertex_through ] )
{
for( VertexId vertex_to = 0; vertex_to < vertex_count; ++vertex_to )
{
if( const auto& route_to = routes_internal_data_[ vertex_through ][ vertex_to ] )
{
RelaxRoute( vertex_from, vertex_to, *route_from, *route_to );
}
}
}
}
}
RoutesInternalData routes_internal_data_;
};
template< typename Weight >
Router< Weight >::Router( const Graph& graph )
: graph_( graph )
, routes_internal_data_( graph.GetVertexCount(),
std::vector< std::optional< RouteInternalData>>( graph.GetVertexCount() ) )
{
InitializeRoutesInternalData( graph );
const size_t vertex_count = graph.GetVertexCount();
for( VertexId vertex_through = 0; vertex_through < vertex_count; ++vertex_through )
{
RelaxRoutesInternalDataThroughVertex( vertex_count, vertex_through );
}
}
template< typename Weight >
std::optional< typename Router< Weight >::RouteInfo > Router< Weight >::BuildRoute( VertexId from, VertexId to ) const
{
const auto& route_internal_data = routes_internal_data_[ from ][ to ];
if( !route_internal_data )
{
return std::nullopt;
}
const Weight weight = route_internal_data->weight;
std::vector< EdgeId > edges;
for( std::optional< EdgeId > edge_id = route_internal_data->prev_edge;
edge_id;
edge_id = routes_internal_data_[ from ][ graph_.GetEdge( *edge_id ).from ]->prev_edge )
{
edges.push_back( *edge_id );
}
std::reverse( std::begin( edges ), std::end( edges ) );
const RouteId route_id = next_route_id_++;
const size_t route_edge_count = edges.size();
expanded_routes_cache_[ route_id ] = std::move( edges );
return RouteInfo { route_id, weight, route_edge_count };
}
template< typename Weight >
EdgeId Router< Weight >::GetRouteEdge( RouteId route_id, size_t edge_idx ) const
{
return expanded_routes_cache_.at( route_id )[ edge_idx ];
}
template< typename Weight >
void Router< Weight >::ReleaseRoute( RouteId route_id )
{
expanded_routes_cache_.erase( route_id );
}
}
|
Java
|
UTF-8
| 10,867 | 1.78125 | 2 |
[] |
no_license
|
package com.example.veradebora.dds.ui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import com.example.veradebora.dds.R;
import com.example.veradebora.dds.adapter.RecyclerViewAdapter;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import in.goodiebag.carouselpicker.CarouselPicker;
public class reqvm2 extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
Toolbar toolbar=null;
// CarouselPicker carousel1;
public TextView username;
public String namauser;
public Integer vcpu=1, ram=1, storage=20;
private static SeekBar seek_bar;
private static TextView text_view;
private static TextView text_view2;
private static TextView text_view3;
private static final String TAG = "reqvm2";
//vars
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reqvm2);
SharedPreferences sharedPreferences = getSharedPreferences("Sementara", Context.MODE_PRIVATE);
namauser = sharedPreferences.getString("UserName","");
//Seekbar
seekvcpu();
seekram();
seekstorage();
// carousel1 = (CarouselPicker) findViewById(R.id.carousel1);
//
// //carousel1
// List<CarouselPicker.PickerItem> OSItems = new ArrayList<>();
// OSItems.add(new CarouselPicker.TextItem("Debian \n8 x64",8));
// OSItems.add(new CarouselPicker.TextItem("CentOS \n7 x64",8));
// OSItems.add(new CarouselPicker.TextItem("Ubuntu \n16.04.2 x64",8));
// CarouselPicker.CarouselViewAdapter textAdapter = new CarouselPicker.CarouselViewAdapter(this,OSItems,0);
// carousel1.setAdapter(textAdapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerview = navigationView.getHeaderView(0);
username = (TextView) headerview.findViewById(R.id.textView2);
username.setText(namauser);
navigationView.setNavigationItemSelectedListener(this);
getImages();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id=item.getItemId();
switch (id){
case R.id.nav_dashboard:
Intent h= new Intent(this,Home.class);
startActivity(h);
break;
case R.id.nav_Wallet:
Intent i= new Intent(this,Wallet.class);
startActivity(i);
break;
case R.id.nav_billing:
Intent j= new Intent(this,Billing.class);
startActivity(j);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void logout(MenuItem item) {
SharedPreferences sharedPreferences = getSharedPreferences("Sementara", Context.MODE_PRIVATE);
sharedPreferences.edit().remove("UserName").commit();
Intent intent = new Intent(this,Login.class);
startActivity(intent);
}
public void seekvcpu( ){
seek_bar = (SeekBar) findViewById(R.id.seek1);
text_view = (TextView) findViewById(R.id.txtvcpu);
text_view.setText("1 vCPU");
seek_bar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int progress_value=1;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
text_view.setText(progress_value+ progress + " vCPU" );
vcpu= progress_value+progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
}
public void seekram( ){
seek_bar = (SeekBar) findViewById(R.id.seek2);
text_view2 = (TextView) findViewById(R.id.txtram);
text_view2.setText("1 GB RAM");
seek_bar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int progress_value;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress_value=1;
if (progress==0){
progress=0;
}else if (progress==1){
progress=1;
}else {
progress=3;
}
text_view2.setText(progress_value+progress + " GB RAM" );
ram= progress_value+progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
}
public void seekstorage(){
seek_bar = (SeekBar) findViewById(R.id.seek3);
text_view3 = (TextView) findViewById(R.id.txtstorage);
text_view3.setText("20 GB Storage");
seek_bar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int progress_value=20;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
if (progress==0){
progress=0;
}else if(progress==1) {
progress=20;
}else{
progress=60;
}
text_view3.setText(progress_value+progress + " GB RAM" );
storage= progress_value+progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
}
public void reqvm2(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setMessage("vCPU:\t\t\t\t"+vcpu+" vCPU\n"+
"Memory:\t\t\t\t"+ram+" GB \n"+
"Storage:\t\t\t\t"+storage+" GB \n"+
"Cost per Hour:\t\t\t\t Rp 9.000.000\n"+
"Cost per Month:\t\t\t\t Rp 99.000.000");
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void getImages(){
Log.d(TAG, "initImageBitmaps: preparing bitmaps.");
mImageUrls.add("https://www.v3.co.uk/w-images/fb8cb057-1288-44c3-a982-11bec8d99e3a/0/debianlogo-580x358.jpg");
mNames.add("Debian 8x64");
mImageUrls.add("https://assets.ubuntu.com/v1/8dd99b80-ubuntu-logo14.png");
mNames.add("Ubuntu 16.04.2x64");
mImageUrls.add("https://bgasparotto.com/wp-content/uploads/2017/10/install-centos-7-logo.png");
mNames.add("CentOS 7x64");
initRecyclerView();
}
private void initRecyclerView(){
Log.d(TAG, "initRecyclerView: init recyclerview");
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, mNames, mImageUrls);
recyclerView.setAdapter(adapter);
}
}
|
Python
|
UTF-8
| 314 | 2.609375 | 3 |
[] |
no_license
|
import requests
def main():
params = {
'q':'python',
}
url = 'https://qiita.com/search/'
r = requests.get(url,params=params)
event_info = r.json()
for event in event_info['events']:
print(event['title'])
# print (event_info)
if __name__ == '__main__':
main()
|
Markdown
|
UTF-8
| 944 | 2.765625 | 3 |
[] |
no_license
|
# Classes in C++
This project creates and tests shape classes in C++.
### Description
C++ header and source files that define and implement several shape classes. The code is tested by running the test.cpp source file.
### Required Libraries and Dependencies
No required Libraries or external dependencies to run this project.
### Contents
- "Shape.hpp" header file contains Shape base class definition
- "Shape.cpp" source file contains Shape class implementation
- "Point.hpp" header file contains Point Class Definition (including added operators to the Point Class)
- "Point.cpp" source file contains Point class implementation
- "Line.hpp" header file contains Line Class definition
- "Line.cpp" source file contains Line Class implementation
- "Circle.hpp" header file contains Circle Class definition
- "Circle.cpp" source file contains Circle Class implementation
- "Test.cpp" source file contains main function to test the program
|
C#
|
UTF-8
| 1,111 | 3.328125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StoreLibrary;
namespace Example01
{
internal class Program
{
private static void Main(string[] args)
{
Product product = new Product();
Console.Write("請輸入產品名稱:");
product.Name = Console.ReadLine();
Console.Write("請輸入{0}的價錢:", product.Name);
Console.WriteLine("共有{0}個Product", Product.TotalProducts);
try
{
int price = 0;
price = int.Parse(Console.ReadLine());
product.Price = price;
Console.WriteLine("產品:{0}的價格是{1}", product.Name, product.Price);
}
catch
{
Console.WriteLine("價格輸入錯誤");
return;
}
Console.WriteLine(product);
Product product2 = product.Clone();
product2.Name = "BB";
Console.WriteLine(product2);
}
}
}
|
SQL
|
UTF-8
| 1,912 | 3.171875 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jun 01, 2018 at 07:15 PM
-- Server version: 5.7.19
-- PHP Version: 7.1.9
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `catering`
--
-- --------------------------------------------------------
--
-- Table structure for table `proizvod`
--
DROP TABLE IF EXISTS `proizvod`;
CREATE TABLE IF NOT EXISTS `proizvod` (
`id` int(100) UNSIGNED NOT NULL AUTO_INCREMENT,
`naziv` varchar(30) NOT NULL,
`opis` varchar(50) NOT NULL,
`cijena_po_jedinici` varchar(10) NOT NULL,
`tip_proizvoda_id` int(100) UNSIGNED NOT NULL,
`foto` varchar(200) DEFAULT 'no_image.jpg',
PRIMARY KEY (`id`),
KEY `tip_proizvoda_id` (`tip_proizvoda_id`)
) ENGINE=MyISAM AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;
--
-- Dumping data for table `proizvod`
--
INSERT INTO `proizvod` (`id`, `naziv`, `opis`, `cijena_po_jedinici`, `tip_proizvoda_id`, `foto`) VALUES
(1, 'Tost s jajima', 'Engleski tip doručka', '1.00', 4, '11.jpg'),
(2, 'Royal burger', 'Meso sa roštilja u pecivu sa susamom', '3.00', 1, '15.jpg'),
(3, 'Losos', 'Brusketi s lososom', '10.00', 2, '18.jpg'),
(4, 'Tart s malinama', 'Kolač s malinama i šlagom', '4.00', 4, '20.jpg'),
(6, 'Biftek s jajima i ruzmarinom', 'Teleće meso sa prilozima', '7.00', 1, '8.jpg'),
(7, 'Vege burger', 'Soja burger sa tikvicom', '12.00', 2, '21.jpg');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
TypeScript
|
UTF-8
| 465 | 2.546875 | 3 |
[] |
no_license
|
export interface Article {
key?: string;
title: string;
category: string;
topic: string;
date: number;
lastModifiedDate: number;
hebrewDate: string;
sections: ArticleSection[];
isActive: boolean;
}
export interface ArticleSection {
header?: string;
content: string;
source?: string;
}
export interface Category {
key?: string;
name: string;
}
export interface Topic {
key?: string;
name: string;
}
|
Java
|
UTF-8
| 6,991 | 1.875 | 2 |
[
"MIT"
] |
permissive
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 NBCO Yandex.Money LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.yandex.money.api.typeadapters;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.yandex.money.api.methods.AccountInfo;
import com.yandex.money.api.methods.JsonUtils;
import com.yandex.money.api.model.AccountStatus;
import com.yandex.money.api.model.AccountType;
import com.yandex.money.api.model.Avatar;
import com.yandex.money.api.model.BalanceDetails;
import com.yandex.money.api.model.Card;
import com.yandex.money.api.model.YandexMoneyCard;
import com.yandex.money.api.utils.Currency;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import static com.yandex.money.api.methods.JsonUtils.getArray;
import static com.yandex.money.api.methods.JsonUtils.getMandatoryBigDecimal;
import static com.yandex.money.api.methods.JsonUtils.getMandatoryString;
import static com.yandex.money.api.methods.JsonUtils.toJsonArray;
/**
* Type adapter for {@link AccountInfo}.
*
* @author Slava Yasevich (vyasevich@yamoney.ru)
*/
public final class AccountInfoTypeAdapter extends BaseTypeAdapter<AccountInfo> {
private static final AccountInfoTypeAdapter INSTANCE = new AccountInfoTypeAdapter();
private static final String MEMBER_ACCOUNT = "account";
private static final String MEMBER_AVATAR = "avatar";
private static final String MEMBER_BALANCE = "balance";
private static final String MEMBER_BALANCE_DETAILS = "balance_details";
private static final String MEMBER_CARDS_LINKED = "cards_linked";
private static final String MEMBER_CURRENCY = "currency";
private static final String MEMBER_SERVICES_ADDITIONAL = "services_additional";
private static final String MEMBER_STATUS = "account_status";
private static final String MEMBER_TYPE = "account_type";
private static final String MEMBER_YANDEX_MONEY_CARDS = "ymoney_cards";
private AccountInfoTypeAdapter() {
}
/**
* @return instance of this class
*/
public static AccountInfoTypeAdapter getInstance() {
return INSTANCE;
}
@Override
protected Class<AccountInfo> getType() {
return AccountInfo.class;
}
@Override
public AccountInfo deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
Currency currency;
try {
int parsed = Integer.parseInt(JsonUtils.getString(object, MEMBER_CURRENCY));
currency = Currency.parseNumericCode(parsed);
} catch (NumberFormatException e) {
currency = Currency.RUB;
}
Avatar avatar = null;
if (object.has(MEMBER_AVATAR)) {
avatar = AvatarTypeAdapter.getInstance().fromJson(object.get(MEMBER_AVATAR));
}
BalanceDetails balanceDetails = BalanceDetailsTypeAdapter.getInstance().fromJson(
object.get(MEMBER_BALANCE_DETAILS));
List<Card> linkedCards = object.has(MEMBER_CARDS_LINKED) ?
getArray(object, MEMBER_CARDS_LINKED, CardTypeAdapter.getInstance()) :
Collections.<Card>emptyList();
List<String> additionalServices = object.has(MEMBER_SERVICES_ADDITIONAL) ?
getArray(object, MEMBER_SERVICES_ADDITIONAL, StringTypeAdapter.getInstance()) :
Collections.<String>emptyList();
List<YandexMoneyCard> yandexMoneyCards = object.has(MEMBER_YANDEX_MONEY_CARDS) ?
getArray(object, MEMBER_YANDEX_MONEY_CARDS, YandexMoneyCardTypeAdapter.getInstance()) :
Collections.<YandexMoneyCard>emptyList();
return new AccountInfo.Builder()
.setAccount(getMandatoryString(object, MEMBER_ACCOUNT))
.setBalance(getMandatoryBigDecimal(object, MEMBER_BALANCE))
.setCurrency(currency)
.setAccountStatus(AccountStatus.parse(getMandatoryString(object, MEMBER_STATUS)))
.setAccountType(AccountType.parse(getMandatoryString(object, MEMBER_TYPE)))
.setAvatar(avatar)
.setBalanceDetails(balanceDetails)
.setLinkedCards(linkedCards)
.setAdditionalServices(additionalServices)
.setYandexMoneyCards(yandexMoneyCards)
.createAccountInfo();
}
@Override
public JsonElement serialize(AccountInfo src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty(MEMBER_ACCOUNT, src.account);
object.addProperty(MEMBER_BALANCE, src.balance);
object.addProperty(MEMBER_CURRENCY, src.currency.numericCode);
object.addProperty(MEMBER_STATUS, src.accountStatus.code);
object.addProperty(MEMBER_TYPE, src.accountType.code);
object.add(MEMBER_AVATAR, AvatarTypeAdapter.getInstance().toJsonTree(src.avatar));
object.add(MEMBER_BALANCE_DETAILS, BalanceDetailsTypeAdapter.getInstance().toJsonTree(
src.balanceDetails));
if (!src.linkedCards.isEmpty()) {
object.add(MEMBER_CARDS_LINKED, toJsonArray(src.linkedCards,
CardTypeAdapter.getInstance()));
}
if (!src.additionalServices.isEmpty()) {
object.add(MEMBER_SERVICES_ADDITIONAL,
toJsonArray(src.additionalServices, StringTypeAdapter.getInstance()));
}
if (!src.yandexMoneyCards.isEmpty()) {
object.add(MEMBER_YANDEX_MONEY_CARDS,
toJsonArray(src.yandexMoneyCards, YandexMoneyCardTypeAdapter.getInstance()));
}
return object;
}
}
|
C++
|
UTF-8
| 1,132 | 3.609375 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
//字面值常量类
/*
1. 数据成员都是字面之类型的聚合类,是字面值常量类
2. 数据成员都是字面值类型;至少含有一个constexpr构造函数;
如果数据成员含有类内初始值,则初始值是常量表达式;
如果成员属于某种类类型,则初始值必须使用成员自己的constexpr构造函数;
类必须使用析构函数的默认定义;
3. constexpr构造函数体一般是空的;
*/
class Debug {
public:
//constexpr构造函数必须初始化所有成员
constexpr Debug(bool b = true): hw(b), io(b), other(b) {}
constexpr Debug(bool h, bool i, bool o):
hw(h), io(i), other(o) {}
constexpr bool any() { return hw || io || other }
void set_io(bool b) { io = b; }
void set_hw(bool b) { hw = b; }
void set_other(bool b) { hw = b; }
private:
bool hw;
bool io;
bool other;
};
int main(void)
{
constexpr Debug io_sub(false, true, true);
if (io_sub.any())
cerr << "print appropriate error messages" << endl;
constexpr Debug prod(false);
if (prod.any())
cerr << "print an error message" << endl;
}
|
Python
|
UTF-8
| 424 | 2.953125 | 3 |
[] |
no_license
|
# PIL(Python Image Library) 객체 활용
from io import BytesIO
from picamera import PiCamera
from PIL import Image
stream = BytesIO()
camera = PiCamera()
print(camera.resolution) # 기본 해상도 확인
camera.rotation = 180 # 180도 회전
camera.capture(stream, format='jpeg')
stream.seek(0) # rewind
image = Image.open(stream)
image.show() # 임시파일 형태로 열린다.
|
Java
|
UTF-8
| 1,995 | 2.609375 | 3 |
[] |
no_license
|
package com.household.pojo;
public class OperationRecords {
private Integer operationId;
private String operationObject;
private String operationBehavior;
private String dataLast;
private String dataNow;
public Integer getOperationId() {
return operationId;
}
public void setOperationId(Integer operationId) {
this.operationId = operationId;
}
public String getOperationObject() {
return operationObject;
}
public void setOperationObject(String operationObject) {
this.operationObject = operationObject == null ? null : operationObject.trim();
}
public String getOperationBehavior() {
return operationBehavior;
}
public void setOperationBehavior(String operationBehavior) {
this.operationBehavior = operationBehavior == null ? null : operationBehavior.trim();
}
public String getDataLast() {
return dataLast;
}
public void setDataLast(String dataLast) {
this.dataLast = dataLast == null ? null : dataLast.trim();
}
public String getDataNow() {
return dataNow;
}
public void setDataNow(String dataNow) {
this.dataNow = dataNow == null ? null : dataNow.trim();
}
public OperationRecords() {
super();
// TODO Auto-generated constructor stub
}
public OperationRecords(Integer operationId, String operationObject, String operationBehavior, String dataLast,
String dataNow) {
super();
this.operationId = operationId;
this.operationObject = operationObject;
this.operationBehavior = operationBehavior;
this.dataLast = dataLast;
this.dataNow = dataNow;
}
@Override
public String toString() {
return "OperationRecords [operationId=" + operationId + ", operationObject=" + operationObject
+ ", operationBehavior=" + operationBehavior + ", dataLast=" + dataLast + ", dataNow=" + dataNow + "]";
}
}
|
PHP
|
UTF-8
| 7,143 | 2.796875 | 3 |
[] |
no_license
|
<?php
class SessionControl {
public static function start_session($user_id, $user_firstname, $user_secondname, $user_lastname, $user_email, $user_password, $user_phone, $user_gender, $user_is_active, $user_kind, $user_creation_date, $user_image) {
// Verificamos que no esté iniciada otra sesión
if (session_id() == '')
{ // Si no está iniciada la sesión para este navegador...
// Habilitamos espacio en la memoria del servidor para la sesión y la iniciamos
session_start();
}
// Guardamos los datos del usuario en el array global $_SESSION, en forma de una cookie en el servidor
$_SESSION['user_id'] = $user_id;
$_SESSION['user_firstname'] = $user_firstname;
$_SESSION['user_secondname'] = $user_secondname;
$_SESSION['user_lastname'] = $user_lastname;
$_SESSION['user_email'] = $user_email;
$_SESSION['user_password'] = $user_password;
$_SESSION['user_phone'] = $user_phone;
$_SESSION['user_gender'] = $user_gender;
$_SESSION['user_is_active'] = $user_is_active;
$_SESSION['user_kind'] = $user_kind;
$_SESSION['user_creation_date'] = $user_creation_date;
$_SESSION['user_image'] = $user_image;
}
public static function close_session() {
// Verificamos que no esté iniciada otra sesión
if (session_id() == '')
{ // Si no está iniciada la sesión para este navegador...
// Habilitamos espacio en la memoria del servidor para la sesión, aunque vayamos a cerrarla luego
session_start();
}
// Verificamos que esté definida una cookie en el servidor para el user_id
if (isset($_SESSION['user_id']))
{ // Si está definida la cookie para el user_id...
// Borramos los datos guardados del user_id en las cookies del servidor
unset($_SESSION['user_id']);
}
// Verificamos que esté definida una cookie en el servidor para el user_firstname
if (isset($_SESSION['user_firstname']))
{ // Si está definida la cookie para el user_firstname...
// Borramos los datos guardados del user_firstname en las cookies del servidor
unset($_SESSION['user_firstname']);
}
// Verificamos que esté definida una cookie en el servidor para el user_secondname
if (isset($_SESSION['user_secondname']))
{ // Si está definida la cookie para el user_secondname...
// Borramos los datos guardados del user_secondname en las cookies del servidor
unset($_SESSION['user_secondname']);
}
// Verificamos que esté definida una cookie en el servidor para el user_lastname
if (isset($_SESSION['user_lastname']))
{ // Si está definida la cookie para el user_lastname...
// Borramos los datos guardados del user_lastname en las cookies del servidor
unset($_SESSION['user_lastname']);
}
// Verificamos que esté definida una cookie en el servidor para el user_email
if (isset($_SESSION['user_email']))
{ // Si está definida la cookie para el user_email...
// Borramos los datos guardados del user_email en las cookies del servidor
unset($_SESSION['user_email']);
}
// Verificamos que esté definida una cookie en el servidor para el user_password
if (isset($_SESSION['user_password']))
{ // Si está definida la cookie para el user_password...
// Borramos los datos guardados del user_password en las cookies del servidor
unset($_SESSION['user_password']);
}
// Verificamos que esté definida una cookie en el servidor para el user_phone
if (isset($_SESSION['user_phone']))
{ // Si está definida la cookie para el user_phone...
// Borramos los datos guardados del user_phone en las cookies del servidor
unset($_SESSION['user_phone']);
}
// Verificamos que esté definida una cookie en el servidor para el user_gender
if (isset($_SESSION['user_gender']))
{ // Si está definida la cookie para el user_gender...
// Borramos los datos guardados del user_gender en las cookies del servidor
unset($_SESSION['user_gender']);
}
// Verificamos que esté definida una cookie en el servidor para el user_is_active
if (isset($_SESSION['user_is_active']))
{ // Si está definida la cookie para el user_is_active...
// Borramos los datos guardados del user_is_active en las cookies del servidor
unset($_SESSION['user_is_active']);
}
// Verificamos que esté definida una cookie en el servidor para el user_kind
if (isset($_SESSION['user_kind']))
{ // Si está definida la cookie para el user_kind...
// Borramos los datos guardados del user_kind en las cookies del servidor
unset($_SESSION['user_kind']);
}
// Verificamos que esté definida una cookie en el servidor para el user_creation_date
if (isset($_SESSION['user_creation_date']))
{ // Si está definida la cookie para el user_creation_date...
// Borramos los datos guardados del user_creation_date en las cookies del servidor
unset($_SESSION['user_creation_date']);
}
// Verificamos que esté definida una cookie en el servidor para el user_image
if (isset($_SESSION['user_image']))
{ // Si está definida la cookie para el user_image...
// Borramos los datos guardados del user_image en las cookies del servidor
unset($_SESSION['user_image']);
}
// Para asegurarnos que todo está bien cerrado, destruimos el espacio en la memoria del servidor para esta sesión
session_destroy();
}
public static function is_the_session_started() {
// Verificamos que no esté iniciada otra sesión
if (session_id() == '')
{ // Si no está iniciada la sesión para este navegador...
// Habilitamos espacio en la memoria del servidor para la sesión
// session_start();
}
// Verificamos que esté definida una cookie en el servidor para los más útiles campos del usuario
if ((isset($_SESSION['user_id'])) && (isset($_SESSION['user_firstname'])) && (isset($_SESSION['user_email'])) && (isset($_SESSION['user_phone'])))
{
return true;
}
else
{
return false;
}
}
}
|
Java
|
UTF-8
| 1,347 | 2.546875 | 3 |
[] |
no_license
|
package com.zadi.zadi.utils;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import com.zadi.zadi.R;
public class DialogUtils {
public static AlertDialog showAlertDialog(Context context, String message,
DialogInterface.OnClickListener negativeClickListener) {
// create the dialog builder & set message
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle(message);
// check negative click listener
if (negativeClickListener != null) {
// not null
// add negative click listener
dialogBuilder.setNegativeButton(context.getString(R.string.yes), negativeClickListener);
} else {
// null
// add new click listener to dismiss the dialog
dialogBuilder.setNegativeButton(context.getString(R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
// create and show the dialog
AlertDialog dialog = dialogBuilder.create();
dialog.show();
return dialog;
}
}
|
Markdown
|
UTF-8
| 2,072 | 2.578125 | 3 |
[] |
no_license
|
### Instalar OpenSSH:
* Ejecutar Powersherll con permisos de administrador
* Verificar si OpenSSH server y client están instalados
~~~
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
~~~
> Nota: si dice ***NotPresent*** significa que no está instalado
* Instalar OpenSSH client si no se ha instalado
~~~
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
~~~
* Instalar OpenSSH server si no se ha instalado
~~~
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
~~~
-----------------------------
### Crear OpenSSH Server:
* Instalar OpenSSH server
~~~
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
~~~
* Abrir el powershell con permisos de administrador
* Iniciar servicio de ssh server
~~~
Start-Service sshd
~~~
* Ajustes opcionales (recomendado)
~~~
Set-Service -Name sshd -StartupType 'Automatic'
~~~
* Transmitir al firewall la regla del servicio
~~~
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
}
~~~
-----------------------------
### Conectar a OpenSSH Server:
* Abrir powershell
* Conectar a ip del servidor
~~~
ssh username@servername
~~~
-----------------------------
### Desinstalar a OpenSSH:
#### Opción 1:
* Abrir ***Settings***, luego ir a ***Apps > Apps & Features***.
* Ir a ***Optional Features***.
* En la lista, seleccionar ***OpenSSH Client*** o ***OpenSSH Server***.
* Seleccionar ***Uninstall***.
#### Opción 2:
* Abrir powershell
* Ejecutar para OpenSSH Client:
~~~
Remove-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
~~~
* Ejecutar para OpenSSH Server:
~~~
Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
~~~
|
C#
|
UTF-8
| 3,704 | 2.796875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using SirLibCore.Data;
using SirLibCore.Utilities;
namespace Solum
{
public class Qds_Setting_Sp
{
#region Fields
protected string connectionStringName;
#endregion
#region Constructors
public Qds_Setting_Sp(string connectionStringName)
{
//ValidationUtility.ValidateArgument("connectionStringName", connectionStringName);
this.connectionStringName = connectionStringName;
}
#endregion
#region Methods
/// <summary>
/// Saves a record to the Qds_Settings table.
/// </summary>
public virtual void Insert(Qds_Setting qds_Setting)
{
ValidationUtility.ValidateArgument("qds_Setting", qds_Setting);
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@Name", qds_Setting.Name),
new SqlParameter("@Description", qds_Setting.Description),
new SqlParameter("@SetValue", qds_Setting.SetValue)
};
SqlClientUtility.ExecuteNonQuery(connectionStringName, CommandType.StoredProcedure, "Qds_Settings_Insert", parameters);
}
/// <summary>
/// Updates a record in the Qds_Settings table.
/// </summary>
public virtual void Update(Qds_Setting qds_Setting)
{
ValidationUtility.ValidateArgument("qds_Setting", qds_Setting);
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@Name", qds_Setting.Name),
new SqlParameter("@Description", qds_Setting.Description),
new SqlParameter("@SetValue", qds_Setting.SetValue)
};
SqlClientUtility.ExecuteNonQuery(connectionStringName, CommandType.StoredProcedure, "Qds_Settings_Update", parameters);
}
/// <summary>
/// Deletes a record from the Qds_Settings table by its primary key.
/// </summary>
public virtual void Delete(string name)
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@Name", name)
};
SqlClientUtility.ExecuteNonQuery(connectionStringName, CommandType.StoredProcedure, "Qds_Settings_Delete", parameters);
}
/// <summary>
/// Selects a single record from the Qds_Settings table.
/// </summary>
public virtual Qds_Setting Select(string name)
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@Name", name)
};
using (SqlDataReader dataReader = SqlClientUtility.ExecuteReader(connectionStringName, CommandType.StoredProcedure, "Qds_Settings_Select", parameters))
{
if (dataReader.Read())
{
return MakeQds_Setting(dataReader);
}
else
{
return null;
}
}
}
/// <summary>
/// Selects all records from the Qds_Settings table.
/// </summary>
public virtual List<Qds_Setting> SelectAll()
{
using (SqlDataReader dataReader = SqlClientUtility.ExecuteReader(connectionStringName, CommandType.StoredProcedure, "Qds_Settings_SelectAll"))
{
List<Qds_Setting> qds_SettingList = new List<Qds_Setting>();
while (dataReader.Read())
{
Qds_Setting qds_Setting = MakeQds_Setting(dataReader);
qds_SettingList.Add(qds_Setting);
}
return qds_SettingList;
}
}
/// <summary>
/// Creates a new instance of the Qds_Settings class and populates it with data from the specified SqlDataReader.
/// </summary>
protected virtual Qds_Setting MakeQds_Setting(SqlDataReader dataReader)
{
Qds_Setting qds_Setting = new Qds_Setting();
qds_Setting.Name = SqlClientUtility.GetString(dataReader, "Name", String.Empty);
qds_Setting.Description = SqlClientUtility.GetString(dataReader, "Description", String.Empty);
qds_Setting.SetValue = SqlClientUtility.GetObject(dataReader, "SetValue", new object());
return qds_Setting;
}
#endregion
}
}
|
C++
|
UTF-8
| 2,362 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
#if !defined (CLUSTER_H)
#define CLUSTER_H
//------------------------------------
// (c) Reliable Software 1997
//------------------------------------
// A cluster of lines that were moved together
class Cluster
{
public:
Cluster (): _len (0) {}
Cluster (int oldLineNo, int newLineNo, int len = 1)
: _oldLineNo (oldLineNo), _newLineNo (newLineNo), _len (len)
{}
void Extend () { _len++; }
void ExtendUp ();
int Len () const { return _len; }
bool IsEmpty () const { return _len == 0; }
int NewLineNo () const { return _newLineNo; }
int OldLineNo () const { return _oldLineNo; }
int Shift () const { return _newLineNo - _oldLineNo; }
bool BetterThan (Cluster * other) const
{
return Len () > other->Len ();
}
bool IsNewIn (int newLineNo) const
{
return newLineNo >= _newLineNo && newLineNo < _newLineNo + _len;
}
bool IsOldIn (int oldLineNo) const
{
return oldLineNo >= _oldLineNo && oldLineNo < _oldLineNo + _len;
}
void ShortenFromFront (int len)
{
if (len >= _len)
_len = 0;
else
{
_newLineNo += len;
_oldLineNo += len;
_len -= len;
}
}
void ShortenFromEnd (int len)
{
_len -= len;
}
Cluster SplitCluster (int offset);
private:
int _oldLineNo;
int _newLineNo;
int _len;
};
// Iterator
typedef std::vector<Cluster *>::iterator CluIter;
// Functors
class CmpOldLines: public std::binary_function<Cluster const *, Cluster const *, bool>
{
public:
bool operator () (Cluster const * const & clu1, Cluster const * const & clu2) const
{
return clu1->OldLineNo () < clu2->OldLineNo ();
}
};
class CmpNewLines: public std::binary_function<Cluster const *, Cluster const *, bool>
{
public:
bool operator () (Cluster const * const & clu1, Cluster const * const & clu2) const
{
return clu1->NewLineNo () < clu2->NewLineNo ();
}
};
class CmpLength: public std::binary_function<Cluster const *, Cluster const *, bool>
{
public:
bool operator () (Cluster const * const & clu1, Cluster const * const & clu2) const
{
return clu1->Len () < clu2->Len ();
}
};
class NotAdded: public std::unary_function<Cluster const *, bool>
{
public:
bool operator () (Cluster * clu) const
{
return clu->OldLineNo () != -1;
}
};
class NotZeroLength: public std::unary_function<Cluster const *, bool>
{
public:
bool operator () (Cluster * clu) const
{
return clu->Len () != 0;
}
};
#endif
|
TypeScript
|
UTF-8
| 1,782 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
export type Plat = {
exit: (code: number) => never
stdout: {
write: (out: string) => void
}
args: string[]
}
const PLAT = {} as Plat
const print = (output: string): void => {
PLAT.stdout.write(output)
}
const println = (output: string): void => {
print(output + '\n')
}
const exit = (code = 0): never => {
return PLAT.exit(code) as never
}
const panic = (message: {
ok?: boolean
description?: string
error?: Error
}): never => {
console.error({ ok: false, ...message })
return exit(1)
}
type _HashMap = { [key in string | number]: any }
const copy = <T>(source: T): T => {
if (source == null) return source
else if (Array.isArray(source)) {
const _t = [] as any[]
source.forEach((v) => {
_t.push(copy(v))
})
return _t as any
} else if (typeof source === 'object') {
// https://github.com/Microsoft/TypeScript/issues/6373
const _s = source as { constructor: { name?: string } }
if (_s.constructor.name !== 'Object') {
return source
} else {
const _s = source as _HashMap
const _t = {} as _HashMap
for (const key of Object.keys(_s)) {
_t[key] = copy(_s[key])
}
return _t as T
}
}
return source
}
const deepCopy = <T extends _HashMap>(source: T): T => {
if (typeof source != 'object' || source === null || Array.isArray(source)) {
throw new TypeError()
}
if (source == {}) {
return {} as T
}
const _t = {} as _HashMap
for (const key of Object.keys(source)) {
_t[key] = copy(source[key])
}
return _t as T
}
export { PLAT }
export { print, println, panic, deepCopy, exit }
|
Java
|
UTF-8
| 464 | 1.65625 | 2 |
[] |
no_license
|
package modelo;
public interface InterrogaModelo {
public String[][] getClientes();
public String[][] getLlamadas(String text);
public String[][] getFacturas(String text);
public String[][] getClientesEntreFechas(String inicio, String fin);
public String[][] getLlamadasEntreFechas(String NIF, String inicio, String fin);
public String[][] getFacturasEntreFechas(String NIF, String inicio, String fin);
public String[] getFactura(String code);
}
|
Java
|
UTF-8
| 4,876 | 1.601563 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.rest.dto.history;
import java.util.Date;
import org.camunda.bpm.engine.history.HistoricDetail;
import org.camunda.bpm.engine.history.HistoricFormField;
import org.camunda.bpm.engine.history.HistoricVariableUpdate;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* @author Roman Smirnov
*
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type"
)
@JsonSubTypes({
@Type(value = HistoricFormFieldDto.class),
@Type(value = HistoricVariableUpdateDto.class)
})
public abstract class HistoricDetailDto {
protected String id;
protected String processDefinitionKey;
protected String processDefinitionId;
protected String processInstanceId;
protected String activityInstanceId;
protected String executionId;
protected String caseDefinitionKey;
protected String caseDefinitionId;
protected String caseInstanceId;
protected String caseExecutionId;
protected String taskId;
protected String tenantId;
protected String userOperationId;
protected Date time;
protected Date removalTime;
protected String rootProcessInstanceId;
public String getId() {
return id;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
public String getTenantId() {
return tenantId;
}
public String getUserOperationId() {
return userOperationId;
}
public Date getTime() {
return time;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDetailDto fromHistoricDetail(HistoricDetail historicDetail) {
HistoricDetailDto dto = null;
if (historicDetail instanceof HistoricFormField) {
HistoricFormField historicFormField = (HistoricFormField) historicDetail;
dto = HistoricFormFieldDto.fromHistoricFormField(historicFormField);
} else if (historicDetail instanceof HistoricVariableUpdate) {
HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
dto = HistoricVariableUpdateDto.fromHistoricVariableUpdate(historicVariableUpdate);
}
fromHistoricDetail(historicDetail, dto);
return dto;
}
protected static void fromHistoricDetail(HistoricDetail historicDetail, HistoricDetailDto dto) {
dto.id = historicDetail.getId();
dto.processDefinitionKey = historicDetail.getProcessDefinitionKey();
dto.processDefinitionId = historicDetail.getProcessDefinitionId();
dto.processInstanceId = historicDetail.getProcessInstanceId();
dto.activityInstanceId = historicDetail.getActivityInstanceId();
dto.executionId = historicDetail.getExecutionId();
dto.taskId = historicDetail.getTaskId();
dto.caseDefinitionKey = historicDetail.getCaseDefinitionKey();
dto.caseDefinitionId = historicDetail.getCaseDefinitionId();
dto.caseInstanceId = historicDetail.getCaseInstanceId();
dto.caseExecutionId = historicDetail.getCaseExecutionId();
dto.tenantId = historicDetail.getTenantId();
dto.userOperationId = historicDetail.getUserOperationId();
dto.time = historicDetail.getTime();
dto.removalTime = historicDetail.getRemovalTime();
dto.rootProcessInstanceId = historicDetail.getRootProcessInstanceId();
}
}
|
Java
|
UTF-8
| 833 | 2.171875 | 2 |
[] |
no_license
|
package br.com.tavares.clockinout.clockinout.v1.facade;
import br.com.tavares.clockinout.clockinout.facade.TimeFacade;
import br.com.tavares.clockinout.clockinout.v1.model.TimeRequest;
import br.com.tavares.clockinout.clockinout.v1.model.TimeResponse;
import org.springframework.stereotype.Component;
import static br.com.tavares.clockinout.clockinout.v1.mapper.TimeMapperContract.mapToTimeModel;
import static br.com.tavares.clockinout.clockinout.v1.mapper.TimeMapperContract.mapToTimeResponse;
@Component
public class TimeFacadeContract {
private TimeFacade timeFacade;
public TimeFacadeContract(TimeFacade timeFacade) {
this.timeFacade = timeFacade;
}
public TimeResponse timeSave(TimeRequest timeRequest) {
return mapToTimeResponse(timeFacade.timeSave(mapToTimeModel(timeRequest)));
}
}
|
Java
|
UTF-8
| 8,029 | 1.945313 | 2 |
[] |
no_license
|
package org.webdsl.serg.beans;
import java.util.*;
import java.io.Serializable;
import static javax.persistence.PersistenceContextType.EXTENDED;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.faces.event.ValueChangeEvent;
import javax.ejb.Stateless;
import javax.ejb.Stateful;
import javax.ejb.Remove;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.RequestParameter;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.core.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Factory;
import org.webdsl.serg.domain.*;
@Stateful @Name("createResearchGroup") public class CreateResearchGroupBean implements CreateResearchGroupBeanInterface
{
@Logger private Log log;
@PersistenceContext(type = EXTENDED) private EntityManager em;
@In private FacesMessages facesMessages;
@Create @Begin public void initialize()
{
log.info("createResearchGroup" + ".initalize()");
ResearchGroup var68 = new ResearchGroup();
researchGroup = var68;
initPerson222List();
initResearchProject55List();
initColloquium10List();
initNews9List();
initPerson99List();
initProject86List();
}
@Destroy @Remove public void destroy()
{ }
public void removePerson15(Person person221)
{
this.getResearchGroup().getMembers().remove(person221);
}
public void addPerson15(Person person221)
{
this.getResearchGroup().getMembers().add(person221);
}
public void removeResearchProject15(ResearchProject researchProject54)
{
this.getResearchGroup().getProjects().remove(researchProject54);
}
public void addResearchProject15(ResearchProject researchProject54)
{
this.getResearchGroup().getProjects().add(researchProject54);
}
public void removeColloquium1(Colloquium colloquium9)
{
this.getResearchGroup().getColloquia().remove(colloquium9);
}
public void addColloquium1(Colloquium colloquium9)
{
this.getResearchGroup().getColloquia().add(colloquium9);
}
public void removeNews1(News news8)
{
this.getResearchGroup().getNews().remove(news8);
}
public void addNews1(News news8)
{
this.getResearchGroup().getNews().add(news8);
}
@End public String cancel()
{
return "/" + "home" + ".seam?" + "";
}
@End public String save()
{
em.persist(this.getResearchGroup());
return "/" + "viewResearchGroup" + ".seam?" + ("group" + "=" + researchGroup.getId() + "");
}
private String newPerson222;
public void setNewPerson222(String p)
{
newPerson222 = p;
}
public String getNewPerson222()
{
return newPerson222;
}
public void selectPerson222(ValueChangeEvent event)
{
log.info("selectPerson222" + ": new value = " + " " + event.getNewValue());
Long id = new Long((String)event.getNewValue());
if(id > 0)
{
Person person222 = em.find(Person.class, id);
addPerson15(person222);
}
}
@DataModel("person222List") private Map<String, String> person222List;
public Map<String, String> getPerson222List()
{
return person222List;
}
@Factory("person222List") public void initPerson222List()
{
log.info("initPerson222List");
person222List = new HashMap<String, String>();
for(Object o : em.createQuery("from " + "Person").getResultList())
{
Person p = (Person)o;
person222List.put(p.getName(), p.getId().toString());
}
}
private String newResearchProject55;
public void setNewResearchProject55(String p)
{
newResearchProject55 = p;
}
public String getNewResearchProject55()
{
return newResearchProject55;
}
public void selectResearchProject55(ValueChangeEvent event)
{
log.info("selectResearchProject55" + ": new value = " + " " + event.getNewValue());
Long id = new Long((String)event.getNewValue());
if(id > 0)
{
ResearchProject researchProject55 = em.find(ResearchProject.class, id);
addResearchProject15(researchProject55);
}
}
@DataModel("researchProject55List") private Map<String, String> researchProject55List;
public Map<String, String> getResearchProject55List()
{
return researchProject55List;
}
@Factory("researchProject55List") public void initResearchProject55List()
{
log.info("initResearchProject55List");
researchProject55List = new HashMap<String, String>();
for(Object o : em.createQuery("from " + "ResearchProject").getResultList())
{
ResearchProject p = (ResearchProject)o;
researchProject55List.put(p.getName(), p.getId().toString());
}
}
private String newColloquium10;
public void setNewColloquium10(String p)
{
newColloquium10 = p;
}
public String getNewColloquium10()
{
return newColloquium10;
}
public void selectColloquium10(ValueChangeEvent event)
{
log.info("selectColloquium10" + ": new value = " + " " + event.getNewValue());
Long id = new Long((String)event.getNewValue());
if(id > 0)
{
Colloquium colloquium10 = em.find(Colloquium.class, id);
addColloquium1(colloquium10);
}
}
@DataModel("colloquium10List") private Map<String, String> colloquium10List;
public Map<String, String> getColloquium10List()
{
return colloquium10List;
}
@Factory("colloquium10List") public void initColloquium10List()
{
log.info("initColloquium10List");
colloquium10List = new HashMap<String, String>();
for(Object o : em.createQuery("from " + "Colloquium").getResultList())
{
Colloquium p = (Colloquium)o;
colloquium10List.put(p.getName(), p.getId().toString());
}
}
private String newNews9;
public void setNewNews9(String p)
{
newNews9 = p;
}
public String getNewNews9()
{
return newNews9;
}
public void selectNews9(ValueChangeEvent event)
{
log.info("selectNews9" + ": new value = " + " " + event.getNewValue());
Long id = new Long((String)event.getNewValue());
if(id > 0)
{
News news9 = em.find(News.class, id);
addNews1(news9);
}
}
@DataModel("news9List") private Map<String, String> news9List;
public Map<String, String> getNews9List()
{
return news9List;
}
@Factory("news9List") public void initNews9List()
{
log.info("initNews9List");
news9List = new HashMap<String, String>();
for(Object o : em.createQuery("from " + "News").getResultList())
{
News p = (News)o;
news9List.put(p.getName(), p.getId().toString());
}
}
@DataModel("person99List") private List<Person> person99List;
public List<Person> getPerson99List()
{
log.info("getPerson99List");
return person99List;
}
@Factory("person99List") public void initPerson99List()
{
log.info("initPerson99List");
person99List = em.createQuery("from " + "Person").getResultList();
}
@DataModel("project86List") private List<ResearchProject> project86List;
public List<ResearchProject> getProject86List()
{
log.info("getProject86List");
return project86List;
}
@Factory("project86List") public void initProject86List()
{
log.info("initProject86List");
project86List = em.createQuery("from " + "ResearchProject").getResultList();
}
private ResearchGroup researchGroup;
public ResearchGroup getResearchGroup()
{
log.info("getResearchGroup");
return researchGroup;
}
public void setResearchGroup(ResearchGroup researchGroup)
{
log.info("setResearchGroup");
this.researchGroup = researchGroup;
}
}
|
PHP
|
UTF-8
| 3,570 | 2.96875 | 3 |
[] |
no_license
|
<?php
// Definition einer Klasse //
class BrowserDetective {
public $userAgent;
public $platform;
public $browserName;
public function __construct() {
$this->set_user_agent();
$this->reset();
}
public function set_user_agent() {
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$this->userAgent = $_SERVER['HTTP_USER_AGENT'];
} else {
$this->userAgent = '';
}
}
public function reset() {
$this->platform = 'Unbekannt';
$this->browserName = 'Unbekannt';
}
public function detect() {
$this->detect_platform();
$this->detect_browser();
return array($this->platform, $this->browserName);
}
public function detect_platform() {
if (preg_match('/linux/i', $this->userAgent)) {
$this->platform = 'Linux';
} elseif (preg_match('/macintosh|mac os/i', $this->userAgent)) {
$this->platform = 'Mac';
} elseif (preg_match('/windows|win32/i', $this->userAgent)) {
$this->platform = 'Windows';
}
}
public function detect_browser() {
if (preg_match('/MSIE/i', $this->userAgent)) {
$this->browserName = 'Internet Explorer';
} elseif(preg_match('/firefox/i', $this->userAgent)) {
$this->browserName = 'Firefox';
} elseif(preg_match('/Chrome/i', $this->userAgent)) {
$this->browserName = 'Chrome';
} elseif(preg_match('/Safari/i', $this->userAgent)) {
$this->browserName = 'Safari';
} elseif(preg_match('/Netscape/i', $this->userAgent)) {
$this->browserName = 'Netscape';
}
}
}
// Der Inspector //
$inspector = new BrowserDetective();
$inspector->detect();
// Close //
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Browser Informationen</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<p>Remote IP: <?php echo htmlspecialchars($_SERVER['REMOTE_ADDR']); ?></p>
<p>User Agent: <?php echo htmlspecialchars($_SERVER['HTTP_USER_AGENT']); ?></p>
<p>Platform: <?php echo htmlspecialchars($inspector->platform); ?></p>
<p>Browser: <?php echo htmlspecialchars($inspector->browserName); ?></p>
<p>Referer: <?php echo htmlspecialchars($_SERVER['HTTP_REFERER']); ?></p>
<p>Request Time (Unix): <?php echo htmlspecialchars($_SERVER['REQUEST_TIME']); ?></p>
<?php date_default_timezone_set("Europe/Berlin"); ?>
<p>Request Time (formatiert): <?php echo htmlspecialchars(date('Y-m-d H:s:i', $_SERVER['REQUEST_TIME'])); ?></p>
<p>Request URI: <?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?></p>
<p>Request Method: <?php echo htmlspecialchars($_SERVER['REQUEST_METHOD']); ?></p>
<p>Query String: <?php echo htmlspecialchars($_SERVER['QUERY_STRING']); ?></p>
<p>HTTP Accept: <?php echo htmlspecialchars($_SERVER['HTTP_ACCEPT']); ?></p>
<p>HTTP Accept Charset: <?php echo htmlspecialchars('HTTP_ACCEPT_CHARSET'); ?></p>
<p>HTTP Accept Encoding: <?php echo htmlspecialchars($_SERVER['HTTP_ACCEPT_ENCODING']); ?></p>
<p>HTTP Accept Language: <?php echo htmlspecialchars($_SERVER['HTTP_ACCEPT_LANGUAGE']); ?></p>
<p>HTTPS: <?php if(isset($_SERVER['HTTPS'])) { echo 'Ja'; } else { echo 'Nein'; } ?></p>
<p>Remote Port: <?php echo htmlspecialchars($_SERVER['REMOTE_PORT']); ?></p>
</body>
</html>
|
Python
|
UTF-8
| 839 | 3.21875 | 3 |
[] |
no_license
|
import pickle
def save_pickle(list_students):
file = open("Students.txt", 'wb')
pickle.Pickler(file).dump(list_students)
file.close()
def load_pickle():
file = open("Students.txt", 'rb')
list_students = pickle.Unpickler(file)
list_s = list_students.load()
file.close()
return list_s
def update_pickle(name, nname=None, nemail=None, npass=None):
ls = load_pickle()
found = False
for i, student in enumerate(ls):
if student.get_name() == name:
found = True
if nname:
student.set_name(nname)
if nemail:
student.set_email(nemail)
if npass:
student.set_pass(npass)
break
if found:
save_pickle(ls)
else:
print("Estudiante {} no encontrado".format(name))
|
PHP
|
UTF-8
| 3,009 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
// Copyright 2012-present Nearsoft, Inc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Nearsoft\SeleniumClient\Http;
use Nearsoft\SeleniumClient\Commands as Commands;
class HttpClient
{
const POST = "POST";
const GET = "GET";
const DELETE = "DELETE";
protected $_traceAll = false;
public function getTraceAll() { return $this->_traceAll; }
public function setTraceAll($value)
{
$this->_traceAll = $value;
return $this;
}
/**
* @return string The response body
* @throws \Exception
*/
public function execute(Commands\Command $command, $trace = false)
{
if ($command->getUrl() == "" || $command->getHttpMethod() == "") { throw new \Exception("Must specify URL and HTTP METHOD"); }
$curl = curl_init($command->getUrl());
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=UTF-8','Accept: application/json'));
if($command->getHttpMethod() == HttpClient::POST)
{
curl_setopt($curl, CURLOPT_POST, true);
if ($command->getParams() && is_array($command->getParams()))
{
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($command->getParams()));
}
else
{
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Length: 0'));
}
}
else if ($command->getHttpMethod() == HttpClient::DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); }
else if ($command->getHttpMethod() == HttpClient::GET) { /*NO ACTION NECESSARY*/ }
$rawResponse = trim(curl_exec($curl));
$responseBody = json_decode($rawResponse, true);
$responseHeaders=curl_getinfo($curl);
if ($this->_traceAll || $trace)
{
echo "\n***********************************************************************\n";
echo "URL: " . $command->getUrl() . "\n";
echo "METHOD: " . $command->getHttpMethod() . "\n";
echo "PARAMETERS: ";
if (is_array($command->getParams())) { echo print_r($command->getParams()); }
else echo "NONE"; { echo "\n"; }
echo "RESULTS:" . print_r($responseBody);
echo "\n";
echo "CURL INFO: ";
echo print_r($responseHeaders);
echo "\n***********************************************************************\n";
}
curl_close($curl);
$response = array(
"headers" => $responseHeaders,
"body" => $responseBody,
);
return $response;
}
}
|
Swift
|
UTF-8
| 399 | 3.140625 | 3 |
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
class DatabaseConnection {
init() {
print("New Database is up and running!")
}
func execute(statement: String) {
print("EXECUTE: \(statement)")
}
}
class DataStore {
lazy var connection = DatabaseConnection()
}
let ds = DataStore()
ds.connection.execute(statement: "SELECT * FROM users")
|
PHP
|
UTF-8
| 9,260 | 2.515625 | 3 |
[] |
no_license
|
<?php
session_start();
$_SESSION['page']='Add_Contest';
date_default_timezone_set('Asia/Kolkata');
$currentdatetime=date_create(date('Y-m-d'));
$result = $currentdatetime->format('Y-m-d h:i');
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$target_dir = "./../uploads/Contest/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
$cid=-1;
if(isset($_POST["submit"])) {
require_once("Config.php");
$name=$_POST['tname'];
$s_date_time=$_POST['s_date_time'];
$e_date_time=$_POST['e_date_time'];
$desc=$_POST['desc'];
//$image=$_POST['image'];
$sql="insert into contest (ContestName,Start,End,Description,Image,RecruiterId) values('".$name."','".$s_date_time."','".$e_date_time."','".$desc."','".$_FILES["image"]["name"]."',".$_SESSION['id'].")";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else{
$sql="select ContestId from contest where ContestName='".$name."'";
$result = $conn->query($sql);
$row=$result->fetch_assoc();
$sql="create table ".$row['ContestId']."_questions (QuestionId int not null auto_increment,Question text not null,Type text not null,Choice1 text not null,
Choice2 text not null,Choice3 text not null,Choice4 text not null,Answer text not null,primary key(QuestionId))";
if(!$result = $conn->query($sql))
die('There was an error running the query [' . $conn->error . ']');
else {
$sql="create table ".$row['ContestId']."_users (UserId int not null auto_increment,UserName varchar(255) not null,UserEmail varchar(255) not null,CollegeName text not null,
Marks int,primary key(UserId))";
if(!$result = $conn->query($sql))
die('There was an error running the query [' . $conn->error . ']');
else{
$cid=$row['ContestId'];
$_SESSION['cid']=$cid;
echo '<script>window.location.href = window.location.href.replace(/[^/]*$/, "")+"Edit_Questions.php?js_test=[]&contestid='.$cid.'&submit=true";</script>';
}
}
}
}
?>
<html>
<head>
<link href="./boot/boot2/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="./boot/css/bootstrap-datetimepicker.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/userhome.css">
<link rel="stylesheet" type="text/css" href="css/add_contest.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="css/global.css">
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#header").load("Header.php");
$("#footer").load("Footer.php");
});
</script>
<script>
function pagesubmit(){
alert("here");
}
</script>
</head>
<body>
<div id="header"></div>
<?php
require_once("Config.php");
?>
<div style="background : #f7f7f7;">
<label style="font-size:30px;
color:black;
font-family: 'Times New Roman', Times, serif;
font-style: normal;
font-weight:normal;
margin-left:20px;
margin-top:15px;
margin-bottom:15px;">Add Contest</label>
</div>
<div class="container">
</div>
<div id="parent" >
<div id="inside">
<form method="post" id="register_form" action="Add_Contest.php" onsubmit="return validate()" enctype="multipart/form-data" >
<div class="form-group">
<label for="organ">Test Name:</label>
<input type="textarea" class="form-control" id="tname" placeholder="Enter Test Name" name="tname" required>
</div>
<div class="form-group">
<label for="email">Start Date and Time:</label>
<div class="controls input-append date form_datetime" id="sdate" data-date="1979-09-16T05:25:07Z" data-date-format="yyyy-mm-dd hh:ii"
data-link-field="dtp_input1">
<input size="20" type="text" style="height: 30px" value="" required onkeypress="return false;" >
<span class="add-on" style="height: 30px"><i class="icon-th"></i></span>
</div>
<input type="text" id="s_date_time" name="s_date_time" value="" hidden />
</div>
<div class="form-group">
<label for="pass">End Date and Time:</label>
<div class="controls input-append date form_datetime2" id="edate" data-date="1979-09-16T05:25:07Z" data-date-format="dd MM yyyy - HH:ii p"
data-link-field="dtp_input1">
<input style="height: 30px" size="20" type="text" value="" required onkeypress="return false;" >
<span class="add-on" style="height: 30px"><i class="icon-th"></i></span>
</div>
<input type="text" id="e_date_time" name="e_date_time" value="" hidden /></div>
<div class="form-group">
<label for="pass">Description:</label>
<input type="textarea" class="form-control" id="desc" placeholder="Enter Description" name="desc" required />
</div>
<div class="form-group">
<label for="pass">Image:</label>
<input type="file" style="height: 45px" class="form-control" id="image" name="image" required />
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="remember" required /> I agree on <a href="tc.htm"> terms and conditions</a>
</label>
</div>
<input type="submit" name="submit" id="submit" value=" Submit " class="btn btn-success">
<button type="reset" class="btn btn-danger"> Reset </button>
</form>
</div>
</div>
<script type="text/javascript" src="./boot/boot2/jquery/jquery-1.8.3.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="./boot/boot2/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="./boot/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="./boot/js/locales/bootstrap-datetimepicker.fr.js" charset="UTF-8"></script>
<script type="text/javascript">
$(".form_datetime").datetimepicker({
format: "dd MM yyyy - hh:ii",
linkField: "s_date_time",
linkFormat: "yyyy-mm-dd hh:ii",
autoclose: true,
//todayBtn: true,
startDate: "<?php echo $result ?>",
minuteStep: 5
});
//var x='2102-12-03 04:00';//document.getElementById("s_date_time").value;
$(".form_datetime2").datetimepicker({
format: "dd MM yyyy - hh:ii",
linkField: "e_date_time",
linkFormat: "yyyy-mm-dd hh:ii",
autoclose: true,
//todayBtn: true,
startDate: "<?php echo $result ?>",
minuteStep: 5
});
</script>
<script>
function validate(){
var start=document.getElementById("s_date_time").value;
var end=document.getElementById("e_date_time").value;
var date1 = new Date(parseInt(start.substr(0,4),10),parseInt(start.substr(5,2),10),parseInt(start.substr(8,2),10)
,parseInt(start.substr(11,2),10),parseInt(start.substr(14,2),10));
var date2 = new Date(parseInt(end.substr(0,4),10),parseInt(end.substr(5,2),10),parseInt(end.substr(8,2),10)
,parseInt(end.substr(11,2),10),parseInt(end.substr(14,2),10));
if (date2 < date1) {
alert("Please Select a valid Date time range.");
return false;
}
else{
}
}
</script>
<div id="footer"></div>
</body>
</html>
|
TypeScript
|
UTF-8
| 1,828 | 3.71875 | 4 |
[
"MIT"
] |
permissive
|
import { OptSpace } from "./stringAliases";
export type integer = number;
export type int32 = number;
export type int64 = number;
export type float = number;
export type NumericCharacter = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
export type Hexadecimal = NumericCharacter | "A" | "B" | "C" | "D" | "E" | "F";
export type Digit = NumericCharacter;
export type TwoDigit = `${Digit}${Digit}`;
export type OptTwoDigit = Digit | TwoDigit;
export type ThreeDigit = `${Digit}${Digit}${Digit}`;
type MostSignificantDigit = "0" | "1" | "2";
export type OptThreeDigit = Digit | TwoDigit | ThreeDigit;
/**
* Provides strong typing for an eight bit number, represented as a string.
* First digit must be 0-3, remaining two digits can be whatever you like.
*
* Must be three digits. If you want to provide length flexibility use `OptEightBitBase10`
* instead.
*/
export type EightBitBase10 = `${MostSignificantDigit}${Digit}${Digit}`;
/**
* Provides strong typing for an eight bit number, represented as a string.
* First digit -- in a three digit number -- is limited to "1" or "2" others
* are any valid digit.
*/
export type OptEightBitBase10 =
| `${Exclude<MostSignificantDigit, "0">}${Digit}${Digit}`
| Digit
| TwoDigit;
export type FourDigit = `${Digit}${Digit}${Digit}${Digit}`;
export type OptFourDigit = Digit | TwoDigit | ThreeDigit | FourDigit;
/** an aspect ration represented in the normal convention of "x:y" */
export type AspectRatioColon = `${number}:${number}`;
/** an aspect ratio represented in the CSS syntax */
export type AspectRatioCss = `${number}${OptSpace}/${OptSpace}${number}`;
/**
* Allows the expression of an Aspect Ratio with both the standard "x:y"
* convention _or_ the CSS variant of "a / y".
*/
export type AspectRatio = AspectRatioColon | AspectRatioCss;
|
C++
|
UTF-8
| 11,783 | 2.6875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
/*=========================================================================
Module: VerdictVector.hpp
Copyright 2003,2006,2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
Under the terms of Contract DE-NA0003525 with NTESS,
the U.S. Government retains certain rights in this software.
See LICENSE for details.
=========================================================================*/
/*
*
* VerdictVector.hpp contains declarations of vector operations
*
* This file is part of VERDICT
*
*/
// .SECTION Thanks
// Prior to its inclusion within VTK, this code was developed by the CUBIT
// project at Sandia National Laboratories.
#ifndef VERDICTVECTOR_HPP
#define VERDICTVECTOR_HPP
#include "verdict.h"
#include <cassert>
#include <cmath>
namespace VERDICT_NAMESPACE
{
class VerdictVector
{
public:
//- Heading: Constructors and Destructor
VerdictVector(); //- Default constructor.
VerdictVector(const double x, const double y, const double z);
//- Constructor: create vector from three components
VerdictVector(const double xyz[3]);
//- Constructor: create vector from tuple
VerdictVector(const VerdictVector& tail, const VerdictVector& head);
//- Constructor for a VerdictVector starting at tail and pointing
//- to head.
VerdictVector(const VerdictVector& copy_from); //- Copy Constructor
//- Heading: Set and Inquire Functions
void set(const double xv, const double yv, const double zv);
//- Change vector components to {x}, {y}, and {z}
void set(const double xyz[3]);
//- Change vector components to xyz[0], xyz[1], xyz[2]
void set(const VerdictVector& tail, const VerdictVector& head);
//- Change vector to go from tail to head.
void set(const VerdictVector& to_copy);
//- Same as operator=(const VerdictVector&)
double x() const; //- Return x component of vector
double y() const; //- Return y component of vector
double z() const; //- Return z component of vector
void get_xyz(double& x, double& y, double& z); //- Get x, y, z components
void get_xyz(double xyz[3]); //- Get xyz tuple
double& r(); //- Return r component of vector, if (r,theta) format
double& theta(); //- Return theta component of vector, if (r,theta) format
void x(const double xv); //- Set x component of vector
void y(const double yv); //- Set y component of vector
void z(const double zv); //- Set z component of vector
void r(const double xv); //- Set r component of vector, if (r,theta) format
void theta(const double yv); //- Set theta component of vector, if (r,theta) format
double normalize();
//- Normalize (set magnitude equal to 1) vector - return the magnitude
VerdictVector& length(const double new_length);
//- Change length of vector to {new_length}. Can be used to move a
//- location a specified distance from the origin in the current
//- orientation.
double length() const;
//- Calculate the length of the vector.
//- Use {length_squared()} if only comparing lengths, not adding.
double length_squared() const;
//- Calculate the squared length of the vector.
//- Faster than {length()} since it eliminates the square root if
//- only comparing other lengths.
double interior_angle(const VerdictVector& otherVector);
//- Calculate the interior angle: acos((a%b)/(|a||b|))
//- Returns angle in degrees.
void perpendicular_z();
//- Transform this vector to a perpendicular one, leaving
//- z-component alone. Rotates clockwise about the z-axis by pi/2.
//- Heading: Operator Overloads *****************************
VerdictVector& operator+=(const VerdictVector& vec);
//- Compound Assignment: addition: {this = this + vec}
VerdictVector& operator-=(const VerdictVector& vec);
//- Compound Assignment: subtraction: {this = this - vec}
VerdictVector& operator*=(const VerdictVector& vec);
//- Compound Assignment: cross product: {this = this * vec},
//- non-commutative
VerdictVector& operator*=(const double scalar);
//- Compound Assignment: multiplication: {this = this * scalar}
VerdictVector& operator/=(const double scalar);
//- Compound Assignment: division: {this = this / scalar}
VerdictVector operator-() const;
//- unary negation.
friend VerdictVector operator~(const VerdictVector& vec);
//- normalize. Returns a new vector which is a copy of {vec},
//- scaled such that {|vec|=1}. Uses overloaded bitwise NOT operator.
friend VerdictVector operator+(const VerdictVector& v1, const VerdictVector& v2);
//- vector addition
friend VerdictVector operator-(const VerdictVector& v1, const VerdictVector& v2);
//- vector subtraction
friend VerdictVector operator*(const VerdictVector& v1, const VerdictVector& v2);
//- vector cross product, non-commutative
friend VerdictVector operator*(const VerdictVector& v1, const double sclr);
//- vector * scalar
friend VerdictVector operator*(const double sclr, const VerdictVector& v1);
//- scalar * vector
friend double operator%(const VerdictVector& v1, const VerdictVector& v2);
//- dot product
static double Dot(const VerdictVector& v1, const VerdictVector& v2);
//- dot product
friend VerdictVector operator/(const VerdictVector& v1, const double sclr);
//- vector / scalar
friend int operator==(const VerdictVector& v1, const VerdictVector& v2);
//- Equality operator
friend int operator!=(const VerdictVector& v1, const VerdictVector& v2);
//- Inequality operator
VerdictVector& operator=(const VerdictVector& from);
private:
double xVal; //- x component of vector.
double yVal; //- y component of vector.
double zVal; //- z component of vector.
};
inline double VerdictVector::x() const
{
return xVal;
}
inline double VerdictVector::y() const
{
return yVal;
}
inline double VerdictVector::z() const
{
return zVal;
}
inline void VerdictVector::get_xyz(double xyz[3])
{
xyz[0] = xVal;
xyz[1] = yVal;
xyz[2] = zVal;
}
inline void VerdictVector::get_xyz(double& xv, double& yv, double& zv)
{
xv = xVal;
yv = yVal;
zv = zVal;
}
inline double& VerdictVector::r()
{
return xVal;
}
inline double& VerdictVector::theta()
{
return yVal;
}
inline void VerdictVector::x(const double xv)
{
xVal = xv;
}
inline void VerdictVector::y(const double yv)
{
yVal = yv;
}
inline void VerdictVector::z(const double zv)
{
zVal = zv;
}
inline void VerdictVector::r(const double xv)
{
xVal = xv;
}
inline void VerdictVector::theta(const double yv)
{
yVal = yv;
}
inline VerdictVector& VerdictVector::operator+=(const VerdictVector& vector)
{
xVal += vector.x();
yVal += vector.y();
zVal += vector.z();
return *this;
}
inline VerdictVector& VerdictVector::operator-=(const VerdictVector& vector)
{
xVal -= vector.x();
yVal -= vector.y();
zVal -= vector.z();
return *this;
}
inline VerdictVector& VerdictVector::operator*=(const VerdictVector& vector)
{
double xcross, ycross, zcross;
xcross = yVal * vector.z() - zVal * vector.y();
ycross = zVal * vector.x() - xVal * vector.z();
zcross = xVal * vector.y() - yVal * vector.x();
xVal = xcross;
yVal = ycross;
zVal = zcross;
return *this;
}
inline VerdictVector::VerdictVector(const VerdictVector& copy_from)
: xVal(copy_from.xVal)
, yVal(copy_from.yVal)
, zVal(copy_from.zVal)
{
}
inline VerdictVector::VerdictVector()
: xVal(0)
, yVal(0)
, zVal(0)
{
}
inline VerdictVector::VerdictVector(const VerdictVector& tail, const VerdictVector& head)
: xVal(head.xVal - tail.xVal)
, yVal(head.yVal - tail.yVal)
, zVal(head.zVal - tail.zVal)
{
}
inline VerdictVector::VerdictVector(const double xIn, const double yIn, const double zIn)
: xVal(xIn)
, yVal(yIn)
, zVal(zIn)
{
}
// This sets the vector to be perpendicular to it's current direction.
// NOTE:
// This is a 2D function. It only works in the XY Plane.
inline void VerdictVector::perpendicular_z()
{
double temp = x();
x(y());
y(-temp);
}
inline void VerdictVector::set(const double xv, const double yv, const double zv)
{
xVal = xv;
yVal = yv;
zVal = zv;
}
inline void VerdictVector::set(const double xyz[3])
{
xVal = xyz[0];
yVal = xyz[1];
zVal = xyz[2];
}
inline void VerdictVector::set(const VerdictVector& tail, const VerdictVector& head)
{
xVal = head.xVal - tail.xVal;
yVal = head.yVal - tail.yVal;
zVal = head.zVal - tail.zVal;
}
inline VerdictVector& VerdictVector::operator=(const VerdictVector& from)
{
xVal = from.xVal;
yVal = from.yVal;
zVal = from.zVal;
return *this;
}
inline void VerdictVector::set(const VerdictVector& to_copy)
{
*this = to_copy;
}
// Scale all values by scalar.
inline VerdictVector& VerdictVector::operator*=(const double scalar)
{
xVal *= scalar;
yVal *= scalar;
zVal *= scalar;
return *this;
}
// Scales all values by 1/scalar
inline VerdictVector& VerdictVector::operator/=(const double scalar)
{
assert(scalar != 0);
xVal /= scalar;
yVal /= scalar;
zVal /= scalar;
return *this;
}
// Returns the normalized 'this'.
inline VerdictVector operator~(const VerdictVector& vec)
{
double mag = std::sqrt(vec.xVal * vec.xVal + vec.yVal * vec.yVal + vec.zVal * vec.zVal);
VerdictVector temp = vec;
if (mag != 0.0)
{
temp /= mag;
}
return temp;
}
// Unary minus. Negates all values in vector.
inline VerdictVector VerdictVector::operator-() const
{
return VerdictVector(-xVal, -yVal, -zVal);
}
inline VerdictVector operator+(const VerdictVector& vector1, const VerdictVector& vector2)
{
double xv = vector1.x() + vector2.x();
double yv = vector1.y() + vector2.y();
double zv = vector1.z() + vector2.z();
return VerdictVector(xv, yv, zv);
// return VerdictVector(vector1) += vector2;
}
inline VerdictVector operator-(const VerdictVector& vector1, const VerdictVector& vector2)
{
double xv = vector1.x() - vector2.x();
double yv = vector1.y() - vector2.y();
double zv = vector1.z() - vector2.z();
return VerdictVector(xv, yv, zv);
// return VerdictVector(vector1) -= vector2;
}
// Cross products.
// vector1 cross vector2
inline VerdictVector operator*(const VerdictVector& vector1, const VerdictVector& vector2)
{
return VerdictVector(vector1) *= vector2;
}
// Returns a scaled vector.
inline VerdictVector operator*(const VerdictVector& vector1, const double scalar)
{
return VerdictVector(vector1) *= scalar;
}
// Returns a scaled vector
inline VerdictVector operator*(const double scalar, const VerdictVector& vector1)
{
return VerdictVector(vector1) *= scalar;
}
// Returns a vector scaled by 1/scalar
inline VerdictVector operator/(const VerdictVector& vector1, const double scalar)
{
return VerdictVector(vector1) /= scalar;
}
inline int operator==(const VerdictVector& v1, const VerdictVector& v2)
{
return (v1.xVal == v2.xVal && v1.yVal == v2.yVal && v1.zVal == v2.zVal);
}
inline int operator!=(const VerdictVector& v1, const VerdictVector& v2)
{
return (v1.xVal != v2.xVal || v1.yVal != v2.yVal || v1.zVal != v2.zVal);
}
inline double VerdictVector::length_squared() const
{
return (xVal * xVal + yVal * yVal + zVal * zVal);
}
inline double VerdictVector::length() const
{
return (std::sqrt(xVal * xVal + yVal * yVal + zVal * zVal));
}
inline double VerdictVector::normalize()
{
double mag = length();
if (mag != 0)
{
xVal = xVal / mag;
yVal = yVal / mag;
zVal = zVal / mag;
}
return mag;
}
// Dot Product.
inline double operator%(const VerdictVector& vector1, const VerdictVector& vector2)
{
return VerdictVector::Dot(vector1, vector2);
}
inline double VerdictVector::Dot(const VerdictVector& vector1, const VerdictVector& vector2)
{
return (vector1.xVal * vector2.xVal + vector1.yVal * vector2.yVal + vector1.zVal * vector2.zVal);
}
} // namespace verdict
#endif
|
Python
|
UTF-8
| 1,968 | 3.046875 | 3 |
[] |
no_license
|
from __future__ import print_function, division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from wordcloud import WordCloud
months = ['january','february','march','april','may','june','july','august','september','october','november','december','jan','feb','aug','sept','nov','oct','dec']
df = pd.read_csv('./spam.csv', encoding='ISO-8859-1')
#stop words
stop = set(stopwords.words('english'))
stop.discard('before')
stop.discard('after')
stop.discard('last')
# drop unnecessary columns
df = df.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1)
# rename columns to something better
df.columns = ['labels', 'data']
# create binary labels
df['b_labels'] = df['labels'].map({'ded': 1, 'nd': 0})
Y = df['b_labels'].values
df['data'] = df['data'].map(lambda s:s.lower())
df['data'].apply(lambda x: [item for item in x if item not in stop])
print(stop)
# split up the data
df_train, df_test, Ytrain, Ytest = train_test_split(df['data'], Y, test_size=0.05)
# try multiple ways of calculating features
tfidf = TfidfVectorizer(decode_error='ignore')
Xtrain = tfidf.fit_transform(df_train)
Xtest = tfidf.transform(df_test)
# count_vectorizer = CountVectorizer(decode_error='ignore')
# Xtrain = count_vectorizer.fit_transform(df_train)
# Xtest = count_vectorizer.transform(df_test)
# create the model, train it, print scores
model = MultinomialNB()
model.fit(Xtrain, Ytrain)
print("train score:", model.score(Xtrain, Ytrain))
print("test score:", model.score(Xtest, Ytest))
sen = ['Deadline to submit the project is 8th january']
df2 = pd.DataFrame(sen,columns = ['data'])
X = tfidf.transform(df2['data'])
prediction = model.predict(X)
print(prediction)
|
C++
|
UTF-8
| 1,900 | 2.734375 | 3 |
[] |
no_license
|
#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#include <utility>
using namespace std;
const int MAXN = 128;
const int INF = 0x3f3f3f3f;
typedef pair<int,int> pii;
bool operator < (const pii &a, const pii &b){
return (a.first > b.first) || (a.first == b.first && a.second > b.second);
}
pii adj[MAXN][MAXN] = {};
int nNeighbor[MAXN] = {};
int dis[MAXN] = {};
int N;
void BFS(int index){
for(int i = 0; i < N; i++){
dis[i] = INF;
}
dis[index] = 0;
priority_queue<pii> pq; // (id, dist)
pq.push(pii(index, 0));
while(!pq.empty()) {
int id = pq.top().first, cur_dist = pq.top().second;
pq.pop();
if(cur_dist > dis[id]) continue;
for(int i = 0; i < nNeighbor[id]; i++){
int next = adj[id][i].first, len = adj[id][i].second;
int new_dis = len + cur_dist;
if(new_dis < dis[next]){
pq.push(pii(next, new_dis));
dis[next] = new_dis;
}
}
}
}
void process() {
int min_dia = INF;
int pos = -1;
for(int k = 0; k < N; k++){
BFS(k);
int max_dis = 0;
for(int i = 0; i < N; i++){
if(dis[i] > max_dis) max_dis = dis[i];
}
if(max_dis < min_dia){
min_dia = max_dis;
pos = k;
}
}
if(pos != -1){
printf("%d %d\n", pos + 1, min_dia);
}
else{
printf("disjoint\n");
}
}
int main(int argc, char const *argv[])
{
while(scanf("%d", &N) != EOF) {
if(!N) break;
for(int i = 0; i < N; i++){
int m;
scanf("%d", &m);
nNeighbor[i] = m;
for (int j = 0; j < m; j++) {
int x, d;
scanf("%d%d", &x, &d);
adj[i][j] = pii(x - 1, d);
}
}
process();
}
return 0;
}
|
SQL
|
UTF-8
| 459 | 2.984375 | 3 |
[] |
no_license
|
drop table if exists 'user';
create table 'user' (
'id' integer primary key autoincrement,
'name' text not null,
'username' text not null,
'password' text not null,
'c_password' text not null,
'email' text not null
);
drop table if exists 'fi';
create table 'fi' (
'id' integer primary key autoincrement,
'title' text not null,
'text' text not null,
'u_name' text not null,
FOREIGN KEY(u_name) REFERENCES user(username)
);
|
C++
|
UTF-8
| 1,838 | 3.484375 | 3 |
[] |
no_license
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <iostream>
#include <cstdio>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(head == NULL || k <= 1)
return head;
ListNode* newHead = new ListNode(0);
ListNode* next = newHead;
ListNode* node = head;
while(node){
int cnt = 0;
ListNode* start = node;
ListNode* end = node;
while(end){
cnt++;
if(cnt == k)
break;
end = end->next;
}
if(cnt == k){
ListNode* first = start;
ListNode* second = first->next;
ListNode* nextGroup = end->next;
while(first != end){
ListNode* tmp = second->next;
second->next = first;
first = second;
second = tmp;
}
next->next = end;
next = start;
start->next = nextGroup;
node = nextGroup;
}
else
break;
}
if(newHead->next == NULL)
newHead->next = head;
return newHead->next;
}
};
int main(){
ListNode* head = new ListNode(1);
ListNode* tail = new ListNode(2);
head->next = tail;
Solution* s = new Solution();
ListNode* newHead = s->reverseKGroup(head,2);
while(newHead){
printf("%d\n",newHead->val);
newHead = newHead->next;
}
return 0;
}
|
Java
|
UTF-8
| 1,674 | 2.875 | 3 |
[] |
no_license
|
package interview_google.round08;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Problem02 {
public boolean canFinish(int n, int[][] prerequisites) {
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int[] prerequisite : prerequisites) {
int prev = prerequisite[1];
int cur = prerequisite[0];
adj[prev].add(cur);
}
int[] inDegreeArr = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < adj[i].size(); j++) {
int cur = adj[i].get(j);
inDegreeArr[cur]++;
}
}
LinkedList<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (inDegreeArr[i] == 0) {
queue.add(i);
}
}
int zeroInDegreeCount = 0;
while (!queue.isEmpty()) {
List<Integer> nodeList = new ArrayList<>();
while (!queue.isEmpty()) {
nodeList.add(queue.removeFirst());
zeroInDegreeCount++;
}
for (Integer node : nodeList) {
for (int i = 0; i < adj[node].size(); i++) {
int cur = adj[node].get(i);
inDegreeArr[cur]--;
if (inDegreeArr[cur] == 0) {
queue.add(cur);
}
}
}
}
return zeroInDegreeCount == n;
}
public static void main(String[] args) {
}
}
|
C++
|
UTF-8
| 6,055 | 3.03125 | 3 |
[] |
no_license
|
/*************************************************
Copyright (C), 2017.10.10-2017.10.13, Trunk Tech.
File name: pathFinder.h
Author: 薛崇 Version: 1.0 Date:2017.10.11
Description: path finder with A* algorithm
leader function is aStar()
check input using judge
check other input and generate nodeMap, using initNodeMap
init and generate paths, using initPaths
call aStep recursively, complete the search
Others: // 其它内容的说明
Function List: // 主要函数列表,每条记录应包括函数名及功能简要说明
1. ....
History: // 修改历史记录列表,每条修改记录应包括修改日期、修改
// 者及修改内容简述
1. Date:2017.10.11
Author:XueChong
Modification:build up the framework
2. Date:2017.10.12
Author:XueChong
Modification:fix the bugs
3. Date:2017.10.13
Author:XueChong
Modification:add detailed comments
4. ...
*************************************************/
#include "pathFinder.h"
#include <iostream>
#include <vector>
#include <limits>
#include <cmath>
#include <math.h>
using std::vector;
using std::abs;
namespace xuechong{
vector<int> aStar(const vector< vector<int> > &weights ,const int srcNode, const int targetNode,const vector<double> &nodeX, vector<double> &nodeY){
//define it firstly, if input is wrong, return the empty path
vector<int> path;
//if there is no path from srcNode to targetNode,return NULL
if( !judge(weights, srcNode, targetNode)){
std::cout<< "input is fault, please check!\n";
path.resize(1,-2);
return path;
}
// init nodeMap
vector< vector<double> > nodeMap;
//there should check if nodeX and nodeY is correct,false lead to empty path return
if( !initNodeMap(weights, nodeX, nodeY, nodeMap)){
std::cout<< "input is fault, please check!\n";
path.resize(1,-2);
return path;
}
//init paths
vector<double> paths;
initPaths(nodeMap, srcNode, targetNode, paths);
//define parents and visited
vector<int> parents(nodeX.size(),-1);
vector<int> visited;
// start calling main algorithm aStep recursively
int result = aStep(srcNode, targetNode, nodeMap, paths, parents, visited);
path.push_back(targetNode);
int tempNode = targetNode;
int step = 0;
while((tempNode = parents[tempNode]) != srcNode && tempNode >= 0){
path.push_back(tempNode);
step ++;
//path doesn't exist
if(step > nodeMap.size()){
path.resize(1);
path[0] = -1;
std::cout << "doesn't exist! \n";
return path;
}
}
//path doesn't exist
if(tempNode < 0){
std::cout << "doesn't exist! \n";
path.resize(1);
path[0] = -1;
return path;
}
path.push_back(srcNode);
//reverse the path, make it start from srcNode and end with targetNode
int temp = 0;
for (int i=0; i< path.size()/2 ; i++){
temp = path[i];
path[i] = path[path.size() - 1 - i];
path[path.size() - 1 - i] = temp;
}
return path;
}
bool judge(const vector< vector<int> > &weights, const int srcNode, const int targetNode){
if(weights.size() <=0){
return false;
}
if(srcNode >= weights.size() || targetNode >= weights.size()){
return false;
}
for(int i=0; i<weights.size(); i++){
if(weights[i].size() != weights.size()){
return false;
}
}
return true;
}
int aStep(int srcNode, const int targetNode,const vector< vector<double> > &nodeMap, vector<double> &paths, vector<int> &parents, vector<int> &visited){
//std::cout << srcNode << "-->";
if( srcNode == targetNode){
return 0;
}
if( visited.size() == nodeMap.size() ){
return 0;
}
//update paths, g_cost
for(int i=0;i<nodeMap.size();i++){
if (nodeMap[srcNode][i] > 0 && nodeMap[srcNode][i] + paths[srcNode] <= paths[i] ){
paths[i] = paths[srcNode] + nodeMap[srcNode][i];
parents[i] = srcNode;
}
}
visited.push_back(srcNode);
//compute h_cost
double distance = std::numeric_limits<double>::max();
for(int i=0; i< nodeMap.size(); i++){
if(!isContain(visited, i) && paths[i] + abs(nodeMap[i][targetNode]) < distance ){
srcNode = i;
distance = paths[i] + abs(nodeMap[i][targetNode]) ;
}
}
return aStep(srcNode, targetNode, nodeMap, paths, parents, visited);
}
bool isContain(const vector<int> &visited, int node){
for(int i=0; i< visited.size(); i++){
if( node == visited[i]){
return true;
}
}
return false;
}
bool initNodeMap(const vector< vector<int> > &weights, const vector<double> &nodeX, const vector<double> &nodeY, vector< vector<double> > &nodeMap){
//check the nodeX and nodeY firstly
if(nodeX.size() != weights.size() || nodeY.size() != weights.size() || nodeX.size()==0){
return false;
}
vector<double> nodeRow(nodeX.size(), 0.0);
nodeMap.resize(nodeX.size(), nodeRow);
for(int i=0; i< nodeX.size(); i++){
for(int j = 0; j< nodeY.size(); j++){
if(weights[i][j] == 1){
nodeMap[i][j] = sqrt( pow(nodeX[i] - nodeX[j] ,2 ) + pow( nodeY[i]-nodeY[j] , 2) );
}else{
nodeMap[i][j] = 0 - sqrt( pow(nodeX[i] - nodeX[j] ,2 ) + pow( nodeY[i]-nodeY[j] , 2) );
}
}
}
return true;
}
void initPaths(const vector< vector<double> > &nodeMap, const int srcNode, const int targetNode, vector<double> &paths){
paths.resize(nodeMap.size(), std::numeric_limits<double>::max());
for(int i=0; i< nodeMap.size(); i++){
if(nodeMap[srcNode][i] > 0){
paths[i] = nodeMap[srcNode][i];
}
}
paths[srcNode] = 0.0;
}
}
|
C++
|
UTF-8
| 7,015 | 3.296875 | 3 |
[] |
no_license
|
/* Trigonometry_routine.cc */
struct Point {
double x,y,z;
};
void write_Point(Point P){
cout << P.x << " " << P.y << " " << P.z << "\n";
};
Point midpoint(Point P, Point Q){
Point R;
R.x=(P.x+Q.x)/2.0;
R.y=(P.y+Q.y)/2.0;
R.z=(P.z+Q.z)/2.0;
return(R);
};
double norm(Point P){
return(sqrt(P.x*P.x+P.y*P.y+P.z*P.z));
};
Point operator*(Point P, double d){
Point Q;
Q.x=P.x*d;
Q.y=P.y*d;
Q.z=P.z*d;
return(Q);
};
Point operator/(Point P, double d){
Point Q;
Q.x=P.x/d;
Q.y=P.y/d;
Q.z=P.z/d;
return(Q);
};
Point operator+(Point P, Point Q){
Point R;
R.x=P.x+Q.x;
R.y=P.y+Q.y;
R.z=P.z+Q.z;
return(R);
};
Point operator-(Point P, Point Q){
Point R;
R.x=P.x-Q.x;
R.y=P.y-Q.y;
R.z=P.z-Q.z;
return(R);
};
Point cross(Point P, Point Q){
Point R;
R.z=P.x*Q.y-P.y*Q.x;
R.y=P.z*Q.x-P.x*Q.z;
R.x=P.y*Q.z-P.z*Q.y;
return(R);
};
double dot(Point P, Point Q){
return(P.x*Q.x+P.y*Q.y+P.z*Q.z);
};
double hdot(Point P, Point Q){
return(P.x*Q.x+P.y*Q.y-P.z*Q.z);
};
class Matrix {
public:
// do I want entries to be public?
vector< vector<double> > e; // implicitly 3x3; e[i] = row i, e[i][j] = row i, column j
Point operator()(Point P){
Point Q;
Q.x = P.x*e[0][0]+P.y*e[0][1]+P.z*e[0][2];
Q.y = P.x*e[1][0]+P.y*e[1][1]+P.z*e[1][2];
Q.z = P.x*e[2][0]+P.y*e[2][1]+P.z*e[2][2];
return(Q);
};
Matrix operator*(Matrix M){
Matrix N;
int i,j;
vector<double> row;
for(i=0;i<3;i++){
row.clear();
for(j=0;j<3;j++){
row.push_back(e[i][0]*M.e[0][j]+e[i][1]*M.e[1][j]+e[i][2]*M.e[2][j]);
};
N.e.push_back(row);
};
return(N);
};
Matrix transpose(){
Matrix N;
int i,j;
vector<double> row;
for(i=0;i<3;i++){
row.clear();
for(j=0;j<3;j++){ // ith column of matrix
row.push_back(e[j][i]);
};
N.e.push_back(row); // is made into ith row of result
};
return(N);
};
Matrix hyp_inv(){ // inverse of M is JM^TJ
Matrix N;
int i;
N=transpose();
for(i=0;i<3;i++){
N.e[i][2]=-N.e[i][2];
};
for(i=0;i<3;i++){
N.e[2][i]=-N.e[2][i];
};
return(N);
};
};
void write_Matrix(Matrix M){
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
cout << M.e[i][j] << " ";
};
cout << "\n";
};
};
Matrix ROT(double angle){ // rotation in xy-plane about origin
// returns matrix C=cos(angle), S=sin(angle)
// (C -S 0)
// (S C 0)
// (0 0 1)
Matrix M;
M.e.clear();
vector<double> row;
row.clear();
row.push_back(cos(angle));
row.push_back(-sin(angle));
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(sin(angle));
row.push_back(cos(angle));
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(0.0);
row.push_back(1.0);
M.e.push_back(row);
return(M);
};
Matrix XZ_ROT(double angle){ // rotation in xz-plane
// returns matrix C=cos(angle), S=sin(angle)
// (C 0 -S)
// (0 1 0)
// (S 0 C)
Matrix M;
M.e.clear();
vector<double> row;
row.clear();
row.push_back(cos(angle));
row.push_back(0.0);
row.push_back(-sin(angle));
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(1.0);
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(sin(angle));
row.push_back(0.0);
row.push_back(cos(angle));
M.e.push_back(row);
return(M);
};
Matrix YZ_ROT(double angle){ // rotation in xz-plane
// returns matrix C=cos(angle), S=sin(angle)
// (1 0 0)
// (0 C -S)
// (0 S C)
Matrix M;
M.e.clear();
vector<double> row;
row.clear();
row.push_back(1.0);
row.push_back(0.0);
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(cos(angle));
row.push_back(-sin(angle));
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(sin(angle));
row.push_back(cos(angle));
M.e.push_back(row);
return(M);
};
Matrix HTR(double dist){ // translation in hyperbolic plane along x axis
// returns matrix c=cosh(dist), s=sinh(dist)
// (c 0 s)
// (0 1 0)
// (s 0 c)
Matrix M;
vector<double> row;
row.clear();
row.push_back(cosh(dist));
row.push_back(0.0);
row.push_back(sinh(dist));
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(1.0);
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(sinh(dist));
row.push_back(0.0);
row.push_back(cosh(dist));
M.e.push_back(row);
return(M);
};
Matrix ETR(double dist){ // translation in Euclidean plane along x axis
// returns matrix
// (1 0 d)
// (0 1 0)
// (0 0 1)
Matrix M;
vector<double> row;
row.clear();
row.push_back(1.0);
row.push_back(0.0);
row.push_back(dist);
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(1.0);
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(0.0);
row.push_back(1.0);
M.e.push_back(row);
return(M);
};
Matrix DIL(double t){ // dilation by t in Euclidean plane centered at 0
// returns matrix
// (t 0 0)
// (0 t 0)
// (0 0 1)
Matrix M;
vector<double> row;
row.clear();
row.push_back(t);
row.push_back(0.0);
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(t);
row.push_back(0.0);
M.e.push_back(row);
row.clear();
row.push_back(0.0);
row.push_back(0.0);
row.push_back(1.0);
M.e.push_back(row);
return(M);
};
double hyp_dist(Point P){ // hyperbolic distance from origin
if(P.z<1.0){
return(0.0);
};
return(acosh(P.z));
};
double hyp_ang(Point P){ // hyperbolic angle from origin; also works as Euclidean angle
double d;
d=hyp_dist(P);
if(d==0.0){
return(0.0);
};
return(atan2(P.y,P.x));
};
double Euc_ang(Point P){
Point Q;
Q=P;
Q.z=0.0;
if(norm(Q)==0.0){
return(0.0);
};
return(atan2(P.y,P.x));
};
double hyp_dist(Point P, Point Q){ // hyperbolic distance between two points *assumed to be on hyperboloid*
return(acosh(-hdot(P,Q)));
};
double sph_dist(Point P, Point Q){ // spherical angle=distance between two points *assumed to be on sphere*
return(acos(dot(P,Q)));
};
double sph_dist(Point P){ // spherical angle=distance from the origin
return(acos(P.z));
};
double sph_ang(Point P){
if(P.z>=1.0){
return(0.0);
};
return(atan2(P.y,P.x));
};
double Euc_dist(Point P, Point Q){ // Euclidean distance between two points *assumed to have z coord = 1*
return(sqrt((P.x-Q.x)*(P.x-Q.x)+(P.y-Q.y)*(P.y-Q.y)));
};
Point hyperboloid_to_Poincare(Point P){ // change coordinates from hyperboloid to Poincare model
// this can be used to change geometry from hyperbolic to Euclidean
Point Q;
Q.x=P.x/(P.z+1.0);
Q.y=P.y/(P.z+1.0);
Q.z=1.0;
return(Q);
};
Point Euclidean_to_sphere(Point Q){
Point R;
R.x=2.0*Q.x/(1.0+Q.x*Q.x+Q.y*Q.y);
R.y=2.0*Q.y/(1.0+Q.x*Q.x+Q.y*Q.y);
R.z=(1.0-Q.x*Q.x-Q.y*Q.y)/(1.0+Q.x*Q.x+Q.y*Q.y);
return(R);
};
Point hyperboloid_to_sphere(Point P){
Point Q,R;
Q=hyperboloid_to_Poincare(P);
// R.x=2.0*Q.x/(1.0+Q.x*Q.x+Q.y*Q.y);
// R.y=2.0*Q.y/(1.0+Q.x*Q.x+Q.y*Q.y);
// R.z=(1.0-Q.x*Q.x-Q.y*Q.y)/(1.0+Q.x*Q.x+Q.y*Q.y);
R=Euclidean_to_sphere(Q);
return(R);
};
|
PHP
|
UTF-8
| 3,806 | 2.65625 | 3 |
[] |
no_license
|
<?php
// index.php
//
// This is the server-side entry point to a Fusion application
//
// Having the entry point server-side instead of a client-side HTML page gives us the following
// benefits:
//
// 1. We save future requests to CreateSession.php and requesting the Application Definition resource as we can do that right here
// 2. The user/developer can implement additional initialization and/or security checks here
//
// Request Parameters:
//
// template - The name of the template to load (required)
// ApplicationDefinition - The resource id of the ApplicationDefinition (optional. If omitted, will use ApplicationDefinition.xml/json from the template dir)
// locale - The locale to use for localized strings (optional. Defaults to "en" if omitted)
// session - The MapGuide session id. (optional. Will not generate one if specified)
// username - The MapGuide user name (optional. Will use this username/password for authentication and generating a session id if provided)
// password - The MapGuide user password (optional. Will use this username/password for authentication and generating a session id if provided)
include(dirname(__FILE__)."/svc/common/php/Utilities.php");
include(dirname(__FILE__)."/svc/MapGuide/php/Common.php");
$template = "";
$appDefId = "";
$appDefJson = "";
if (array_key_exists("template", $_REQUEST)) {
$template = $_REQUEST["template"];
} else {
echo "ERROR: Missing required parameter 'template'";
die;
}
if (array_key_exists("ApplicationDefinition", $_REQUEST)) {
$appDefId = $_REQUEST["ApplicationDefinition"];
}
//Resolve template path based on template name
$tplPath = dirname(__FILE__)."/templates/mapguide/$template/index.templ";
if (!file_exists($tplPath)) {
echo "ERROR: Could not find template file: $tplPath";
die;
}
//Application Definition resolution priority
//
// 1. Resource ID, if specified
// 2. ApplicationDefinition.xml on the template dir
// 3. ApplicationDefinition.json on the template dir
//
// If we get an XML document, convert it to JSON with xml2json() (#2 won't be the case)
if (strlen($appDefId) == 0) {
$xmlPath = dirname(__FILE__)."/templates/mapguide/$template/ApplicationDefinition.xml";
if (!file_exists($xmlPath)) {
$jsonPath = dirname(__FILE__)."/templates/mapguide/$template/ApplicationDefinition.json";
if (!file_exists($jsonPath)) {
echo "ERROR: Could not find ApplicationDefinition.xml or ApplicationDefinition.json in template path";
die;
} else {
$appDefJson = file_get_contents($jsonPath);
}
} else {
$doc = DOMDocument::load($xmlPath);
$appDefJson = xml2json($doc);
}
} else {
$resId = new MgResourceIdentifier($appDefId);
$appDefContent = $resourceService->GetResourceContent($resId);
$doc = DOMDocument::loadXML($appDefContent->ToString());
$appDefJson = xml2json($doc);
}
//Make a session ID if needed
$site = $siteConnection->GetSite();
$sessionID = $site->GetCurrentSession();
if (strlen($sessionID) == 0) {
$site = $siteConnection->GetSite();
$sessionID = $site->CreateSession();
$user->SetMgSessionId($sessionID);
}
$scripts = "";
// Find and replace the following tokens if found:
//
// %PAGE_TITLE% - The title of the page
// %SCRIPTS% - A list of script tags (for Google/Bing/OSM)
// %APP_DEF% - The Application Definition JSON
// %SESSION_ID% - The MapGuide Session ID
//
$tplContent = file_get_contents($tplPath);
$tplContent = str_replace("%PAGE_TITLE%", $template, $tplContent);
$tplContent = str_replace("%SCRIPTS%", $scripts, $tplContent);
$tplContent = str_replace("%APP_DEF%", $appDefJson, $tplContent);
$tplContent = str_replace("%SESSION_ID%", $sessionID, $tplContent);
header("Content-type: text/html");
echo $tplContent;
?>
|
SQL
|
UTF-8
| 2,457 | 4 | 4 |
[] |
no_license
|
show processlist;
show databases;
use mysql;
show tables;
desc user;
## 使用create user创建新用户
create user 'jason'@'localhost' identified by '123456'; -- 若主机名为‘%’则表示对所有主机开放权限
select * from user where User='jason2';
## 避免使用明文指定用户密码
select password('123456');
create user 'jason1'@'localhost' identified by password '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9';
## 使用grant创建用户Jason2,并授予对所有数据库表的select和update权限
grant select,update on *.* to 'jason2'@'localhost' identified by '123456';
## 使用insert into向user表插入数据
insert into user(Host,User,Password) values('localhost','jason3',password('123456'));
## 删除用户
drop user 'jason'@'localhost'; -- 删除用户在本地登录的权限
delete from user where host='localhost' and user='jason1';
## 修改root用户密码
mysqladmin -u root -h localhost -p password '12345';
## 修改user表
update mysql.user set Password=password('12345') where user='root' and host='localhost';
## 使用set
set password=password('123456');
select user,password from user;
## root用户修改普通用户密码
set password for 'jason3'@'localhost'=password('123456'); -- 失败
update mysql.user set password=password('123456') where user='jason3' and host='localhost';
grant usage on *.* to 'jason2'@'localhost' identified by '12345';
create database team;
use team;
create table player(
playid int primary key,
playname varchar(30) not null,
teamnum int not null unique,
info varchar(50)
);
## 创建新用户account1通过本地主机连接数据库,密码为oldpwd1
##,授权该用户对team数据库中的play表的insert、select权限,并对info字段的update权限
grant select,insert,update(info) on team.player to 'account1'@'localhost' identified by 'oldpwd1';
## 使用表查看权限
select * from mysql.user;
select * from mysql.tables_priv;
select * from mysql.columns_priv;
## 修改密码
grant usage on team.player to 'account1'@'localhost' identified by 'newpwd1';
update mysql.user set password=password('newpwd') where user='account1' and host='localhost';
## 查看权限
show grants for 'account1'@'localhost';
## 回收权限
revoke select,insert,update on team.player from 'account1'@'localhost';
## 删除用户
delete from mysql.user where host='localhost' and user='account1';
drop user 'account1'@'localhost';
|
Markdown
|
UTF-8
| 5,105 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# Практическая работа №2 "Связные списки"
Реализуйте простой плейер с графическим интерфейсом. Предусмотрите
следующий функционал:
1) создание плейлиста;
2) удаление плейлиста;
3) добавление музыкальной композиции в плейлист;
4) удаление музыкальной композиции из плейлиста;
5) перемещение музыкальной композиции на другую позицию плейлисте (изменение порядка);
6) проигрывание музыкальной композиции;
7) запуск предыдущей музыкальной композиции;
8) запуск последующей музыкальной композиции;
9) после завершения проигрывания последне композиции в плейлисте он
должен начинаться сначала.
Подсказка:
> Используйте кольцевой двусвязный список
## Требования к реализации
Реализуйте класс `Composition`, представляющий музыкальную композицию, и
класс `PlayList`, реализующий логику работы плейлиста. Класс `PlayList`
унаследуйте от базового класса `LinkedList`, реализующего операции над
связным списком:
- `append_left(self, item)` - добавление элемента в начало списка;
- `append_right(self, item)` - добавление элемента в конец списка;
- `append(self, item)` - алиас для `append_right`;
- `remove(self, item)` - удаление элемента, при его отсутствии в списке
должно возбуждать исключение `ValueError`;
- `insert(self, previous, item)` - добавление элемента `item` после
элемента `previous`.
Добавьте поддержку "магических" методов в классе `LinkedList`:
- `__len__` - длина списка;
- `__iter__` - получение итератора;
- `__next__` - получение следующего элемента;
- `__getitem__` - получение элемента по индексу;
- `__contains__` - поддержка оператора `in`;
- `__reversed__` - поддержка функции `reversed`.
Предусмотрите следующие методы в классе `PlayList`:
- `play_all(self, item)` - начать проигрывать все треки, начиная с `item`;
- `next_track(self)` - перейти к следующему треку;
- `previous_track(self)` - перейти к предыдущему треку;
- `current(self)` - получить текущи трек, реализовать в виде свойства.
Реализовать пользовательский интерфейс можно на любой библиотеке (веб
или десктоп), например `PyQt` или `Flask`. Использование
`QMediaPlaylist` фреймворка `PyQt` для реализации плейлиста не
допускается.
Подсказка:
> Проигрывание музыкальных композиций можно реализовать с помощью
> `pygame`.
<!-- ## Входные и выходные данные -->
## Методика оценивания
Оценка выставляется в соответствии со следующими требованиями:
1) Общие требования:
- код работы проходит проверку утилитой `pylint` с конфигурационным
файлом `.pylintrc`.
- код работы успешно проходит тесты, если таковые имеются.
2) На оценку 3 балла:
- программа поддерживает только один плейлист;
- реализовать пункты 3, 4, 6, 7 и 8.
3) На оценку 4 балла:
- дополнительно реализовать пункты 5 и 9.
4) На оценку 5 балла:
- реализовать все методы, указанные в описании к работе.
## Полезные материалы
- [Multiply two numbers represented by Linked Lists](https://www.geeksforgeeks.org/multiply-two-numbers-represented-linked-lists/)
- [Data Structures In The Real World — Linked List](https://medium.com/journey-of-one-thousand-apps/data-structures-in-the-real-world-508f5968545a)
- [How is Python's List Implemented?](https://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented)
- [Playing mp3 song on python](https://stackoverflow.com/questions/20021457/playing-mp3-song-on-python)
|
Markdown
|
UTF-8
| 1,546 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
# How To Stake Tokens
### Goal
Stake tokens for your account.
### Before you begin
* Install the currently supported version of `cleos`.
* Ensure the reference system contracts from `cyberway.contracts` repository is deployed and used to manage system resources.
* Understand the following:
* What is an [account](https://docs.cyberway.io/users/glossary#account);
* What is a [stake](https://docs.cyberway.io/users/glossary#stake);
* What is a [bandwidth](https://docs.cyberway.io/users/glossary#bandwidth) in CyberWay;
* What are [CPU](https://docs.cyberway.io/users/glossary#cpu), [NET](https://docs.cyberway.io/users/glossary#net), [RAM](https://docs.cyberway.io/users/glossary#ram) and [Storage](https://docs.cyberway.io/users/glossary#storage) resources.
### Steps
Stake 100 CYBER tokens for `alice` account:
```sh
$ cleos push action cyber.token transfer '[alice, cyber.stake, "100.0000 CYBER"]' -p alice@active
```
or using "system stake" operation:
```sh
$ cleos system stake alice "100.0000 CYBER"
```
> **Note**
> When you perform a transaction, you do not need to worry about which specific resource (RAM, NET, CPU or Storage) will be consumed more (or less) and how the staked tokens should be spent. The system dynamically and optimally distributes your staked tokens.
### Useful links
* [The bandwidth in CyberWay](https://docs.cyberway.io/users/bandwidth_implementation#bandwidth-sharing)
* [The cyberway.stake contract](https://docs.cyberway.io/devportal/system_contracts/cyber.stake_contract)
|
Python
|
UTF-8
| 296 | 2.796875 | 3 |
[] |
no_license
|
def main():
n = int(input())
a = list(map(int,input().split()))
b = [0 for i in range(n + 1)]
a.sort()
ans = n
for i in range(n):
b[i + 1] = b[i] + a[i]
for i in range(1,n):
if b[i + 1] - b[i] > 2 * b[i]:
ans = n - i
print(ans)
main()
|
C
|
UTF-8
| 4,677 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
#include <types.h>
#include <err.h>
#include <sys.h>
#include <c.h>
#include <mesg.h>
#include <proc0.h>
#include <stdarg.h>
#include <string.h>
#include <log.h>
#include <eth.h>
#include <ip.h>
#include <net_dev.h>
#include <net.h>
#include "net.h"
bool
arp_match_ip(struct net_dev *net,
uint8_t *ip_src,
uint8_t *mac_dst)
{
struct net_dev_internal *i = net->internal;
struct arp_entry *e;
for (e = i->arp_entries; e != nil; e = e->next) {
if (memcmp(e->ip, ip_src, 4)) {
memcpy(mac_dst, e->mac, 6);
return true;
}
}
return false;
}
void
arp_request(struct net_dev *net, uint8_t *ipv4,
void (*func)(struct net_dev *net, void *arg, uint8_t *mac),
void *arg)
{
uint8_t dst[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
uint8_t mac[6];
if (arp_match_ip(net, ipv4, mac)) {
func(net, arg, mac);
return;
}
struct net_dev_internal *i = net->internal;
struct arp_request *r;
uint8_t *pkt, *bdy;
if (!create_eth_pkt(net, dst,
0x0806,
28,
&pkt, (uint8_t **) &bdy))
{
return;
}
if ((r = malloc(sizeof(struct arp_request))) == nil) {
free(pkt);
return;
}
memcpy(r->ip, ipv4, 4);
r->func = func;
r->arg = arg;
r->next = i->arp_requests;
i->arp_requests = r;
/* hardware type (ethernet 1) */
bdy[0] = 0;
bdy[1] = 1;
/* protocol type (ipv4 0x0800) */
bdy[2] = 0x08;
bdy[3] = 0x00;
/* len (eth = 6, ip = 4)*/
bdy[4] = 6;
bdy[5] = 4;
/* operation (1 request, 2 reply) */
bdy[6] = 0;
bdy[7] = 1;
memcpy(&bdy[8], net->mac, 6);
memcpy(&bdy[14], net->ipv4, 4);
memset(&bdy[18], 0, 6);
memcpy(&bdy[24], ipv4, 4);
send_eth_pkt(net, pkt, 28);
}
static void
arp_add_entry(struct net_dev *net, uint8_t *ipv4, uint8_t *mac)
{
struct net_dev_internal *i = net->internal;
struct arp_request **r, *f;
struct arp_entry *e;
log(LOG_INFO, "adding entry for %i.%i.%i.%i", ipv4[0], ipv4[1], ipv4[2], ipv4[3]);
for (e = i->arp_entries; e != nil; e = e->next) {
if (memcmp(e->ip, ipv4, 4)) {
break;
}
}
if (e == nil) {
if ((e = malloc(sizeof(struct arp_entry))) == nil) {
log(LOG_WARNING, "malloc failed");
return;
}
e->next = i->arp_entries;
i->arp_entries = e;
memcpy(e->ip, ipv4, 4);
}
memcpy(e->mac, mac, 6);
r = &i->arp_requests;
while (*r != nil) {
if (memcmp((*r)->ip, ipv4, 4)) {
f = *r;
*r = (*r)->next;
f->func(net, f->arg, mac);
free(f);
} else {
r = &(*r)->next;
}
}
}
static void
handle_arp_request(struct net_dev *net, uint8_t *src_mac, uint8_t *src_ipv4)
{
uint8_t *pkt, *bdy;
log(LOG_WARNING, "asking about us!!!");
if (!create_eth_pkt(net, src_mac,
0x0806,
28,
&pkt, (uint8_t **) &bdy))
{
return;
}
/* hardware type (ethernet 1) */
bdy[0] = 0;
bdy[1] = 1;
/* protocol type (ipv4 0x0800) */
bdy[2] = 0x08;
bdy[3] = 0x00;
/* len (eth = 6, ip = 4)*/
bdy[4] = 6;
bdy[5] = 4;
/* operation (1 request, 2 reply) */
bdy[6] = 0;
bdy[7] = 2;
memcpy(&bdy[8], net->mac, 6);
memcpy(&bdy[14], net->ipv4, 4);
memcpy(&bdy[18], src_mac, 6);
memcpy(&bdy[24], src_ipv4, 4);
send_eth_pkt(net, pkt, 28);
arp_add_entry(net, src_ipv4, src_mac);
}
static void
handle_arp_response(struct net_dev *net, uint8_t *bdy, size_t len)
{
uint8_t *src_ip, *src_mac;
log(LOG_INFO, "got arp response");
src_mac = bdy + 8;
src_ip = bdy + 14;
arp_add_entry(net, src_ip, src_mac);
}
void
handle_arp(struct net_dev *net,
struct eth_hdr *hdr,
uint8_t *bdy, size_t len)
{
uint16_t htype, ptype;
uint8_t hlen, plen;
uint16_t oper;
log(LOG_INFO, "handle arp pkt");
static uint8_t broadcast_mac[6] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
if (len < 8) {
log(LOG_WARNING, "arp packet with bad len %i", len);
return;
}
htype = bdy[0] << 8 | bdy[1];
ptype = bdy[2] << 8 | bdy[3];
hlen = bdy[4];
plen = bdy[5];
oper = bdy[6] << 8 | bdy[7];
if (len < 8 + hlen * 2 + plen * 2) {
log(LOG_WARNING, "arp packet with bad len %i expected %i",
len, 8 + hlen * 2 + plen * 2);
return;
}
if (htype != 1 || ptype != 0x800) {
log(LOG_WARNING, "arp packet with unsupported protocols %i 0x%x",
htype, ptype);
return;
}
if (memcmp(hdr->dst, broadcast_mac, 6)) {
uint8_t *src_ipv4 = bdy + 14;
uint8_t *tgt_ipv4 = bdy + 24;
if (memcmp(tgt_ipv4, net->ipv4, 4)) {
handle_arp_request(net, hdr->src, src_ipv4);
} else {
log(LOG_INFO, "arp broadcast pkt not for us");
}
} else if (memcmp(hdr->dst, net->mac, 6)) {
switch (oper) {
case 1:
log(LOG_WARNING, "unhandled arp pkt oper %i",
oper);
break;
case 2:
handle_arp_response(net, bdy, len);
break;
default:
log(LOG_WARNING, "arp packet with bad oper %i", oper);
return;
}
}
}
|
Markdown
|
UTF-8
| 2,943 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "648. Replace Words"
date: 2019-03-07 17:24
author: Botao Xiao
categories: Leetcode
description:
---
## 648. Replace Words
### Question
In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
```
Example 1:
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
```
Note:
* The input will only have lower-case letters.
* 1 <= dict words number <= 1000
* 1 <= sentence words number <= 1000
* 1 <= root length <= 100
* 1 <= sentence words length <= 1000
### Thinking:
* Method 1:Trie Tree
```Java
class Solution {
private static class TrieTree{
public static class Node{
boolean isLeaf;
Node[] childs;
public Node(){
this.childs = new Node[26];
}
}
private Node root;
public TrieTree(){
this.root = new Node();
}
public void insert(String s){
char[] arr = s.toCharArray();
Node node = root;
for(int i = 0; i < arr.length; i++){
if(node.isLeaf) return;
int c = arr[i] - 'a';
if(node.childs[c] == null){
node.childs[c] = new Node();
}
node = node.childs[c];
}
node.isLeaf = true;
}
public String findClosest(String s){
char[] arr = s.toCharArray();
Node node = root;
for(int i = 0; i < arr.length; i++){
int c = arr[i] - 'a';
if(node.childs[c] == null){
return s;
}else{
node = node.childs[c];
if(node.isLeaf){
return s.substring(0, i + 1);
}
}
}
return s;
}
}
public String replaceWords(List<String> dict, String sentence) {
if(sentence == null || sentence.length() == 0) return "";
if(dict == null || dict.size() == 0) return sentence;
TrieTree tree = new TrieTree();
for(String s : dict){
tree.insert(s);
}
StringBuilder sb = new StringBuilder();
String[] tokens = sentence.split(" ");
for(String token : tokens){
sb.append(" " + tree.findClosest(token));
}
return sb.toString().substring(1);
}
}
```
|
TypeScript
|
UTF-8
| 1,027 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import {Message} from 'discord.js';
import {AkairoArgumentType, DiceCommand, DiceCommandCategories} from '../../structures/DiceCommand';
import {sum} from '../../util/reducers';
export default class AverageCommand extends DiceCommand {
constructor() {
super('average', {
aliases: ['average-numbers', 'avg-numbers', 'avg', 'mean'],
description: {content: 'Get the mean of a set of numbers.', examples: ['192 168 1 1'], usage: '<...numbers>'},
category: DiceCommandCategories.Util,
args: [
{
id: 'numbers',
match: 'separate',
type: AkairoArgumentType.Number,
prompt: {start: 'What numbers should be averaged?', retry: 'Invalid numbers provided, please try again'}
}
]
});
}
async exec(message: Message, {numbers}: {numbers: number[]}): Promise<Message | undefined> {
if (numbers.length > 0) {
// eslint-disable-next-line unicorn/no-reduce, unicorn/no-fn-reference-in-iterator
return message.util?.send((numbers.reduce(sum) / numbers.length).toLocaleString());
}
}
}
|
JavaScript
|
UTF-8
| 1,619 | 3.359375 | 3 |
[
"Apache-2.0"
] |
permissive
|
//CORE JS FUNCTIONALITY
//Contains only the most essential functions for the theme. No jQuery.
// Get the header
const header = document.getElementById('header')
// Get the offset position of the navbar
const sticky = header.offsetTop
/* ==========================================================================
Mobile Menu Toggle
========================================================================== */
document.addEventListener('DOMContentLoaded', function () {
var menu_element = document.getElementById('menu-mobile-open')
var menu_exists = !!menu_element
if (menu_exists) {
menu_element.addEventListener('click', function () {
document.body.classList.add('menu-mobile-active')
})
document.getElementById('menu-mobile-close').addEventListener('click', function () {
document.body.classList.remove('menu-mobile-active')
})
}
})
/* ==========================================================================
handleStickyHeader
========================================================================== */
// When the user scrolls the page, execute myFunction
window.onscroll = function () {
handleSticky()
}
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function handleSticky () {
if (document.body.classList.contains('cpo-sticky-header')) { // only run if sticky header is actually enabled
if (window.pageYOffset >= sticky) {
header.classList.add('cpo-sticky')
} else {
header.classList.remove('cpo-sticky')
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.