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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 2,385
| 3.1875
| 3
|
[] |
no_license
|
1、StatelessWidget
2、StatefulWidget
```
无状态静态的视图展示使用StatelessWidget,而有交互,需要动态变化的使用StatefulWidget.
StatelessWidget初始化之后就无法改变,如果想改变,那便需要重新创建,new另一个StatelessWidget进行替换。但StatelessWidget因为是静态的,他没有办法重新创建自己。所以StatefulWidget便提供了这样的机制,通过调用`setState((){})`标记自身为dirty状态,以等待下一次系统的重绘检查。
1.Stateless widgets 是不可变的,这意味着它们的属性不能改变——所有的值都是 final。
2.Stateful widgets 持有的状态可能在 widget 生命周期中发生变化,实现一个 stateful widget 至少需要两个类:1)一个 StatefulWidget 类;2)一个 State 类,StatefulWidget 类本身是不变的,但是 State 类在 widget 生命周期中始终存在。
```
# StatelessWidget
Flutter中的`StatelessWidget`是一个不需要状态更改的widget - 它没有要管理的内部状态,也不依赖于对象本身中的配置信息以及widget的BuildContext 。
也就是说如如果widget不会出现任何修改一直是静态显示的则用`StatelessWidget`这个东西。
StatelessWidget初始化之后就无法改变,如果想改变,那便需要重新创建,new另一个StatelessWidget进行替换。但StatelessWidget因为是静态的,他没有办法重新创建自己。
无状态widget的build方法通常只会在以下三种情况调用:
- 将widget插入树中时
- 当widget的父级更改其配置时
- 当它依赖的[InheritedWidget](https://docs.flutter.io/flutter/widgets/InheritedWidget-class.html)发生变化时
# StatefulWidget
持有的状态可能在 widget 生命周期中发生变化,实现一个 stateful widget 至少需要两个类:1)一个 StatefulWidget 类;2)一个 State 类,StatefulWidget 类本身是不变的,但是 State 类在 widget 生命周期中始终存在。
[StatefulWidget](https://docs.flutter.io/flutter/widgets/StatefulWidget-class.html) 是可变状态的widget。 使用`setState`方法管理StatefulWidget的状态的改变。调用`setState`告诉Flutter框架,某个状态发生了变化,Flutter会重新运行build方法,以便应用程序可以应用最新状态。
|
Ruby
|
UTF-8
| 2,072
| 3.0625
| 3
|
[] |
no_license
|
require_relative 'manufacturer'
require_relative 'validation'
class Train
include Manufacturer
include InstanceCounter
include Validation
attr_reader :train_number, :train_type, :route, :current_route, :wagons, :current_station
NUMBER_FORMAT = /^[а-я0-9]{3}-*[а-я0-9]{2}$/i.freeze
validate :train_number, :presence
validate :train_number, :format, NUMBER_FORMAT
@@trains = {}
def initialize(train_number, train_type)
@train_number = train_number
@train_type = train_type
@wagons = []
@speed = 0
@@trains[train_number] = self
register_instance
validate!
end
def self.trains_list
@@trains
end
def self.find(train_number)
@@trains[train_number]
end
def add_speed(add_speed)
self.speed += add_speed
end
def slow_down(minus_speed)
self.speed -= minus_speed
end
def unhook_wagon
@wagons.pop if @speed != 0 && @wagons.count.positive?
end
def hook_ap_wagon(wagon)
@wagons << wagon if @speed.zero? && wagon.type == train_type
end
def add_route(route)
@current_route = route
@index = 0
edit_current_station
end
def to_next_station
if not_last?
@index += 1
edit_current_station
end
end
def to_previous_station
if not_first? && not_last?
@index -= 1
edit_current_station
end
end
def not_last?
@current_station != @current_route.all_stations.last
end
def not_first?
@current_station[@index] != @current_route.all_stations.first
end
def edit_current_station
@current_station = @current_route.all_stations[@index]
@current_station.get_train(self)
end
def train_wagons(&block)
@wagons.each(&block) if block_given?
end
protected
attr_writer :speed
# def validate!
# raise 'Номер не может быть пустым!' if @train_number.empty?
# raise 'Номер не соотвествует формату ' if @train_number !~ NUMBER_FORMAT
#
# true
# end
#
# def valid?
# validate!
# rescue StandardError
# false
# end
end
|
PHP
|
UTF-8
| 4,935
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
//public const
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $first_name;
/**
* @ORM\Column(type="string", length=255)
*/
private $last_name;
/**
* @ORM\Column(type="string", length=255, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles;
/**
* @ORM\Column(type="string", length=255)
*/
private $password;
/**
* @ORM\OneToMany(targetEntity=Ticket::class, mappedBy="handling_agent")
*/
private $ticket;
/**
* @ORM\OneToMany(targetEntity=CommentHistory::class, mappedBy="created_by")
*/
private $commentHistories;
/**
* @ORM\Column(type="boolean")
*/
private $isVerified = false;
public function __construct()
{
$this->ticket = new ArrayCollection();
$this->commentHistories = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFirstName(): ?string
{
return $this->first_name;
}
public function setFirstName(string $first_name): self
{
$this->first_name = $first_name;
return $this;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getRoles(): array
{
$roles = $this->roles;
$roles[] = "ROLE_USER";
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @return Collection|Ticket[]
*/
public function getTickets(): Collection
{
return $this->ticket;
}
public function addTicket(Ticket $ticket): self
{
if (!$this->ticket->contains($ticket)) {
$this->ticket[] = $ticket;
$ticket->setHandlingAgent($this);
}
return $this;
}
public function removeTicket(Ticket $ticket): self
{
if ($this->ticket->contains($ticket)) {
$this->ticket->removeElement($ticket);
// set the owning side to null (unless already changed)
if ($ticket->getHandlingAgent() === $this) {
$ticket->setHandlingAgent(null);
}
}
return $this;
}
/**
* @return Collection|CommentHistory[]
*/
public function getCommentHistories(): Collection
{
return $this->commentHistories;
}
public function addCommentHistory(CommentHistory $commentHistory): self
{
if (!$this->commentHistories->contains($commentHistory)) {
$this->commentHistories[] = $commentHistory;
$commentHistory->setCreatedBy($this);
}
return $this;
}
public function removeCommentHistory(CommentHistory $commentHistory): self
{
if ($this->commentHistories->contains($commentHistory)) {
$this->commentHistories->removeElement($commentHistory);
// set the owning side to null (unless already changed)
if ($commentHistory->getCreatedBy() === $this) {
$commentHistory->setCreatedBy(null);
}
}
return $this;
}
public function getSalt()
{
// TODO: Implement getSalt() method.
}
public function getUsername()
{
// TODO: Implement getUsername() method.
}
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
}
|
Markdown
|
UTF-8
| 1,841
| 3.0625
| 3
|
[] |
no_license
|
# I/O HW3
* Snapshot of C library’s execution time in 4B-sized and 4KB-sized.
4B:

4KB:

* Snapshot of System Call’s execution time in 4B-sized and 4KB-sized.
4B:

4KB:

* Snapshot of Memory-mapped file’s execution time in 4B-sized and 4KB-sized.
4B:

4KB:

* Compare the execution time under the different methods, C library, System Call and Memory-mapped file, in the 4B-sized and explain the results.
* Execute time: System Call >> C library / Memory-mapped file
* Both library call and memory-mapped file only makes system call to write disk when user buffer is full. And every system call takes up mcuh resource.
* Compare the execution time under the different methods, C library, System Call and Memory-mapped file, in the 4KB-sized and explain the results.
* The time consumed does not differ from one another since the frequencie of system calls are similar.
* Compare the execution time between 4B-sized and 4KB-sized in the C library and explain the results.
* The time consumed for 4B is slightly longer than that of 4KB since the frequency of replication is more.
* Compare the execution time between 4B-sized and 4KB-sized in the System Call and explain the results.
* The time consumed for 4B is ***much*** longer than that of 4KB due to the difference of the frequency of system calls.
* Compare the execution time between 4B-sized and 4KB-sized in the Memory-mapped file and explain the results.
* The time consumed for 4B is slightly longer than that of 4KB since the frequency of replication is more.
|
Java
|
UTF-8
| 1,504
| 1.992188
| 2
|
[] |
no_license
|
package com.panhong.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.panhong.dao.UserPropertyDao;
import com.panhong.model.UserProperty;
import com.panhong.service.UserPropertyService;
@Service("userPropertyService")
public class UserPropertyServiceImpl implements UserPropertyService {
@Resource
private UserPropertyDao userPropertyDao;
public UserPropertyDao getUserPropertyDao() {
return userPropertyDao;
}
public void setUserPropertyDao(UserPropertyDao userPropertyDao) {
this.userPropertyDao = userPropertyDao;
}
@Override
public UserProperty getUserPropertyById(int property) {
return userPropertyDao.getUserPropertyById(property);
}
@Override
public void addUserProperty(UserProperty up) {
userPropertyDao.addUserProperty(up);
}
@Override
public void updateProperty(UserProperty up) {
userPropertyDao.updateProperty(up);
}
@Override
public void deleteProperty(UserProperty up) {
userPropertyDao.deleteProperty(up);
}
@Override
public List<UserProperty> getAllUserProperty() {
return userPropertyDao.getAllUserProperty();
}
@Override
public List<UserProperty> getVIPUserProperty(String isVip) {
return userPropertyDao.getVIPUserProperty(isVip);
}
@Override
public UserProperty getUserPropertyByGradeName(String gradeName) {
return userPropertyDao.getUserPropertyByGradeName(gradeName);
}
}
|
Markdown
|
UTF-8
| 3,695
| 2.640625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
---
id: 62-pear-channels-and-frameworks
author: matthew
title: 'PEAR, Channels, and Frameworks'
draft: false
public: true
created: '2005-04-11T21:32:20-04:00'
updated: '2005-04-11T21:55:40-04:00'
tags:
- php
---
[Greg Beaver writes in his blog](http://greg.chiaraquartet.net/comment.php?type=trackback&entry_id=38)
about PEAR, the new PEAR channels, and some issues he sees with PEAR and its
developers. Greg is responsible for the latest version of PEAR and the PEAR
installer — and for the development of PEAR channels. The particular link
referenced above makes reference to a thread on the PEAR-dev mailing list…
that I originated, when asking whether or not Cgiapp might be a good fit for
PEAR.
<!--- EXTENDED -->
I've been following with some interest Greg's development of channels, but for a
while couldn't see quite what the point was… until pearified.net started
offering Smarty via a pear channel. Installing Smarty via the PEAR installer is
incredibly simple — and points towards a great method of distribution of PHP
code.
Greg is absolutely right in his post — the best thing about PEAR is the
installer. However, there's some wonderful code in the repository as well. I
couldn't do my job without the likes of Log, DB, Cache_Lite, Pager, and others;
they provide the little pieces that make a large job into a few lines of code.
However, I've also been observing the pear-dev list for over six months now,
while trying to decide whether or not to propose some of my own code for
inclusion. I feel that the code I have is definitely in the spirit of PEAR —
good, reusable, extensible, glue code that can be used for a variety of
projects. However, it also falls under an umbrella that appears to be anathema
to many PEAR developers: the framework. And that's how the whole thread
exploded.
I still think Cgiapp would be a good fit for PEAR. However, I am not going to
consider it at this time, for several reasons:
- I don't have the time or energy to argue why I think Cgiapp would fit. If I
thought it would be an easy argument, or that it would simply involve tweaking
Cgiapp slightly, I'd do it in an instant. But from the comments I've read in
response to my query, it sounds like some very core and vocal members of PEAR
simply feel frameworks of any sort are not PEAR's territory, and I think they
would lobby effectively against the proposal.
- I truly feel that Cgiapp should stay as true as possible to its Perl
predecessor. I want the APIs to be the same, and I want it to develop in the
same direction. I suspect that if I were to go through the PEAR proposal
process, I'd have to lose this integrity in order for it to pass muster.
- With the advent of PEAR channels in the upcoming 1.4.0 release, there's no
reason I couldn't set up a PEAR channel of my own on the sourceforge site —
or join pearified.net. I think Greg hit the nail on the head here: channels
open up possibilities for PHP developers, and particularly for PHP
developers who may not want to or have the time to go through the PEAR
proposal process — or who are offering packages that fall outside PEAR's
scope. The PEAR installer, coupled with channels, creates an incredible
distribution channel.
I have the utmost respect for PEAR, and I've seen it advance tremendously in the
past year; as mentioned above, I couldn't do my job nearly as well or
effectively without the tools PEAR provides. However, I simply don't see how
Cgiapp could possibly thrive in PEAR at this time. I think Greg's admonishment
to his fellow PEAR devs should definitely be heeded. PEAR needs to look beyond
itself if it wishes to attract new and talented PHP developers.
|
C++
|
UTF-8
| 434
| 3.109375
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <cmath>
int main(int argc, char *argv[]) {
std::string s;
std::cin >> s;
int x = 0, y = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == 'U') {
y++;
} else if(s[i] == 'R') {
x++;
} else if(s[i] == 'D') {
y--;
} else if(s[i] == 'L') {
x--;
}
}
if(s.length() % 2 == 1) {
std::cout << "-1";
} else {
std::cout << (abs(x) + abs(y)) / 2;
}
return 0;
}
|
Java
|
UTF-8
| 273
| 3.015625
| 3
|
[] |
no_license
|
public static void printInBin(int x){
StringBuilder sb = new StringBuilder();
System.out.print(x+ " in bin: ");
for (int i=31;i>=0;i--){
if (x%2==0){
sb.append("0");
}else sb.append("1");
x>>>=1;
}
sb.reverse().append("\n");
System.out.print(sb);
}
|
PHP
|
UTF-8
| 4,111
| 2.625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"AFL-2.1",
"AFL-3.0",
"OSL-3.0",
"MIT"
] |
permissive
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Indexer\Model;
/**
* Provide functionality for executing user functions in multi-thread mode.
*/
class ProcessManager
{
/**
* Threads count environment variable name
*/
const THREADS_COUNT = 'MAGE_INDEXER_THREADS_COUNT';
/** @var bool */
private $failInChildProcess = false;
/** @var \Magento\Framework\App\ResourceConnection */
private $resource;
/** @var \Magento\Framework\Registry */
private $registry;
/** @var int|null */
private $threadsCount;
/**
* @param \Magento\Framework\App\ResourceConnection $resource
* @param \Magento\Framework\Registry $registry
* @param int|null $threadsCount
*/
public function __construct(
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Framework\Registry $registry = null,
int $threadsCount = null
) {
$this->resource = $resource;
if (null === $registry) {
$registry = \Magento\Framework\App\ObjectManager::getInstance()->get(
\Magento\Framework\Registry::class
);
}
$this->registry = $registry;
$this->threadsCount = (int)$threadsCount;
}
/**
* Execute user functions
*
* @param \Traversable $userFunctions
*/
public function execute($userFunctions)
{
if ($this->threadsCount > 1 && $this->isCanBeParalleled() && !$this->isSetupMode() && PHP_SAPI == 'cli') {
$this->multiThreadsExecute($userFunctions);
} else {
$this->simpleThreadExecute($userFunctions);
}
}
/**
* Execute user functions in singleThreads mode
*
* @param \Traversable $userFunctions
*/
private function simpleThreadExecute($userFunctions)
{
foreach ($userFunctions as $userFunction) {
call_user_func($userFunction);
}
}
/**
* Execute user functions in multiThreads mode
*
* @param \Traversable $userFunctions
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
private function multiThreadsExecute($userFunctions)
{
$this->resource->closeConnection(null);
$threadNumber = 0;
foreach ($userFunctions as $userFunction) {
$pid = pcntl_fork();
if ($pid == -1) {
throw new \RuntimeException('Unable to fork a new process');
} elseif ($pid) {
$this->executeParentProcess($threadNumber);
} else {
$this->startChildProcess($userFunction);
}
}
while (pcntl_waitpid(0, $status) != -1) {
//Waiting for the completion of child processes
}
if ($this->failInChildProcess) {
throw new \RuntimeException('Fail in child process');
}
}
/**
* Is process can be paralleled
*
* @return bool
*/
private function isCanBeParalleled(): bool
{
return function_exists('pcntl_fork');
}
/**
* Is setup mode
*
* @return bool
*/
private function isSetupMode(): bool
{
return $this->registry->registry('setup-mode-enabled') ?: false;
}
/**
* Start child process
*
* @param callable $userFunction
* @SuppressWarnings(PHPMD.ExitExpression)
*/
private function startChildProcess(callable $userFunction)
{
$status = call_user_func($userFunction);
$status = is_integer($status) ? $status : 0;
exit($status);
}
/**
* Execute parent process
*
* @param int $threadNumber
*/
private function executeParentProcess(int &$threadNumber)
{
$threadNumber++;
if ($threadNumber >= $this->threadsCount) {
pcntl_wait($status);
if (pcntl_wexitstatus($status) !== 0) {
$this->failInChildProcess = true;
}
$threadNumber--;
}
}
}
|
Java
|
UTF-8
| 1,434
| 2.890625
| 3
|
[] |
no_license
|
package baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class P2668 {
static public boolean dfs(ArrayList<Integer>[] ar, int start) {
Queue<Integer> q = new LinkedList<Integer>();
boolean visited[] = new boolean[ar.length];
q.add(start);
visited[start]=true;
while(!q.isEmpty()) {
int v=q.poll();
for(Integer a:ar[v]) {
if(a==start) {
return true;
}else {
if(!visited[a])
q.add(a);
visited[a]=true;
}
}
}
return false;
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
ArrayList<Integer>[] ar = new ArrayList[N + 1];
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < N + 1; i++)
ar[i] = new ArrayList<>();
for (int i = 1; i < N + 1; i++) {
int num = Integer.parseInt(br.readLine());
ar[i].add(num);
}
for (int i = 1; i < N + 1; i++) {
if (dfs(ar, i)) {
result.add(i);
}
}
Integer []arr=result.toArray(new Integer[result.size()]);
Arrays.sort(arr);
System.out.println(arr.length);
for (Integer a : arr) {
System.out.println(a);
}
}
}
|
JavaScript
|
UTF-8
| 3,290
| 3.578125
| 4
|
[] |
no_license
|
// Placing tests within the $() function to avoid running until DOM is ready.
$(function() {
describe('RSS Feeds', function() {
it('are defined', function() {
// Checks if allFeed variable has beedn defined
expect(allFeeds).toBeDefined();
// Checkes if allFeed variable is not empty
expect(allFeeds.length).not.toBe(0);
});
it("contain url", function() {
allFeeds.forEach(function(feed) {
// Checks if each feed has an url
expect(feed.url).toBeDefined();
// Checks if url has a reasonable size
expect(feed.url.length).not.toBe(0);
// Checks if url has clear characteristics
expect(feed.url).toContain("://");
});
});
it("contain name", function() {
allFeeds.forEach(function(feed) {
// Checks if each feed has a name
expect(feed.name).toBeTruthy();
// Checks if name has a reasonable size
expect(feed.name.length).not.toBe(0);
});
});
});
describe("The menu", function() {
// Creates variable for body
const body = document.querySelector("body");
it("is hidden", function() {
// Checks if class for hidden menu exists in body
expect(body.classList).toContain("menu-hidden");
});
it("changes visibility by click", function() {
// Creates variable for icon Menu
const iconMenu = $(".menu-icon-link");
// Open menu by first click
iconMenu.click();
expect(body.classList).not.toContain("menu-hidden");
// Close menu by second click
iconMenu.click();
expect(body.classList).toContain("menu-hidden");
});
});
describe("Initial Entries", function() {
// Inform testing framework that asynchronous loadFeed has completed
beforeEach(function(done) {
loadFeed(0, function() {
done();
});
});
// Run test after completion of loadFeed
it("have at least a count of one", function() {
// Create variable for feed entrys
const entry = document.querySelectorAll(".feed .entry");
// Number of feed entries should be > 0
expect(entry.length).not.toBe(0);
});
});
describe("New Feed Selection", function() {
// Create variable for first load of feed
let firstRun;
// Create variable for second load of feed
let secondRun;
// Inform testing framework that asynchronous loadFeed has completed
beforeEach(function(done) {
loadFeed(0, function() {
// Store html feed of first load in variable
firstRun = $(".feed").html();
loadFeed(1, function() {
// Store html feed of second load in variable
secondRun = $(".feed").html();
done();
});
});
});
// Test if html feed changes after second run
it("has changed after second load", function() {
expect(firstRun).not.toEqual(secondRun);
});
});
}());
|
Java
|
UTF-8
| 5,282
| 2.359375
| 2
|
[] |
no_license
|
package com.jzl.search_service.service;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jzl.api.ISearchService;
import com.jzl.entity.TProduct;
import com.jzl.mapper.TProductMapper;
import com.jzl.vo.ResultBean;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* 项目名:v16
* HAPPY JAVA !
* Create by jiangzonglin on 2019-08-08 下午 5:50
*/
@Service
public class SearchServiceImpl implements ISearchService {
@Autowired
private TProductMapper tProductMapper;
@Autowired
private SolrClient solrClient;
/**
* 全量添加到索引库中,只需一次,测试同步就OK了
* @return
*/
@Override
public ResultBean synAllSearch() {
//获取商品集合
List<TProduct> list = tProductMapper.list();
//遍历集合
for (TProduct tProduct : list) {
//将对象存入solr文档中
SolrInputDocument solrInputFields = new SolrInputDocument();
solrInputFields.setField("id",tProduct.getId());
solrInputFields.setField("product_name",tProduct.getName());
solrInputFields.setField("product_price",tProduct.getSalePrice());
solrInputFields.setField("product_images",tProduct.getImages());
solrInputFields.setField("product_sale_point",tProduct.getSalePoint());
//solrclient数据同步
try {
solrClient.add(solrInputFields);
} catch (SolrServerException | IOException e){
e.printStackTrace();
return new ResultBean<>("500","数据同步失败");
}
}
//提交数据
try {
solrClient.commit();
} catch (SolrServerException | IOException e) {
e.printStackTrace();
return new ResultBean<>("500","数据提交失败");
}
return new ResultBean<>("500","数据导入成功");
}
/**
* 单个添加到索引库
* @param id
* @return
*/
@Override
public ResultBean synGetByIdSearch(Long id) {
//获取当前ID对象
TProduct tProduct = tProductMapper.selectByPrimaryKey(id);
//将对象存入solr文档中
SolrInputDocument solrInputField = new SolrInputDocument();
solrInputField.setField("id",tProduct.getId());
solrInputField.setField("product_name",tProduct.getName());
solrInputField.setField("product_price",tProduct.getSalePrice());
solrInputField.setField("product_images",tProduct.getImages());
solrInputField.setField("product_sale_point",tProduct.getSalePoint());
//solrclient添加同步数据
try {
solrClient.add(solrInputField);
//提交数据
solrClient.commit();
} catch (SolrServerException |IOException e) {
e.printStackTrace();
return new ResultBean("500","数据同步失败");
}
return new ResultBean("200","数据同步成功");
}
/**
* 按关键字查询(分页)
* @param currentPage
* @param pageSize
* @return
*/
@Override
public PageInfo<TProduct> queryByIdKeyWord(Integer currentPage, Integer pageSize,String keywords) {
//构建查询条件
SolrQuery solrQuery = new SolrQuery();
if (StringUtils.isEmpty(keywords)) {
solrQuery.setQuery("*:*");
}else {
solrQuery.setQuery("product_keywords:"+keywords);
}
PageHelper.startPage(currentPage,pageSize);
//获取查询集合数据
try {
QueryResponse response =solrClient.query(solrQuery);
//获取到查询结果集
SolrDocumentList documentList = response.getResults();
//遍历
List<TProduct>list = new ArrayList<>(documentList.size());
for (SolrDocument document : documentList) {
TProduct product = new TProduct();
product.setId(Long.parseLong(document.getFieldValue("id").toString()));
product.setName(document.getFieldValue("product_name").toString());
product.setImages(document.getFieldValue("product_images").toString());
product.setSalePrice(Long.parseLong(document.getFieldValue("product_price").toString()));
product.setSalePoint(document.getFieldValue("product_sale_point").toString());
list.add(product);
}
PageInfo pageInfo = new PageInfo(list,5);
return pageInfo;
} catch (SolrServerException |IOException e) {
e.printStackTrace();
return null;
}
}
}
|
C++
|
UTF-8
| 21,273
| 2.96875
| 3
|
[] |
no_license
|
#ifndef POLYNOM_H
#define POLYNOM_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <limits>
#include <complex>
#include <ctime>
#include <stdexcept>
namespace iat {
enum class PolynomRootSearchMethod
{
BISECTION,
CHORDS,
TANGENTS,
COMBINED
};
template<class T>
class Polynom
{
public:
Polynom();
Polynom(int degree, T val); // Парметры конструктора - степень полинома и заполнитель для коэффициентов
Polynom(const std::string&fileName); // Параметр конструктора - имя файла из которого будут считываться коэффициенты
Polynom(const std::vector<T> &_coefficients); // Параметр конструктора - вектор коэффициентов полинома
Polynom(std::vector<T> &&_coefficients);
Polynom(const std::initializer_list<T> &il);
Polynom(const Polynom &other) = default; //Default copy constructor
Polynom(Polynom &&other) = default; //Default move constructor
virtual ~Polynom() = default;
inline bool isZero(){
return _degree == 0 && _coefficients[0] == static_cast<T>(0);
}
void readPolynom(const std::string &fileName); // Считать полином из файла
bool setValueAt(int i, const T&value); // Установить значение коэффициента элемента степени i
T getCoefAt(int i) const; // Считать значение коэффициента элемента степени i
int degree() const; // Получить степень полинома
T calcVal(const T&) const;
Polynom power(int) const;
std::string convertToString(int prec) const;
void showInConsole(int prec) const;
void writeToFile(std::string fileName, int prec) const;
bool rootInAnInterval(T leftLimit, T rightLimit, double eps, T &root,
PolynomRootSearchMethod method = PolynomRootSearchMethod::BISECTION);
Polynom firstDerivative();
Polynom derivative(int order);
T derivativeAtPoint(int order, T arg);
Polynom intergal(T initCondition);
T definiteIntegral(T leftLimit, T rightLimit);
//Operators
Polynom &operator=(const Polynom &other) = default;
Polynom &operator=(Polynom &&other) = default;
T& operator[](int index);
bool operator==(const Polynom&) const;
bool operator!=(const Polynom& Polynom) const;
Polynom operator+(const Polynom&) const;
Polynom operator+(const T&);
Polynom operator-(const Polynom&) const;
Polynom operator-(const T&);
Polynom operator*(const Polynom&) const;
Polynom operator*(const T&);
//Division operator returns a pair: first pair element - integral part, second - residual
std::pair<Polynom<T>, Polynom<T>> operator/(const Polynom& denominator) const;
Polynom operator/(const T&);
Polynom &operator+=(const Polynom&);
Polynom &operator+=(const T&);
Polynom &operator-=(const Polynom&);
Polynom &operator-=(const T&);
Polynom &operator*=(const Polynom&);
Polynom &operator*=(const T&);
Polynom &operator/=(const T&);
void validateDegree();
private:
int _degree;
std::vector<T> _coefficients;
};
template<class T>
void Polynom<T>::validateDegree()
{
bool isLeadingCoefficientZero = true;
int i = _degree;
while(isLeadingCoefficientZero)
{
if(!this->getCoefAt(i))
_degree--;
else
isLeadingCoefficientZero = false;
--i;
}
}
template<class T>
Polynom<T>::Polynom():Polynom(0, static_cast<T>(0))
{}
template<class T>
Polynom<T>::Polynom(int degree, T value)
{
if(degree < 0)
degree = 0;
else
this->_degree = degree;
for(int i = 0; i <= degree; ++i)
_coefficients.push_back(value);
}
template<class T>
Polynom<T>::Polynom(const std::string& fileName)
{
std::ifstream fi(fileName);
fi >> _degree;
if(_degree < 0) _degree = 0;
for(int i = 0; i <= _degree; ++i)
{
T value;
fi >> value;
_coefficients.push_back(value);
}
fi.close();
}
template<class T>
Polynom<T>::Polynom(const std::vector<T> &coefficients)
{
_degree = coefficients.size() - 1;
this->_coefficients = coefficients;
}
template<class T>
Polynom<T>::Polynom(const std::initializer_list<T> &il)
{
_degree = il.size() - 1;
for(auto el: il)
_coefficients.push_back(el);
}
template<class T>
Polynom<T>::Polynom(std::vector<T> &&coefficients)
{
_degree = coefficients.size() - 1;
this->_coefficients = std::move(coefficients);
}
template<class T>
void Polynom<T>::readPolynom(const std::string &fileName)
{
std::ifstream fi(fileName);
fi >> _degree;
for(int i = 0; i <= _degree; ++i)
{
T value;
fi >> value;
_coefficients.push_back(value);
}
}
template<class T>
bool Polynom<T>::setValueAt(int i, const T &value)
{
if(i >= 0 && i < _coefficients.size())
{
_coefficients[i] = value;
return true;
}
return false;
}
template<class T>
T Polynom<T>::getCoefAt(int i) const
{
if(i >= 0 && i < int(_coefficients.size()))
return _coefficients[i];
else if(i >= int(_coefficients.size()))
return static_cast<T>(0.0);
else
return std::numeric_limits<T>::quiet_NaN();
}
template<class T>
int Polynom<T>::degree() const
{
return _degree;
}
template<class T>
T Polynom<T>::calcVal(const T &value) const
{
T result = static_cast<T>(0);
for(int i = 0; i <= _degree; ++i)
result += getCoefAt(i) * pow(value, i);
return result;
}
template<class T>
Polynom<T> Polynom<T>::power(int exponent) const
{
Polynom<T> product(0, static_cast<T>(1));
Polynom<T> polynom = *this;
for(int i = 1; i <= exponent; ++i)
product *= polynom;
return product;
}
template<class T>
void Polynom<T>::showInConsole(int prec) const
{
std::cout << convertToString(prec) << std::endl;
}
template<class T>
std::string Polynom<T>::convertToString(int prec) const
{
std::stringstream stream;
stream << std::setprecision(prec) << getCoefAt(_degree) << " * X**" << _degree;
for(int i = _degree - 1; i > 0; --i)
{
if(getCoefAt(i) > 0)
stream << " + " << getCoefAt(i) << " * X**" << i;
else if(getCoefAt(i) < 0)
stream << " - " << fabs(getCoefAt(i)) << " * X**" << i;
else
continue;
}
if(getCoefAt(0) > 0)
stream << " + " << std::setprecision(prec) << getCoefAt(0);
else if(getCoefAt(0) < 0)
stream << " - " << std::setprecision(prec) << fabs(getCoefAt(0));
return stream.str();
}
template<class T>
void Polynom<T>::writeToFile(std::string fileName, int prec) const
{
std::ofstream of(fileName);
of << convertToString(prec);
of.close();
}
template<class T>
bool Polynom<T>::rootInAnInterval(T a, T b, double eps,
T &root, PolynomRootSearchMethod method)
{
static int ITERR_LIM = 5000;
if(calcVal(a) * calcVal(b) > 0)
return false;
if(method != PolynomRootSearchMethod::BISECTION &&
derivativeAtPoint(2, a) < 0)
std::swap(a, b);
T x_next = a;
int counter = 0;
while(true)
{
if(method == PolynomRootSearchMethod::BISECTION ||
method == PolynomRootSearchMethod::COMBINED)
{
if(method == PolynomRootSearchMethod::BISECTION)
{
T c = (a + b) / 2;
if(calcVal(c) * calcVal(a) > 0)
a = c;
if(calcVal(c) * calcVal(b) > 0)
b = c;
}
else
{
a -= calcVal(a) / derivativeAtPoint(1, a);
b -= calcVal(b) / (calcVal(b) - calcVal(a)) * (b - a);
}
if(fabs(a - b) < eps)
{
root = 0.5 * (a + b);
return true;
}
}
else if(method == PolynomRootSearchMethod::CHORDS ||
method == PolynomRootSearchMethod::TANGENTS)
{
a = x_next;
x_next = method == PolynomRootSearchMethod::CHORDS ?
a - calcVal(a) / (calcVal(b) - calcVal(a)) * (b - a):
a - calcVal(a) / derivativeAtPoint(1, a);
if(fabs(a - x_next) < eps)
{
root = x_next;
return true;
}
}
std::cout << "Iterration number: " << counter << std::endl;
if(++counter > ITERR_LIM) break;
}
return false;
}
template<class T>
Polynom<T> Polynom<T>::firstDerivative()
{
if(_degree > 0)
{
Polynom<T> der(_degree - 1, static_cast<T>(0));
for(int i = 1; i <= _degree; ++i)
der[i - 1] = i * this->getCoefAt(i);
return der;
}
else
return Polynom<T>();
}
template<class T>
Polynom<T> Polynom<T>::derivative(int order)
{
Polynom<T> res(*this);
if(order > _degree) order = _degree;
for(int i = 0; i < order; ++i)
res = res.firstDerivative();
return res;
}
template<class T>
T Polynom<T>::derivativeAtPoint(int order, T arg)
{
Polynom<T> der((*this).derivative(order));
return der.calcVal(arg);
}
template<class T>
Polynom<T> Polynom<T>::intergal(T initCondition)
{
Polynom<T> res(_degree + 1, static_cast<T>(0));
res[0] = initCondition;
for(int i = 1; i <= res.degree(); ++i)
res[i] = this->getCoefAt(i - 1) / i;
return res;
}
template<class T>
T Polynom<T>::definiteIntegral(T leftLimit, T rightLimit)
{
Polynom<T> integral((*this).intergal(0));
return integral.calcVal(rightLimit) -
integral.calcVal(leftLimit);
}
template<class T>
bool Polynom<T>::operator==(const Polynom &pol) const
{
if(_degree != pol.degree()) return false;
bool isEqual = true;
for(int i = 0; i < _degree; ++i)
{
if(getCoefAt(i) != pol.getCoefAt(i))
{
isEqual = false;
break;
}
}
return isEqual;
}
template<class T>
bool Polynom<T>::operator!=(const Polynom &pol) const
{
if(_degree != pol.degree()) return true;
bool isNotEqual = false;
for(int i = 0; i < _degree; ++i)
{
if(getCoefAt(i) != pol.getCoefAt(i))
{
isNotEqual = true;
break;
}
}
return isNotEqual;
}
//lvalue
template<class T>
T& Polynom<T>::operator[](int index)
{
if(index < 0 || index > _degree)
throw std::invalid_argument("index out of range");
return _coefficients.at(index);
}
template<class T>
Polynom<T> Polynom<T>::operator+(const Polynom& pol) const
{
int resDegree = std::max(_degree, pol._degree);
Polynom<T> summa(resDegree, static_cast<T>(0));
for(int i = 0; i <= resDegree; ++i)
summa._coefficients[i] = getCoefAt(i) + pol.getCoefAt(i);
return summa;
}
template<class T>
Polynom<T> Polynom<T>::operator+(const T& value)
{
Polynom<T> summa(_degree, static_cast<T>(0));
for(int i = 0; i <= _degree; ++i)
summa._coefficients[i] = getCoefAt(i);
summa._coefficients[0] += value;
return summa;
}
template<class T>
Polynom<T> Polynom<T>::operator-(const Polynom& pol) const
{
int resDegree = std::max(_degree, pol._degree);
Polynom<T> difference(resDegree, static_cast<T>(0));
for(int i = 0; i <= resDegree; ++i)
difference._coefficients[i] = getCoefAt(i) - pol.getCoefAt(i);
return difference;
}
template<class T>
Polynom<T> Polynom<T>::operator-(const T& value)
{
Polynom<T> difference(_degree, static_cast<T>(0));
for(int i = 0; i <= _degree; ++i)
difference._coefficients[i] = getCoefAt(i);
difference._coefficients[0] -= value;
return difference;
}
template<class T>
Polynom<T> Polynom<T>::operator*(const Polynom& pol) const
{
int productDegree = _degree + pol._degree;
Polynom<T> product(productDegree, static_cast<T>(0));
for(int i = 0; i <= _degree; ++i)
for(int j = 0; j <= pol._degree; ++j)
product._coefficients[i + j] += this->getCoefAt(i) * pol.getCoefAt(j);
return product;
}
template<class T>
Polynom<T> Polynom<T>::operator*(const T& value)
{
Polynom<T> product(_degree, static_cast<T>(0));
for(int i = 0; i <= _degree; ++i)
product._coefficients[i] = getCoefAt(i) * value;
return product;
}
template<class T>
std::pair<Polynom<T>, Polynom<T>> Polynom<T>::operator/(const Polynom& denominator) const
{
Polynom<T> numerator(*this);
Polynom<T> integralPart(numerator.degree() - denominator.degree(),
static_cast<T>(0));
Polynom<T> residual(denominator.degree() - 1, static_cast<T>(0));
if(numerator.degree() < denominator.degree())
residual = numerator;
else
{
Polynom<T> tmp(numerator);
bool isEndOfOperation = false;
int i = integralPart.degree();
while(!isEndOfOperation)
{
integralPart[i] = (tmp[tmp.degree()] / denominator.getCoefAt(denominator.degree()));
Polynom<T> facient(i, static_cast<T>(0));
facient[facient.degree()] = integralPart[i];
tmp -= denominator * facient;
tmp.validateDegree();
if(tmp.degree() < denominator.degree())
isEndOfOperation = true;
--i;
}
residual = tmp;
}
integralPart.validateDegree();
residual.validateDegree();
return std::make_pair(integralPart, residual);
}
template<class T>
Polynom<T> Polynom<T>::operator/(const T &value)
{
Polynom<T> product(_degree, static_cast<T>(0));
for(int i = 0; i <= _degree; ++i)
if(value != static_cast<T>(0))
product._coefficients[i] = getCoefAt(i) / value;
return product;
}
template<class T>
Polynom<T>& Polynom<T>::operator+=(const Polynom &other)
{
if(other.degree() > _degree)
{
_degree = other.degree();
_coefficients.resize(_degree + 1);
}
for(int i = 0; i <= _degree; ++i)
_coefficients[i] += other.getCoefAt(i);
return *this;
}
template<class T>
Polynom<T>& Polynom<T>::operator+=(const T& value)
{
_coefficients[0] += value;
return *this;
}
template<class T>
Polynom<T>& Polynom<T>::operator-=(const Polynom& other)
{
if(other.degree() > _degree) _coefficients.resize(other.degree());
for(int i = 0; i <= _degree; ++i)
_coefficients[i] -= other.getCoefAt(i);
return *this;
}
template<class T>
Polynom<T>& Polynom<T>::operator-=(const T& value)
{
_coefficients[0] -= value;
return *this;
}
template<class T>
Polynom<T>& Polynom<T>::operator*=(const Polynom& other)
{
//Определяем степень результирующего полинома
int productDegree = _degree + other.degree();
Polynom<T> product(productDegree, static_cast<T>(0));
for(int i = 0; i <= _degree; ++i)
for(int j = 0; j <= other.degree(); ++j)
product._coefficients[i + j] += getCoefAt(i) * other.getCoefAt(j);
_degree = productDegree;
_coefficients.resize(productDegree + 1);
for(int i = 0; i <= productDegree; ++i)
_coefficients[i] = product.getCoefAt(i);
return *this;
}
template<class T>
Polynom<T>& Polynom<T>::operator*=(const T& value)
{
for(int i = 0; i <= _degree; ++i)
_coefficients[i] *= value;
return *this;
}
template<class T>
Polynom<T>& Polynom<T>::operator/=(const T& value)
{
if(value != static_cast<T>(0))
for(int i = 0; i <= _degree; ++i)
_coefficients[i] /= value;
return *this;
}
//Перегрузка операторов икрементации и декрементации
template <class T>
Polynom<T>& operator++(Polynom<T> &pol)
{
pol.setValueAt(0, pol.getCoefAt(0) + static_cast<T>(1));
return pol;
}
template <class T>
Polynom<T> operator++(Polynom<T> &pol, int)
{
Polynom<T> old = pol;
pol.setValueAt(0, pol.getCoefAt(0) + static_cast<T>(1));
return old;
}
template <class T>
Polynom<T>& operator--(Polynom<T> &pol)
{
pol.setValueAt(0, pol.getCoefAt(0) - static_cast<T>(1));
return pol;
}
template <class T>
Polynom<T> operator--(Polynom<T> &pol, int)
{
Polynom<T> old = pol;
pol.setValueAt(0, pol.getCoefAt(0) - static_cast<T>(1));
return old;
}
//Перегрузка операторов потокового ввода-вывода добавить для rvalue
////////////////////////////////Console///////////////////////////
template<class T>
std::istream& operator>>(std::istream &stream, Polynom<T> &pol)
{
for(int i = 0; i <= pol.degree(); ++i)
{
T tmp;
stream >> tmp;
pol.setValueAt(i, tmp);
}
return stream;
}
//For lvalue
template <typename T>
std::ostream& operator<<(std::ostream &stream, Polynom<T> &pol)
{
std::ostringstream oss;
oss << pol;
stream << oss.str();
return stream;
}
//For rvalue
template <typename T>
std::ostream& operator<<(std::ostream &stream, Polynom<T> &&pol)
{
stream << pol;
return stream;
}
//////////////////////////////Files//////////////////////////
template <typename T>
std::ifstream& operator>>(std::ifstream &stream, Polynom<T> &pol)
{
for(int i = 0; i <= pol.degree(); ++i)
{
T tmp;
stream >> tmp;
pol.setValueAt(i, tmp);
}
return stream;
}
template <typename T>
std::ofstream& operator<<(std::ofstream &stream, Polynom<T> &pol)
{
std::ostringstream oss;
oss << pol;
stream << oss.str();
return stream;
}
//For rvalue
template <typename T>
std::ofstream& operator<<(std::ofstream &stream, Polynom<T> &&pol)
{
stream << pol;
return stream;
}
//////////////////////////Stringstreams///////////////////////////
template <typename T>
std::istringstream& operator>>(std::istringstream &stream, Polynom<T> &pol)
{
for(int i = 0; i <= pol.degree(); ++i)
{
T tmp;
stream >> tmp;
pol.setValueAt(i, tmp);
}
return stream;
}
template <typename T>
std::ostringstream& operator<<(std::ostringstream &stream, Polynom<T> &pol)
{
for(int i = 0; i <= pol.degree(); ++i)
stream << std::setprecision(15) << pol.getCoefAt(i) << " ";
stream << std::endl;
return stream;
}
//For rvalue
template <typename T>
std::ostringstream& operator<<(std::ostringstream &stream, Polynom<T> &&pol)
{
stream << pol;
return stream;
}
}
#endif // POLYNOM_H
|
Markdown
|
UTF-8
| 2,506
| 2.875
| 3
|
[] |
no_license
|
# Overview of application:
The application has 3 parts:
## Frontend:
Main Tech Stack: React.js, Redux(not really used it in this app), React Router V4, Webpack4, Babel.
## Backend:
Main Tech Stack: Express.js, MySql, Pm2(for running node.js server)
## Deployment:
Main Tech Stack: Docker
## Running app on development server:
1. Go to `frontend` folder & execute `npm i` && `npm start` command.
2. Go to `backend` (mysql database needed see Nothing works) folder & execute `npm i` && `npm run dev` command.
3. Application will run on `http://localhost:8080`
## Running app in docker:
1. Install docker in case if you don't have from [here](https://docs.docker.com/docker-for-mac/install/#install-and-run-docker-for-mac).
2. Start Docker & go to the directory `twyla_code_challenge` from terminal.
3. RUN `docker-compose build`.
4. RUN `docker-compose up`. (`docker-compose up --build` to skip above step).
5. There is some problem interacting with mysql because they changed some authencation stuff and now in order to interact with mysql using node.js we need to have either ssl connection or some modules which disables this authencation thingy.
[here is the issue](https://github.com/mysqljs/mysql/issues/1507)
6. A quick fix is you need to do the following steps:
* RUN `docker ps` & find the container id(the container name will be similar to "")
* RUN `docker exec -it <id> mysql -u root -p123456`. <id> => CONTAINER ID (e.g "3343c2c77c55") of ""
* You will be ask for password. Type 123456
* You will see mysql prompt => mysql >
* RUN `ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456'`;
* RUN `ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456'`;
7. Restart the running docker container from directory `book-review-app` by Running `docker-compose up`
8. It should work now.
## Nothing works(in-case):
1. Install MySql.
2. Go to folder mysqldump and copy the content of setup.sql and paste it into mysql console. It will gonna create the DATABASE name book_review_db.
3. Create a mysql user with name: `root` and password `123456` and server `localhost`
4. Go to `frontend` folder from terminal RUN `npm i` && `npm run local:prod`
5. Go to `backend` folder from terminal RUN `npm i` && `npm start`. pm2 will start node js server which replicates the prod environment
6. Go to `http://localhost:3000`
7. To stop pm2 sever run `npm run stop`.
|
Java
|
UTF-8
| 1,316
| 2.390625
| 2
|
[] |
no_license
|
package com.springboot.maven.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.springboot.maven.entity.UserEntity;
import com.springboot.maven.model.User;
import com.springboot.maven.repository.UserRepository;
@Controller
public class HelloFriend {
@Autowired(required=true)
private UserRepository userRepository;
@Autowired
private UserEntity userEntity;
@RequestMapping("/hello")
public String hello() {
return "WOWOWOWO - Spring Boot 4.0!!! Again";
}
@RequestMapping("/")
public String welcome() {
return "index";
}
@RequestMapping(value="/adduser", method=RequestMethod.POST)
public ModelAndView addUser(@ModelAttribute User user ) {
ModelAndView mv = new ModelAndView();
mv.setViewName("adduser");
mv.addObject("userReceived", user);
System.out.println(user.fname + " " + user.lname);
userEntity = new UserEntity();
userEntity.setFname(user.fname);
userEntity.setLname(user.lname);
userRepository.save(userEntity);
return mv;
}
}
|
Python
|
UTF-8
| 2,860
| 3.25
| 3
|
[] |
no_license
|
"""CSC111 Final Project: Exploring Using Graph Based Data Structures to Implement a Connect 4 AI
Module Description
==================
This module contains functions that pertain to the creation and loading of a 'opening book' for
the ComplexAIPlayer to use. An 'opening book' is a dictionary that maps board positions to
evaluations. These opening books can be generated from any list of connect 4 positions, however, the
functions in this module deal with saving the transposition table built up by the AI during play.
The boards are converted into hashes using the Zobrist hashing algorithm on which a detailed
explanation can be found here: https://en.wikipedia.org/wiki/Zobrist_hashing
The keys used in for the Zobrist hashing can be found in:
data/Zobrist_Hash_keys/Zobrist_red_keys.csv
data/Zobrist_Hash_keys/Zobrist_yellow_keys.csv
Copyright and Usage Information
===============================
This file is Copyright (c) 2021 Brian Cho and Luke Avveduto
"""
import csv
import math
def save_opening_book(output: str, table: dict[int: (int, 'str', int)],
original_depth: int) -> None:
"""Saves a transposition table into a csv file to be read from later. Different starting
depths are incompatible with each other and so separate files are created. These files are
indexed by adding '_' + str(original_depth) + '.csv' to the end of there name.
Preconditions:
- original_depth >= 0
- table must be a transposition table produced by AIPlayerComplex
"""
with open(output + '_' + str(original_depth) + '.csv', 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
for board in table:
row = [board, table[board][0], table[board][1], table[board][2]]
writer.writerow(row)
csv_file.close()
def load_opening_book(file: str) -> {int: (int, str)}:
"""Returns a dictionary (transposition table) that maps board hashes to their evaluation.
Preconditions:
- 'file' must be a path to a file created by 'save_opening_book'
"""
opening_book = {}
with open(file) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
if row[1] == 'inf':
value = math.inf
elif row[1] == '-inf':
value = -math.inf
else:
value = int(row[1])
opening_book[int(row[0])] = (value, row[2], int(row[3]))
return opening_book
if __name__ == '__main__':
import doctest
doctest.testmod()
import python_ta
python_ta.check_all(config={
'extra-imports': ['csv', 'math'], # the names (strs) of imported modules
'allowed-io': ['load_opening_book', 'save_opening_book'], # the names (strs) of functions that call print/open/input
'max-line-length': 100,
'disable': ['E1136']
})
|
Python
|
UTF-8
| 422
| 4.3125
| 4
|
[] |
no_license
|
""" Create a list with the names of friends and colleagues. Search for the
name ‘John’ using a for a loop. Print ‘not found’ if you didn't find it.
"""
friend_list = ['John','SRK','Bomzi','Charlotte','','Shakira','Franziska']
search_keyword = input("Whom do you want to search?\n")
for word in friend_list:
if search_keyword == word:
print("Found", word)
break
else:
print("Not found")
|
Java
|
UTF-8
| 2,416
| 2.125
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright 2019-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.stats.eval.impl;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.stats.eval.Statistics;
import com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.stats.eval.impl.vals.NamedAggregateValue;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class NamedCounter implements IStatistic<NamedAggregateValue> {
private static final Logger LOG = LogManager.getLogger(NamedCounter.class);
private boolean empty;
private Map<String, NamedAggregateValue> counters;
public NamedCounter() {
counters = new ConcurrentHashMap<>();
empty = true;
}
@Override
public Statistics type() {
return Statistics.NAMED_COUNTERS;
}
@Override
public void calculate(String key, Number value) {
synchronized (this) {
NamedAggregateValue mapValue =
counters.getOrDefault(
key, new NamedAggregateValue(0L, Statistics.NAMED_COUNTERS, key));
try {
Number numb = mapValue.getValue();
long number = mapValue.getValue().longValue();
long newNumber = number + 1;
mapValue.update(newNumber);
counters.put(key, mapValue);
empty = false;
} catch (Exception ex) {
LOG.error("Caught an exception while calculating the counter value", ex);
}
}
}
@Override
public Collection<NamedAggregateValue> get() {
return counters.values();
}
@Override
public boolean isEmpty() {
return empty;
}
}
|
Markdown
|
UTF-8
| 909
| 3.609375
| 4
|
[] |
no_license
|
# Express
## Middleware
Middleware functions have access to the request and response objects plus a special `next` function. When `next` is invoked it simply calls the next middleware function.
If the current middleware function doesn't end the request/response cycle then you much call next otherwise the request will hang out forever and never leave.
The anatomy of a middleware function looks something like this
```js
app.get('/', (req, res, next) => {
next();
})
```
`.get()` is the HTTP method for which the middleware appliesx
`./` is the path for which the middleware applies
The function is thee middleware function with the `req`, `res` and `next` respectively.
---
A middleware function such as –
```js
const myLogger = (req, res, next) => {
console.log('LOG')
next()
}
```
can be loaded in using `app.use()` and specifying the middleware function.
```js
app.user(myLogger)
```
|
Python
|
UTF-8
| 1,588
| 3.765625
| 4
|
[] |
no_license
|
'''
DMOJ
CCC 2000 S3 - Surfing
https://dmoj.ca/problem/ccc00s3
Jerry Cheng
'''
import sys
import re
input = sys.stdin.readline
link_format = re.compile("<A HREF=\"([^\"]*)\">")
class Graph:
def __init__(self, n):
self.num_nodes = n
self.num_edges = 0
self.edges = {}
def add_edge(self, start_node, end_node):
if start_node in self.edges:
self.edges[start_node].append(end_node)
else:
self.edges[start_node] = [end_node]
def adj(self, node):
if node not in self.edges:
return []
return self.edges[node]
def dfs(self, node, visited):
if node not in visited:
visited.append(node)
for n in self.adj(node):
self.dfs(n, visited)
return visited
n = int(input().strip())
links_g = Graph(n)
for i in range(n):
cur_page = str(input().strip())
while True:
cur_line = str(input().strip())
if '</HTML>' in cur_line:
break
links = re.findall(link_format, cur_line)
for l in links:
print("Link from %s to %s" % (cur_page, l))
links_g.add_edge(cur_page, l)
while True:
start_node = str(input().strip())
if start_node == "The End":
break
end_node = str(input().strip())
surf = False
for i in links_g.dfs(start_node, []):
if i == end_node:
surf = True
print("Can surf from %s to %s." % (start_node, end_node))
if surf is False:
print("Can't surf from %s to %s." % (start_node, end_node))
|
Swift
|
UTF-8
| 2,599
| 2.921875
| 3
|
[] |
no_license
|
//
// NumberKeys.swift
// Calculator
//
// Created by Joachim Neumann on 20/09/2021.
//
import SwiftUI
struct NumberKeys: View {
@ObservedObject var brain: Brain
let t: TE
var body: some View {
VStack(spacing: t.spaceBetweenkeys) {
HStack(spacing: t.spaceBetweenkeys) {
Key("C", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.ac_plus_minus_percentProperties)
Key("+/-", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.ac_plus_minus_percentProperties)
Key("%", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.ac_plus_minus_percentProperties)
Key("/", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.colorOpProperties)
}
HStack(spacing: t.spaceBetweenkeys) {
Key("7", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("8", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("9", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("x", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.colorOpProperties)
}
HStack(spacing: t.spaceBetweenkeys) {
Key("4", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("5", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("6", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("-", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.colorOpProperties)
}
HStack(spacing: t.spaceBetweenkeys) {
Key("1", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("2", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("3", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("+", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.colorOpProperties)
}
HStack(spacing: t.spaceBetweenkeys) {
Key("0", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_0)
Key(",", requiresValidNuber: false, brain: brain, t: t, keyProperties: t.digits_1_9)
Key("=", requiresValidNuber: true, brain: brain, t: t, keyProperties: t.colorOpProperties)
}
}
}
}
|
Java
|
UTF-8
| 4,216
| 2.671875
| 3
|
[] |
no_license
|
package com.mastek.training.hrapp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.mastek.training.hrapp.apis.DepartmentService;
import com.mastek.training.hrapp.apis.EmployeeService;
import com.mastek.training.hrapp.apis.ProjectService;
import com.mastek.training.hrapp.entities.Department;
import com.mastek.training.hrapp.entities.Employee;
import com.mastek.training.hrapp.entities.Project;
//Initialise the Junit test with Spring boot application environment
// Spring boot test : used to test spring ApplicationContext
// With all the test cases identified
@RunWith(SpringRunner.class)
@SpringBootTest
public class HrAppApplicationTests {
//////////////////////////////////////
@Autowired
EmployeeService empService;
@Autowired
Employee emp;
@Test
public void addEmployeeUsingService() {
emp.setEmpno(38);
emp.setName("Emp_service test Up");
emp.setSalary(55);
emp = empService.registerOrUpdateEmployee(emp);
}
@Test
public void simpleTest() {
System.out.println("System Test Executed");
}
@Test
public void findByEmpnoUsingService() {
int empno = 38 ;
assertNotNull(empService.findByEmpno(empno));
}
@Test
public void deleteByEmpnoUsingService() {
int empno = 58 ;
empService.deleteByEmployeeNumber(empno);
assertNull(empService.findByEmpno(empno));
}
@Test
public void checkFetchBySalary() {
List<Employee> emps = empService.fetchEmployeesBySalaryRange(0, 100);
for (Employee employee : emps) {
System.out.println(employee);
}
assertEquals(emps.size(), 1);
}
///////////////////////////////////
@Autowired
DepartmentService deptService;
@Autowired
Department dept;
@Test
public void addDepartmentUsingService() {
dept.setDeptno(1);
dept.setName("Dept Test");
dept.setLocation("Leeds");
dept = deptService.registerOrUpdateDepartment(dept) ; //.registerOrUpdateEmployee(emp)
}
@Test
public void findByDeptnoUsingService() {
int deptno = 44 ;
assertNotNull(deptService.findByDeptno(deptno));
}
@Test
public void checkFetchByLocation() {
List<Department> depts = deptService.fetchDeparmetByLocation("Leeds");
for (Department department : depts) {
System.out.println(department);
}
assertEquals(depts.size(), 8);
}
///////////////////////////////////////////////
@Autowired
ProjectService projService;
@Autowired
Project proj;
@Test
public void addProjectUsingService() {
proj.setProjectId(1);
proj.setName("nameForProject Tests");
proj.setCustomerName("Customer Name Test");
proj = projService.registerOrUpdateProject(proj);
}
@Test
public void findByProjnoUsingService() {
int projno = 42 ;
assertNotNull(projService.findByProjno(projno));
}
@Test
public void checkFetchByCustomerName() {
List<Project> cust = projService.fetchProjectByCustomerName("James");
for (Project project : cust) {
System.out.println(project);
}
assertEquals(cust.size(), 1);
}
@Test
public void manageAssociation() {
Department d1 = new Department();
d1.setName("Admin");
d1.setLocation("UK");
Employee emp1 = new Employee();
emp1.setName("Admin Emp 1");
emp1.setSalary(2342);
Employee emp2 = new Employee();
emp2.setName("Admin Emp 2");
emp2.setSalary(2837);
Project p1 = new Project();
p1.setName("UK Project");
p1.setCustomerName("UK Customer");
Project p2 = new Project();
p2.setName("US Project");
p2.setCustomerName("US Customer");
// one to Many : one Deparment has many employees
d1.getMembers().add(emp1);
d1.getMembers().add(emp2);
// many to One for each Employye to assing the department
emp1.setCurrentDepartment(d1);
emp2.setCurrentDepartment(d1);
//Many to Many
emp1.getAssignments().add(p2);
emp1.getAssignments().add(p1);
emp2.getAssignments().add(p1);
deptService.registerOrUpdateDepartment(d1);
}
}
|
Java
|
UTF-8
| 904
| 2.015625
| 2
|
[] |
no_license
|
package com.codegym.services;
import com.codegym.models.Product;
import com.codegym.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.List;
import java.util.Optional;
public interface ProductService {
Iterable<Product> findAllBook();
Optional<Product> findById(Long id);
void save(Product product);
void remove(Long id);
Iterable<Product> findByName(String name);
Iterable<Product> findProductsByNameContaining(String name);
List<Product> findByNameContaining (String name);
List<Product> findByCategoryId (Long id);
List<Product> findByPromotionId (Long id);
Page<Product> findAll(Pageable pageable);
}
|
PHP
|
UTF-8
| 945
| 2.59375
| 3
|
[] |
no_license
|
<?php session_start(); include 'connect.php';
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
// UPDATE TABLE SET COLUMN = VALUE, COLUMN = VALUE,.... WHERE CONDITION;
try {
$date = new DateTime();
$date_time = $date->format('Y-m-d H:i:s');
// use proper indentation so code look clean
$stmt = $pdo->prepare('
UPDATE users SET
record_status = :record_status,
updated_date_time = :updated_date_time
WHERE user_id = :user_id'
);
$criteria = [
'user_id' => $_POST['id'],
'record_status' => '2',
'updated_date_time' => "'".$date_time."'",
];
$stmt->execute($criteria);
$stmt = $pdo->prepare('Update job SET record_status = 2 WHERE id = :id');
$stmt->execute(['id' => $_POST['id']]);
} catch(PDOException $e) {
echo '<div>'.$e->getMessage().'</div>';
} catch(Error $e) {
echo '<div>'.$e->getMessage().'</div>';
}
header('location: index.php');
}
|
Markdown
|
UTF-8
| 1,270
| 2.53125
| 3
|
[] |
no_license
|
## java 代理模式进行数据源的切换
通过代理模式,使用自定义注解实现当前数据源的动态切换,不使用aop的相关注解
## 实现方式
主要是参考了事务tx在spring中间的运用,tx在应用系统调用声明了 @Transactional 的目标方法时,Spring Framework 默认使用 AOP 代理,在代码运行时生成一个代理对象,根据 @Transactional 的属性配置信息,这个代理对象决定该声明 @Transactional 的目标方法是否由拦截器 TransactionInterceptor 来使用拦截
下面是自定义注解需要注册的bean

## 多数据源的注册
为了实现这个动态切换,需要自动注册多数据源而且让动态数据源选择器来管理,因此也要注册动态数据源选择器的bean
下面是流程图

## 使用与感想
引入包,然后在需要的地方使用注解`DataSourceComponent`就好了
目前上传到maven中央库还是失败的.不过等传成功之后我再测试一下对应的代码优化情况
.这个项目还有很多东西没讲到的,还是尽量通过看代码来熟悉
> 代码地址: <a>https://github.com/fulln/proxys</a>
|
Java
|
UTF-8
| 3,526
| 1.976563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.mooc.ppjoke.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.ItemKeyedDataSource;
import androidx.paging.PagedList;
import androidx.paging.PagedListAdapter;
import com.mooc.libnavannotation.FragmentDestination;
import com.mooc.ppjoke.R;
import com.mooc.ppjoke.exoplayer.PageListPlayDetector;
import com.mooc.ppjoke.model.Feed;
import com.mooc.ppjoke.ui.AbsListFragment;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
@FragmentDestination(pageUrl = "main/tabs/home", asStarter = true)
public class HomeFragment extends AbsListFragment<Feed,HomeViewModel> {
private PageListPlayDetector playDetector;
private String feedType;
private boolean shouldPause;
public static HomeFragment newInstance(String feedType) {
Bundle args=new Bundle();
args.putString("feedType",feedType);
HomeFragment fragment=new HomeFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected void afterCreateView() {
mViewModel.getCacheLiveData().obseve
}
//将检测列表自动播放逻辑进行更新,复写getAdapter方法。
@Override
public PagedListAdapter getAdapter() {
feedType=getArguments()==null?"all":getArguments().getString("feedType");
return new FeedAdapter(getContext(),feedType){
@Override
public void onStartFeedDetailActivity(Feed feed) {
boolean isVideo=feed.itemType==Feed.TYPE_VIDEO;
shouldPause=!isVideo;
}
@Override
protected void onViewAttachedToWindow2(ViewHolder holder) {
if (holder.isVideoItem()){
playDetector.addTarget(holder.getListplayerView());
}
}
@Override
protected void onViewDetachedFromWindow2(ViewHolder holder) {
playDetector.removeTarget(holder.getListplayerView());
}
@Override
public void onCurrentListChanged(@Nullable PagedList<Feed> previousList, @Nullable PagedList<Feed> currentList) {
//这个方法是在我们每提交一次 pagelist对象到adapter 就会触发一次
//每调用一次 adpater.submitlist
if (previousList != null && currentList != null) {
if (!currentList.containsAll(previousList)) {
mRecyclerView.scrollToPosition(0);
}
}
}
};
}
@Override
public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//上拉分页
Feed feed = adapter.getCurrentList().get(adapter.getItemCount() - 1);
mViewModel.loadAfter(feed.id,new ItemKeyedDataSource)
}
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden){
playDetector.onPause();
}else {
playDetector.onResume();
}
}
}
|
Shell
|
UTF-8
| 1,414
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
set -e
TOPDIR=`pwd`
# pegasus bin directory is needed to find keg
BIN_DIR=`pegasus-config --bin`
# build the dax generator
PYTHONPATH=`pegasus-config --python`
export PYTHONPATH=".:$PYTHONPATH"
# generate the dax
./local_hierarchy.py > outer.dax
echo "inner.dax $TOPDIR/inner.dax site=local" > rc.data
# create the site catalog
cat >sites.xml <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<sitecatalog xmlns="http://pegasus.isi.edu/schema/sitecatalog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pegasus.isi.edu/schema/sitecatalog http://pegasus.isi.edu/schema/sc-4.0.xsd" version="4.0">
<site handle="local" arch="x86" os="LINUX">
<directory type="shared-scratch" path="$TOPDIR/work">
<file-server operation="all" url="file://$TOPDIR/work"/>
</directory>
<directory type="local-storage" path="$TOPDIR/outputs">
<file-server operation="all" url="file://$TOPDIR/outputs"/>
</directory>
</site>
<site handle="condorpool" arch="x86" os="LINUX">
<profile namespace="pegasus" key="style" >condor</profile>
<profile namespace="condor" key="universe" >vanilla</profile>
</site>
</sitecatalog>
EOF
# plan and submit the workflow
pegasus-plan \
--conf pegasusrc \
--sites local \
--dir work/dags \
--output-site local \
--dax outer.dax \
--submit
|
C#
|
UTF-8
| 881
| 3.765625
| 4
|
[] |
no_license
|
using System;
using static System.Console;
namespace DivisibleSumPairs
{
class Program
{
static int DivisibleSumPairs(int k, int[] ar)
{
var divisiblePairCount = 0;
for (int i = 0; i < ar.Length; i++)
{
for (int j = i + 1; j < ar.Length; j++)
{
if ((ar[i] + ar[j]) % k == 0)
divisiblePairCount++;
}
}
return divisiblePairCount;
}
static void Main(String[] args)
{
var tokens_n = ReadLine().Split(' ');
var divisor = int.Parse(tokens_n[1]);
var ar_val = ReadLine().Split(' ');
var ar = Array.ConvertAll(ar_val, int.Parse);
var result = DivisibleSumPairs(divisor, ar);
WriteLine(result);
}
}
}
|
Java
|
UTF-8
| 696
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.minimalj.example.erp.model;
import java.math.BigDecimal;
import org.minimalj.model.Keys;
import org.minimalj.model.Rendering;
import org.minimalj.model.annotation.Size;
public class OfferArticle implements Rendering {
public static final OfferArticle $ = Keys.of(OfferArticle.class);
public ArticleView article;
@Size(3)
public Integer numberof;
@Size(10)
public BigDecimal price;
@Override
public String render() {
StringBuilder s = new StringBuilder();
s.append(article.article);
if (numberof != null) {
s.append(", ").append(numberof).append(" Stück");
}
if (price != null) {
s.append(", Preis: ").append(price);
}
return s.toString();
}
}
|
Python
|
UTF-8
| 2,305
| 2.75
| 3
|
[] |
no_license
|
#! /usr/bin/python
#coding=utf-8
from __future__ import print_function
from pyspark.sql import SparkSession
from pyspark.mllib.recommendation import ALS,Rating,MatrixFactorizationModel
import sys
def SaveModel(sc):
try:
model.save(sc,Path+"ALSmodel")
print("已存储Model在ALSmodel")
except Exception:
print('Model已经存在,请先删除再存储')
def PrepareData(sc):
print("开始读取电影id与名称字典...")
itemRDD = sc.textFile(Path+"data/ml-100k/u.item")
movieTitle = itemRDD.map(lambda line: line.split("|")).map(lambda a:(float(a[0]),a[1])).collectAsMap()
return movieTitle
def loadModel(sc):
try:
model = MatrixFactorizationModel.load(sc,Path+"ALSmodel")
print("载入ALSModel模型")
except Exception:
print("找不到ALSModel模型,请先训练")
return model
def RecommendMovies(model,movieTitle,inputUserID):
RecommendMovie = model.recommendProducts(inputUserID, 10)
print("针对用户id"+str(inputUserID)+'推荐下列电影:')
for rmd in RecommendMovie:
print("推荐电影{0}推荐评分{1}".format(movieTitle[rmd[1]],rmd[2]))
def RecommendUsers(model,movieTitle,inputMovieID):
RecommendUser = model.recommendUsers(inputMovieID, 10)
print("针对电影id{0}电影名:{1}推荐下列用户:".format(inputMovieID,movieTitle[inputMovieID]))
for rmd in RecommendUser:
print("推荐用户{0}推荐评分{1}".format(rmd[0],rmd[2]))
def Recommend(model):
if sys.argv[1] == '--U':
RecommendMovies(model,movieTitle,int(sys.argv[2]))
if sys.argv[1] == '--M':
RecommendUsers(model,movieTitle,int(sys.argv[2]))
if __name__ == '__main__':
Path = "file:/home/coolingshooter/workspace/ALSspark/" #你的项目路径
if len(sys.argv) != 3:
print("请输入2个参数")
sys.exit(-1)
spark = SparkSession.builder.appName('RT').enableHiveSupport().config("spark.some.config.option","some-value").master("local[*]").getOrCreate()
sc = spark.sparkContext
print("===========数据准备阶段===========")
movieTitle = PrepareData(sc)
print("===========载入模型==============")
model = loadModel(sc)
print("===========进行推荐============")
Recommend(model)
|
PHP
|
UTF-8
| 674
| 2.53125
| 3
|
[] |
no_license
|
<?php
namespace Bookstore\Genre\Repositories;
use Bookstore\Genre\Models\Genre;
use Bookstore\Genre\Transformers\GenreTransformer;
use Bookstore\Library\Exceptions\ItemNotDeletedException;
use Bookstore\Library\Exceptions\ItemNotFoundException;
use Bookstore\Library\Exceptions\ItemNotSavedException;
use Bookstore\Library\Repositories\ObjectRepository;
use mysqli as MySQL;
class GenreRepository extends ObjectRepository
{
protected $tableName = 'genres';
protected $primaryKey = 'id';
public function __construct(MySQL $connection)
{
parent::__construct($connection);
$this->transformer = new GenreTransformer($connection);
}
}
|
Python
|
UTF-8
| 1,144
| 3.890625
| 4
|
[] |
no_license
|
def index_equals_value_search(arr):
# Sorted array -
# return the first one
# check arr[i] = i
#
left = 0
right = len(arr) - 1
mid = int((left + right) / 2)
while (left <= right):
if arr[mid] == mid:
if arr[mid - 1] == mid - 1:
right = mid - 1
mid = int(left + right) / 2
else:
return mid
else:
if arr[mid] > mid:
right = mid - 1
mid = int(left + right) / 2
else:
left = mid + 1 # left - 2
mid = int(left + right) / 2 # mid - 2 + 3/2
return -1
arr1 = [-8, 0, 2, 5]
arr2 = [-1, 0, 3, 6]
arr3 = [-1, 0, 2, 3, 4, 6, 7]
print(index_equals_value_search(arr1))
print(index_equals_value_search(arr2))
print(index_equals_value_search(arr3))
'''
bef|after
|
|indices
| * - values
| * -
|*-
-*
- *|
* |
01234567
^
'''
"""
bs
mid = int(left + right)/2
if arr[mid] == mid:
return mid
else:
if arr[mid] > mid:
right = mid -1
mid = int(left + right)/2
else:
left = mid + 1
mid = int(left + right)/2
"""
|
Java
|
UTF-8
| 6,251
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.parquet.thrift.projection.amend;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.*;
import org.apache.parquet.thrift.struct.ThriftField;
import org.apache.parquet.thrift.struct.ThriftType;
import org.apache.parquet.thrift.struct.ThriftType.StructType;
import java.util.*;
/**
* fill in default value for required fields in TProtocols after projection is specified.
*/
public class ProtocolEventsAmender {
List<TProtocol> rootEvents;
List<TProtocol> fixedEvents = new ArrayList<TProtocol>();
public ProtocolEventsAmender(List<TProtocol> rootEvents) {
this.rootEvents = rootEvents;
}
/**
* Given a thrift definition, protocols events, it checks all the required fields,
* and create default value if a required field is missing
*
* @param recordThriftType the Thrift Struct definition for events
* @return a list of events
* @throws TException if there is an error while amending events
*/
public List<TProtocol> amendMissingRequiredFields(StructType recordThriftType) throws TException {
Iterator<TProtocol> protocolIter = rootEvents.iterator();
checkStruct(protocolIter, recordThriftType);
return fixedEvents;
}
private TProtocol acceptProtocol(TProtocol p) {
this.fixedEvents.add(p);
return p;
}
private void checkStruct(Iterator<TProtocol> eventIter, ThriftType.StructType thriftStructType) throws TException {
TStruct tStruct = acceptProtocol(eventIter.next()).readStructBegin();
List<ThriftField> childrenFields = thriftStructType.getChildren();
Set<Short> includedFieldsIds = new HashSet<Short>();
while (true) {
TProtocol next = eventIter.next();
TField field = next.readFieldBegin();
if (isStopField(field))
break;
acceptProtocol(next);
includedFieldsIds.add(field.id);
ThriftField fieldDefinition = thriftStructType.getChildById(field.id);
checkField(field.type, eventIter, fieldDefinition);
acceptProtocol(eventIter.next()).readFieldEnd();
}
for (ThriftField requiredField : childrenFields) {
if (!isRequired(requiredField)) {
continue;
}
if (!includedFieldsIds.contains(requiredField.getFieldId())) {
fixedEvents.addAll(new DefaultProtocolEventsGenerator().createProtocolEventsForField(requiredField));
}
}
acceptProtocol(DefaultProtocolEventsGenerator.READ_FIELD_STOP);
acceptProtocol(eventIter.next()).readStructEnd();
}
private void checkField(byte type, Iterator<TProtocol> eventIter, ThriftField fieldDefinition) throws TException {
switch (type) {
case TType.STRUCT:
checkStruct(eventIter, (ThriftType.StructType) fieldDefinition.getType());
return;
case TType.LIST:
checkList(eventIter, fieldDefinition);
return;
case TType.MAP:
checkMap(eventIter, fieldDefinition);
return;
case TType.SET:
checkSet(eventIter, fieldDefinition);
return;
}
checkPrimitiveField(type, eventIter);
}
/**
* check each element of the Set, make sure all the element contain required fields
*
* @param eventIter
* @param setFieldDefinition
* @throws TException
*/
private void checkSet(Iterator<TProtocol> eventIter, ThriftField setFieldDefinition) throws TException {
TSet thriftSet = acceptProtocol(eventIter.next()).readSetBegin();
ThriftField elementFieldDefinition = ((ThriftType.SetType) setFieldDefinition.getType()).getValues();
int setSize = thriftSet.size;
for (int i = 0; i < setSize; i++) {
checkField(thriftSet.elemType, eventIter, elementFieldDefinition);
}
acceptProtocol(eventIter.next()).readSetEnd();
}
private void checkMap(Iterator<TProtocol> eventIter, ThriftField mapFieldForWriting) throws TException {
TMap thriftMap = acceptProtocol(eventIter.next()).readMapBegin();
ThriftField keyFieldForWriting = ((ThriftType.MapType) mapFieldForWriting.getType()).getKey();
ThriftField valueFieldForWriting = ((ThriftType.MapType) mapFieldForWriting.getType()).getValue();
int mapSize = thriftMap.size;
for (int i = 0; i < mapSize; i++) {
//readkey
checkField(thriftMap.keyType, eventIter, keyFieldForWriting);
//readValue
checkField(thriftMap.valueType, eventIter, valueFieldForWriting);
}
acceptProtocol(eventIter.next()).readMapEnd();
}
private void checkList(Iterator<TProtocol> eventIter, ThriftField listFieldUsedForWriting) throws TException {
ThriftField valueFieldForWriting = ((ThriftType.ListType) listFieldUsedForWriting.getType()).getValues();
TList thriftList = acceptProtocol(eventIter.next()).readListBegin();
int listSize = thriftList.size;
for (int i = 0; i < listSize; i++) {
checkField(thriftList.elemType, eventIter, valueFieldForWriting);
}
acceptProtocol(eventIter.next()).readListEnd();
}
/**
* Once reached primitive field, just the copy the event.
*
* @param type
* @param eventIter
* @throws TException
*/
private void checkPrimitiveField(byte type, Iterator<TProtocol> eventIter) throws TException {
acceptProtocol(eventIter.next());
}
private boolean isStopField(TField field) {
return field.type == TType.STOP;
}
private boolean isRequired(ThriftField requiredField) {
return requiredField.getRequirement() == ThriftField.Requirement.REQUIRED;
}
}
|
Ruby
|
UTF-8
| 2,800
| 2.59375
| 3
|
[] |
no_license
|
#!/usr/bin/ruby-rvm-env 1.9.3
# encoding: UTF-8
raise "Please use Ruby 1.9.3 or later." if RUBY_VERSION < "1.9.3"
require 'socket'
require 'io/wait'
require 'thread'
require_relative 'packets'
require_relative 'jumps_on_command'
if File.exist? 'config.rb'
require_relative 'config.rb'
else
require_relative 'default_config.rb'
end
Thread.abort_on_exception = true
class Bot
attr_reader :health
def initialize
@whitelist = []
end
def run
@mutex = Mutex.new
puts "Connecting to #{HOSTNAME}:#{PORT}..."
@socket = TCPSocket.open HOSTNAME, PORT
send_handshake username, HOSTNAME, PORT
receive_packet
send_login_request(username: username)
eid = receive_packet[:eid]
last_keep_alive = Time.at(0)
regular_updates_thread = Thread.new do
while true
sleep 0.05
synchronize do
if @position
update_position
send_player_position_and_look squelch: true
else
# the server has not told us our position yet
end
if Time.now - last_keep_alive >= 1
send_keep_alive(squelch: true)
last_keep_alive = Time.now
end
end
end
end
while true
receive_packet(whitelist: @whitelist)
end
end
def username
USERNAME
end
def synchronize(&block)
@mutex.synchronize(&block)
end
def parse_message(fields)
end
def parse_time(fields)
end
def respond_explosion(fields)
end
def handle_health(fields)
@health = fields[:health]
if dead?
later(1) { send_respawn }
end
end
def dead?
@health <= 0
end
def respond_entity_look(fields)
end
def handle_destroy_entity(fields)
end
def handle_entity_relative_move(fields)
end
def handle_entity_status(fields)
end
def handle_entity_look_and_relative_move(fields)
end
def handle_entity_teleport(fields)
end
def handle_chat(message)
puts message
end
def handle_named_entity_spawn(fields)
end
def handle_respawn(fields)
end
def update_position
fall
@position[:on_ground] = 1
end
def fall(rate = 0.1)
change_y -rate
end
def change_y(dy)
@position[:y] += dy
@position[:stance] += dy
end
def handle_player_position_and_look(fields = {})
@position = fields
#puts "Received position: #{position_to_string}"
send_player_position_and_look squelch: true
end
def position_to_string(position = @position)
return "" if position.nil?
"x,y,z = %3.2f,%3.2f,%3.2f g=%d p,y=%3.2f,%3.2f" % [
position[:x], position[:y], position[:z],
position[:on_ground], position[:pitch], position[:yaw]
]
end
def parse_disconnect(fields = {})
puts "Disconnected: #{fields[:reason].encode('US-ASCII')}"
exit
end
def chat(message)
send_chat_message message: message
end
def later(time, &block)
Thread.new do
sleep(time)
synchronize(&block)
end
end
end
|
Java
|
UTF-8
| 1,172
| 1.945313
| 2
|
[] |
no_license
|
package com.taixin.android.onvif.sdk.obj;
public class MediaProfilesInfo {
private String token;
private String name;
private String VSCToken;
private String VSCName;
private String videoSourceToken;
private String VECToken;
private String VECName;
public MediaProfilesInfo(){
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVSCToken() {
return VSCToken;
}
public void setVSCToken(String vSCToken) {
VSCToken = vSCToken;
}
public String getVSCName() {
return VSCName;
}
public void setVSCName(String vSCName) {
VSCName = vSCName;
}
public String getVideoSourceToken() {
return videoSourceToken;
}
public void setVideoSourceToken(String videoSourceToken) {
this.videoSourceToken = videoSourceToken;
}
public String getVECToken() {
return VECToken;
}
public void setVECToken(String vECToken) {
VECToken = vECToken;
}
public String getVECName() {
return VECName;
}
public void setVECName(String vECName) {
VECName = vECName;
}
}
|
PHP
|
UTF-8
| 1,141
| 2.59375
| 3
|
[] |
no_license
|
<?php
/**
* @description
* This script counts unevaluated letters for the status bar while saving letters as
* acknowledgements.
*
* @author Chezre Fredericks
* @date_created 14/04/2014
* @Changes
*
*/
# BOOTSTRAP
include("inc/globals.php");
# CALCULATE THE UNPROCESSED LETTERS
$u = $_SESSION['dms_user']['userid'];
$fileList = glob("unevaluated/$u.*.xml");
$total = $_GET['t'];
$completed = $total - count($fileList);
$percentage = number_format($completed/$total*100,2);
# SHOW STATUS IF THERE ARE STILL UNPROCESSED LETTERS
if ($completed<$total) {
?>
<div style="padding: 10px;" id="progressBar"><progress value="<?php echo $completed; ?>" max="<?php echo $total; ?>" class="html5"></progress></div>
<div id="cntDiv"><span id="totalCompleted"><?php echo $completed; ?></span>/<?php echo $total; ?></div>
<div id="perComplete"><?php echo $percentage; ?> %</div>
<?php
# ELSE SHOW THE USER THAT THE PDF'S ARE BEING MERGED
} elseif (file_exists("acklists/$u.result.htm")) { echo 'completed';
} else {
echo 'merging pdf\'s';
}
?>
|
Java
|
UTF-8
| 2,807
| 2.03125
| 2
|
[] |
no_license
|
package com.gideondev.survey.feature.home;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.gideondev.survey.FormModel;
import com.gideondev.survey.databases.dao.FormDAO;
import com.gideondev.survey.databases.dao.SqliteDAOFactory;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.gideondev.survey.R;
import java.util.ArrayList;
import java.util.List;
public class LocationTagActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private SupportMapFragment mapFragment;
private List<FormModel> formModelList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_tag);
initModel();
// mapView = (MapView) findViewById(R.id.map);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.googleMap);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));
// *** Marker (Loop)
if (formModelList != null && !formModelList.isEmpty() && formModelList.size() > 0){
for (int i = 0; i < formModelList.size(); i++) {
// Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
// Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
// String name = location.get(i).get("LocationName").toString();
MarkerOptions marker = new MarkerOptions().position(new LatLng(formModelList.get(i).getLatitude(), formModelList.get(i).getLongitude())).title(formModelList.get(i).getAddress());
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_person_pin_circle_red_a400_24dp));
googleMap.addMarker(marker);
}
}
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
private void initModel() {
FormDAO mFormDao = new FormDAO(this,
new SqliteDAOFactory(this).getConnection());
formModelList.addAll(mFormDao.getFormModels());
}
}
|
Python
|
UTF-8
| 1,652
| 3.59375
| 4
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
"""a test module """
__author__ = 'Michael Liao'
def func1():
args = sys.argv
print(args)
if len(args) == 1:
print('Hello, world!')
elif len(args) == 2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments!')
class Student(object):
"""
afasfasdf
"""
__slots__ = ('__name', 'score')
count = 0
def __init__(self, name, score):
self.__name = name
self.score = score
Student.count += 1
def print_score(self):
print('%s: %s' % (self.__name, self.score))
if __name__ == '__main__':
func1()
print(func1.__code__)
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()
print(type(bart))
print(type(bart) == Student)
print(dir(bart))
print(bart.__doc__)
print(Student.count)
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
hasattr(obj, "x")
class Screen(object):
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@width.setter
def width(self, value):
self._width = value
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self._width * self._height
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
|
SQL
|
UTF-8
| 1,215
| 3.796875
| 4
|
[] |
no_license
|
-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
DROP DATABASE IF EXISTS tournament;
CREATE DATABASE tournament;
\c tournament;
-- Create list of players in the current tournament.
CREATE TABLE playerList ( id SERIAL PRIMARY KEY,
fullname TEXT NOT NULL);
-- wins integer DEFAULT 0.0,
-- matches integer DEFAULT 0.0);
-- Create list of to track tournament match results.
CREATE TABLE matchList ( id integer PRIMARY KEY REFERENCES playerList(id),
wins integer DEFAULT 0.0,
matches integer DEFAULT 0.0);
-- Creates a list of tournament matches players for the next round of the tournament.
CREATE TABLE swissPairings(id1 integer REFERENCES playerlist(id),
name1 TEXT, id2 integer REFERENCES playerlist(id),
name2 TEXT);
CREATE VIEW finalStandings as (SELECT id,fullname,wins,matches from playerlist
left join matchlist using (id) order by wins desc);
|
Markdown
|
UTF-8
| 1,104
| 2.59375
| 3
|
[] |
no_license
|
# Optym
Search task project for inteview
What is the objective ?
1. Read from a url every 8 secs and save it to a Database. Basisc CRUD
2. Design a basic UI with a text Box, 1 search button for basic search ; url/dropdown for Advanced search And clear button
3. Key based search on the “setup” and “ punchline” fields
columns and return all matched jokes.
4. Advance search Forms should have a Dropdown and 1 text field for search by key
5. Navigator for latest searches
6. Extract found jokes into an excel
How to do it ?
We can divide the project into 3 different modules as following:
1.FeederService for reading data from an endpoint and saving into the DB
2.SearchSearvice for connecting to any type of DB fed by any feeder
3.SearchUI for providing essential UI connections to a SearchService
This kind of module division allows us to decouple the services and make them pluggable.
Simple UI

How to run the services:
Order of starting the services:
1. Feeder
2. Search
3. Searcher
|
Swift
|
UTF-8
| 4,154
| 2.5625
| 3
|
[] |
no_license
|
//
// DetailViewController.swift
// Assignment1_PG
//
// Created by Aini Zahari on 5/04/2015.
// Copyright (c) 2015 Siti Nur Aini Zahari. All rights reserved.
//
import Foundation
import UIKit
class DetailViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate
{
var movieL = ModelMovies().movieList
var filteredMovies = [Movies]()
@IBOutlet var searchBar: UITableView!
/* Insert MovieList to TableView Cells*/
override func tableView(tableView:UITableView, numberOfRowsInSection section: Int)->Int
{
if tableView == self.searchDisplayController!.searchResultsTableView{
return self.filteredMovies.count
} else {
return movieL.movieList.count;
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)->UITableViewCell
{
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var movie:Movies
if tableView == self.searchDisplayController!.searchResultsTableView{
movie = filteredMovies[indexPath.row]
} else {
movie = movieL.movieList[indexPath.row]
}
cell.textLabel?.text = movie.movieTitle
cell.detailTextLabel?.text = movie.date
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
/* Insert data to title on the next page according to selected movie*/
override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("MovieDetail", sender: tableView)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "MovieDetail"{
let MovieController = segue.destinationViewController as MovieDetailController
if sender as UITableView == self.searchDisplayController!.searchResultsTableView
{
let indexPath = self.searchDisplayController!.searchResultsTableView.indexPathForSelectedRow()!
let destinationTitle = self.filteredMovies[indexPath.row].movieTitle
let destinationImage = self.filteredMovies[indexPath.row].imageName
let destinationShowtime = self.filteredMovies[indexPath.row].date
MovieController.title = destinationTitle
MovieController.movieName = destinationTitle
MovieController.imageName = destinationTitle
MovieController.movieShowtime = destinationShowtime
}else{
let indexPath = self.tableView.indexPathForSelectedRow()!
let destinationTitle = self.movieL.movieList[indexPath.row].movieTitle
let destinationImage = self.movieL.movieList[indexPath.row].imageName
let destinationShowtime = self.movieL.movieList[indexPath.row].date
MovieController.title = destinationTitle
MovieController.movieName = destinationTitle
MovieController.imageName = destinationTitle
MovieController.movieShowtime = destinationShowtime
}
}
}
func filterContentForSearchText(searchText:String){
self.filteredMovies = movieL.movieList.filter({
(movie:Movies)->Bool in
let nameMatch =
(searchText == "All")
||
(movie.movieTitle.lowercaseString.rangeOfString(searchText.lowercaseString) != nil)
return nameMatch
}
)
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool
{
self.filterContentForSearchText(searchString)
return true
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool
{
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
return true
}
}
|
PHP
|
UTF-8
| 1,937
| 3.46875
| 3
|
[] |
no_license
|
<?php
namespace Cart\Classes;
class Cart
{
/**
* @var $id
*/
private $id;
/**
* @var $name
*/
private $name;
/**
* @var $quantity
*/
private $quantity;
/**
* @var $price
*/
private $price;
/**
* @var $currency
*/
private $currency;
/**
* Cart constructor.
* @param $id
* @param $name
* @param $quantity
* @param $price
* @param $currency
*/
public function __construct($id, $name, $quantity, $price, $currency)
{
$this->id = $id;
$this->name = $name;
$this->quantity = $quantity;
$this->price = $price;
$this->currency = $currency;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id): void
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name): void
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* @param mixed $quantity
*/
public function setQuantity($quantity): void
{
$this->quantity = $quantity;
}
/**
* @return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* @param mixed $price
*/
public function setPrice($price): void
{
$this->price = $price;
}
/**
* @return mixed
*/
public function getCurrency()
{
return $this->currency;
}
/**
* @param mixed $currency
*/
public function setCurrency($currency): void
{
$this->currency = $currency;
}
}
|
C++
|
UTF-8
| 847
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
if(!root)
return ans;
queue<TreeNode*> q;
stack<vector<int>> s;
q.push(root);
while(!q.empty()){
int levelNum = q.size();
vector<int> levVec;
for(int i=0;i<levelNum;i++){
TreeNode* nd = q.front();
q.pop();
//childern
if(nd->left)
q.push(nd->left);
if(nd->right)
q.push(nd->right);
levVec.push_back(nd->val);
}
s.push(levVec);//not to ans
}
//reverse
while(!s.empty()){
vector<int> levVec = s.top();
ans.push_back(levVec);
s.pop();
}
return ans;
}
};
|
Markdown
|
UTF-8
| 2,622
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
To view this unstyled markup visit [http://mrmrs.io/html](http://mrmrs.io/html)
# HTML
Common markup patterns I use for developing websites.
# Features
* All non-media elements in the HTML5 spec are included on one page and are ready to be styled.
* Modular Structure - add your own patterns, or delete the ones you don't like.
* Semantic and accessible markup examples for common design patterns.
* Thoroughly commented code (notes and reference links for new HTML developers)
# Getting the Code
* Create a new repo for your project on Github
* In terminal run
```bash
git clone git@github.com:mrmrs/html.git yourNewRepoName
cd [yourNewRepoName]
git remote rm origin
git remote add origin git@github.com:yourUserName/yourNewRepoName.git
git remote -v
```
* git remote -v will allow you to check that you have changed the remote origin correctly. The output should look like:
```bash
origin git@github.com:yourUserName/yourNewRepoName.git (fetch)
origin git@github.com:yourUserName/yourNewRepoName.git (push)
```
Now you're set up to use this in a new project.
# Getting Started
## The HTML
* Open up index.html with your favorite text editor and hack away. It's that simple.
* To preview changes at http://localhost:8000 - open up terminal.app and type
```
python -m SimpleHTTPServer
```
# Author
[MRMRS](http://mrmrs.cc "Adam Morse - Designer Developer")
# Reference
[Mozilla HTML element list](http://https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/HTML5_element_list "Mozilla HTML element list")
# MIT LICENSE
Copyright (c) 2018 Adam Morse http://opensource.org/licenses/MIT
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.
|
Python
|
UTF-8
| 203
| 3.609375
| 4
|
[] |
no_license
|
number_dogs = int(input())
number_animals = int(input())
dog_food_price = 2.5
animal_food_price = 4
result = number_dogs * dog_food_price + number_animals * animal_food_price
print(f'{result} lv')
|
Java
|
UTF-8
| 6,233
| 3.46875
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.Random;
/**
* Lab 6: Java Collection Framework, Skip List and Apache ANT <br />
* The {@code SkipList} class
* @param <K> {@code K} key of each skip list node
* @param <V> {@code V} value of each skip list node
*/
public class SkipList<K extends Comparable<K>, V> {
/**
* The {@code Node} class for {@code SkipList}
*/
private class Node {
public K key;
public V value;
public ArrayList<Node> forwards = new ArrayList<Node>();
public Node(K key, V value, int level) {
this.key = key;
this.value = value;
for (int i = 0; i < level; i++)
forwards.add(null);
}
public String toString() {
return String.format("%s(%s,%d)", value, key, forwards.size());
}
}
private Node head;
private ArrayList<Node> updates = new ArrayList<Node>();
/**
* Level of the skip list. An empty skip list has a level of 1
*/
private int level = 1;
/**
* Size of the skip list
*/
private int size = 0;
private static final double CHANCE = 0.5;
Random rand = new Random();
public SkipList() {
head = new Node(null, null, 1);
}
public boolean coinFlipHeads() {
return rand.nextFloat() > CHANCE ? true : false;
}
public int calcLevel() {
int num = 1;
while (coinFlipHeads())
num++;
return num;
}
public void resetUpdates() {
updates = new ArrayList<Node>();
for (int i = 0; i < level; i++) {
updates.add(null);
}
return;
}
/**
* Insert an new element into the skip list
* @param key {@code K} key of the new element
* @param value {@code V} value of the new element
*/
public void insert(K key, V value) {
// TODO: Lab 5 Part 1-1 -- skip list insertion
if (search(key) != null) {
findNode(key).value = value;
return;
}
else {
int newLevel = calcLevel();
Node node = new Node(key, value, newLevel);
for (int i = 0; i < Math.min(level, newLevel); i++) {
node.forwards.set(i, updates.get(i).forwards.get(i));
updates.get(i).forwards.set(i, node);
}
if (newLevel > level) {
for (int i = head.forwards.size(); i < newLevel; i++)
head.forwards.add(node);
level = newLevel;
}
}
}
/**
* Remove an element by the key
* @param key {@code K} key of the element
* @return {@code V} value of the removed element
*/
public V remove(K key) {
// TODO: Lab 5 Part 1-2 -- skip list deletion
if (search(key) != null) {
Node forward = findNode(key);
for (int i = 0; i < forward.forwards.size(); i++) {
if (updates.get(i).forwards.get(i) != null)
updates.get(i).forwards.set(i, updates.get(i).forwards.get(i).forwards.get(i));
}
for (int i = level - 1; i >= 0; i--) {
if (head.forwards.get(i) == null)
level--;
}
return forward.value;
}
else
return null;
}
/**
* Search for an element by the key
* @param key {@code K} key of the element
* @return {@code V} value of the target element
*/
public V search(K key) {
// TODO: Lab 5 Part 1-3 -- skip list node search
return findNode(key) != null ? findNode(key).value : null;
}
public Node findNode(K key) {
resetUpdates();
Node curr = head;
for (int i = level - 1; i >= 0; i--) {
while (curr.forwards.get(i) != null && key.compareTo(curr.forwards.get(i).key) > 0) {
curr = curr.forwards.get(i);
}
updates.set(i, curr);
}
return curr.forwards.get(0) != null && curr.forwards.get(0).key.compareTo(key) == 0 ? curr.forwards.get(0) : null;
}
/**
* Get the level of the skip list
* @return {@code int} level of the skip list
*/
public int level() {
return level;
}
/**
* Get the size of the skip list
* @return {@code int} size of the skip list
*/
public int size() {
return size;
}
public String levelToString(Node node, int l) {
return
node == null
? "null"
: String.format("%s -> %s", node.toString(), levelToString(node.forwards.get(l), l));
}
/**
* Print the skip list
* @return {@code String} the string format of the skip list
*/
public String toString() {
// TODO: Lab 5 Part 1-4 -- skip list printing
String out = "";
for (int i = level - 1; i >= 0; i--)
out += String.format("Level %d: ", i + 1) + levelToString(head, i) + "\n";
return out;
}
/**
* Main entry
* @param args {@code String[]} Command line arguments
*/
public static void main(String[] args) {
SkipList<Integer, String> list = new SkipList<Integer, String>();
int[] keys = new int[10];
for (int i = 0; i < 10; i++) { // Insert elements
keys[i] = (int) (Math.random() * 200);
list.insert(keys[i], "\"" + keys[i] + "\"");
}
System.out.println(list);
for (int i = 0; i < 10; i += 3) {
int key = keys[i];
// Search elements
System.out.println(String.format("Find element %3d: value=%s", key, list.search(key)));
// Remove some elements
System.out.println(String.format("Remove element %3d: value=%s", key, list.remove(key)));
// Search the removed elements
System.out.println(String.format("Find the removed element %3d: value=%s", key, list.search(key)));
}
System.out.println(list);
}
}
|
C++
|
UTF-8
| 392
| 2.8125
| 3
|
[] |
no_license
|
#pragma once
#include <GLFW/glfw3.h>
#include <functional>
typedef double time__;
class Time{
time__ time, dt;
public:
bool Init(){
dt = 0;
time = glfwGetTime();
return true;
}
void Update(std::function<void()> f){
dt = glfwGetTime() - time;
if (dt <= 0) dt = 0;
else{
f();
}
time += dt;
}
time__ DeltaTime(){
return dt;
}
};
|
Python
|
UTF-8
| 1,038
| 2.921875
| 3
|
[] |
no_license
|
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
Motor1A = 16
Motor1B = 18
Motor1E = 22
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
print ("Going forwards")
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(3)
print ("Going backwards")
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(3)
print ("Going forwards")
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(3)
print ("Going backwards")
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(5)
print ("Going forwards")
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(3)
print ("Going backwards")
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
sleep(3)
print ("Now stop")
GPIO.output(Motor1E,GPIO.LOW)
GPIO.cleanup()
|
Ruby
|
UTF-8
| 141
| 2.8125
| 3
|
[] |
no_license
|
student_names = Array.new(24, "Student")
student_names << "Test"
student_names << "Grumpy Cat"
puts student_names[1]
puts student_names[25]
|
Python
|
UTF-8
| 2,353
| 3.53125
| 4
|
[] |
no_license
|
import pandas as pd
def store_list():
print("---------------------------------------------------------------------------------------------------")
print(" STORE LIST ")
store={'Item':['Chicken Strips','French Fries','Hamburger','Hotdog','Large Drink','Medium Drink','Milk Shake','Salad','Small Drink'],
'Rate':['$3.50','$2.50','$4.00','$3.50','$1.75','$1.50','$2.25','$3.75','$1.25']}
labels=['1','2','3','4','5','6','7','8','9']
data=pd.DataFrame(store,labels)
print(data)
print("0\t To exit ")
print("---------------------------------------------------------------------------------------------------")
def check(x,lst): #to check wheather item already ordered or not
for element in lst:
if x==element:
return 1,
return 0
def item_name(x):
Item=['Chicken Strips','French Fries','Hamburger','Hotdog','Large Drink','Medium Drink','Milk Shake','Salad','Small Drink']
temp=Item[x-1]
return temp
def rate_query(x):
Rate=['$3.50','$2.50','$4.00','$3.50','$1.75','$1.50','$2.25','$3.75','$1.25']
temp=Rate[x-1]
return temp
def price_calculation(r,q):
r=float(r[1:])
p=r*q
p='$'+str(p)
return p
def total_calculation(p):
t=float(0)
for x in p:
x=float(x[1:])
t+=x
t='$'+str(t)
return t
lst,item,quantity,rate,price,label=[],[],[],[],[],[]
i=1
k=1
while k==1:
store_list()
string=input("Enter your orders : ")
for x in string:
x=int(x)
if x==0:
print("EXIT--As you pressed 0")
exit()
if check(x,lst)==0:
lst.append(x)
quantity.append(1)
item.append(item_name(x))
rate.append(rate_query(x))
price.append(rate_query(x))
label.append(i)
i+=1
else:
quantity[lst.index(x)]+=1
price[lst.index(x)]=price_calculation(rate[lst.index(x)],quantity[lst.index(x)])
temp={'Item':item,'Quantity':quantity,'Rate':rate,'Price':price}
orders=pd.DataFrame(temp,label)
print()
print(" YOUR ORDER ")
print()
print(orders)
total=total_calculation(price)
print()
print("\t\t Total Price : " + total)
print()
k=int(input("Do you want to order more (1-Yes/2-No) : "))
|
PHP
|
UTF-8
| 406
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\App\Traits;
trait Sluggable
{
public function scopeBySlug($query,$slug)
{
return $query->where('slug',$slug);
}
public static function findBySlug($slug)
{
return static::where('slug',$slug)->first();
}
public static function slugExists($slug,$id)
{
return static::where('slug',$slug)->where('id','<>',$id)->first();
}
}
|
JavaScript
|
UTF-8
| 4,620
| 2.640625
| 3
|
[] |
no_license
|
module.exports = async (Discord, interaction, axios, { get_role }) => {
if (get_role(interaction)) {
await interaction.reply("กำลังจัดโต๊ะสำหรับ Roulette")
const get_countdown = interaction.options.getInteger("countdown")
const get_point = interaction.options.getInteger("point")
let mess = await interaction.channel.send(`✨ ตานี้ค่าลงเดิมพันคือ ${get_point} tokens ต่อสี ✨
ถ้าชนะสี 🔵 / 🔴 ตานี้จะได้ คะแนน ${get_point * 2} tokens
ถ้าชนะสี 🟢 ตานี้จะได้คะแนน ${get_point * 4} tokens`)
mess.react("🔵")
mess.react("🔴")
mess.react("🟢")
let all = []
const roulette_filter = (reaction, user) => {
return user.bot == false && reaction.message.id == mess.id;
};
const roulette_collector = mess.createReactionCollector({ roulette_filter, time: get_countdown * 1000 });
roulette_collector.on("end",async collected => {
let mutipie = {
"blue" : -1,
"red" : -1,
"green" : -1
}
let rng = Math.floor(Math.random() * 100)
if (rng > 0 && rng <= 45) {
interaction.channel.send("Blue Win")
mutipie.blue = 1
}else if(rng > 45 && rng <= 90){
interaction.channel.send("Red Win")
mutipie.red = 1
}else if(rng > 90){
interaction.channel.send("Green Win")
mutipie.green = 2
}
let winner = 0
let blue = []
let red = []
let green = []
collected.map(user => {user.users.cache.some(user_info => {
if (!user_info.bot) {
interaction.guild.members.cache.some(get_id => {
if(get_id.id == user_info.id){
if(user.emoji.name === '🔵'){
all.push({
"discord_id" : get_id.id,
"coin" : (get_point * mutipie.blue),
"event" : "Roulette",
"giver" : interaction.member.displayName
})
blue.push(user_info)
}
if(user.emoji.name === '🔴'){
all.push({
"discord_id" : get_id.id,
"coin" : (get_point * mutipie.red),
"event" : "Roulette",
"giver" : interaction.member.displayName
})
red.push(user_info)
}
if(user.emoji.name === '🟢'){
all.push({
"discord_id" : get_id.id,
"coin" : (get_point * mutipie.green),
"event" : "Roulette",
"giver" : interaction.member.displayName
})
green.push(user_info)
}
}
})
}
})})
mess.reactions.removeAll()
await axios.post("https://itgg.herokuapp.com/discord/coins",all)
.then(done => {
if (mutipie.blue > 0) {
winner = blue.length
blue.forEach(user => {
user.send(`ยินดีด้วยคุณชนะพนัน ได้รับ Token ทั้งหมด ${get_point * mutipie.blue}`)
})
}else if(mutipie.red > 0){
winner = red.length
red.forEach(user => {
user.send(`ยินดีด้วยคุณชนะพนัน ได้รับ Token ทั้งหมด ${get_point * mutipie.red}`)
})
}else if(mutipie.green > 0){
winner = green.length
green.forEach(user => {
user.send(`ยินดีด้วยคุณชนะพนัน ได้รับ Token ทั้งหมด ${get_point * mutipie.green}`)
})
}
interaction.channel.send(`ผู้ชนะทั้งหมด ${winner} คน`)
done.data.fail.forEach(user => {
interaction.channel.send(`🛑 <@${user}> คุณยังไม่ได้ยืนยันตัว กรุณายืนยันตัว(__**/auth**__) แล้วรีบแจ้ง GG Admin โดยด่วน 🛑`)
})
})
.catch((err) => {
interaction.channel.send("⚠️ มีบางอย่างไม่ถุกต้องไปเรียก GG-Admin มาดู ⚠️")
console.log(err)
})
})
} else {
interaction.reply("🗨️🤖 : อันนี้ของเล่นแอดมิน ไม่ให้ใช้หรอกอิอิ")
}
}
|
Python
|
UTF-8
| 14,501
| 2.9375
| 3
|
[] |
no_license
|
"""
Hello this is created by majidabdulred. Below is the structural documentation of the program.
Variables:
recruits:[] To store id of recruits.
data:{} To store the data of the recruits.It contains one more dict which has keys given below:
steps: Stores the steps recruiter has completed.
username: Username.
playstyle: Playstyle.
screenshot_link: Link of the screenshot.
comment: A comment
Flow of code:
1)Whenever a member joins on_member_join() is triggered a channel is created in Recruits category with the name of the the user (like a ticket)) and a message is send.
2)On getting the reaction on_raw_reaction add and checking it on_intro()
3)Like wise every function runs controlled by the steps the user has completed.
Steps:
This is the important key stored in data[<theusername>].
If on_intro() function has ran the users steps is changed to 1.
If add_username() function has ran the users steps is changed to 2.
If add_playstyle() function has ran the users steps is changed to 3.
If add_screenshot() function has ran the users steps is changed to 4.
If add_comment() function has ran the users steps is changed to 5.
"""
import discord
import os
intent = discord.Intents.default()
intent.members = True
intent.typing = False
client = discord.Client(intents=intent)
recruits = []
data = {}
thecategory = 0
hrs = []
the_HR_role = 0
#theguildid = "632799582350475265" # Bot test server
theguildid = "745346902287188138" # True Grit
roles_for_hr = ["CEO","High Command","Corp Affairs Officer","HR"]
the_welcome_message="""Welcome! Just to go over a few things about GRIT.
We are Half-Indy, Half-PvP based (split into two corporations, GRIT for Indy/Mining/Trade and GR1T gritheads for PvP/PvE/Ratting). We do not have strict orders for people to play a certain way. Play how you want in either corporation and support the corporation when needed. That being said, we do have some requirements.
-------------------------------------------------------------
1. Do not be an asshole to corp members or alliance members, If something comes up. If someone says something dumb. If you get into an argument. Bring it over to @Corp Affairs Officer or @Enoka and we will handle it
2. Do not talk in local chat while out in Null-Sec All 1,000+ players in the alliance follows this rule. There are problems with the reporting system and it can lead to enemies spam reporting you and getting you banned. Just don’t.
3. Always pay attention to LOCAL while in null sec, it is not required but we do hope that you can post updated information on if you see reds/neuts in our system
4. We follow a Not Blue Shoot It policy meaning anyone who doesn't show as Green / Purple / Blue is free game to kill.
5. During a Fleet op or a CTA discord VOICE CHAT IS MANDATORY. This is for your safety. Just listen, if you can’t listen- don’t join the fleet op. We don’t want you dying and losing your ship because you were unable to organize with the fleet.
-------------------------------------------------------------"""
the_accpet_letter = """"[GRIT] ACCEPTANCE LETTER - PLEASE READ COMPLETELY
— PLEASE READ: ABOUT US —
Corporation Headquarters: CZDJ-1 < DEKLEIN (North, Caldari)
Alliance Citadel: RG9-7U (Next to Corporation Headquarters)
— PLEASE READ: DISCORD —
Have a look through our discord server!
- Specifically the "#about-us”, and “#corp-announcements” channels are a great way to learn about our corporation and stay up to date on Corporation information
- If you have any questions please ping @Corp Affairs Officer on discord, we will answer them to the best of our ability
— PLEASE READ: Fleet Doctrine — (Fleet doctrines will be reimbursed if lost during fleet ops)
Mandatory
https://docs.google.com/spreadsheets/d/15-HyOz-hCVI03cXMl2ngn3Iw1MvQVBc6XrWEYfE0Pto/edit?usp=sharing
https://docs.google.com/spreadsheets/d/1vGjTBW_tLRtusEohZIOmdtvCY_lYGV5HoZihTOuDhDM/edit?usp=sharing
https://docs.google.com/document/d/1Iulb8-2_2F10wwUBl-uY4nvSHNEQ4WsS5DPj76XdKrE/edit?usp=sharing
Optional
https://docs.google.com/document/d/1CS0ox5nuk4-WwjsMDEadg5UKxb4ammsPa40XylC9ksk/edit?usp=sharing
https://docs.google.com/document/d/1v6z626knWFoda5cNmuuPU3BRPNOOFjy7rghKg4PNBuI/edit?usp=sharing
JOIN ALLIANCE DISCORD - https://discord.gg/g4K6qrs
upon joining the alliance discord change your nickname to [GRIT] your name
Then react with "2" and say "requesting access"""
@client.event
async def on_ready():
global the_HR_role,theredman, theguild, logsch , thecategory,hrs
theguild = client.get_guild(int(theguildid)) # The Server
logsch = client.get_guild(632799582350475265).get_channel(763674672105259008) #log channel in Bot test server for sending logs
print("Started")
# Crating the list of HR in the server
for i in theguild.roles:
if i.name in roles_for_hr:
for j in i.members:
hrs.append(j.id)
print(hrs)
the_HR_role = theguild.get_role(764360399977971722)
for i in theguild.by_category():
try:
if i[0].id == 767228054434611201:
thecategory = i[0] # The Recruits category (I didnt found any function like theguild.get_category(id))
print("The category =",thecategory)
break
except:
continue
print("Ready")
@client.event
async def on_member_join(member):
global data
global recruits
print("member joined")
perm = discord.PermissionOverwrite(attach_files=True,embed_links=True ,read_message_history=True,read_messages=True,send_messages=True,add_reactions=True,manage_channels=True,manage_permissions=True)
overwrites ={
member: discord.PermissionOverwrite(attach_files=True,embed_links=True ,read_message_history=True,read_messages=True,send_messages=True,add_reactions=True,),
theguild.default_role: discord.PermissionOverwrite(read_messages=False),
theguild.me: perm,
the_HR_role: perm} # Permission rules for the channel that will be created
try:
mem_ch = await theguild.create_text_channel(member.name,category=thecategory, overwrites=overwrites) # Creating a new channel for all purposes
except Exception as E:
print(E)
print("A channel created")
mem_mes = await mem_ch.send(f"{member.mention}",embed=discord.Embed(
description="Welcome!, Hello looking to join?"))
thename = str(member)
data[thename] = {}
data[thename]["steps"] = 0
recruits.append(member.id)
await mem_mes.add_reaction("\U00002714")
await mem_mes.add_reaction("\U0000274C")
await logsch.send("[+]{} joined the server . Sent the greet message".format(member.name))
@client.event
async def on_message(message):
global data
global recruits
theuser = str(message.author)
if message.author.bot or message.author.id == 757099374261305385: # Not a bot
return
if message.channel.id == 763674672105259008 and "!log" in message.content: # If its a message in log_recruits channels
print("Devmode", message.content)
await devmode(message)
return
if message.channel.category_id not in (766897112632918036,thecategory.id) :
return
print(str(message.author.name), " said :", message.content)
if message.author.id in recruits:
await logsch.send("{} : {}".format(message.author.name, message.content))
if data[theuser]["steps"] == 1:
await add_username(message, theuser)
elif data[theuser]["steps"] == 2:
await add_playstyle(message, theuser)
elif data[theuser]["steps"] == 3:
await add_screenshot(message, theuser)
elif data[theuser]["steps"] == 4:
await add_comment(message, theuser)
elif message.channel.category_id == thecategory.id and message.author.id in hrs:
if message.content == "!accept" :
await message.channel.send(the_accpet_letter)
elif message.content == "!close" and message.channel.id not in (767235327961071627,745506583219273810,758785868663619615,745349097652748310):
await message.channel.delete(reason="Interview ended")
elif message.channel.category_id == 766897112632918036 and message.author.id in hrs:
if "!start" in message.content :
try:
for i in message.mentions:
await on_member_join(i)
except:
pass
@client.event
async def on_raw_reaction_add(payload):
global recruits
global data
theuser = client.get_user(payload.user_id)
if theuser.bot or payload.user_id == 757099374261305385 or payload.channel_id == 763674672105259008:
return
await logsch.send("{} reacted with {}".format(theuser.name, payload.emoji))
print(theuser, recruits)
if theuser.id in recruits:
thechannel = client.get_channel(payload.channel_id)
theuser = str(theuser)
if data[theuser]["steps"] == 0:
if payload.emoji.name == "\U00002714":
await on_intro(thechannel)
data[theuser]["steps"] = 1
return
elif payload.emoji.name == "\U0000274C":
await thechannel.send("No problem!")
else:
pass
await thechannel.send("Please react with the given emojis")
@client.event
async def on_intro(thechannel):
await thechannel.send(the_welcome_message)
await thechannel.send(
embed=discord.Embed(
description="Hey I will just do your verification process then an HR will contact you. If you want to ask any questions or anything like that, everything after the verification\nSo please co-ordinate with me."
"Please send your username in the format:.\n!u <username>\nExamples:\n!u "
"majidabdulred\n!u thename"))
await logsch.send("Send welcome message to {}".format(thechannel.name))
@client.event
async def add_username(message, theuser):
global data
if "!u" in message.content or "!U" in message.content:
data[theuser]["username"] = message.content.lstrip("!u")
data[theuser]["steps"] = 2
await message.channel.send(
embed=discord.Embed(
description="Thanks.\nNow please send your playstyle in format\n!t pve,pvp,miner,industry,"
"hauler\nExamples:\n"
"!t miner,pve\n!t pvp,industry\n!t pve,hauler"))
await logsch.send("[+]Added username : {} : {}".format(theuser, message.content.lstrip("!u")))
else:
await message.channel.send(
embed=discord.Embed(
description="Please write your username in correct format.\n!u <username>\nExamples:\n!u "
"majidadublred\n!u thename"))
await logsch.send("[-]Wrong username format send the retry message to {}".format(theuser))
@client.event
async def add_playstyle(message, theuser):
global data
if "!t" in message.content or "!T" in message.content:
data[theuser]["playstyle"] = message.content[2:]
data[theuser]["steps"] = 3
await message.channel.send(embed=discord.Embed(
description="Thanks.\nNow please send your in-game profile screenshot'''\nLike this.").set_image(
url="https://cdn.discordapp.com/attachments/745295219175456888/761944550825918495/IMG-20201003-WA0036.jpg"))
await logsch.send("[+]Added playstyle : {} : {}".format(theuser, message.content.lstrip("!t")))
else:
await message.channel.send(
embed=discord.Embed(
description=" Please write playstyle in correct format.\n!t pve,pvp,miner,industry,hauler\nExamples:\n"
"!t miner,pve\n!t pvp,industry\n!t pve,hauler"))
await logsch.send("[-]Wrong playstyle format send the retry message to {}".format(theuser))
@client.event
async def add_screenshot(message, theuser):
global data
if len(message.attachments) > 0:
data[theuser]["screenshot_link"] = message.attachments[0].url
data[theuser]["steps"] = 4
await message.channel.send(
embed=discord.Embed(
description="You interview is almost completed.\nJust tell something about you.\nFormat:\n!c your "
"comment goes here.\nExamples\n!c Hi I am a good eve echoes player trying to live in "
"this world.\n!c Hey . I just want to move to null sec as soon as possible."))
await logsch.send("[+]Added screenshot : {}".format(theuser))
else:
await message.channel.send(embed=discord.Embed(description=" PLease send the screenshot"))
await logsch.send("[-]Didnt send the ss send the retry message to {}".format(theuser))
@client.event
async def add_comment(message, theuser):
global data
if "!c" in message.content or "!C" in message.content:
data[theuser]["comment"] = message.content.lstrip("!c")
data[theuser]["steps"] = 5
await logsch.send("[+]Sending report of {}".format(theuser))
await send_report(message, theuser)
@client.event
async def send_report(message, theuser):
print("Generating Report")
embed = discord.Embed(title=f"__{message.author}__",
type="rich",
description=f"Hey {message.author} wants to join our corp. \nUsername : {data[theuser]['username']}\nPlaystyle : {data[theuser]['playstyle']}\n{data[theuser]['comment']}",
colour=discord.Colour.blue())
embed.set_image(url=f"{data[theuser]['screenshot_link']}")
embed.set_thumbnail(
url="https://cdn.discordapp.com/attachments/745295219175456888/760487391151652884/PicsArt_09-29-09.59.35.png")
embed.set_author(name="Application",
url="https://cdn.discordapp.com/attachments/745295219175456888/760487391151652884/PicsArt_09-29-09.59.35.png")
await message.channel.send(embed=embed)
await message.channel.send("Thanks Now wait till an HR comes and contacts you.")
del data[theuser]
@client.event
async def devmode(message):
con = message.content
if "var" in con:
if "data" in con:
await logsch.send(data)
if "recruit" in con:
await logsch.send(recruits)
token = os.environ['token']
client.run(token)
|
Java
|
UTF-8
| 6,235
| 3.421875
| 3
|
[] |
no_license
|
/**
* Fabian Flores
* Date created: 03/27/2020
* Last modified: 04/07/2020
* Table output aided by code found here ->
* https://www.logicbig.com/how-to/code-snippets/jcode-java-cmd-command-line-table.html
*/
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class SJF {
public SJF() {
}
public static int menu() {
Scanner in = new Scanner(System.in);
int option;
System.out.println("Select from the following options:");
System.out.println("1. Simulate 20 trials with 5 jobs");
System.out.println("2. Simulate 20 trials with 10 jobs");
System.out.println("3. Simulate 20 trials with 15 jobs");
System.out.println("4. Exit\n");
System.out.print("> ");
option = in.nextInt();
in.close();
return option;
}
/**
* Use bubble sort to sort the lists in ascending order based on times
*
* @param names
* @param times
*/
public static void sort(ArrayList<String> names, ArrayList<Integer> times) {
String tmpName;
int tmpTime;
for (int i = 0; i < times.size() - 1; i++) {
for (int j = 0; j < times.size() - i - 1; j++) {
if (times.get(j) > times.get(j + 1)) {
tmpName = names.get(j);
tmpTime = times.get(j);
names.set(j, names.get(j + 1));
times.set(j, times.get(j + 1));
names.set(j + 1, tmpName);
times.set(j + 1, tmpTime);
}
}
}
}
/**
* Perform Shortest-Job-First scheduling algorithm
*
* @param file method needs a file that contains the job names and lengths
* @param n number of jobs in the file. Used for running the simulations
*/
public static double sjf(File file, int n) {
Scanner in;
CommandLineTable table = new CommandLineTable();
ArrayList<String> processNames = new ArrayList<>();
ArrayList<Integer> processTimes = new ArrayList<>();
ArrayList<Integer> completedTimes = new ArrayList<>();
int totalTime = 0, startTime, sum;
try {
in = new Scanner(file);
table.setShowVerticalLines(true);
table.setHeaders("Job #", "Start time", "End time", "Job completion");
// based on the input data size selected by user
if (n == 0) {
// save process names and their respective process times
while (in.hasNextLine()) {
processNames.add(in.nextLine());
processTimes.add(Integer.parseInt(in.nextLine()));
}
} else {
for (int i = 0; i < n; i++) {
processNames.add(in.nextLine());
processTimes.add(Integer.parseInt(in.nextLine()));
}
}
for (int i = 0; i < processTimes.size(); i++) {
completedTimes.add(0);
}
// sorting based on shortest job
sort(processNames, processTimes); // objects are pass-by-reference
for (int i = 0; i < processNames.size(); i++) {
startTime = totalTime;
totalTime += processTimes.get(i);
completedTimes.set(i, totalTime);
table.addRow(processNames.get(i), Integer.toString(startTime), Integer.toString(totalTime),
processNames.get(i) + " completed @ " + totalTime);
}
if (n == 0) {
table.print();
System.out.println("Average Turnaround Time");
System.out.print("= (");
}
sum = 0;
for (int i = 0; i < completedTimes.size(); i++) {
sum += completedTimes.get(i);
if (n == 0) {
System.out.print(completedTimes.get(i));
if (i < completedTimes.size() - 1)
System.out.print(" + ");
else
System.out.println(") / " + completedTimes.size());
}
}
double averageTurnaroundTime = (sum * 1.0) / processTimes.size();
// do not print for simulation
if (n == 0)
System.out.printf("= %.2f ms\n", averageTurnaroundTime);
in.close();
return averageTurnaroundTime;
} catch (Exception e) {
System.out.println(e);
}
return -1;
}
/**
* simulate the scheduling algorithm over 20 trials over the first n jobs each
* file
*
* @param n the number of jobs to use in each input file (first 5, first 10, all
* 15)
*/
public static void simulate(int n) {
File file;
int runs = 20;
double sum = 0, averageTurnaroundTime;
for (int i = 0; i < runs; i++) {
// loop through each input data file and run algorithm
file = new File("../input/jobs" + (i + 1) + ".txt");
sum += sjf(file, n);
}
averageTurnaroundTime = sum / runs;
System.out.println("Average Turnaround Time for " + runs + " trials with " + n + " jobs");
System.err.printf("= %.2f ms\n", averageTurnaroundTime);
}
/**
* To run over a specific file, simply given file path as argument when running
* program; otherwise, a menu will prompt with the number of jobs to run for the
* simulation over data sets in input folder
*
* @param args
*/
public static void main(String[] args) {
System.out.println("SJF Scheduling Algorithm\n");
if (args.length > 0) {
sjf(new File(args[0]), 0);
} else {
int option = menu();
switch (option) {
case 1:
simulate(5);
break;
case 2:
simulate(10);
break;
case 3:
simulate(15);
break;
default:
break;
}
}
}
}
|
Python
|
UTF-8
| 3,491
| 2.65625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import re
import requests
from bs4 import BeautifulSoup
import lxml
import csv
import codecs
url = "http://repetitory.freeads.kz/ru-i-classifieds-i-page-i-31-4-i-index.html"
voc = [u'язик',
u'скому',
u'цкому',
u'цкий',
u'ский',
u'ского',
u'цкого',
]
from BeautifulSoup import UnicodeDammit
# http://scriptcult.com/subcategory_176/article_852-use-beautifulsoup-unicodedammit-with-lxml-html.html
def decode_html(html_string):
converted = UnicodeDammit(html_string, isHTML=True)
if not converted.unicode:
raise UnicodeDecodeError(
"Failed to detect encoding, tried [%s]",
', '.join(converted.triedEncodings))
return converted.unicode
def phonify(phone, code = '7'):
non_decimal = re.compile(r'[^\d]+')
phone = non_decimal.sub('', phone)
if len(phone) == 11:
return "+" + phone
if len(phone) == 10:
return "+" + str(code) + phone
return None
def get_page():
j = 1
for i in range(35):
yield "http://repetitory.freeads.kz/ru-i-classifieds-i-page-i-"+str(i+1)+"-"+str(j)+"-i-index.html"
if (i + 1) % 10 == 0:
j += 1
def get_profile_url(base):
source_code = requests.get(base)
plain_text = decode_html(source_code.content)
soup = BeautifulSoup(plain_text)
for link in soup.findAll('a'):
href = link.get('href')
if u'Подробнее' in link.get_text("|", strip=True):
if u'ru-i-offer' in href:
yield href
def get_data(item_url):
source_code = requests.get(item_url)
plain_text = decode_html(source_code.content)
soup = BeautifulSoup(plain_text) # windows-1251
li = item_url.find('.')
name = " "
phone1 = "not found"
phone2 = "not found"
subject = "not found"
languages = False
city = item_url[7:li]
if city == 'almaty': city = u'Алматы'
if city == 'astana': city = u'Астана'
if city == 'semipalatinsk': city = u'Семипалатинск'
for offer in soup.findAll('div', {'class':'offerdetail'}):
subject = offer.h1.get_text("|", strip=True)[0:-13]
for l in voc:
if l in subject.lower():
languages = True
break
for boxheader in soup.findAll('div', {'class': 'boxheader'}):
if u'Контактные' in boxheader.b.string:
pass
tb = boxheader.next_sibling.next_sibling.table
for tr in tb.findAll('tr'):
a = []
for i in tr.stripped_strings:
a.append(i)
if u'Имя' in a[0]:
name = a[1]
if u'Контактный телефон' in a[0]:
phone1 = a[1]
if u'Мобильный телефон' in a[0]:
phone2 = a[1]
return name.encode('utf-8'), phone1.encode('utf-8'), phone2.encode('utf-8'), subject.encode('utf-8'), languages, city.encode('utf-8')
f = csv.writer(open("kz3.csv", "wb"))
f.writerow(["name", "phone", "languages", "city", "subject"])
for page in get_page():
for pu in get_profile_url(page):
a,b,c,d,e,g = get_data(pu)
phones = b.split(',') + c.split(',')
for ph in phones:
pretty = phonify(ph, '7')
if pretty:
f.writerow((a, pretty, e, g, d))
# print a, pretty, e, g, d
|
Python
|
UTF-8
| 4,278
| 3.125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# Chuck norris gets reincarnated before he dies !
import sys
sys.setrecursionlimit(1000000) # this should be f*cking default parameter !
###############################################################################
#
# The real stuff
#
###############################################################################
def count_wp( line ):
w = float(0)
s = float(0)
for i,c in enumerate(line):
if c == '.':
continue
if c == '1':
w += 1
s += 1
continue
if c == '0':
s += 1
continue
return w/s
def count_wp( line, throw=-1 ):
w = float(0)
s = float(0)
for i,c in enumerate(line):
if i==throw:
continue
if c == '.':
continue
if c == '1':
w += 1
s += 1
continue
if c == '0':
s += 1
continue
#if( throw != -1 ):
# print "WP " + line + " throwing " + str(throw) + " = " + str(w/s)
return w/s
def number_match( line ):
s = 0
for c in line:
if c == '1' or c=='0':
s += 1
#print "number match " + line + " = " + str(s)
return s
def solve(score_lines):
W = [float(0) for i in score_lines]
OWP = [float(0) for i in score_lines]
OOWP = [float(0) for i in score_lines]
# calculate WP
WP = [count_wp(score) for score in score_lines]
#print "WP=", WP
# calculate OWP
for i, score in enumerate(score_lines):
for j,c in enumerate(score):
if i==j :
continue
if c == '.':
continue
OWP[i] += count_wp(score_lines[j], i)
#print "OWP[" + str(i) + "] before divide = " + str(OWP[i])
OWP[i] /= number_match(score)
#print "OWP=", OWP
# calculate OOWP
for i, score in enumerate(score_lines):
for j,c in enumerate(score):
if c == '1' or c=='0':
OOWP[j] += OWP[i]
continue
# divide by the number of match played
for i, score in enumerate(score_lines):
OOWP[i] = OOWP[i] / number_match(score)
#print "OOWP=", OOWP
RPI = [0 for i in score]
for i,score in enumerate(score_lines):
RPI[i] = 0.25 * WP[i] + 0.50 * OWP[i] + 0.25 * OOWP[i]
#print "RPI=", RPI
for r in RPI:
print r
###############################################################################
#
# Arg parsing
#
###############################################################################
# object to quickly get stuff from a input line
class Case(object):
def __init__(self, line):
self.line = line
self.line_split = line.split(" ")
self.index = 0
def get_str(self):
s = str( self.line_split[self.index] )
self.index += 1
return s
def get_int(self):
n = int( self.line_split[self.index] )
self.index += 1
return n
def get_int_list(self, size=None):
if size is None:
# first number is the size of the list
size = int( self.line_split[self.index] )
self.index += 1
l = [int(self.line_split[i]) for i in xrange(self.index, self.index + size)]
self.index += size
return l
def get_str_list(self, size=None):
if size is None:
# first number is the size of the list
size = int( self.line_split[self.index] )
self.index += 1
l = [self.line_split[i] for i in xrange(self.index, self.index + size)]
self.index += size
return l
def parse_and_solve_case(scores):
return solve(scores) # call to solve !
def parse_and_solve(ifile):
f = open(ifile)
n = int(f.readline().strip())
for i in xrange(1,n+1):
case = int(f.readline().strip())
scores = []
for j in xrange(0,case):
scores.append( f.readline().strip() )
print "Case #" + str(i) + ":"
parse_and_solve_case(scores)
# main code
if len(sys.argv) < 2:
print "You may want to give me an input file, jackass ?"
sys.exit(1)
parse_and_solve(sys.argv[1])
|
JavaScript
|
UTF-8
| 1,151
| 3.828125
| 4
|
[] |
no_license
|
let name="wenting"
/// test
console.log(`hello ${name}`) // console.log("hello" + name)
// Math package
console.log(Math.trunc(3.64))
console.log(Math.round(3.64))
const day = "Monday"
// If
if (day === "Monday"){
console.log("Workday")
} else {
console.log("Not Monday")
}
// For and while
const a = [1, 2, "12"]
for (let e in a){
console.log(`${e} ${a[e]}`) //e == key
}
for (let e of a){
console.log(`${e}`) // the value of e
}
for (let i=0; i<a.length; ++i){
console.log(`${a[i]}`)
}
var i=0
while (i<a.length) {
// if (!(i < a.length)) break
console.log(`${a[i]}`)
i ++
}
// Function definition
function factorial(n){
var ret = 1
for (;n>=1; n--){
ret *= n
}
return ret
}
console.log(`Factorial(5) = ${factorial(5)}`)
function Sum(n){
let ret = 0
for (;n>0;n--) {
ret += factorial(n)
}
return ret
}
function facsum(n){
let s = 0
for (let i=1; i<=n; i ++) {
s += factorial(i)
}
return s
}
// todo
function facsum(n){
let s = 0
let f = 1
for (let i=1; i<=n; ++i){
f *= i
s += f
}
return s
}
|
Java
|
UTF-8
| 467
| 2.25
| 2
|
[] |
no_license
|
package com.seniorproject.game.helpers;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.seniorproject.game.ShooterGame;
public class TextFieldHelper {
TextField textField;
public TextFieldHelper(int width, int height, ShooterGame game) {
textField = new TextField("", game.defaultSkin);
textField.setSize(width, height);
}
public TextField getTextField() {
return textField;
}
public void dispose() {
//skin.dispose();
}
}
|
JavaScript
|
UTF-8
| 1,149
| 3.078125
| 3
|
[] |
no_license
|
// John Dulaney
// This module creates a function that edits events. this is thrown together
//┌(° ͜ʖ͡°)┘
const db = require("../Database")
let editEvents = function(event) {
console.log("im the edit function")
const eventEl = document.getElementById("event__post")
const btnId = event.target.id
const btnIdNum = btnId.split("__")[1];
//if statement for getting proper id selected for edit
if (btnId.startsWith("button__")) {
const Database = db.load()
let eventToEdit = document.getElementById("event__" + btnIdNum)
console.log("You are trying to use the wrong code on: ", eventToEdit)
// // delete functionality
// // eventEl.removeChild(eventToRemove)
//parse id number
const parseForEdit = parseInt(btnIdNum)
//filter out unworthy ids
// const filterArray = Database.articles.filter(article => article.id !== parseId)
// set our db to the new filtered array
// Database.articles = filterArray
//resave it to our db
db.save(Database, "events")
// module.exports = editEvents
}}
|
Markdown
|
UTF-8
| 2,286
| 2.609375
| 3
|
[] |
no_license
|
---
layout: post
title: "New year, new blog"
date: 2016-02-12
categories: update
---
Hi, my name's Zaran. I'm going to post updates on the projects I'm working on here. Let's see how the [Checkers AI](https://rcos.io/projects/zlalvani/checkers-learner/profile) pans out.
For fun, here's the worst function I've ever written, posted for the sake of posterity:
{% highlight python %}
def printForGnuplot(learn_points, a_star, b_star, which):
gpScript = open(which + 'script.gp', 'w+')
ones = open(which + 'ones.dat', 'w+')
fives = open(which + 'fives.dat', 'w+')
positive = open(which + 'pos.dat', 'w+')
negative = open(which + 'neg.dat', 'w+')
for point in learn_points:
if point.value == 1:
ones.write(str(point.avg_int) + " " + str(point.avg_sym) + "\n")
else:
fives.write(str(point.avg_int) + " " + str(point.avg_sym) + "\n")
map_points = []
pos_points = []
neg_points = []
for x in np.arange(-1, 1, .005):
for y in np.arange(-1, 1, .005):
map_points.append(Point(x, y, -1))
for point in map_points:
if getClassification(point, a_star, b_star, learn_points) > 0:#10.0 ** -1:
pos_points.append(point)
positive.write(str(point.avg_int) + " " + str(point.avg_sym) + "\n")
else:
neg_points.append(point)
negative.write(str(point.avg_int) + " " + str(point.avg_sym) + "\n")
gpScript.write('' \
+ 'set terminal pngcairo transparent enhanced size 640, 480\n'
+ "set output '" + which + "output.png'\n"
+ 'set samples 800, 800\n'
+ 'set title "Digits: 1 vs Not 1, ' + which + '"\n'
+ 'set title font ",20" norotate\n'
+ 'set xlabel "Average Intensity"\n'
+ 'set ylabel "Symmetry"\n'
+ 'set xr [-1:1]\n'
+ 'set yr [-1:1]\n'
+ 'unset key\n'
+ "plot '" + positive.name + "' title 'Positive' with points pointtype 2 ps .3 linecolor rgb '#e5eeff','"
+ negative.name + "' title 'Negative' with points pointtype 5 ps .3 linecolor rgb '#ffcccc','"
+ ones.name + "' title 'Ones' with points pointtype 19 linecolor rgb 'blue','"
+ fives.name + "' title 'Not Ones' with points pointtype 2 linecolor rgb 'red'\n")
{% endhighlight %}
Yes, for a time I wrote gnuplot scripts in Python instead of using matplotlib.
|
Markdown
|
UTF-8
| 2,483
| 2.6875
| 3
|
[] |
no_license
|
# Rainforest
Rainforest是一个围绕保险业务的生态系统,以区块链为基础,连接生态个参与方,主要包括保险中台系统(分为业务运营和销售平台)、区块链销售平台,区块链跨机构协作平台……
## business operation platform
保险中台系统-业务运营平台
主要支持保险公司业务人员定义产品,发布产品,渠道管理,保单查询,客户查询,账单查询,理赔报案处理……
## sales platform
保险中台系统-销售平台
主要支持保险公司在线报价,核保,承保,退保,客户报案……
## product
保险中台系统-产品工厂
主要支持产品结构定义,保费计算定义,核保规则定义……
## policy admin
保险中台系统-保单管理
主要支持保单模型,保单数据维护……
## rating
保险中台系统-计算引擎
主要支持费率表定义,保额计算,保费计算,收退费计算,核保规则校验……
## finance
保险中台系统-财务管理
主要支持账单的记录,在线收银台……
## customer
保险中台系统-客户管理
主要支持客户数据的维护……
## channel
保险中台系统-渠道管理
主要支持渠道的定义,销售协议的定义……
## claim
保险中台系统-理赔管理
主要支持理赔报案的受理,理赔立案,同步核心系统理赔状态……
## operation
保险中台系统-运营管理
主要支持线上的运营活动管理,用户管理、礼品管理……
## system
保险中台系统-系统管理
主要支持用户管理,组织机构管理,权限管理……
## foundation
保险中台系统-基础平台
主要提供系统所需要的非业务公共功能……
## sales horizon
基于区块链的销售前端
主要支持渠道通过区块链来连接保险公司的场景下,渠道通过这个前端系统可以实现报价、核保、承保、退保等功能,产品数据从区块链获取,承保和批改数据写入区块链,保险共识的业务运营系统可以从区块链获取保单和批改数据……
## collaboration horizon
基于区块链的跨机构协作平台
主要支持生态系统中需要机构间进行业务数据流转的场景,比如再保需要分出公司把分出保单信息发送给分入公司,之后分入公司处理结果又需要发回分出公司,类似的业务场景……
|
C#
|
UTF-8
| 4,080
| 3.109375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RecommenderSystem.Core.Helper;
namespace RecommenderSystem.Core.Model
{
public class Time
{
public enum Period_Of_Day
{
All = 0,
Morning = 1,
Afternoon = 2,
Night = 3
}
public enum Period_Of_Week
{
All = 0,
Weekday = 1,
Weekend = 2
}
public enum Season
{
All = 0,
Spring = 1,
Summer = 2,
Autumn = 3,
Winter = 4
}
/*
* Properties
*/
public Period_Of_Day period_of_day { get; set; }
public Period_Of_Week period_of_week { get; set; }
public Season season { get; set; }
public Time()
{
period_of_day = Period_Of_Day.All;
period_of_week = Period_Of_Week.All;
season = Season.All;
}
public Time(string pod, string pow, string ss)
{
if (pod == "Morning")
period_of_day = Time.Period_Of_Day.Morning;
else if (pod == "Afternoon")
period_of_day = Time.Period_Of_Day.Afternoon;
else if (pod == "Night")
period_of_day = Time.Period_Of_Day.Night;
else
period_of_day = Time.Period_Of_Day.All;
if (pow == "Weekday")
period_of_week = Time.Period_Of_Week.Weekday;
else if (pow == "Weekend")
period_of_week = Time.Period_Of_Week.Weekend;
else
period_of_week = Time.Period_Of_Week.All;
if (ss == "Spring")
season = Time.Season.Spring;
else if (ss == "Summer")
season = Time.Season.Summer;
else if (ss == "Autumn")
season = Time.Season.Autumn;
else if (ss == "Winter")
season = Time.Season.Winter;
else
season = Time.Season.All;
}
public Time(Period_Of_Day period_of_day, Period_Of_Week period_of_week, Season season)
{
this.period_of_day = period_of_day;
this.period_of_week = period_of_week;
this.season = season;
}
public Time(DateTime dt)
{
if (dt.Hour >= 5 && dt.Hour <= 11)
this.period_of_day = Period_Of_Day.Morning;
else if (dt.Hour > 11 && dt.Hour <= 17)
this.period_of_day = Period_Of_Day.Afternoon;
else
this.period_of_day = Period_Of_Day.Night;
if (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
this.period_of_week = Period_Of_Week.Weekend;
else
this.period_of_week = Period_Of_Week.Weekday;
if (dt.Month >= 1 && dt.Month <= 3)
this.season = Season.Spring;
else if (dt.Month >= 4 && dt.Month <= 6)
this.season = Season.Summer;
else if (dt.Month >= 7 && dt.Month <= 9)
this.season = Season.Autumn;
else if (dt.Month >= 10 && dt.Month <= 12)
this.season = Season.Winter;
}
public static List<Time> GetAll()
{
List<Time> result = new List<Time>();
foreach (Period_Of_Day pod in Enum.GetValues(typeof(Period_Of_Day)))
{
foreach (Period_Of_Week pow in Enum.GetValues(typeof(Period_Of_Week)))
{
foreach (Season ss in Enum.GetValues(typeof(Season)))
{
Time obj = new Time(pod, pow, ss);
result.Add(obj);
}
}
}
return result;
}
}
}
|
Python
|
UTF-8
| 1,562
| 2.546875
| 3
|
[] |
no_license
|
__author__ = "gabe"
import cmdinterface
from stockroles import Player
from stockroles import roles_lookup
class SerialKiller(Player):
def __init__(self, name):
super(SerialKiller, self).__init__(name, "Serial Killer")
self.team = "Dark"
self.night_action_rank = 5.0
self.purpose = "stab"
def night_turn(self, players):
targets_list = []
for i in players:
if not i.health < 1 and i.num_id != self.num_id:
targets_list.append(i)
msg = (
f"Ask the {self.role_hr} ({self.name}) who they would like to"
f"{self.purpose}."
)
target = cmdinterface.target_selector(targets_list, msg)
target.attacked = 1
target.attack_info = {
"attacker_name": self.name,
"attacker_role": self.role_hr,
"attack_cause": self.purpose,
}
log_line = (
f"The {self.role_hr} ({self.name}) choose to"
f"{self.purpose} the {target.role_hr} ({target.name})."
)
return log_line
def win_lose_logic(self, players):
end_state = None
livePlayers = [i for i in players if not i.health == 0]
if self.health == 1 and len(livePlayers) == 1:
end_state = (
f"The {self.role_hr} has won by killing all players!"
f"Congratulations, {self.name}!"
)
return end_state
extra_roles_lookup = {"Serial Killer": SerialKiller}
roles_lookup = {roles_lookup, extra_roles_lookup}
|
Swift
|
UTF-8
| 904
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// iFoodie_app
//
// Created by Victor Garcia Torres on 21/12/2019.
// Copyright © 2019 iFoodieTeam. All rights reserved.
//
import UIKit
var user: [String] = []
class RegisterController: UIViewController {
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var emailTF: UITextField!
@IBOutlet weak var nameTF: UITextField!
@IBOutlet weak var surnamesTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func register(_ sender: Any) {
if(!(nameTF.text!.isEmpty && surnamesTF.text!.isEmpty && emailTF.text!.isEmpty && passwordTF.text!.isEmpty)){
user.append(nameTF.text!)
user.append(surnamesTF.text!)
user.append(emailTF.text!)
user.append(passwordTF.text!)
print(user)
}else{
print("falta info")
}
}
}
|
C#
|
UTF-8
| 2,366
| 3.671875
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Homework5
{
class Complex
{
public double X { get; private set; }
public double Y { get; private set; }
public Complex(double x, double y)
{
this.X = x;
this.Y = y;
}
public static Complex operator -(Complex z1, Complex z2)
{
return new Complex(z1.X - z2.X, z2.Y - z2.Y);
}
public Complex GetConjugate()
{
return new Complex(this.X, -this.Y);
}
public static Complex operator -(Complex z, int a)
{
return new Complex(z.X - a, z.Y);
}
public static Complex operator *(Complex z1, Complex z2)
{
return new Complex(z1.X * z2.X - z1.Y * z2.Y, z1.X * z2.Y + z1.Y * z2.X);
}
public static Complex operator *(Complex z, int a)
{
return new Complex(z.X * a, z.Y * a);
}
public static Complex operator *(int a, Complex z)
{
return z*a;
}
public static Complex operator /(Complex z1, Complex z2)
{
if (z2.X == 0 && z2.Y == 0)
{
throw new DivideByZeroException("Нельзя делить на ноль!");
}
else
{
return new Complex((z1.X * z2.Y + z1.Y * z2.Y) / (z2.X * z2.X + z2.Y * z2.Y),
(z1.Y * z2.X - z1.X * z2.Y) / (z2.X * z2.X + z2.Y * z2.Y));
}
}
public override string ToString()
{
if (this.X == 0 & this.Y == 0)
{
return " 0";
}
else if(this.Y == 0)
{
return " " + this.X;
}
else if (this.X == 0)
{
if (this.Y < 0)
{
return " -" + this.Y + "i";
}
else
{
return " " + this.Y + "i";
}
}
else if (this.Y > 0)
{
return " " + this.X + " + " + this.Y + "i";
}
else
{
return " " + this.X + " - " + this.Y + "i";
}
}
}
}
|
Python
|
UTF-8
| 3,705
| 2.703125
| 3
|
[] |
no_license
|
# -*- coding:utf-8 -*-
from __future__ import division
from gensim.models import word2vec
from sklearn.manifold import MDS
from sklearn.manifold import TSNE
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from sklearn.metrics import euclidean_distances
from mpl_toolkits.mplot3d import Axes3D
import os
import sys
import numpy as np
import xlrd
"""
optional:
if there is a error in the encode('utf-8'),
should set the sys encoding to 'utf-8',
"""
reload( sys )
sys.setdefaultencoding( 'utf8' )
data_path = os.path.abspath( '.' )
xlsx_file = xlrd.open_workbook( data_path + '/oldFile_hitProducts.xlsx')
model = word2vec.Word2Vec.load( data_path + "/cookpad_v2.model" )
sheet_name = xlsx_file.sheet_names()[0]
sheet = xlsx_file.sheet_by_index( 0 )
#calculate distance of two items, if the i = j, its means the same item, so the distance is 0
dist_space = []
"""
get the length of ni * nj for average distance calculation
because the xlrd package, each row has the same columns with the max columns item
"""
lenth = []
for ith in range( 1, 87 ):
count = 0
for col in range( 3, len(sheet.row(1) )):
word = sheet.row( ith )[col].value
word.encode('utf-8')
if len( word ) <= 0:
break
else:
count += 1
lenth.append( count )
lenth = np.array( lenth )
for i_th in range( 1, 87 ):
elem = []
for j_th in range( 1, 87 ):
temp_sum = 0.0
for col in range( 3, len(sheet.row(1)) ):
wordi = sheet.row( i_th )[col].value
wordi.encode( 'utf-8' )
wordj = sheet.row( j_th )[col].value
wordj.encode( 'utf-8' )
if len( wordi ) <= 0 or len( wordj ) <= 0:
break
else:
Wi = np.array( model[wordi] ).reshape((1, 200))
Wj = np.array( model[wordj] ).reshape((1, 200))
temp_dist = np.sum( pow( (Wi - Wj), 2), axis=1, keepdims=True )
temp_sum += np.sqrt( temp_dist )
temp_sum = temp_sum / ( lenth[i_th-1] * lenth[j_th-1] )
elem.append( temp_sum )
dist_space.append( elem )
mds = TSNE( n_components=3, init='pca', random_state=0 )
dist_matrix = np.array( dist_space ).reshape((86, 86))
print dist_matrix, dist_matrix.shape
#print dist_matrix[14].reshape((1, 86))
#print dist_matrix[13].reshape((1, 86))
#assert( dist_matrix.shape == ( 86, 86 ) )
changed = mds.fit_transform( dist_matrix )
print changed, changed.shape
np.savetxt( "3dims_pos.csv", changed, delimiter="," )
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs = [ changed[i][0] for i in range( 86 ) ]
ys = [ changed[i][1] for i in range( 86 ) ]
zs = [ changed[i][2] for i in range( 86 ) ]
ax.scatter(xs, ys, zs, c='r', marker='^')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
#plot the items after be dealt by MDS_2dim
"""
similarities = euclidean_distances( dist_matrix )
s = 100
fig = plt.figure( 1 )
ax = plt.axes([0., 0., 1., 1.])
plt.scatter( changed[:, 0], changed[:, 1], color='turquoise', s=s, lw=0, label='MDS')
plt.legend( scatterpoints=1, loc='best', shadow=False )
similarities = similarities.max() / similarities * 100
similarities[np.isinf(similarities)] = 0
start_idx, end_idx = np.where( changed )
segments = [[changed[i, :], changed[j, :]]
for i in range(86) for j in range(86)]
values = np.abs( similarities )
lc = LineCollection(segments, zorder=0, cmap=plt.cm.Blues, norm=plt.Normalize(0,values.max()))
lc.set_array( similarities.flatten())
lc.set_linewidths( np.full(len(segments), 0.5))
ax.add_collection( lc )
plt.show()
"""
|
C++
|
UTF-8
| 3,653
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
#include "RT_Mesh.h"
#include "RT_ArrayBuffer.h"
#include "RT_IndexBuffer.h"
#include "..\Abstract\RT_Material.h"
#include "RT_Shader.h"
#include "RT_Uniform.h"
#include "RT_UniformType.h"
#include <sstream>
RT_Mesh::RT_Mesh() :
indexBuffer(nullptr),
id(0)
{
glGenVertexArrays(1, &id);
}
RT_Mesh::~RT_Mesh()
{
if (indexBuffer)
{
delete indexBuffer;
indexBuffer = nullptr;
}
for (std::unordered_map<GLchar*,
RT_ArrayBuffer*>::
iterator i = attributes.begin();
i != attributes.end(); i++)
{
delete i->second;
}
attributes.clear();
for (std::unordered_map<GLchar*,
RT_Uniform*>::
iterator i = uniforms.begin();
i != uniforms.end(); i++)
{
delete i->second;
}
uniforms.clear();
glDeleteVertexArrays(1, &id);
}
void RT_Mesh::AddAttribute(GLchar *name, RT_ArrayBuffer *data)
{
if (attributes.find(name) != attributes.end())
{
std::stringstream ss;
ss << "Attribute already exists: "
<< name << std::endl;
throw std::out_of_range(ss.str());
}
if (!data)
{
std::stringstream ss;
ss << "Data can't be null!" << std::endl;
throw std::out_of_range(ss.str());
}
attributes[name] = data;
}
GLuint RT_Mesh::GetId() const
{
return id;
}
RT_Mesh &RT_Mesh::SetIndexBuffer(RT_IndexBuffer *_indexBuffer)
{
if (indexBuffer)
{
delete indexBuffer;
}
indexBuffer = _indexBuffer;
return (*this);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, RT_BaseUniformType *type, void *value)
{
if (!value)
{
delete uniforms[name];
uniforms.erase(name);
}
else
{
if (uniforms.find(name) != uniforms.end())
delete uniforms[name];
uniforms[name] = new RT_Uniform(type, value);
}
return(*this);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, RT::Mat3f *matrix)
{
return SetUniform(name, new Matrix3, matrix);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, RT::Mat4f *matrix)
{
return SetUniform(name, new Matrix4, matrix);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, RT::Vec2f *vector)
{
return SetUniform(name, new Vector2, vector);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, RT::Vec3f *vector)
{
return SetUniform(name, new Vector3, vector);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, RT::Vec4f *vector)
{
return SetUniform(name, new Vector4, vector);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, GLint value)
{
return SetUniform(name, new Intenger, &value);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, GLfloat value)
{
return SetUniform(name, new Float, &value);
}
RT_Mesh &RT_Mesh::SetUniform(GLchar *name, bool value)
{
return SetUniform(name, new Boolean, &value);
}
RT_Mesh &RT_Mesh::Draw(RT_Material *material)
{
if (!material || attributes.size() == 0)
{
return (*this);
}
RT_Shader *shader = material->GetShader();
glBindVertexArray(id);
shader->Bind();
for (std::unordered_map<GLchar*,
RT_ArrayBuffer*>::
iterator i = attributes.begin();
i != attributes.end(); i++)
{
RT_ArrayBuffer *buffer = i->second;
buffer->Bind();
shader->SetAttribute(i->first, buffer);
buffer->Unbind();
}
for (std::unordered_map<GLchar*,
RT_Uniform*>::
iterator i = uniforms.begin();
i != uniforms.end(); i++)
{
i->second->Set(*shader, i->first);
}
material->Apply();
if (!indexBuffer)
{
std::unordered_map<GLchar*,
RT_ArrayBuffer*>::
iterator i = attributes.begin();
i->second->Draw();
}
else
{
indexBuffer->Draw();
}
for (std::unordered_map<GLchar*,
RT_ArrayBuffer*>::
iterator i = attributes.begin();
i != attributes.end(); i++)
{
shader->SetAttribute(i->first, nullptr);
}
//material->Apply();
shader->Unbind();
glBindVertexArray(NULL);
return (*this);
}
|
Markdown
|
UTF-8
| 772
| 2.71875
| 3
|
[] |
no_license
|
# Divi Image Height Matcher
When you insert images with different sizes in an html row dif, sometimes you want all of them to have the same height.
What this plugin does is to force the height of all images to be the same, while keeping the aspect ratio.
Height matcher is used in Wordpress Divi.
When inserting more than 1 column in a row, and using the image module in each column: if the images' aspect ratio differs, then _Divi will display both images at **different heights** in order to match a percentage of the true image size_. This plugin corrects this:
## Usage
Install it, and it will automatically apply to divs having the `.et_pb_row` class.
## TODO
Make the class customizable, such that the user can decide to which classes this plugin should apply.
|
C#
|
UTF-8
| 1,368
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Drawing;
using System.Windows.Forms;
using Model;
namespace UI
{
public partial class Main_Form : Form
{
private string tafelnr;
private Werknemer huidigeGebruiker = new Werknemer();
public Main_Form(Werknemer huidigGebruiker_in)
{
huidigeGebruiker = huidigGebruiker_in;
InitializeComponent();
lbl_naam.Text = huidigeGebruiker.Naam;
lbl_functie.Text = Enum.GetName(typeof(Functie), huidigeGebruiker.Functie);
Size = new Size(768, 1024);
}
public Main_Form()
{
InitializeComponent();
}
private void btn_Tafel_Click(object sender, EventArgs e)
{
this.Close();
OverzichtRestaurant_Form overzichtform = new OverzichtRestaurant_Form(huidigeGebruiker);
overzichtform.Show();
}
private void btn_LogUit_Click(object sender, EventArgs e)
{
this.Close();
Login_Form login = new Login_Form();
login.Show();
}
public void SetTafelNummer(int tafelnummer)
{
tafelnr = tafelnummer.ToString();
btn_Tafel.Text = tafelnr;
}
public void updateTafelNR()
{
btn_Tafel.Text = tafelnr;
}
}
}
|
JavaScript
|
UTF-8
| 4,188
| 3.390625
| 3
|
[] |
no_license
|
var winCount = 3;
function checkRows(playerChosen, grid, gridLength) {
for (let row = 0; row < gridLength; row++) {
let count = 0;
for (let col = 0; col < gridLength; col++) {
if (grid[row][col] === playerChosen) {
count++;
} else {
count = 0;
}
if (count === winCount) {
console.log("win on row");
return true;
}
}
}
}
function checkCols(playerChosen, grid, gridLength) {
for (let col = 0; col < gridLength; col++) {
let count = 0;
for (let row = 0; row < gridLength; row++) {
if (grid[row][col] === playerChosen) {
count++;
} else {
count = 0;
}
if (count === winCount) {
console.log("win on col");
return true;
}
}
}
}
function checkDiagLR(playerChosen, grid, gridLength) {
// Diagonal line running from top left corner to bottom right corner
let count = 0;
let maxLength = gridLength - winCount + 1;
// Looking at left portion of diagonal line (including middle strip)
for (let rowStart = 0; rowStart < maxLength; rowStart++) {
for (
let row = rowStart, col = 0;
row < gridLength && col < gridLength;
row++, col++
) {
if (grid[row][col] === playerChosen) {
count++;
} else {
count = 0;
}
if (count === winCount) {
console.log("Win left portion of diagonal top left to bottom right");
return true;
}
}
}
// Looking at right portion of diagonal line (excluding middle strip)
for (var colStart = 1; colStart < maxLength; colStart++) {
for (
var col = colStart, row = 0;
col < gridLength && row < gridLength;
col++, row++
) {
if (grid[row][col] === playerChosen) {
count++;
} else {
count = 0;
}
if (count === winCount) {
console.log("Win right portion of diagonal top left to bottom right");
return true;
}
}
}
}
function checkDiagRL(playerChosen, grid, gridLength) {
// Diagonal line running from top right corner to bottom left corner
var count = 0;
var maxLength = gridLength - winCount + 1;
// Looking at right portion of diagonal line (including middle strip)
for (let rowStart = 0; rowStart < maxLength; rowStart++) {
for (
let row = rowStart, col = gridLength - 1;
row < gridLength && col >= 0;
row++, col--
) {
if (grid[row][col] === playerChosen) {
count++;
} else {
count = 0;
}
if (count === winCount) {
console.log("Win right portion of diagonal top right to bottom left");
return true;
}
}
}
// Looking at left portion of diagonal line (excluding middle strip)
for (let colStart = gridLength - 2; colStart > winCount - 2; colStart--) {
for (
var col = colStart, row = 0;
col >= 0 && row <= gridLength - 2;
col-- && row++
) {
if (grid[row][col] === playerChosen) {
count++;
} else {
count = 0;
}
if (count === winCount) {
console.log("Win left portion of diagonal top right to bottom left");
return true;
}
}
}
}
export function findWinner(playerChosen, grid, gridLength) {
if (checkRows(playerChosen, grid, gridLength)) {
return localStorage.getItem(playerChosen);
}
if (checkCols(playerChosen, grid, gridLength)) {
return localStorage.getItem(playerChosen);
}
if (checkDiagLR(playerChosen, grid, gridLength)) {
return localStorage.getItem(playerChosen);
}
if (checkDiagRL(playerChosen, grid, gridLength)) {
return localStorage.getItem(playerChosen);
}
// Otherwise do nothing
return null;
}
export function areAllSquaresClicked(grid, gridLength) {
// Declare variable to store number of clicked squares.
let count = 0;
// Iterate over all squares
for (let row = 0; row < gridLength; row++) {
for (let col = 0; col < gridLength; col++) {
if (grid[row][col] !== null) {
count++;
}
}
}
// Check if all squares are clicked (filled)
if (count === gridLength * gridLength) {
return true;
} else {
return false;
}
}
|
Python
|
UTF-8
| 493
| 2.90625
| 3
|
[] |
no_license
|
import RPi.GPIO as GPIO
import time
class Luz():
def __init__(self):
self.intensidad=0
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.OUT)
self.foco=GPIO.PWM(7,100)
self.foco.start(self.intensidad)
def cambiarIntensidad(self, intensidad):
self.intensidad=intensidad
print("Intensidad que llega={}".format(self.intensidad))
#self.foco.ChangeDutyCycle(self.intensidad)
self.foco.stop()
self.foco=GPIO.PWM(7,100)
self.foco.start(self.intensidad)
|
Python
|
UTF-8
| 691
| 3.890625
| 4
|
[] |
no_license
|
class Employee:
name = "강감찬"
count = 0
def __init__(self, name="없음"):
# print(name, self.count)
Employee.count += 1
print(Employee.count) #클래스의 변수를 출력할꺼면ㅡ
def display(self, a = 0):
print(self.count, a)
def __del__(self):
print("delete")
class Employee2(Employee):
def __init__(self):
print("Employee2 생성자")
def display2(self):
print("Employee2 Display2")
def display(self, a=0, b =1):
print(a, b)
e4 = Employee2()
e4.display()
e4.display2()
# e = Employee()
# e.display()
# e.display(10)
# e.b = 10
|
Python
|
UTF-8
| 2,696
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Copyright (c) 2013 OpenStack Foundation
#
# 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.
""" Methods to create and manipulate the XML
"""
import data_structures
import neutron.plugins.ml2.drivers.datacom.utils as utils
class ManagedXml:
def __init__(self):
self.xml = data_structures.CfgData()
def find_vlan(self, vid):
""" Find the vlan with the specified vid
"""
reduced_list = [i for i in self.xml.vlans if i.vid == vid]
if reduced_list:
return reduced_list[0]
else:
return None
def add_vlan(self, vid, name='', ports=[]):
""" This method adds a vlan to the XML an returns it's instance.
"""
if self.find_vlan(vid):
raise utils.XMLVlanError("Vlan already exists "+str(vid))
vlan = data_structures.VlanGlobal(vid)
if name:
name = str(name)
vlan.name = name
if ports:
vlan.ports = data_structures.Pbits(ports)
self.xml.vlans.append(vlan)
return vlan
def remove_vlan(self, vid):
""" This method revmoes a vlan on the XML if it exists.
"""
if not self.find_vlan(vid):
raise utils.XMLVlanError("Vlan does not exsits or the vid " + \
str(vid) + " is invalid")
vlan = self.find_vlan(vid)
del vlan.active
def add_ports_to_vlan(self, vid, ports):
""" This method adds ports to an existing vlan
"""
vlan = self.find_vlan(vid)
if vlan:
vlan.ports.add_bits(ports)
else:
raise utils.XMLPortError("No such vlan "+str(vid))
def remove_ports_from_vlan(self, vid, ports):
""" This method removoes ports from an existing vlan
"""
vlan = self.find_vlan(vid)
if vlan:
vlan.ports.remove_bits(ports)
else:
raise utils.XMLVlanError("No such vlan "+str(vid))
def as_xml(self):
""" This method returns the xml version of the object
"""
return self.tostring()
def tostring(self):
""" An alias to as_xml()
"""
return self.xml.as_xml_text()
|
Java
|
UTF-8
| 1,541
| 2.21875
| 2
|
[] |
no_license
|
package syn.pos.data.dao;
import android.content.ContentValues;
import android.content.Context;
import syn.pos.data.model.Payment;
public class PayType {
private DataBaseHelper dbHelper;
public PayType(Context context){
dbHelper = new DataBaseHelper(context);
}
public long insertPayType(Payment pm){
dbHelper.openDataBase();
try {
dbHelper.myDataBase.execSQL("BEGIN");
dbHelper.myDataBase.execSQL("DELETE FROM PayType");
ContentValues cv;
for(Payment.PayType pt : pm.getPayType()){
cv = new ContentValues();
cv.put("PayTypeID", pt.getPayTypeID());
cv.put("PayTypeCode", pt.getPayTypeCode());
cv.put("PayTypeName", pt.getPayTypeName());
try {
dbHelper.myDataBase.insert("PayType", null, cv);
} catch (Exception e) {
e.printStackTrace();
}
}
dbHelper.myDataBase.execSQL("DELETE FROM PaymentTypeButton");
for(Payment.PaymentAmountButton pab : pm.getPaymentAmountButton()){
cv = new ContentValues();
cv.put("PaymentAmountID", pab.getPaymentAmountID());
cv.put("PaymentAmount", pab.getPaymentAmountID());
try {
dbHelper.myDataBase.insert("PaymentAmountButton", null, cv);
} catch (Exception e) {
e.printStackTrace();
}
}
dbHelper.myDataBase.execSQL("COMMIT");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
dbHelper.myDataBase.execSQL("ROLLBACK");
}
dbHelper.closeDataBase();
return 0;
}
}
|
Markdown
|
UTF-8
| 758
| 2.609375
| 3
|
[] |
no_license
|
# Welcome!
<br>
<i> Conservation of Crop Wild Relatives (CWR) in Canada </i> is an app that lets you identify the native range of CWR, and the extent of those species’ ranges that are conserved ex situ in Canadian botanic gardens.
From the left navigation panel you'll be able to access the maps and data concerning the current status of CWR conservation in Canada.
<p align="center">
<img width="460" height="300" src="saskatoon_berry.png">
</p>
You can access our full data set of Canadian CWR
[here](https://github.com/jensculrich/CWR_project/blob/main/all_garden_accessions_with_geo_data.csv).
This app has been made with [shiny](https://shiny.rstudio.com/) and you may
find the code on [github](https://github.com/jensculrich/CWR_Shiny).
|
Markdown
|
UTF-8
| 1,309
| 2.96875
| 3
|
[] |
no_license
|
# Test Prioritisation Exercise
We will implement a simple, additional greedy based Test Case Prioritisation (TCP) toolchain based on [coverage.py](https://coverage.readthedocs.io/en/coverage-5.5/) and [PyTest](https://docs.pytest.org/en/6.2.x/).
The included `sample.py` contains examples of:
1. How to invoke `coverage.py` from within Python script, and
2. How to execute PyTest test cases from within Python script.
However, to implement TCP, we need to figure out the following.
## Task 1: Get Individual Coverage of Each Test Case
Because we need the coverage of each indivudal test case (=test function, in PyTest terms). There are two related subgoals, which are:
- Identify all the test functions, and
- Execute each of the test functions individually, while recording coverage
Fill in `collect_tc_coverage.py` to achieve Task 1. Use the `mid.py` under `examples` directory as an example.
## Task 2: Generate test case execution sequence using greedy prioritisation
Once you collect individual coverage of each test case, you need to set the order between them. We will try additional greedy algorithm, i.e., choosing whichever test case that will increase the accumulated coverage by the maximum. Fill in `tcp.py` to achieve Task 2. Use the `mid.py` under `examples` directory as an example.
|
C#
|
UTF-8
| 1,634
| 2.515625
| 3
|
[] |
no_license
|
using Pathfinding;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeartSystem : MonoBehaviour
{
public GameObject[] hearts; //[0] [1] [2]
public int life; //3
private bool dead;
public string script;
public int MaxLife;
public GameObject audio1;
public GameObject audio2;
public GameObject DeathScreen;
private void Start()
{
life = hearts.Length;
MaxLife = life;
}
// Update is called once per frame
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
FindObjectOfType<AudioManager>().Play("auuChracterSound");
TakeDamge(1);
}
if(collision.gameObject.tag =="healspot")
{
FindObjectOfType<AudioManager>().Play("healSound");
new WaitForSeconds(60f);
hearts[life].gameObject.SetActive(true);
life += 1;
}
}
public void TakeDamge(int d) //d = dmg
{
life -= d;
// Destroy(hearts[life].gameObject);
hearts[life].gameObject.SetActive(false);
if (life < 1)
{
audio1.SetActive(false);
audio2.SetActive(true);
FindObjectOfType<AudioManager>().Play("characterDeathSound");
DeathScreen.SetActive(true);
FindObjectOfType<AudioManager>().Play("GameOverSound");
}
}
}
|
Shell
|
UTF-8
| 379
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
set -Eeuxo pipefail
PROJECT_NAME=
if [[ ! -d .container_home_dir ]]; then
mkdir -p .container_home_dir
fi
touch .container_home_dir/.bash_history
docker build --tag ${PROJECT_NAME} .
docker run -it --rm \
-v $(pwd):/workdir \
-v $(pwd)/.container_home_dir:/home/user/.bash_history \
-w /workdir \
--name ${PROJECT_NAME} ${PROJECT_NAME}
|
SQL
|
UTF-8
| 1,408
| 3.203125
| 3
|
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : Achter
Source Server Version : 50515
Source Host : localhost:3306
Source Database : shop
Target Server Type : MYSQL
Target Server Version : 50515
File Encoding : 65001
Date: 2020-05-31 20:52:55
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int(18) NOT NULL AUTO_INCREMENT COMMENT '用户编号',
`userName` varchar(30) DEFAULT NULL COMMENT '用户姓名',
`userAddress` varchar(100) DEFAULT NULL COMMENT '用户地址',
`phone` int(11) DEFAULT NULL COMMENT '用户联系方式',
`typeNum` int(11) DEFAULT NULL COMMENT '用户类型',
PRIMARY KEY (`userId`),
KEY `typeNum` (`typeNum`),
CONSTRAINT `user_ibfk_1` FOREIGN KEY (`typeNum`) REFERENCES `usertype` (`typeNum`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'aaaa', 'sf jajbfbsha', '12334455', '1');
INSERT INTO `user` VALUES ('2', 'bbbb', 'fsdgdsgdsgd', '12336234', '2');
INSERT INTO `user` VALUES ('3', 'ccccc', 'jhkdsjafsdajkg', '456897666', '3');
INSERT INTO `user` VALUES ('4', 'dddd', 'vdbshjdgv', '654593', '3');
INSERT INTO `user` VALUES ('5', 'eeee', 'dgshjgs', '875347', '2');
|
PHP
|
UTF-8
| 2,351
| 2.640625
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: ThinkPad
* Date: 2015/10/25
* Time: 9:37
*/
use Goutte\Client;
use Symfony\Component\DomCrawler\Crawler;
class kat_cr_Parser implements parserInterface
{
function __construct()
{
$this->client = new Client();
}
public function parseTVSerialsinfo($url)
{
$crawler = $this->client->request('get',$url);//这步骤为什么有问题呢?怎么获得一部电视剧的每一集的清单呢?后来发现是什么证书的事情
//获取电视剧信息播放信息
// $(".torrentMediaInfo .dataList li").filter(function(){return $(this).html().match(/Original run/)}).html()
// "<strong>Original run: </strong>13 June 2005 — 12 December 2010"
$dom0 = $crawler->filter(".torrentMediaInfo .dataList li");
$info = [];
$dom0->each(function($node) use(&$info){
if (preg_match('%<strong>Original run: </strong>(.+) — (.+)%m', $node->html(), $regs)) {
$info = [
'start'=>$regs[1],
'end'=>$regs[2]
] ;
}
});
//获取剧集信息
$dom = $crawler->filter('h3');
//获取季度的相应html数据
$seasons = [];
$dom->each(function($node) use(&$seasons){
$season = $node->html();
if(preg_match('|Season|',$season)){
$seasons[$season]=$node->nextAll()->html();
}
});
//抽取出其中的一些epesode数据
foreach($seasons as $season=>$row){
preg_match_all('%<span class="versionsEpNo">(.+)\s</span>\s*<span class="versionsEpName">(.+)</span>\s*<section>\s*<span class="versionsEpDate">(.*)</span>%m', $row, $result, PREG_PATTERN_ORDER);
$num = $result[1];
$title = $result[2];
$date = $result[3];
$result = [];
foreach($num as $key=>$value){
$result[]=[
'num'=>(int)preg_replace('|Episode\s+([0-9]+)|','$1',$num[$key]),
'title'=>$title[$key],
'date'=>$date[$key]
];
}
$seasons[(int) preg_replace('|^Season\s+([0-9]+)$|','$1',$season)]=$result;
}
return ['info'=>$info,'seasons'=>$seasons];
}
}
|
Java
|
UTF-8
| 3,762
| 2.15625
| 2
|
[] |
no_license
|
package com.kpi.scineticle.model.subsystemOfDataBase.electronic_resource;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import com.kpi.scineticle.model.subsystemOfDataBase.ScientWork;
import java.io.Serializable;
@Entity (tableName = "el_resource_table")
public class ElectronicResource extends ScientWork implements Serializable {
@PrimaryKey(autoGenerate = true)
private int id;
private String authors;
private String name;
private String placePublish;
private String publish;
private String date;
private String updateDate;
private String url;
private String userLogin;
private int newest;
public int getNewest() {
return newest;
}
public void setNewest(int newest) {
this.newest = newest;
}
public ElectronicResource() {
super.setTypeOfWork("Електроний ресурс");
}
public ElectronicResource(String authors, String name, String placePublish, String publish, String date, String updateDate, String url) {
this.authors = authors;
this.name = name;
this.placePublish = placePublish;
this.publish = publish;
this.date = date;
this.updateDate = updateDate;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlacePublish() {
return placePublish;
}
public void setPlacePublish(String placePublish) {
this.placePublish = placePublish;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
@Override
public String toString() {
return "ElectronicResource{" +
"authors='" + authors + '\'' +
", name='" + name + '\'' +
", placePublish='" + placePublish + '\'' +
", publish='" + publish + '\'' +
", date='" + date + '\'' +
", updateDate='" + updateDate + '\'' +
", url='" + url + '\'' +
", userLogin=" + userLogin +
'}';
}
public boolean isValidAuthors() {
return mTextValidator.validateAuthorsName(authors);
}
public boolean isValidName() {
return mTextValidator.validateName(name);
}
public boolean isValidPlacePublish() {
return mTextValidator.validateStatement(placePublish);
}
public boolean isValidPublish() {
return mTextValidator.validateName(publish);
}
public boolean isValidDate() {
return mTextValidator.validateDate(date);
}
public boolean isValidUpdateDate() {
return mTextValidator.validateYear(updateDate);
}
public boolean isValidURL() {
return mTextValidator.validURL(url);
}
}
|
C++
|
UTF-8
| 695
| 2.609375
| 3
|
[] |
no_license
|
#include<cstdio>
using namespace std;
#define MAX 1001
#define MAX2 6*MAX
#define DICE 6
double p[MAX][MAX2], prob = 1.0/6.0;
double solve(int n, int k)
{
if(p[n][k] != -1.0)
return p[n][k];
if(n == 0)
{
if(k != 0)
return p[n][k] = 0.0;
else
return p[n][k] = 1.0;
}
p[n][k] = 0.0;
for(int i=1; i<=DICE; ++i)
{
if(k-i >= 0)
p[n][k] += prob*solve(n-1, k-i);
else
break;
}
return p[n][k];
}
int main()
{
int t, n, k;
for(int i=0; i<MAX; ++i)
for(int j=0; j<MAX2; ++j)
p[i][j] = -1.0;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &n, &k);
if(n > MAX || k > MAX2)
puts("0");
else
printf("%d\n", (int)(100*solve(n, k)));
}
return 0;
}
|
Ruby
|
UTF-8
| 1,191
| 4.125
| 4
|
[] |
no_license
|
require_relative 'human'
class Samurai < Human
@@how_many = 0
attr_accessor :strength, :intelligence, :stealth, :health
def initialize
@@how_many += 1
@strength = 3
@intelligence = 3
@stealth = 175
@health = 200
end
def death_blow(enemy)
args = method(__method__).parameters.map { |arg| arg[1] }
if enemy.class.ancestors.include?(Human)
puts "Enemy Health 0 / Samurai attacking #{args} #{enemy.class} with Death Blow"
enemy.health = 0
else
puts "#{args} #{enemy.class} is not a human."
end
self
end
def meditate
self.health = 200
puts "Health 200 / Samurai Meditate"
self
end
def how_many
puts "How many Samurais?"
return @@how_many
end
end
tom=Samurai.new
jerry=Human.new
legend=Samurai.new
p tom.death_blow(jerry).health
p jerry.health
p tom.attack(tom).health
p tom.meditate.health
p legend.how_many
# Enemy Health 0 / Samurai attacking [:enemy] Human with Death Blow
# 200
# 0
# Enemy Health -10 / Attacking the [:enemy]
# 190
# Health 200 / Samurai Meditate
# 200
# How many Samurais?
# 2
|
Markdown
|
UTF-8
| 1,720
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
---
layout: page
title: Cameo Series Blue White Columbine
---
<div class="row">
<div class="col-md-4">
<div class="plant-image plant-image-large" style="background-image: url("https://s3-us-west-1.amazonaws.com/images.plantwithbloom.com/cameo_series_blue_white_columbine.jpg");"></div>
</div>
<div class="col-md-8">
<div>
<p>A favorite for late spring color...delicately nodding, long lasting, two-tone blooms of blue and white stand upright on compact clumps of gray-green foliage. An easy-to-grow plant for mixed borders, containers and mass planting. Attracts hummingbirds and butterflies. Herbaceous perennial. Compact Habit. Attracts Hummingbirds. Compact Form. Bird Friendly.</p>
<div class="row">
<div class="col-md-3">
<strong>Size</strong>
</div>
<div class="col-md-9">12.0" W X 8.0" H</div>
</div>
<div class="row">
<div class="col-md-3">
<strong>Type</strong>
</div>
<div class="col-md-9">Herbaceous Perennial</div>
</div>
<div class="row">
<div class="col-md-3">
<strong>Flower Color</strong>
</div>
<div class="col-md-9">Blue</div>
</div>
<div class="row">
<div class="col-md-3">
<strong>Foliage Color</strong>
</div>
<div class="col-md-9">Gray-green</div>
</div>
<div class="row">
<div class="col-md-3">
<strong>Lighting</strong>
</div>
<div class="col-md-9">Partial shade to full sun</div>
</div>
</div>
<hr/>
<a class="btn btn-default" href="http://app.plantwithbloom.com/search">Discover More Plants Like This</a>
</div>
</div>
|
Markdown
|
UTF-8
| 593
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
---
title: "Chart 模板指南"
weight: 5
---
# Chart模板开发者指南
该指南提供Helm Chart模板的介绍,重点强调模板语言。
模板会生成manifest文件,使用Kubernetes可以识别的YAML格式描述。我们会看到模板是如何结构化的,
它们如何被使用,如何编写Go模板,以及如何调试你们的工作内容。
该指南聚焦于以下概念:
- Helm模板语言
- values值的使用
- 使用模板工作的技术点
该指南面向学习Helm模板语言的来龙去脉。其他指南提供介绍性资料,示例和最佳实践。
|
TypeScript
|
UTF-8
| 366
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
import type ICanvasContext from './ICanvasContext'
export default interface IDrawable {
/**
* 绘制当前实例
* @param x 当前实例父容器左上角的 x 坐标
* @param y 当前实例父容器左上角的 y 坐标
* @param viewHeight 整个画布的高度
*/
draw: (ctx: ICanvasContext, x: number, y: number, viewHeight: number) => void
}
|
PHP
|
UTF-8
| 959
| 2.921875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Menghubungkan CI dengan Database</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<h1>Belajar Model Pada Code Igniter</h1>
<table border="1">
<tr>
<th>Nama</th>
<th>Alamat</th>
<th>Pekerjaan</th>
</tr>
<?php foreach($user as $u){ ?>
<tr>
<!-- $u adalah variabel foreach -> nama field dalam tabel -->
<td><?php echo $u->nama ?></td>
<td><?php echo $u->alamat ?></td>
<td><?php echo $u->pekerjaan ?></td>
</tr>
<?php }?>
</table>
</body>
</html>
|
SQL
|
UTF-8
| 205
| 2.625
| 3
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
--liquibase formatted sql
--changeset uk.gov.pay:index_transaction_type_for_filtering runInTransaction:false
CREATE INDEX CONCURRENTLY IF NOT EXISTS transaction_type_idx ON transaction USING btree(type);
|
Java
|
UTF-8
| 181
| 1.953125
| 2
|
[] |
no_license
|
package com.example.design.mode.demo.abstr.factory;
/**
* @author liuxiaojing
* @description
* @date 2021/6/30 下午3:18
*/
public interface Journal {
String create();
}
|
Ruby
|
UTF-8
| 1,126
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
require "test_helper"
class ComplexityCalculatorTest < Minitest::Test
def setup
@calc = McClimate::ComplexityCalculator.new
end
def parse(source)
RubyParser.for_current_ruby.parse("def foo; #{source}; end")
end
def test_empty_method_source
sexp = parse("")
assert_equal 1, @calc.score(sexp)
end
def test_single_source
sexp = parse("x = 1 + 1")
assert_equal 4, @calc.score(sexp)
end
def test_basic_source
sexp = parse("x = 1 + y * 2")
assert_equal 5, @calc.score(sexp)
end
def test_complex_source
sexp = parse("y = 3 + 3; x = 1 + y * 2")
assert_equal 8, @calc.score(sexp)
end
def test_double_assign_source
sexp = parse("x = 1 + (y = 3 + 3) * 2")
assert_equal 11, @calc.score(sexp)
end
def test_ignore_symbolized_operators
sexp = parse("a = :+")
assert_equal 1, @calc.score(sexp)
end
def test_conditional_score
sexp = parse("if (a = 1 + 1) == 2; end")
assert_equal 4, @calc.score(sexp)
end
def test_while_score
sexp = parse("while (a = 1 + 1) == 2; end")
assert_equal 4, @calc.score(sexp)
end
end
|
PHP
|
UTF-8
| 1,621
| 3.265625
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
$precio = 1000; // Precio del producto
$pagado = 2000; // Pagado por el cliente
// array con los billetes y monedas disponibles
$disponible = array(500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01);
$nodisponible = array(0.1, 0.2);
$cambio = $pagado - $precio;// Calculamos el cambio que debe ser devuelto
echo "el cambio a dar es de: ".$cambio."€</br>";
echo "Billetes no disponibles: $nodisponible[0] y $nodisponible[1] el cambio a dar es:</br>";
$i = 0;// inicializamos $i en 0
/* Creamos un do while donde; mientras el billete o moneda disponible se mayor a cambio,
incremente el contador hasta que consiga un que sea menor o igual y lo imprime;
despues vuelve a calcular el cambio, con el cambio anterior segun lo pagado por el cliente y
le resta la moneda o billete que en la posicion $i osea el que fue encontrado menor o igual,
todo esto pasara mientras el cambio sea mayor que la moneda o billete disponibles, contando
los elementos del array */
do {
while($disponible[$i] >= $cambio){
$i++;// incremente
}if ($disponible[$i] == $nodisponible[0] || $disponible[$i] == $nodisponible[1]){
$i++;// incremente, pasa a la siguiente moneda
$i++;// Incrementa el segundo elemento encontrado
}
echo "$".($disponible[$i])."€ </br>";
$cambio = $cambio - $disponible[$i]; // se le resta la moneda usada
}while ($cambio > $disponible[count($disponible)-1]);
/* mientras el $cambio sea mayor que una de las monedas
disponibles entonces cuando; ya $cambio es 0 por que es menor que una de las moneda para. */
?>
|
Markdown
|
UTF-8
| 6,723
| 3.34375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# It's Not Magic
This role playing game adventure takes you through a Wizard's Dungeon to find the invasion of an other worldly power.
## Table of Contents
* **Psionics**: An introduction to the powers fueling this journey into insanity.
* **Adventure Hooks**: Ideas on how to make the adventure more engaging for your players.
* **Prologue**: Introducing the adventure.
* **Chapter 1**: Someone Has Come Along
* **Chapter 2**: Enter the Madhouse
* **Chapter 3**: Caverns of Respite
* **Chapter 4**: Return to Madness
* **Chapter 5**: In & Out
* **Epilogue**
## Encountering The Other
In the worlds of Dungeons & Dragons, magic is as natural as water. While sometimes not common, it is known and understood to exist. Characters in the worlds of D&D recognize that magic is a great power that flows through the multiverse as a power that can build or destroy worlds. Now imagine what it would be like to learn there is another power, a greater power that does not come from manipulating nature, it comes from within.
Welcome to *It’s Not Magic* an adventure that takes players in a world where magic is not the ultimate power. Deep into a Wizard’s Dungeon known as The Madhouse players will encounter other worldly horrors, deadly traps and awaken dormant powers within themselves.
This journey into darkness is best for 2-4 players levels 3-5. Ideal character classes for this are non-magical classes like Fighters, Monks, Rangers, Thieves, etc. Magic is not the best tool here but a steady sword or better yet, steady hands can save the day.
## Themes
*It’s Not Magic* is about encountering the unknown when greed for things or knowledge leads to our darkest places.
Throughout this adventure the players will be facing fear, other worldly horrors and powers unlike anything seen before. Take inspiration for this adventure from tales where humanity seeks forbidden knowledge such as the stories of H.P. Lovecraft or strange journeys like William Hope Hodgson. The experiences of the players are other worldly, strange and from these things, terrifying.
### Sanity & Horror
In this adventure we will be exploring horrors of another world that pull apart the player's sanity. To represent this, implement the optional **Sanity** score. Each encounter with madness will eat away at this score until all that is left is a slobering, blob of player character.
All player characters start with 10 sanity.
* **Ten (10)** represents a firm grip on the player character's known world.
* **Six (6)** represents the player character is slipping. Halucinations can occur but the PC still knows what is real.
* **Three (3)** represents the PC can't distinguish between what is real and what isn't anymore.
* **Zero (0)** represents total madness where the PC is catatonic.
Take madness as a great opportunity to role play and reward PCs who explore their character's grip on reality.
## Mood
Setting the mood for the adventure is always critical for the best time. The player’s journey from tavern to dungeon to caverns to deeper dungeons is a journey into darkness both literally and figuratively. Match this journey with proper lighting and audio support.
**Lighting** for this adventure is best when using LED Candles. Get the large candles that kick off a lot of light, not the tea lights. Start the Tavern with a room full of light. This is the brightest time for the players. As your party moves into the dungeon, bring the lights down or switch to only use the LED Candles (representing the player’s torches). In the Caverns reduce the number of candles to heighten the sense of darkness and isolation. Using lighting to adjust the mood can add a powerful element to your game.
**Audio** provides a heighten sense of drama throughout the game. Matching the lighting, audio can be used to take the players from jovial to forboding as they descend into the dungeon.
When working with music avoid soundtracks. If a soundtrack starts playing and the players’ mind goes to the movie associated with the soundtrack, the mood will be broken.
## Setting
So where is this adventure? Well that is up to you. The content here is kept fairly generic and can be modified to be where ever you’d like be it the Forgotten Realms, Equestria or Malifaux. Be creative and adapt to your world how you see fit. As an example, you could start in the Yawning Portal tavern in Forgotten Realms and take the players into an undiscovered mountain cavern deep in the Sword Mountains. Have fun with the setting and take the players from the familiar to the alien. That makes things more fun for everyone.
## Story Summary
Players start in a tavern where drunk barbarians are claiming they found the ancient dungeon. During this time players can learn the rumors of Dmitry and the strange happenings in the village. Once the players obtain the map to the dungeon they go off to find it in the mountains east of the tavern. While the map to the dungeon is accurate, the second map, the map of the dungeon is incorrect and a forgery.
In the dungeon, players immediately feel the impact of the psionic assault trying to determine their danger to the Beast. Through numerous traps and encounters the Beast is testing the players and eventually trying to stop them from getting to the Beast’s lair. Throughout the dungeon players find the possessions of an old wizard who was trying to connect to a realm that housed a new, more potent, magic that comes from within instead of the natural order of the multiverse.
The only relief from the psionic assault is when the players descend into the caverns below the dungeon. The cavern walls are lined with obsidian which naturally dampens psionic powers. Within the caverns players encounter Dmitry, the cursed wizard who created the rip in the multiverse to an unknown dimension where dark things slithered through the portal – wounding the wizard and taking over his dungeon. Dmitry tells the players of a tool he crafted from his studies of the Beast’s powers and how it was left above in the dungeon.
Players return to the dungeon to hunt for the tool (an Obsidian Scraab). As the players press deeper into the dungeon they encounter the Beast’s Guardian, an animated puppet that appears more like a bloated rag doll than the muscle to a monster from another dimension.
Beyond the Guardian, the players encounter the Beast in the sanctuary of the dungeon complex. After battling the Beast, the players need to close the portal to the other dimension by shattering the stone in the center of the room that is holding the rift open. Once the stone is shattered, the portal collapses and any psionic powers the players had manifested end.
Continue to [Psionics](Psionics.md)
|
Java
|
UTF-8
| 4,737
| 2.484375
| 2
|
[] |
no_license
|
package org.cocome.storesservice.controller;
import java.util.Collection;
import java.util.LinkedList;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.cocome.storesclient.domain.StockItemTO;
import org.cocome.storesclient.domain.StoreTO;
import org.cocome.storesservice.domain.StockItem;
import org.cocome.storesservice.domain.Store;
import org.cocome.storesservice.exceptions.CreateException;
import org.cocome.storesservice.exceptions.QueryException;
import org.cocome.storesserviceservice.StoreQuery.IStockQuery;
import org.cocome.storesserviceservice.StoreQuery.IStoreQuery;
/**
* RESTful resource for stores and nested stock items. To create stores or fetch
* them by their trading enterprise associaton, the TradingEnterpriseResource is
* used.
*
* @author Nils Sommer
*
*/
@RequestScoped
@Path("/stores")
public class StoreResource {
@EJB
private IStoreQuery storeQuery;
@EJB
private IStockQuery stockQuery;
private static final Logger LOG = Logger.getLogger(StoreResource.class);
@GET
public Collection<StoreTO> findAll() {
LOG.debug("REST: Retrieve all Enterprises");
Collection<StoreTO> collection = new LinkedList<StoreTO>();
for (Store store : storeQuery.getAllStores()) {
collection.add(toStoreTO(store));
}
return collection;
}
@GET
@Path("/{id}")
public StoreTO find(@PathParam("id") Long id) {
LOG.debug("REST: Try to find store with id: " + id);
Store store;
try {
store = storeQuery.getStoreById(id);
} catch (QueryException e) {
LOG.debug("REST: " + e.getMessage());
throw new NotFoundException(e.getMessage());
}
return toStoreTO(store);
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_XML)
public Response update(@PathParam("id") Long id, StoreTO storeTO) {
LOG.debug("REST: Try to update store with name: " + storeTO.getName() + " and id:" + id);
try {
storeQuery.updateStore(id, storeTO.getName(), storeTO.getLocation());
} catch (QueryException e) {
LOG.debug("REST: " + e.getMessage());
throw new NotFoundException(e.getMessage());
}
return Response.noContent().build();
}
@DELETE
@Path("/{id}")
public Response delete(@PathParam("id") Long id) {
LOG.debug("REST: Trying to delete Store with id: " + id);
try {
storeQuery.deleteStore(id);
} catch (QueryException e) {
LOG.debug("REST: " + e.getMessage());
throw new NotFoundException(e.getMessage());
}
return Response.noContent().build();
}
// Creating and fetching nested stock items
@GET
@Path("/{id}/stock-items")
public Collection<StockItemTO> findStockItems(@PathParam("id") Long storeId) {
LOG.debug("REST: Trying to find ALL stock items of store with id: " + storeId);
Store store;
try {
store = storeQuery.getStoreById(storeId);
} catch (QueryException e) {
LOG.debug("REST: " + e.getMessage());
throw new NotFoundException(e.getMessage());
}
Collection<StockItemTO> collection = new LinkedList<StockItemTO>();
for (StockItem item : store.getStockItems()) {
collection.add(StockItemResource.toStockItemTo(item));
}
return collection;
}
@POST
@Path("/{id}/stock-items")
@Consumes(MediaType.APPLICATION_XML)
public Response createStockItem(@Context UriInfo uriInfo, @PathParam("id") Long storeId, StockItemTO stockItemTO) {
LOG.debug("REST:Trying to create stockItem with productId: " + stockItemTO.getProductId()
+ " in store with id: " + storeId);
Long id;
try {
id = stockQuery.createStockItem(stockItemTO.getSalesPrice(), stockItemTO.getAmount(),
stockItemTO.getMinStock(), stockItemTO.getMaxStock(), stockItemTO.getBarcode(),
stockItemTO.getIncomingAmount(), stockItemTO.getProductId(), storeId, stockItemTO.getName());
} catch (CreateException e) {
LOG.debug("REST: " + e.getMessage());
throw new NotFoundException(e.getMessage());
}
UriBuilder builder = UriBuilder.fromUri(uriInfo.getBaseUri()).path(StockItemResource.class).path(id.toString());
return Response.created(builder.build()).build();
}
public static StoreTO toStoreTO(Store store) {
StoreTO storeTO = new StoreTO();
storeTO.setId(store.getId());
storeTO.setLocation(store.getLocation());
storeTO.setName(store.getName());
storeTO.setEnterpriseId(store.getEnterprise().getId());
return storeTO;
}
}
|
C
|
UTF-8
| 169
| 3
| 3
|
[] |
no_license
|
// Control Flow
#include <stdio.h>
int main()
{
int a = 10;
if (a < 20)
{
printf("a is less than 20");
}
else
{
return 0;
}
}
|
Python
|
UTF-8
| 1,298
| 2.53125
| 3
|
[] |
no_license
|
#-*- coding:utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.db import models
# Create your models here.
class User(models.Model):
"""
作者模型
"""
name = models.CharField(verbose_name =u'姓名', max_length= 30)
mail = models.EmailField(verbose_name = u'邮箱', max_length=100)
class Meta:
verbose_name = u'作者'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
def __unicode__(self):
return self.name
class Entry(models.Model):
"""
文章模型
"""
STATUS_DRAFT = 'draft'
STATUS_PUBLIC = 'public'
STATUS_SET = (
(STATUS_DRAFT,'草稿'),
(STATUS_PUBLIC,'公开'),
)
title = models.CharField(max_length=100, verbose_name=u'标题')
body = models.TextField()
created_at = models.DateTimeField(default=datetime.now(),verbose_name=u'添加时间')
updated_at = models.DateTimeField(default = datetime.now(),verbose_name=u'修改时间')
status = models.CharField(choices=STATUS_SET, default= STATUS_DRAFT, max_length=8)
author = models.ForeignKey(User, related_name = 'entries')
def __str__(self):
return self.title
def __unicode__(self):
return self.title
|
PHP
|
UTF-8
| 213
| 2.546875
| 3
|
[] |
no_license
|
<?php
namespace ApiBundle\Provider;
class HashProvider
{
/**
* @param string $string
*
* @return string
*/
public function getHash($string)
{
return md5($string);
}
}
|
Swift
|
UTF-8
| 2,836
| 2.921875
| 3
|
[] |
no_license
|
//
// mosquedetails.swift
// hw3
//
// Created by sarah alshammari on 5/7/20.
// Copyright © 2020 sarah. All rights reserved.
//
import SwiftUI
struct mosquedetails: View {
var mo : mousque
var body: some View {
ZStack{
Color.black
.edgesIgnoringSafeArea(.all)
VStack{
ZStack {
Rectangle().foregroundColor(.clear).frame(maxWidth:.infinity)
.background( Image(mo.names)
.resizable()
.edgesIgnoringSafeArea(.all))
Text(mo.names)
.font(.system(size: 50))
.font(.largeTitle)
.foregroundColor(.white)
ScrollView(.horizontal){
HStack(spacing:30){
ForEach(mo.sheikh , id: \.self){ mo in
Image(mo)
.resizable()
.scaledToFit()
.frame(width:120,height: 200)
.clipShape(Circle())
.overlay(Circle().stroke(Color.white,lineWidth: 8))
}
}
}.offset(y:150)
}
ScrollView(.vertical){
HStack(spacing:100){
VStack(spacing:20){
ForEach(mo.time,id:\.self){ mo in
Text(mo)
.font(.callout)
.foregroundColor(.white)
}
}
VStack(spacing:20){
ForEach(mo.prayer,id:\.self){ mo in
Text(mo)
.font(.callout)
.foregroundColor(.white)
}
}
}
}
.offset(y:80)
}
}
}
struct mosquedetails_Previews: PreviewProvider {
static var previews: some View {
mosquedetails(mo:mousque(names: "المشعان", sheikh: ["الطرابلسي",
"الكندري",
"العفاسي",])
) }
}
}
|
Python
|
UTF-8
| 594
| 3.359375
| 3
|
[] |
no_license
|
correct = 0
soma = 0.0
while (True):
x = float(input())
if (x < 0.0 or x > 10):
print ("nota invalida")
else:
soma += x
if (correct == 1):
print ("media = {:.2f}".format(soma/2))
soma = 0
correct = 0
print ("novo calculo (1-sim 2-nao)")
x = float(input())
while (x < 1.0 or x > 2.0):
print ("novo calculo (1-sim 2-nao)")
x = float(input())
else:
if (x == 2.0):
break
else:
correct += 1
|
C#
|
UTF-8
| 2,188
| 2.921875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace assignment3
{
class Program
{
static void Main(string[] args)
{
Restaurantmenu.Chooseoption();
// Customer c = new Customer();
// Type type2 = (Type)Enum.Parse(typeof(Type), "Chicken_Biryani");
// Console.WriteLine("Enter customer order");
//c.order(2, (Type)Enum.Parse(typeof(Type), "Chicken_Biryani"));
//c.order(1, (Type)Enum.Parse(typeof(Type), "Punjabi_Chicken"));
//c.order(3, (Type)Enum.Parse(typeof(Type), "Paneer_Sahi"));
//c.order(2, (Type)Enum.Parse(typeof(Type), "Chicken_Biryani"));
//c.order(1, (Type)Enum.Parse(typeof(Type), "Punjabi_Chicken"));
//c.order(3, (Type)Enum.Parse(typeof(Type), "Paneer_Sahi"));
// c.bill();
Console.ReadKey();
}
//Addition
//
/*
public void (string names, string authornames, Class1.BookType booktypes)
{
public static int Addition(int input_1, int input_2)
{
int result = input_1 + input_2;
return result;
}
//Substraction
public static int Subtraction(int input_1, int input_2)
{
int result = input_1 + input_2;
return result;
}
//Multiplication
public static int Multiplication(int input_1, int input_2)
{
int result = input_1 + input_2;
return result;
}
//Division
public static int Division(int input_1, int input_2)
{
int result = input_1 + input_2;
return result;
}
*/
}
}
|
SQL
|
UTF-8
| 7,766
| 3.015625
| 3
|
[] |
no_license
|
-- --------------------------------------------------------
-- Host: 192.168.0.101
-- Wersja serwera: 10.1.30-MariaDB - mariadb.org binary distribution
-- Serwer OS: Win32
-- HeidiSQL Wersja: 9.5.0.5261
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Zrzut struktury bazy danych ycckatowice_shop
CREATE DATABASE IF NOT EXISTS `ycckatowice_shop` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
USE `ycckatowice_shop`;
-- Zrzut struktury tabela ycckatowice_shop.category
DROP TABLE IF EXISTS `category`;
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4;
-- Zrzucanie danych dla tabeli ycckatowice_shop.category: ~9 rows (około)
DELETE FROM `category`;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` (`id`, `name`) VALUES
(3, 'Dom i ogród'),
(4, 'Supermarket'),
(5, 'Dziecko'),
(7, 'Kultura'),
(8, 'Sport i wypoczynek'),
(9, 'Motoryzacja'),
(12, 'English from book'),
(13, 'Twoje słówka angielskie'),
(17, 'Hack!');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
-- Zrzut struktury tabela ycckatowice_shop.product
DROP TABLE IF EXISTS `product`;
CREATE TABLE IF NOT EXISTS `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text,
`category_id` int(11) DEFAULT NULL,
`cost` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8mb4;
-- Zrzucanie danych dla tabeli ycckatowice_shop.product: ~70 rows (około)
DELETE FROM `product`;
/*!40000 ALTER TABLE `product` DISABLE KEYS */;
INSERT INTO `product` (`id`, `name`, `category_id`, `cost`) VALUES
(3, 'PS4 KONSOLA PRO 1TB BIAŁA ', 1, 1599),
(4, 'GŁOŚNIK PRZENOŚNY BLUETOOTH JBL FLIP 4 IPX7 - 24h', 1, 387.22),
(5, 'Walizka PUCCINI Duża Twarda Złoty - PC020A 6', 2, 399),
(6, 'Buty męskie LACOSTE OUTLET 45', 2, 259),
(7, 'BUTY SALOMON ELIOS 2 M 391872 r.43', 2, 374),
(8, 'Apaszka opaska bandana w grochy do włosów ', 2, 5.84),
(9, 'Meble Ogrodowe Zestaw na balkon ROSARIO brąz+obrus', 3, 386),
(10, 'Drabina stalowa podrest Baulich 125kg 2 stopnie', 3, 29),
(11, 'Komplet pościeli Sentenza 160x200cm Dwustronna 105', 3, 29.99),
(12, 'Koc narzuta mikrofibra Maddox 150x200cm różowy', 3, 29.99),
(13, 'Kinkiet ogrodowy Lampa SANICO BRETANIA LED INOX', 3, 50),
(14, 'Glebogryzarka X-GT65-2 ZS Agregat tylny 2Bieg Hort', 3, 2149),
(15, 'CHAPPI WOŁOWINA DRÓB WARZYWA 13.5 KG x2 (27KG)', 4, 115.98),
(16, 'Przysmak dla kota Dreamies z pysznym serem 5 sztuk', 4, 25),
(17, 'OPŁATEK TORT ZESTAW PSI PATROL GRATIS GRUBY', 4, 25),
(18, 'GURMAR Gymnema sylvestre 100G SunLife', 4, 19.99),
(19, 'BIHELDON - tabletki na odrobaczanie PIES KOT 10szt', 4, 28),
(20, 'Mop płaski Vileda UltraMax BOX + WIADRO +WYCISKACZ', 4, 84.99),
(21, 'Mop obrotowy VILEDA Easy Wring and Clean Turbo', 4, 109.99),
(22, 'Lukier Plastyczny Masa Cukrowa w 25 kolorach 1 kg', 4, 17),
(23, 'ORZECHY WŁOSKIE 1kg ŁUSKANE', 4, 37.44),
(24, 'Yerba Mate CANARIAS 1kg ', 4, 34.5),
(25, 'Dolce Gusto Nescafe Kapsułki Stojak DUŻY na 28 szt', 4, 28),
(26, 'PAMPERS Pieluszki Premium Care 4 Maxi 104 + LENOR', 5, 99.99),
(27, 'PAMPERS Pieluszki ZAPAS 3 Midi aż 208 szt NOWOŚĆ', 5, 129.99),
(28, 'Wózek spacerowy spacerówka Kinderkraft PILOT lekki', 5, 489),
(29, 'LEGO MINECRAFT Żelazny Golem 21123', 5, 89),
(30, 'LEGO MINDSTORMS 31313 EV3 ', 5, 1338),
(31, 'ROWER ROWEREK BIEGOWY LIONELO DAN KASK EVA HAMULEC', 5, 138),
(32, 'HULAJNOGA SKŁADANA DUŻA LIONELO LUCA AMORTYZATOR', 5, 149),
(33, 'Butla z helem 0,42 m3 na 50 szt. balonów + balony', 5, 123),
(34, 'PIASEK DO PIASKOWNICY SUPER JASNY ATEST Dostawa', 5, 349),
(35, 'SMOBY Zjeżdżalnia Funny 200cm Powłoka UV WODA NEW', 5, 399),
(36, 'NOBLE HEALTH ACEROLA', 6, 29.99),
(37, 'OLIMP THERM LINE PRO 30 tabl+30 kaps MOCNY SPALACZ', 6, 39.99),
(38, 'LOREAL INFALLIBLE 24h Podkład 140 200 220 235 300', 6, 26.99),
(39, 'SUNone Lampa UV LED 48W Hybrydy Żele', 6, 129.99),
(40, 'INHALATOR NEBULIZATOR SANITAS SIH 21', 6, 29),
(41, 'Wkłady do maszynki Gillette Mach3 Start 4 sztuki', 6, 49.99),
(42, 'Maszynka do golenia Gillette Mach3 Start + 6 wkład', 6, 65.99),
(43, 'Szczoteczka elektryczna Oral-B Pro790 2szt. zestaw', 6, 249.99),
(44, 'Dieta warzywno-owocowa dr Ewy Dąbrowskiej', 7, 20.43),
(45, 'Książka: Inteligencja kwiatów', 7, 24.43),
(46, 'CIVILIZATION VI 6 | RISE AND FALL - DLC | Auto24/7', 7, 65),
(47, 'GRAND THEFT AUTO V | GTA 5 | PC PL | Auto 24/7', 7, 75.4),
(48, 'GEORGE R.R. MARTIN Pakiet 8 Części GRA O TRON', 7, 280),
(49, 'Rower DIAMONDBACK SYNC 4.0 27.5 \'', 8, 1899),
(50, 'DAMSKIE LEGGINSY SPORTOWE 4F H4Z17 SPDF003 M', 8, 89),
(51, 'ZESTAW HANTLI 2x20,5kg + 2 ŚCISKACZE HOP-SPORT *PA', 8, 137),
(52, 'Zestaw TREX 47kg sztanga, obciążenia i gryfy *1U8', 8, 127),
(53, 'SP51 Ściskacz dłoni rąk regulowany opór(10-40kg)', 8, 10.59),
(54, 'DRĄŻEK DO PODCIĄGANIA ĆWICZEŃ ŚCIENNY EFEKT SPORT', 8, 104),
(55, 'ZAPIĘCIE ROWEROWE STALOWY ŁAŃCUCH MOTOR 8x1000mm', 8, 45),
(56, '1x opona 205/55R16 UNIROYAL RAINSPORT 3 91V 2018', 9, 149),
(57, 'Opony Letnie 195/65R15 Continental ContiPremiumCon', 9, 204),
(58, '4x opony Uniroyal 195/65R15 RainExpert 3 91H 2018', 9, 724),
(59, '4x OPONY LETNIE 195/65R15 91H DĘBICA PRESTO HP', 9, 659),
(60, 'MODEKA UPSWING KURTKA MOTOCYKL SKUTER LATO L', 9, 499),
(61, 'SAKWA wałek Torba na motocykl Oxford T50 Aqua 50L', 9, 201),
(62, 'FARBA CZARNA DO RENOWACJI SKÓR KIEROWNIC TAPICERKI', 9, 39.99),
(63, 'SOFT99 Fusso Coat 12 Months - Dark Colour Wax Wosk', 9, 108.9),
(64, 'Pierścienie tłokowe bmw e90 e87 e83 x3 1,6 1,8 2,0', 9, 99),
(65, 'KAMAZ TARCZA SPRZĘGŁA NOWA LUBLIN', 9, 75),
(66, 'ZDERZAK PRZEDNI FORD MONDEO MK5 FUSION 13-17r NOWY', 9, 250),
(67, 'FIAT DUCATO FORD TRANSIT 2.2 JTD TDCI SILNIK 06-11', 9, 5999),
(68, 'Kask integralny SMK TWISTER ATTACK MA243 - M', 9, 359),
(69, 'CHUSTA Bandama komin TERMOAKTYWNA CZACHA czaszka', 9, 3.73),
(70, 'Stojak Podnośnik Motocyklowy TYŁ', 9, 99),
(71, 'Muszka czarna', 4, 17.5),
(72, 'Muszka czarna', 4, 17.5),
(73, 'Muszka czarna', 4, 17.5),
(74, 'Muszka czarna', 4, 17.5),
(75, 'Muszka czarna', 4, 17.5),
(76, 'Muszka czarna', 4, 17.5),
(77, 'Muszka czarna', 4, 17.5),
(78, 'Muszka czarna', 4, 17.5),
(79, 'Muszka czarna', 4, 17.5),
(80, 'Muszka czarna', 4, 17.5),
(81, 'Muszka czarna', 4, 17.5),
(82, 'Muszka czarna', 4, 17.5),
(83, 'Muszka czarna', 4, 17.5),
(84, 'Muszka czarna', 4, 17.5),
(85, 'Muszka czarna', 4, 17.5),
(86, 'Muszka czarna', 4, 17.5),
(87, 'Muszka czarna', 4, 17.5),
(88, 'Muszka czarna', 4, 17.5),
(89, 'Muszka czarna', 4, 17.5);
/*!40000 ALTER TABLE `product` ENABLE KEYS */;
-- Zrzut struktury tabela ycckatowice_shop.user
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` text,
`last_name` text,
`email` text,
`city` text,
`role` int(11) DEFAULT NULL,
`password` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- Zrzucanie danych dla tabeli ycckatowice_shop.user: ~2 rows (około)
DELETE FROM `user`;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` (`id`, `first_name`, `last_name`, `email`, `city`, `role`, `password`) VALUES
(1, 'Mikołaj', 'Woźniak', 'wmikolaj.pol@gmail.com', 'Katowice', 1, '$2y$10$Rn4JD8F.WqnSeR0PplJdPekIQA0XOqHWoagMHSDuIYUv63DXKVW8i'),
(2, 'Oskar', NULL, 'oskar@gmail.com', 'Bytom', 0, '$2y$10$r1fHZNwp8ivZuEWH9m5pnOGIH5IRbqJfNypvnnwuZh/zmtm/K3SJS');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.