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
|
---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 1,165 | 2.515625 | 3 |
[] |
no_license
|
var Todo = require('./models/todo');
// expose the routes to our app with module.exports
module.exports = function(app){
// routes ======================================================================
// api ---------------------------------------------------------------------
// get all todos
app.get('/api/todos', function(req,res){
Todo.find(function(err,todos){
if(err)
res.send(err);
res.json(todos);
});
});
app.post('/api/todos',function(req,res){
console.log(req.body);
Todo.create({
text: req.body.text,
done: false
},function(err, todo){
if(err)
res.send(err);
Todo.find(function(err,todos){
if(err)
res.send(err);
res.json(todos);
});
});
});
app.delete('/api/todos/:todo_id',function(req,res){
Todo.remove({_id: req.params.todo_id},function(err,todo){
if(err)
res.send(err);
Todo.find(function(err,todos){
if(err)
res.send(err);
res.json(todos);
});
})
});
app.get('*',function(req,res){
res.sendfile('./public/index.html');
});
};
|
Markdown
|
UTF-8
| 1,638 | 3.21875 | 3 |
[] |
no_license
|
# Welcome to Car Store API Project!
This project was implemented in order to demonstrate how to build rest APIs using Spring Boot. The project structure was generated using [Spring Initilizr](https://start.spring.io/)
For this demonstration purpose, we are creating a collection of APIs to manage a car store.
The project is using the memory database H2 in order to facilitate the demonstration. When the application starts the database is created and some cars are inserted into the database.
I also implemented a front end project in order to show how to consume the APIs: [car-store-front-end](https://github.com/aaperei/car-store-front-end)
# Requirements
All project dependencies are managed by Maven. Besides maven dependencies, you will need the following:
- JDK 11
- In order to deploy the application to a server you will need any web server compatible with Java 11. I recommend Tomcat 9. You can download Tomcat from this link: [https://tomcat.apache.org/download-90.cgi](https://tomcat.apache.org/download-90.cgi)
# Available APIs
All APIs use JSON format as the communication pattern to send and receive information
- `GET /veiculos` - Return all cars
- `GET /veiculos/find` - Return a list of cars according to the parameter q
- `GET /veiculos/{id}` - Return the details of a specific car
- `POST /veiculos` - Adds a new car
- `PUT /veiculos` - Updates car attributes
- `PATH /veiculos/{id}` - Updates some car attributes
- `DELETE /veiculos/{id}`- Deletes a specific car
# Testing the application
As we are testing a Maven project, you can run the application by using:
./mvnw spring-boot:run
|
C
|
UTF-8
| 3,908 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <libopticon/react.h>
#include <stdlib.h>
#include <string.h>
pathnode OPTICONF_ROOT;
/** Allocate a pathnode */
pathnode *pathnode_alloc (void) {
pathnode *self = (pathnode *) malloc (sizeof (pathnode));
if (! self) return NULL;
self->prev = self->next = self->parent =
self->first = self->next = NULL;
self->idmatch[0] = 0;
self->rcount = 0;
self->reactions = NULL;
return self;
}
/** Add a reaction to a pathnode */
void pathnode_add_reaction (pathnode *self, reaction_f f) {
if (self->rcount == 0) {
self->reactions = (reaction_f *) malloc (sizeof (reaction_f));
self->reactions[0] = f;
self->rcount = 1;
}
else {
self->rcount++;
self->reactions = (reaction_f *)
realloc (self->reactions, self->rcount * sizeof (reaction_f));
self->reactions[self->rcount -1] = f;
}
}
/** Find a pathnode that matches against a given id. Wildcards will
* be honored. */
pathnode *pathnode_find_match (pathnode *self, const char *id) {
pathnode *res = self->first;
if (! res) return NULL;
while (res) {
if (res->idmatch[0] == '*' && res->idmatch[1] == 0) return res;
if (strcmp (res->idmatch, id) == 0) return res;
res = res->next;
}
return NULL;
}
/** Find or create a pathnode with a specific match string. */
pathnode *pathnode_get_idmatch (pathnode *self, const char *id) {
pathnode *res = self->first;
while (res) {
if (strcmp (res->idmatch, id) == 0) return res;
res = res->next;
}
res = pathnode_alloc();
strncpy (res->idmatch, id, 127);
res->idmatch[127] = 0;
res->parent = self;
if (self->first) {
res->prev = self->last;
self->last->next = res;
self->last = res;
}
else {
self->first = res;
self->last = res;
}
return res;
}
/** Set up a configuration reaction to a specific configuration
* path, separated by forward slashes. A path match against '*'
* means that the reaction function will be called for each
* child of the node.
* \param path The slash-separated path match.
* \param f The reaction function to call.
*/
void opticonf_add_reaction (const char *path, reaction_f f) {
pathnode *T = &OPTICONF_ROOT;
char *oldstr, *tstr, *token;
oldstr = tstr = strdup (path);
while ((token = strsep (&tstr, "/")) != NULL) {
T = pathnode_get_idmatch (T, token);
}
pathnode_add_reaction (T, f);
free (oldstr);
}
/** Internal handler for opticonf_handle_config(). */
void opticonf_handle (var *conf, pathnode *path) {
uint32_t gen = (conf->root) ? conf->root->generation : conf->generation;
int c = var_get_count (conf);
updatetype tp = UPDATE_NONE;
var *vcrsr;
pathnode *pcrsr;
for (int i=0; i<c; ++i) {
vcrsr = var_find_index (conf, i);
pcrsr = pathnode_find_match (path, vcrsr->id);
if (! pcrsr) continue;
if (pcrsr->rcount) {
tp = UPDATE_NONE;
if ((vcrsr->generation) < gen) {
tp = UPDATE_REMOVE;
}
else if (vcrsr->lastmodified == gen) {
if ((vcrsr->firstseen) == gen) tp = UPDATE_ADD;
else tp = UPDATE_CHANGE;
}
if (tp != UPDATE_NONE) {
for (int ri=0; ri<(pcrsr->rcount); ++ri) {
pcrsr->reactions[ri](vcrsr->id, vcrsr, tp);
}
}
}
if (vcrsr->type == VAR_ARRAY || vcrsr->type == VAR_DICT) {
opticonf_handle (vcrsr, pcrsr);
}
}
}
/** Feed a configuration variable space to the reaction framework.
* Consequent calls with the same space will only communicate
* actual changes. */
void opticonf_handle_config (var *conf) {
pathnode *T = &OPTICONF_ROOT;
opticonf_handle (conf, T);
}
|
C++
|
UTF-8
| 1,881 | 2.671875 | 3 |
[] |
no_license
|
#include "AvailabilityServer.h"
#include "Socket.h"
#include "Utils.h"
#include <string>
#include <iostream>
#include <intrin.h>
using namespace Backend;
using namespace std;
AvailabilityServer::AvailabilityServer(IProductReader^ productReader)
{
_productReader = productReader;
_isRunning = false;
}
void AvailabilityServer::Start()
{
cout << "Starting up server" << endl;
_isRunning = true;
Socket socket(TCP);
if (!socket.Listen("127.0.0.1", 5000))
{
cout << "Unable to startup socket" << endl;
return;
}
char* buffer = new char[1024];
for(int i = 0; i < 1024; i++)
buffer[i] = 0;
cout << "Waiting for client" << endl;
while (_isRunning)
{
if (!socket.AcceptClient(100))
continue;
cout << "Client connected" << endl;
while(true)
{
// Receive the size of the Id
if(!socket.GetData(&buffer, 2))
{
cout << "No data closing connection" << endl;
socket.CloseClientConnection();
break;
}
int idSize = (buffer[1] << 8) + buffer[0];
int count = -1;
if(idSize > 0)
{
// Read the id
if(!socket.GetData(&buffer, idSize))
{
cout << "No data closing connection" << endl;
socket.CloseClientConnection();
break;
}
string productId(buffer);
cout << "Request received for productId: " << productId << endl;
// Find data
count = _productReader->GetAvailibility(gcnew System::String(productId.c_str()));
}
// Create mapping
buffer[3] = count >> 24;
buffer[2] = count >> 16;
buffer[1] = count >> 8;
buffer[0] = count;
socket.SendData(&buffer, 4);
}
if (!socket.CloseClientConnection())
{
cout << "Client connection could not be closed" << endl;
}
cout << "Client connection closed" << endl;
}
cout << "Server stopped" << endl;
}
bool AvailabilityServer::IsAlive()
{
return _isRunning;
}
void AvailabilityServer::Stop()
{
_isRunning = false;
}
|
SQL
|
UTF-8
| 751 | 3.109375 | 3 |
[] |
no_license
|
-- CREATE DATABASE itp;
-- \c itp
CREATE TABLE mqtt_message (
id SERIAL PRIMARY KEY,
topic TEXT NOT NULL,
payload TEXT,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE sensor_data (
id SERIAL PRIMARY KEY,
device VARCHAR(50),
measurement VARCHAR(50),
reading NUMERIC(6, 2),
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE sensor_data_text (
id SERIAL PRIMARY KEY,
device VARCHAR(50),
measurement VARCHAR(50),
reading TEXT,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
GRANT SELECT ON TABLE mqtt_message TO public;
GRANT SELECT ON TABLE sensor_data TO public;
GRANT SELECT ON TABLE sensor_data_text TO public;
|
Java
|
UTF-8
| 978 | 2.34375 | 2 |
[] |
no_license
|
/*
* Copyright (c) www.bugull.com
*/
package com.bugull.redis.recipes;
import com.bugull.redis.RedisConnection;
import com.bugull.redis.exception.RedisException;
import com.bugull.redis.utils.JedisUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
*
* @author Frank Wen(xbwen@hotmail.com)
*/
public abstract class AbstractListRecipe extends BaseRecipe {
public long getSize(String listName) throws RedisException {
return getSize(listName.getBytes());
}
public long getSize(byte[] listName) throws RedisException {
long size = 0;
JedisPool pool = RedisConnection.getInstance().getPool();
Jedis jedis = null;
try{
jedis = pool.getResource();
size = jedis.llen(listName);
}catch(Exception ex){
throw new RedisException(ex.getMessage(), ex);
}finally{
JedisUtil.returnToPool(pool, jedis);
}
return size;
}
}
|
Java
|
UTF-8
| 3,056 | 2.3125 | 2 |
[] |
no_license
|
package com.itheima.dao;
import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class IUserDaoTest {
/**
* 初始化方法
*/
private InputStream in;
private SqlSession sqlSession;
@Before
public void init() throws IOException {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
sqlSession = sqlSessionFactory.openSession();
}
/**
* 结束方法
*/
@After
public void destory() throws IOException {
in.close();
sqlSession.commit();
sqlSession.close();
}
/**
* 查询所有
* @throws IOException
*/
@Test
public void findAlltest() throws IOException {
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
List<User> users = userDao.findAll();
for(User u:users){
System.out.println("u = " + u);
}
}
/**
* 插入
*/
@Test
public void insertUserTest(){
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User user = new User();
user.setAddress("湖北潜江");
user.setBirthday(new Date());
user.setSex("男");
user.setUsername("大哥");
userDao.insert(user);
System.out.println("user = " + user);
}
/**
* 更新
*/
@Test
public void updateUserTest(){
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User user = new User();
user.setUsername("pengzihao");
user.setAddress("qianjiang");
user.setSex("男");
user.setBirthday(new Date());
user.setId(41);
userDao.update(user);
}
/**
* 根据id删除用户
*/
@Test
public void deleteUserTest(){
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
userDao.deleteUser(41);
}
/**
* 根据id查询用户
*/
@Test
public void queryUserTest(){
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
User u = userDao.QueryById(42);
System.out.println("u = " + u);
}
/**
* 根据名称模糊查询
*/
@Test
public void QueryByNameTest(){
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
List<User> userList = userDao.QueryByName("%王%");
System.out.println("userList = " + userList);
}
/**
* 查询总用户数
*/
@Test
public void QueryTotalTest(){
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
int total = userDao.QueryTotal();
System.out.println("total = " + total);
}
}
|
Markdown
|
UTF-8
| 8,103 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# MSBuild.Xrm.SourceControl
## Releases
## 2.0.0
Added Environment variable to support multiple extracts for people who work across multiple projects environments
## 1.0.4
Initial release supporting Extract of Customisations.
**Build and Release Status**: 
## Description
MSBuild.Xrm.SourceControl provides a simple but powerful method for extracting Dynamics 365 customisations. The extension uses PowerShell scripts that can seamlessly extract customisations from a Dynamics 365 instance and then subsequently rebuild them into a zipped Solution file ready for import when necessary.
The scripts use the *SolutionPackager.exe* tool provided by the Dynamics 365 SDK. It supports file mappings, managed and unmanaged solutions, and the export of AutoNumber and Calendar settings.
MSBuild.Xrm.SourceControl extends the MSBuild process for the Clean and AfterBuild targets:
1. **Clean** - Executes a custom PowerShell script to export solution files from Dynamics and unpack them with *SolutionPackager.exe* to the "Src" folder.
2. **AfterBuild** - Executes a custom PowerShell script to pack the "Src" folder into Managed (for Release configuration) and Unmanaged (for Release and Debug configuration) Dynamics solution files using *SolutionPackager.exe*.
## Table of Contents
* [Installation](#Installation)
* [Usage](#Usage)
* [Contributing](#Contributing)
* [Credits](#Credits)
* [License](#License)
## Installation
### Prerequisites
* Minimum .NET Framework: 4.5.1
* PowerShell 4.0+
Create a new class project in Visual Studio and install this extension by either searching for "MSBuild.Xrm.SourceControl" from 'Manage Nuget Packages' or run the command line `Install-Package MSBuild.Xrm.SourceControl` in the 'Package Manager Console'.
More detailed installation instructions can be found on the [wiki](https://github.com/Capgemini/msbuild-xrm-sourcecontrol/wiki).
## Usage
The configuration shown below demonstrates a basic setup to extract the customisations into source control.
### Configuration
When the [Nuget package](https://www.nuget.org/packages/MsBuild.Xrm.SourceControl/) is first installed, two configuration files will be added into the project.
#### CrmConfiguration.props
##### Default Values
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<CrmSolutionName>NOT_DEFINED</CrmSolutionName>
<CrmConnectionString>AuthType=OAuth;Url=url; Username=user; Password=password;ClientId=clientid;RedirectUri=redirectUri;</CrmConnectionString>
<ExportAutoNumberSettings>0</ExportAutoNumberSettings>
<ExportCallendarSettings>0</ExportCallendarSettings>
</PropertyGroup>
</Project>
```
The first step is to populate the values for each of the elements:
- **CrmSolutionName**: The Name of the Dynamics Solution
- **CrmConnectionString**: The connection string that will be used to connect to the Dynamics instance, for more information, see [here](https://msdn.microsoft.com/en-gb/library/mt608573.aspx?f=255&MSPPError=-2147217396)
- **ExportAutoNumberSettings**: Option for whether to Export the AutoNumber Settings for the Solution, 0 for No, 1 for Yes
- **ExportCallendarSettings**: Option for whether to Export the Calendar Settings for the Solution, 0 for No, 1 for Yes
#### MappingFile.xml
##### Default Values
```xml
<?xml version="1.0" encoding="utf-8"?>
<Mapping>
</Mapping>
```
The Mapping configuration is used when the Solution is being rebuilt from the extracted files. The mapping file can define mappings between a file that is contained in the extracted solution files, to a file that is in another location on the file system. An example usage of this is for Web Resources, but it can also be used for compiled solution components such as Plugin .dll files. When the solution is being built, the mapped files will be used instead of the ones already in the solution. This is to try to make sure that the latest version of the files are used.
##### Example
```xml
<?xml version="1.0" encoding="utf-8"?>
<Mapping>
<FileToPath map="WebResources\*.*" to="..\..\XXX.Base.CrmPackage\WebResources\**" />
<FileToPath map="WebResources\**\*.*" to="..\..\XXX.Base.CrmPackage\WebResources\**" />
<FileToFile map="Capgemini.Base.Workflows.dll" to="..\..\XXX.Base.Workflows\bin\**\Capgemini.Base.Workflows.dll" />
<FileToFile map="Capgemini.Base.Plugins.dll" to="..\..\XXX.Base.Plugins\bin\**\Capgemini.Base.Plugins.dll" />
</Mapping>
```
You can either use the FileToPath or FileToFile elements to map a collection of files or just a single file.
### Solution Extraction
The installation of the Nuget package will modify the .csproj file to add tasks into the project build process. When the "Clean" command is run on the project, the `ExtractCrmCustomizations.ps1` PowerShell script will be executed using the configuration files that are mentioned on the [Setup page](https://github.com/Capgemini/msbuild-xrm-sourcecontrol/wiki/Setup) to connect to Dynamics and extract the solution files into the "Src" folder of the project.

**NOTE**: It is not recommended to select the 'Include in Project' option for the Src folder or any of its contents, as this will lead to unnecessary modifications to the project file every time a "Clean" is performed. Instead it is recommended to simply use the "Show All Files" button, to show the files. 
The "Src" folder and its contents should be included in Source Control. Every time the "Clean" command is executed, and the changes are synced, a history will be built in Source Control giving more visibility of changes.
### Solution Build
When the "Build" command is run on the project, the `BuildCrmCustomizations.ps1` PowerShell script will be executed using the configuration files that are previously mentioned and pack the solution files in the "Src" folder into a Dynamics Solution file. There are two different types of Dynamics solution, Managed or Unmanaged. If the Build Configuration in Visual Studio is set to Debug, only the Unmanaged version of the Dynamics solution will be built, if the Build Configuration is set to Release, both Managed and Unmanaged versions will be built.
The built solution files will be output to the project's "bin" folder. Ready to be manually deployed to another environment or used in an automated CI process:

#### Use in CI Pipeline
As the extensions are for MSBuild, they can be used not only through Visual Studio, but anywhere that MSBuild can be executed, this means that the rebuilding of the solution files can be done and is recommended to be done through a CI pipeline, such as those available in Azure DevOps:

**NOTE**: You may need to include the */bin/coretools/* folder and its contents into Source Control for this to work. For git repositories, this would involve editing your git.ignore file.

## Contributing
The source code for the extension will be made available soon. All contributions will be appreciated.
To contact us, please email [nuget.uk@capgemini.com](mailto:nuget.uk@capgemini.com).
## Credits
Capgemini UK Microsoft Team
This extension uses the excellent [Microsoft.Xrm.Data.Powershell](https://github.com/seanmcne/Microsoft.Xrm.Data.PowerShell), by [seanmcne](https://github.com/seanmcne).
## License
[MIT](https://github.com/Capgemini/msbuild-xrm-sourcecontrol/blob/master/LICENSE)
|
Python
|
UTF-8
| 316 | 3.71875 | 4 |
[] |
no_license
|
#Raul Conover
total_secs = int(input("How many seconds, in total? "))
hours = total_secs //3600
secs_still_remaining = total_secs %3600
minutes = secs_still_remaining //60
secs_finally_remaining = secs_still_remaining %60
print("Hours = ", hours, " minutes = ", minutes, " seconds = ", secs_finally_remaining)
|
C
|
UTF-8
| 161 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
int main(){
int n,a[100],i=0;
scanf("%d",&n);
while(i<n){
scanf("%d",&a[i]);
i++;
}
while(i>0){
i--;
printf("%d\n",a[i]);
}
}
|
C
|
UTF-8
| 3,137 | 2.546875 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parsing.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rhallste <rhallste@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/16 00:08:39 by rhallste #+# #+# */
/* Updated: 2018/03/18 01:04:59 by rhallste ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "../libft/inc/libft.h"
#include "../inc/fdf.h"
static size_t array_len(char **words)
{
size_t count;
count = 0;
while (words[count])
count++;
return (count);
}
static unsigned int get_color(char *hex)
{
unsigned int color;
char *hex_key;
int i;
char *pos;
int len;
hex_key = "0123456789abcdef";
color = 0;
ft_strtolow(hex);
len = ft_strlen(hex) - 2;
hex += 2;
i = 0;
while (i < len)
{
color <<= 4;
pos = ft_strchr(hex_key, hex[i]);
if (pos)
color |= pos - hex_key;
i++;
}
return (color);
}
static t_fdf_point3d set_point(unsigned int i, int line_index,
char *alt_str)
{
char **param_split;
t_fdf_point3d point;
point.x = i * FDF_POINT_SEP;
point.y = line_index * FDF_POINT_SEP;
param_split = ft_strsplit(alt_str, ',');
point.z = ft_atoi(param_split[0]) * FDF_POINT_SEP;
point.color = (param_split[1]) ? get_color(param_split[1]) : 0xffffff;
ft_free_2d_array((void ***)¶m_split, (param_split[1]) ? 2 : 1);
return (point);
}
static t_fdf_point3d *get_line_points(int fd, unsigned int *width,
int line_index)
{
char *line;
t_fdf_point3d *points;
char **alt_strs;
unsigned int i;
if ((get_next_line(fd, &line)) < 1)
return (NULL);
alt_strs = ft_strsplit(line, ' ');
free(line);
if (line_index == 0)
*width = array_len(alt_strs);
if (!(points = ft_memalloc(sizeof(t_fdf_point3d) * *width)))
return (NULL);
i = 0;
while (i < *width && alt_strs[i])
{
points[i] = set_point(i, line_index, alt_strs[i]);
i++;
}
ft_free_2d_array((void ***)&alt_strs, i);
if (i < *width)
fdf_shortline_error();
return (points);
}
t_fdf_point3d **fdf_parse_file(int fd, unsigned int *width,
unsigned int *height)
{
t_fdf_point3d *line_points;
t_fdf_point3d **points;
size_t arsz_new;
size_t arsz_old;
if (!(points = ft_memalloc(sizeof(t_fdf_point3d *))))
return (NULL);
*height = 0;
arsz_old = 0;
while ((line_points = get_line_points(fd, width, *height)))
{
arsz_new = arsz_old + sizeof(t_fdf_point3d *);
if (!(points = ft_memrealloc((void *)points, arsz_new, arsz_old)))
return (NULL);
arsz_old = arsz_new;
points[*height] = line_points;
(*height)++;
}
return (points);
}
|
Java
|
UTF-8
| 524 | 2.109375 | 2 |
[] |
no_license
|
public /*explicit*/ redecl_iterator(redecl_iterator<decl_type> $Prm0) {
//START JInit
this.Current = $Prm0.Current;
this.Starter = $Prm0.Starter;
this.PassedFirst = $Prm0.PassedFirst;
//END JInit
}
@Override
public boolean $eq(Object other) {
return $eq_redecl_iterator(this, (redecl_iterator)other);
}
@Override
public boolean $noteq(Object other) {
return $noteq_redecl_iterator(this, (redecl_iterator)other);
}
@Override public redecl_iterator<decl_type> clone() {
return new redecl_iterator(this);
}
|
SQL
|
UTF-8
| 178 | 2.609375 | 3 |
[] |
no_license
|
SELECT timeStamp, temperature FROM ThermometerOBSERVATION o
WHERE timestamp>'2017-11-18T08:35:00Z' AND timestamp<'2017-11-19T08:35:00Z' AND temperature>=12 AND temperature<=48
|
Python
|
UTF-8
| 2,690 | 2.875 | 3 |
[] |
no_license
|
import sklearn
from sklearn.neural_network import MLPClassifier
from sklearn.neural_network import MLPRegressor
from sklearn import datasets, linear_model
import cPickle
from emotion import *
# Returns a classifier that analyzes the correlation between data.
def trainOnData(data):
X = [pair[0] for pair in data]
Y = [pair[1] for pair in data]
#clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(15,), random_state=1)
clf = MLPRegressor(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(15,), random_state=1)
clf.fit(X, Y)
return clf
# Parses emotion from the return value of the Microsoft Emotion API.
def parseEmotion(data):
best = 0
for i in range(1, len(data)):
if data[i]['faceRectangle']['width'] > data[best]['faceRectangle']['width']:
best = i
print("Target face is number " + str(best + 1) + " of " + str(len(data)))
return [data[best]['scores'][em] for em in emotions]
# Makes a prediction about a vector based on a classifier.
def makePrediction(clf, vec):
return clf.predict([vec])[0]
def saveClassifier(filename, clf):
with open(filename, 'wb') as fid:
cPickle.dump(clf, fid)
def loadClassifier(filename):
with open(filename, 'rb') as fid:
return cPickle.load(fid)
def rebuildClassifier():
# Input is [sad, happy, disgust, anger, surprise, fear, neutral, contempt]
# Output is [rap, hardrock, metal, classical, jazz, pop, classrock, edm, country]
X = [
[1, 0, 0, 0, 0, 0, 0, 0], # Sad
[1, 0, 0, 0, 0, 0, 0, 0], # Sad
[1, 0, 0, 0, 0, 0, 0, 0], # Sad
[0, 1, 0, 0, 0, 0, 0, 0], # Happy
[0, 1, 0, 0, 0, 0, 0, 0], # Happy
[0, 1, 0, 0, 0, 0, 0, 0], # Happy
[0, 0, 0, 1, 0, 0, 0, 0], # Angry
[0, 0, 0, 1, 0, 0, 0, 0], # Angry
[0, 0, 0, 1, 0, 0, 0, 0], # Angry
[0, 0, 0, 0, 0, 0, 1, 0], # Neutral
[0, 0, 0, 0, 0, 0, 1, 0], # Neutral
[0, 0, 0, 0, 0, 0, 1, 0] # Neutral
]
Y = [
[0, 0, 0, 1, 0, 0, 0, 0, 0], # Sad
[0, 0, 0, 0, 1, 0, 0, 0, 0], # Sad
[0, 0, 0, 0, 0, 0, 0, 0, 1], # Sad
[0, 0, 0, 0, 0, 1, 0, 0, 0], # Happy
[0, 0, 0, 0, 0, 0, 1, 0, 0], # Happy
[0, 0, 0, 0, 0, 0, 0, 1, 0], # Happy
[1, 0, 0, 0, 0, 0, 0, 0, 0], # Angry
[0, 1, 0, 0, 0, 0, 0, 0, 0], # Angry
[0, 0, 1, 0, 0, 0, 0, 0, 0], # Angry
[0, 0, 0, 0, 0, 0, 1, 0, 0], # Neutral
[0, 0, 0, 0, 0, 0, 0, 1, 0], # Neutral
[0, 0, 0, 0, 0, 0, 0, 0, 1] # Neutral
]
clf = trainOnData([(X[i], Y[i]) for i in range(len(Y))])
saveClassifier('./classifier.pkl', clf)
|
Markdown
|
UTF-8
| 13,840 | 2.640625 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: "教程:Azure Active Directory 与 Grovo 集成 | Microsoft Docs"
description: "了解如何在 Azure Active Directory 和 Grovo 之间配置单一登录。"
services: active-directory
documentationCenter: na
author: jeevansd
manager: femila
ms.reviewer: joflore
ms.assetid: 399cecc3-aa62-4914-8b6c-5a35289820c1
ms.service: active-directory
ms.workload: identity
ms.tgt_pltfrm: na
ms.devlang: na
ms.topic: article
ms.date: 10/30/2017
ms.author: jeedes
ms.openlocfilehash: 66e5731d185399267a581e5c6b2485fb4fc7f503
ms.sourcegitcommit: e5355615d11d69fc8d3101ca97067b3ebb3a45ef
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 10/31/2017
---
# <a name="tutorial-azure-active-directory-integration-with-grovo"></a>教程:Azure Active Directory 与 Grovo 集成
在本教程中,了解如何将 Grovo 与 Azure Active Directory (Azure AD) 集成。
将 Grovo 与 Azure AD 集成提供以下优势:
- 可在 Azure AD 中控制谁有权访问 Grovo。
- 可使用户通过其 Azure AD 帐户自动登录 Grovo(单一登录)。
- 可在中心位置(即 Azure 门户)管理帐户。
如需了解有关 SaaS 应用与 Azure AD 集成的详细信息,请参阅 [Azure Active Directory 的应用程序访问与单一登录是什么](active-directory-appssoaccess-whatis.md)。
## <a name="prerequisites"></a>先决条件
若要配置 Azure AD 与 Grovo 的集成,需要准备好以下各项:
- 一个 Azure AD 订阅
- 已启用 Grovo 单一登录的订阅
> [!NOTE]
> 不建议使用生产环境测试本教程中的步骤。
测试本教程中的步骤应遵循以下建议:
- 除非必要,请勿使用生产环境。
- 如果没有 Azure AD 试用环境,可以[获取一个月的试用版](https://azure.microsoft.com/pricing/free-trial/)。
## <a name="scenario-description"></a>方案描述
在本教程中,将在测试环境中测试 Azure AD 单一登录。 本教程中概述的方案包括两个主要构建基块:
1. 从库中添加 Grovo
2. 配置并测试 Azure AD 单一登录
## <a name="adding-grovo-from-the-gallery"></a>从库中添加 Grovo
若要配置 Grovo 与 Azure AD 的集成,需要从库中将 Grovo 添加到托管 SaaS 应用列表。
**若要从库中添加 Grovo,请执行以下步骤:**
1. 在 **[Azure 门户](https://portal.azure.com)**的左侧导航面板中,单击“Azure Active Directory”图标。
![“Azure Active Directory”按钮][1]
2. 导航到“企业应用程序”。 然后转到“所有应用程序”。
![企业应用程序][2]
3. 若要添加新应用程序,请单击对话框顶部的“新建应用程序”按钮。
![“新建应用程序”按钮][3]
4. 在搜索框中,键入“Grovo”,在结果面板中选择“Grovo”,然后单击“添加”按钮添加该应用程序。

## <a name="configure-and-test-azure-ad-single-sign-on"></a>配置和测试 Azure AD 单一登录
在本部分中,基于一个名为“Britta Simon”的测试用户使用 Grovo 配置和测试 Azure AD 单一登录。
若要运行单一登录,Azure AD 需要知道与 Azure AD 用户相对应的 Grovo 用户。 换句话说,需要建立 Azure AD 用户与 Grovo 中相关用户之间的链接关系。
在 Grovo 中,将 Azure AD 中“用户名”的值指定为“用户名”的值来建立此关联。
若要配置和测试 Grovo 的 Azure AD 单一登录,需要完成以下构建基块:
1. **[配置 Azure AD 单一登录](#configure-azure-ad-single-sign-on)** - 使用户能够使用此功能。
2. **[创建 Azure AD 测试用户](#create-an-azure-ad-test-user)** - 使用 Britta Simon 测试 Azure AD 单一登录。
3. **[创建 Grovo 测试用户](#create-a-grovo-test-user)** - 在 Grovo 中创建 Britta Simon 的对应用户,并将其链接到用户的 Azure AD 表示形式。
4. **[分配 Azure AD 测试用户](#assign-the-azure-ad-test-user)** - 使 Britta Simon 能够使用 Azure AD 单一登录。
5. **[测试单一登录](#test-single-sign-on)** - 验证配置是否正常工作。
### <a name="configure-azure-ad-single-sign-on"></a>配置 Azure AD 单一登录
在本部分中,将介绍如何在 Azure 门户中启用 Azure AD 单一登录并在 Grovo 应用程序中配置单一登录。
**若要配置 Grovo 的 Azure AD 单一登录,请执行以下步骤:**
1. 在 Azure 门户中的 Grovo 应用程序集成页上,单击“单一登录”。
![配置单一登录链接][4]
2. 在“单一登录”对话框中,选择“基于 SAML 的单一登录”作为“模式”以启用单一登录。

3. 在“Grovo 域和 URL”部分中,如果要在“IDP”发起的模式下配置应用程序,请执行以下步骤:

a. 在“标识符”文本框中,使用以下模式键入 URL:`https://<subdomain>.grovo.com/sso/saml2/metadata`
b. 在“回复 URL”文本框中,使用以下模式键入 URL:`https://<subdomain>.grovo.com/sso/saml2/saml-assertion`
4. 选中“显示高级 URL 设置”,执行以下步骤:

a. 在“中继状态”文本框中,使用以下格式键入 URL:`https://<subdomain>.grovo.com`
b. 如果要在“SP”发起的模式下配置应用程序,请执行以下步骤:

在“登录 URL”文本框中,使用以下模式键入 URL:`https://<subdomain>.grovo.com/sso/saml2/saml-assertion`
> [!NOTE]
> 这些不是实际值。 请使用标识符、回复 URL、登录 URL 和中继状态更新这些值。 若要获取这些值,请联系 [Grovo 支持团队](https://www.grovo.com/contact-us)。
5. Grovo 应用程序需要特定格式的 SAML 断言。 请为此应用程序配置以下声明。 可以在应用程序集成页的“用户属性”部分管理这些属性的值。 以下屏幕截图显示一个示例。

6. 在“单一登录”对话框的“用户属性”部分,按图中所示配置 SAML 令牌属性,然后执行以下步骤:
| 属性名称 | 属性值 |
| ------------------- | -------------------- |
| 名字 | user.givenname |
| 姓氏 | user.surname |
a. 单击“添加属性”,打开“添加属性”对话框。


b. 在“名称”文本框中,键入为该行显示的属性名称。
c. 在“值”列表中,选择为该行显示的属性值。
d. 单击“确定” 。
7. 在“SAML 签名证书”部分中,单击“证书(base64)”,并在计算机上保存证书文件。

8. 单击“保存”按钮。

9. 在“Grovo 配置”部分,单击“配置 Grovo”打开“配置登录”窗口。 从“快速参考”部分中复制“SAML 实体 ID 和 SAML 单一登录服务 URL”。

10. 在另一个 Web 浏览器窗口中,以管理员身份登录到 Grovo。
11. 转到“管理” > “集成”。

12. 单击“SP 发起的 SAML 2.0”部分下的“设置”。

13. 在“SP 发起的 SAML 2.0”弹出窗口中执行以下步骤:

a. 将从 Azure 门户复制的“SAML 实体 ID”值粘贴到“实体 ID”文本框中。
b. 在“单一登录服务终结点”文本框中,粘贴从 Azure 门户复制的“SAML 单一登录服务 URL”值。
c. 为“单一登录服务终结点绑定”选择 `urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect`。
d.单击“下一步”。 在记事本中打开从 Azure 门户下载的 **Base64 编码证书**,将其粘贴到“公钥”文本框中。
e.在“新建 MySQL 数据库”边栏选项卡中,接受法律条款,并单击“确定”。 单击“下一步”。
> [!TIP]
> 之后在设置应用时,就可以在 [Azure 门户](https://portal.azure.com)中阅读这些说明的简明版本了! 从“Active Directory”>“企业应用程序”部分添加此应用后,只需单击“单一登录”选项卡,即可通过底部的“配置”部分访问嵌入式文档。 可在此处阅读有关嵌入式文档功能的详细信息:[ Azure AD 嵌入式文档]( https://go.microsoft.com/fwlink/?linkid=845985)
### <a name="create-an-azure-ad-test-user"></a>创建 Azure AD 测试用户
本部分的目的是在 Azure 门户中创建名为 Britta Simon 的测试用户。
![创建 Azure AD 测试用户][100]
**若要在 Azure AD 中创建测试用户,请执行以下步骤:**
1. 在 Azure 门户的左窗格中,单击“Azure Active Directory”按钮。

2. 若要显示用户列表,请转到“用户和组”,然后单击“所有用户”。

3. 若要打开“用户”对话框,在“所有用户”对话框顶部单击“添加”。

4. 在“用户”对话框中,执行以下步骤:

a.在“横幅徽标”下面,选择“删除上传的徽标”。 在“姓名”框中,键入“BrittaSimon”。
b.保留“数据库类型”设置,即设置为“共享”。 在“用户名”框中,键入用户 Britta Simon 的电子邮件地址。
c. 选中“显示密码”复选框,然后记下“密码”框中显示的值。
d. 单击“创建” 。
### <a name="create-a-grovo-test-user"></a>创建 Grovo 测试用户
本部分的目的是在 Grovo 中创建名为 Britta Simon 的用户。 Grovo 支持默认启用的实时预配。 此部分不存在任何操作项。 如果新用户尚不存在,可在尝试访问 Grovo 期间创建该用户。
>[!Note]
>如果需要手动创建用户,请联系 [Grovo 支持团队](https://www.grovo.com/contact-us)。
### <a name="assign-the-azure-ad-test-user"></a>分配 Azure AD 测试用户
在本部分中,通过授予 Britta Simon 访问 Grovo 的权限,使其能够使用 Azure 单一登录。
![分配用户角色][200]
**若要将 Britta Simon 分配到 Grovo,请执行以下步骤:**
1. 在 Azure 门户中打开应用程序视图,导航到目录视图,接着转到“企业应用程序”,并单击“所有应用程序”。
![分配用户][201]
2. 在应用程序列表中,选择“Grovo”。

3. 在左侧菜单中,单击“用户和组”。
![“用户和组”链接][202]
4. 单击“添加”按钮。 然后在“添加分配”对话框中选择“用户和组”。
![“添加分配”窗格][203]
5. 在“用户和组”对话框的“用户”列表中,选择“Britta Simon”。
6. 在“用户和组”对话框中单击“选择”按钮。
7. 在“添加分配”对话框中单击“分配”按钮。
### <a name="test-single-sign-on"></a>测试单一登录
在本部分中,使用访问面板测试 Azure AD 单一登录配置。
在访问面板中单击 Grovo 磁贴时,应会自动登录到 Grovo 应用程序。
有关访问面板的详细信息,请参阅 [Introduction to the Access Panel](active-directory-saas-access-panel-introduction.md)(访问面板简介)。
## <a name="additional-resources"></a>其他资源
* [有关如何将 SaaS 应用与 Azure Active Directory 集成的教程列表](active-directory-saas-tutorial-list.md)
* [Azure Active Directory 的应用程序访问与单一登录是什么?](active-directory-appssoaccess-whatis.md)
<!--Image references-->
[1]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_01.png
[2]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_02.png
[3]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_03.png
[4]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_04.png
[100]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_100.png
[200]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_200.png
[201]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_201.png
[202]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_202.png
[203]: ./media/active-directory-saas-grovo-tutorial/tutorial_general_203.png
|
Java
|
UTF-8
| 4,620 | 1.976563 | 2 |
[] |
no_license
|
/* */ package com.cicro.wcm.dao.zwgk.ser;
/* */
/* */ import com.cicro.util.DateUtil;
/* */ import com.cicro.wcm.bean.logs.SettingLogsBean;
/* */ import com.cicro.wcm.bean.zwgk.ser.SerCategoryBean;
/* */ import com.cicro.wcm.dao.PublicTableDAO;
/* */ import com.cicro.wcm.db.DBManager;
/* */ import java.util.HashMap;
/* */ import java.util.List;
/* */ import java.util.Map;
/* */
/* */ public class SerCategoryDAO
/* */ {
/* */ public static List<SerCategoryBean> getAllSerCategoryList()
/* */ {
/* 31 */ return DBManager.queryFList("getAllSerCategoryList", "");
/* */ }
/* */
/* */ public static SerCategoryBean getSerCategoryBean(int ser_id)
/* */ {
/* 41 */ return (SerCategoryBean)DBManager.queryFObj("getSerCategoryBean", Integer.valueOf(ser_id));
/* */ }
/* */
/* */ public static boolean insertSerCategory(SerCategoryBean scb, SettingLogsBean stl)
/* */ {
/* 52 */ if (DBManager.insert("insert_ser_category", scb))
/* */ {
/* 54 */ PublicTableDAO.insertSettingLogs("添加", "场景式服务主题节点", scb.getSer_id(), stl);
/* 55 */ return true;
/* */ }
/* 57 */ return false;
/* */ }
/* */
/* */ public static boolean updateSerCategory(SerCategoryBean scb, SettingLogsBean stl)
/* */ {
/* 68 */ if (DBManager.update("update_ser_category", scb))
/* */ {
/* 70 */ PublicTableDAO.insertSettingLogs("修改", "场景式服务主题节点", scb.getSer_id(), stl);
/* 71 */ return true;
/* */ }
/* 73 */ return false;
/* */ }
/* */
/* */ public static boolean updateSerCategoryStatus(String ser_ids, String publish_status, SettingLogsBean stl)
/* */ {
/* 84 */ Map m = new HashMap();
/* 85 */ m.put("ser_ids", ser_ids);
/* 86 */ m.put("publish_status", publish_status);
/* 87 */ if ("0".equals(publish_status))
/* 88 */ m.put("publish_time", "");
/* */ else
/* 90 */ m.put("publish_time", DateUtil.getCurrentDateTime());
/* 91 */ if (DBManager.update("update_ser_category_status", m))
/* */ {
/* 93 */ PublicTableDAO.insertSettingLogs("修改", "场景式服务主题节点发布状态", ser_ids, stl);
/* 94 */ return true;
/* */ }
/* 96 */ return false;
/* */ }
/* */
/* */ public static boolean sortSerCategory(String ids, SettingLogsBean stl)
/* */ {
/* */ try
/* */ {
/* 108 */ Map m = new HashMap();
/* 109 */ String[] tempA = ids.split(",");
/* 110 */ for (int i = 0; i < tempA.length; i++)
/* */ {
/* 112 */ m.put("sort_id", Integer.valueOf(i + 1));
/* 113 */ m.put("ser_id", tempA[i]);
/* 114 */ DBManager.update("sort_ser_category", m);
/* */ }
/* 116 */ PublicTableDAO.insertSettingLogs("保存排序", "场景式服务主题节点", ids, stl);
/* 117 */ return true;
/* */ }
/* */ catch (Exception e)
/* */ {
/* 121 */ e.printStackTrace();
/* 122 */ }return false;
/* */ }
/* */
/* */ public static boolean moveSerCategory(Map<String, String> m, SettingLogsBean stl)
/* */ {
/* 134 */ if (DBManager.update("move_ser_category", m))
/* */ {
/* 136 */ PublicTableDAO.insertSettingLogs("移动", "场景导航目录", (String)m.get("ser_id"), stl);
/* 137 */ return true;
/* */ }
/* */
/* 140 */ return false;
/* */ }
/* */
/* */ public static boolean deleteSerCategory(String ser_ids, SettingLogsBean stl)
/* */ {
/* 151 */ Map m = new HashMap();
/* 152 */ m.put("ser_ids", ser_ids);
/* */
/* 154 */ if (DBManager.delete("delete_ser_category", m))
/* */ {
/* 157 */ DBManager.delete("delete_info_category_forSer", m);
/* 158 */ DBManager.delete("delete_info_category_model_forSer", m);
/* 159 */ PublicTableDAO.insertSettingLogs("删除", "场景式服务主题节点", ser_ids, stl);
/* 160 */ return true;
/* */ }
/* */
/* 163 */ return false;
/* */ }
/* */
/* */ public static boolean updateSerTemplateContent(String template_content_id)
/* */ {
/* 173 */ return DBManager.delete("update_category_model_forSer", template_content_id);
/* */ }
/* */ }
/* Location: C:\Users\Administrator\Desktop\wcm\shared\classes.zip
* Qualified Name: classes.com.cicro.wcm.dao.zwgk.ser.SerCategoryDAO
* JD-Core Version: 0.6.2
*/
|
C++
|
UTF-8
| 4,242 | 3.046875 | 3 |
[] |
no_license
|
#include "Game.h"
//functions private
void Game::initVariables() {
this->window = nullptr;
this->points = 0;
this->tiles = 16;
this->ballPositionX = 5;
this->ballPositionY = 2;
srand(time(NULL));
}
void Game::initWindow() {
this->videoMode.height = 600;
this->videoMode.width = 800;
this->window = new sf::RenderWindow(this->videoMode, "Game", sf::Style::Titlebar | sf::Style::Close);
//fps, limit 60, to smooth
this->window->setFramerateLimit(60);
}
//init platform, otherwise player
void Game::initPlatform() {
this->platform.setPosition(300.f, 550.f);
this->platform.setSize(sf::Vector2f(200.f, 10.f));
this->platform.setFillColor(sf::Color::White);
}
void Game::initCircle() {
this->ball.setRadius(10.f);
this->ball.setPosition(0.f, 80.f);
}
void Game::initTiles() {
int positionX = 0;
int positionY = 0;
for (int i = 0; i < this->tiles; i++) {
sf::RectangleShape tile;
tile.setSize(sf::Vector2f(195.f, 25.f));
tile.setFillColor(sf::Color(rand() %255 + 1, rand() % 255 + 1, rand() % 255 + 1));
tile.setOutlineThickness(5.f);
tile.setOutlineColor(sf::Color::Black);
tile.setPosition(positionX, positionY);
this->tileArray.push_back(tile);
if (positionX > 800.f) {
positionX = 0;
positionY += 30;
}
else positionX += 200.f;
}
}
//Construcots / Destructors
//init all game resources
Game::Game() {
this->initVariables();
this->initWindow();
this->initPlatform();
this->initCircle();
this->initTiles();
}
Game::~Game() {
//cleaning memory
delete this->window;
}
//Accesors
const bool Game::getWindowIsOpen() const {
return this -> window -> isOpen();
}
//control plaftorm functions and also public functions
void Game::movePlatformLeft() {
if (this->platform.getPosition().x > 0.f) {
this->platform.move(-25, 0);
}
}
void Game::movePlatformRigth() {
if (this->platform.getPosition().x < 600.f) {
this->platform.move(25, 0);
}
}
void Game::jumpingBall()
{
//OX parametrs
if (this->ball.getPosition().x > 760.f)
this->ballPositionX = -5;
else if (this->ball.getPosition().x < 0.f)
this->ballPositionX = 5;
//OY parametrs
if (this->ball.getPosition().y > 560.f) {
this->window->close();
printf("You lose :(\n");
}
else if (this->ball.getPosition().y < 0.f)
this->ballPositionY = rand() % 5 + 1;
//rendering ball
this->ball.move(ballPositionX, ballPositionY);
}
void Game::checkCollisionPlatformWithBall() {
if (this->ball.getGlobalBounds().intersects(this->platform.getGlobalBounds())) {
this->ballPositionY = (rand() % 5 + 1) - 5;
}
}
void Game::checkCollisionBallWithTile() {
for (int i = 0; i < this->tileArray.size(); i++) {
if (this->ball.getGlobalBounds().intersects(this->tileArray[i].getGlobalBounds())) {
printf("%d position\n", i + 1);
this->tileArray.erase(this->tileArray.begin() + i);
this->ballPositionY = rand() % 5 + 1;
}
}
}
//Checking the game status
void Game::checkWinStatus() {
if (this->tileArray.size() == 0) {
printf("You win the game! Congratulations!\n");
this->window->close();
}
}
//functions public
void Game::poolEvents()
{
//event pooling
while (this -> window ->pollEvent(this->event)) {
switch (this->event.type) {
case sf::Event::Closed:
this->window->close();
break;
case sf::Event::KeyPressed:
if (this->event.key.code == sf::Keyboard::Escape)
this->window->close();
else if (this->event.key.code == sf::Keyboard::A)
this->movePlatformLeft();
else if (this->event.key.code == sf::Keyboard::D)
this->movePlatformRigth();
break;
}
}
}
//updating all important functions and objects
void Game::update()
{
this->poolEvents();
this->jumpingBall();
this->checkCollisionPlatformWithBall();
this->checkCollisionBallWithTile();
this->checkWinStatus();
}
void Game::renderTiles() {
/*
@return void
returning all the tiles on the top bar
*/
for (int i = 0; i < this->tileArray.size(); i++) {
this->window->draw(tileArray[i]);
}
}
void Game::render()
{
/*
* @return void
*
* - clearing old frame
* - rendering objects
* - display new frame
*/
this->window->clear();
//drawing game
this->window->draw(this->platform);
this->window->draw(this->ball);
this->renderTiles();
this->window->display();
}
|
PHP
|
UTF-8
| 493 | 2.59375 | 3 |
[] |
no_license
|
--TEST--
Test retrieving the SVM training parameters.
--SKIPIF--
<?php
if (!extension_loaded('svm')) die('skip');
?>
--FILE--
<?php
$svm = new svm();
$params = $svm->getOptions();
if(count($params) > 2) {
echo "ok 1\n";
} else {
echo "retrieving params failed";
}
if(isset($params[SVM::OPT_CACHE_SIZE])) {
echo "ok 2\n";
} else {
echo "missing cache size";
}
if($params[SVM::OPT_CACHE_SIZE] == 100) {
echo "ok 3\n";
} else {
echo "invalid cache size";
}
?>
--EXPECT--
ok 1
ok 2
ok 3
|
JavaScript
|
UTF-8
| 1,211 | 2.640625 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import './App.css';
import Clock from './clock';
import Heading from './heading';
import Stopwatch from './stopwatch';
class App extends Component{
constructor(props){
super(props);
this.state={
deadline:'',
newDeadline:'',
timerNumber:null,
newTimer:null
}
}
changeDeadline(){
this.setState({deadline:this.state.newDeadline})
}
changeTimer(){
this.setState({timerNumber:this.state.newTimer})
}
render(){
return ( <div className="App">
<Heading />
<div>
<div className="date">{this.state.deadline}</div>
<Clock deadLine={this.state.deadline} />
</div>
<div>
<input
onChange={event=>this.setState({newDeadline:event.target.value})} placeholder="dd month yyyy" />
<button onClick={()=>this.changeDeadline()}>Submit</button>
</div>
<div className="timer-display">{this.state.timerNumber}</div>
<Stopwatch timer={this.state.timerNumber} />
<input
onChange={event=>this.setState({newTimer:event.target.value})} placeholder="Enter in seconds" />
<button onClick={()=>this.changeTimer()}>Submit</button>
</div>);
}
}
export default App;
|
Java
|
UTF-8
| 13,577 | 1.945313 | 2 |
[] |
no_license
|
package com.bsl.service.user.impl;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.bsl.common.pojo.BSLException;
import com.bsl.common.pojo.EasyUIDataGridResult;
import com.bsl.common.utils.BSLResult;
import com.bsl.common.utils.JsonUtils;
import com.bsl.dao.JedisClient;
import com.bsl.mapper.BslUserInfoMapper;
import com.bsl.mapper.BslUsertypeInfoMapper;
import com.bsl.pojo.BslUserInfo;
import com.bsl.pojo.BslUserInfoExample;
import com.bsl.pojo.BslUserInfoExample.Criteria;
import com.bsl.pojo.BslUsertypeInfo;
import com.bsl.pojo.BslUsertypeInfoExample;
import com.bsl.select.ErrorCodeInfo;
import com.bsl.select.QueryExample;
import com.bsl.service.user.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.CaseFormat;
/**
* 用户管理
*
* @author huangyl
*
*/
@Service
public class UserServiceImpl implements UserService {
private static Logger log = Logger.getLogger(UserServiceImpl.class);
@Autowired
private BslUserInfoMapper bslUserInfoMapper;
@Autowired
private BslUsertypeInfoMapper bslUserTypeMapper;
@Autowired
private JedisClient jedisClient;
@Value("${REDIS_USER_SESSION_KEY}")
private String REDIS_USER_SESSION_KEY;
@Value("${SSO_SESSION_EXPIRE}")
private Integer SSO_SESSION_EXPIRE;
@Value("${SSO_DOMAIN_BASE_URL}")
private String SSO_DOMAIN_BASE_URL;
@Value("${SSO_PAGE_LOGIN_URL}")
private String SSO_PAGE_LOGIN_URL;
@Value("${REDIS_USER_ROLE_KEY}")
private String REDIS_USER_ROLE_KEY;
@Value("${REDIS_NEXT_USER_ID_KEY}")
private String REDIS_NEXT_USER_ID_KEY;
/**
* 用户信息查询
*/
@Override
public EasyUIDataGridResult getUserList(int page, int rows) {
BslUserInfoExample example = new BslUserInfoExample();
// 分页处理
PageHelper.startPage(page, rows);
example.setOrderByClause("`user_id` asc");
List<BslUserInfo> list = bslUserInfoMapper.selectByExample(example);
// 创建一个返回值对象
EasyUIDataGridResult result = new EasyUIDataGridResult();
result.setRows(list);
// 取记录总条数
PageInfo<BslUserInfo> pageInfo = new PageInfo<BslUserInfo>(list);
result.setTotal(pageInfo.getTotal());
result.setClassName("userServiceImpl");//UserServiceImpl.class.getName()
result.setMethodName("queryUserList");
return result;
}
/**
* 根据条件查询用户信息
*/
@Override
public BSLResult queryUserList(QueryExample queryExample) {
BslUserInfoExample example = new BslUserInfoExample();
if (queryExample != null) {
Criteria criteria = example.createCriteria();
if (!StringUtils.isBlank(queryExample.getUserId())) {
criteria.andUserIdLike("%"+queryExample.getUserId()+"%");
}
if (!StringUtils.isBlank(queryExample.getUserName())) {
criteria.andUserNameLike("%"+queryExample.getUserName()+"%");
}
// 分页处理
if(queryExample.getPage() != null && queryExample.getRows() != null) {
PageHelper.startPage(Integer.valueOf(queryExample.getPage()), Integer.valueOf(queryExample.getRows()));
}
//调用sql查询
if(StringUtils.isBlank(queryExample.getSort()) || StringUtils.isBlank(queryExample.getOrder())){
example.setOrderByClause("`user_id` asc");
}else{
String sortSql = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, queryExample.getSort());
if(!StringUtils.isBlank(sortSql)){
example.setOrderByClause("`"+sortSql+"` "+ queryExample.getOrder());
}
}
}
List<BslUserInfo> list = bslUserInfoMapper.selectByExample(example);
PageInfo<BslUserInfo> pageInfo = new PageInfo<BslUserInfo>(list);
return BSLResult.ok(list, "userServiceImpl", "queryUserList",pageInfo.getTotal(),list);
}
/**
* 新增用户
*/
@Override
public BSLResult register(BslUserInfo bslUserInfo) {
String userId = queryNewUserId();
bslUserInfo.setCrtDate(new Date());
bslUserInfo.setUserId(userId);
bslUserInfo.setUserStatus("0");//0-正常
bslUserInfo.setUserPassword("123456");//密码默认123456
int insert = bslUserInfoMapper.insert(bslUserInfo);
if(insert<0){
throw new BSLException(ErrorCodeInfo.错误类型_数据库错误,"sql执行异常!");
}else if(insert==0){
throw new BSLException(ErrorCodeInfo.错误类型_查询无记录,"新增失败");
}
return BSLResult.ok(userId);
}
/**
* 修改用户信息
*/
@Override
public BSLResult update(BslUserInfo bslUserInfo) {
int updateByPrimaryKeySelective = bslUserInfoMapper.updateByPrimaryKeySelective(bslUserInfo);
if(updateByPrimaryKeySelective<0){
throw new BSLException(ErrorCodeInfo.错误类型_数据库错误,"sql执行异常!");
}else if(updateByPrimaryKeySelective==0){
throw new BSLException(ErrorCodeInfo.错误类型_查询无记录,"修改失败");
}
return BSLResult.ok();
}
/**
* 删除用户信息
*/
@Override
public BSLResult delete(String userId) {
int deleteByPrimaryKey = bslUserInfoMapper.deleteByPrimaryKey(userId);
if(deleteByPrimaryKey<0){
throw new BSLException(ErrorCodeInfo.错误类型_数据库错误,"sql执行异常!");
}else if(deleteByPrimaryKey==0){
throw new BSLException(ErrorCodeInfo.错误类型_查询无记录,"删除失败");
}
return BSLResult.ok();
}
/**
* 修改密码
*/
@Override
public BSLResult editPwd(String inputUser, String oldPwd, String newPwd) {
BslUserInfo bslUserInfo = bslUserInfoMapper.selectByPrimaryKey(inputUser);
if(!oldPwd.equals(bslUserInfo.getUserPassword())){
return BSLResult.build(ErrorCodeInfo.错误类型_状态校验错误, "原密码错误!");
}
bslUserInfo.setUserPassword(newPwd);
int result = bslUserInfoMapper.updateByPrimaryKeySelective(bslUserInfo);
if(result<0){
throw new BSLException(ErrorCodeInfo.错误类型_数据库错误,"sql执行异常!");
}else if(result==0){
throw new BSLException(ErrorCodeInfo.错误类型_查询无记录,"修改密码失败");
}
return BSLResult.ok(inputUser);
}
/**
* 修改电话
*/
@Override
public BSLResult editTel(String userId, String userTel,HttpServletRequest request, HttpServletResponse response) {
BslUserInfo bslUserInfo = bslUserInfoMapper.selectByPrimaryKey(userId);
bslUserInfo.setUserTel(userTel);
int result = bslUserInfoMapper.updateByPrimaryKeySelective(bslUserInfo);
if(result<0){
throw new BSLException(ErrorCodeInfo.错误类型_数据库错误,"sql执行异常!");
}else if(result==0){
throw new BSLException(ErrorCodeInfo.错误类型_查询无记录,"修改电话号码失败");
}
//更新redis
// String token = UUID.randomUUID().toString();
HttpSession session = request.getSession();
//将数据存储到session中
String token = String.valueOf(session.getAttribute("TT_TOKEN"));
// jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(bslUserInfo));
jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
// 添加写cookie的逻辑,cookie的有效期是关闭浏览器失效。
// CookieUtils.setCookie(request, response, "TT_TOKEN", token);
return BSLResult.ok(userId);
}
/**
* 用户登录
*/
@Override
public BSLResult login(String userId, String password, HttpServletRequest request, HttpServletResponse response) {
// String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
HttpSession session = request.getSession();
//将数据存储到session中
String token = String.valueOf(session.getAttribute("TT_TOKEN"));
log.info("token:"+token);
BSLResult bslResult = getUserByToken(token);
if(bslResult != null && bslResult.getStatus() == ErrorCodeInfo.交易成功) {
BslUserInfo userInfo = (BslUserInfo) bslResult.getData();
if(userInfo != null) {
log.info("userInfo用户登录:"+userInfo);
jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
return BSLResult.ok(token);
}
}
BslUserInfo user = bslUserInfoMapper.selectByPrimaryKey(userId);
if(user == null ){
return BSLResult.build(400, "用户不存在或密码错误");
}
// 比对密码
// if(!user.getUserPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
if (!user.getUserPassword().equals(password)) {
return BSLResult.build(400, "用户不存在或密码错误");
}
if (!"0".equals(user.getUserStatus())) {
return BSLResult.build(400, "该员工账号已停用");
}
log.info("login_userId:"+userId+",pwd:"+password);
// 生成token
token = UUID.randomUUID().toString();
// 保存用户之前,把用户对象中的密码清空
user.setUserPassword(null);
//获取用户角色信息
StringBuffer sBuffer = new StringBuffer("");
BslUsertypeInfoExample bslUsertypeInfoExample = new BslUsertypeInfoExample();
com.bsl.pojo.BslUsertypeInfoExample.Criteria criteria = bslUsertypeInfoExample.createCriteria();
criteria.andUserIdEqualTo(userId);
List<BslUsertypeInfo> bslUsertypeInfos = bslUserTypeMapper.selectByExample(bslUsertypeInfoExample);
for (BslUsertypeInfo bslUsertypeInfo : bslUsertypeInfos) {
sBuffer.append(bslUsertypeInfo.getUserType()+";");
}
user.setRemark(sBuffer.toString());
// 把用户信息写入redis
jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));
jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
// 添加写cookie的逻辑,cookie的有效期是关闭浏览器失效。
// CookieUtils.setCookie(request, response, "TT_TOKEN", token);
session.setAttribute("TT_TOKEN", token);
// 返回token
return BSLResult.ok(token);
}
@Override
public BSLResult getUserByToken(String token) {
// 根据token
String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);
log.info("getUserByToken:"+json);
if (StringUtils.isBlank(json)) {
return BSLResult.build(400, "此session已过期,请重新登录");
}
// 更新过期时间
jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
BslUserInfo user = (BslUserInfo) JsonUtils.jsonToPojo(json, BslUserInfo.class);
return BSLResult.ok(user);
}
@Override
public BSLResult checkData(String content, Integer type) {
BslUserInfoExample example = new BslUserInfoExample();
Criteria criteria = example.createCriteria();
// 对数据进行校验:1、2、3分别代表username、phone、email
// 用户名校验
if (1 == type) {
criteria.andUserNameEqualTo(content);
// 电话校验
} else if (2 == type) {
criteria.andUserTelEqualTo(content);
}
List<BslUserInfo> list = bslUserInfoMapper.selectByExample(example);
if (list == null || list.size() == 0) {
return BSLResult.ok(true);
}
return BSLResult.ok(false);
}
@Override
public String getLoginUrl() {
return SSO_DOMAIN_BASE_URL + SSO_PAGE_LOGIN_URL;
}
@Override
public BSLResult checkUserRole(String userType) {
// String json = jedisClient.get(REDIS_USER_ROLE_KEY + ":" + userType);
// if (!StringUtils.isBlank(json)) {
//// BslRole bslRole = JsonUtils.jsonToPojo(json, BslRole.class);
//// if (bslRole != null && bslRole.getUserType() != null)
// return BSLResult.ok(json);
// }
// BslRoleExample example = new BslRoleExample();
// com.bsl.pojo.BslRoleExample.Criteria criteria = example.createCriteria();
// criteria.andUserTypeEqualTo(userType);
// List<BslRole> bslRoles = bslRoleMapper.selectByExample(example);
// if(bslRoles == null || bslRoles.size() == 0) {
// BslRole bslRole = (BslRole) null;
// jedisClient.set(REDIS_USER_ROLE_KEY + ":" + userType, JsonUtils.objectToJson(bslRole));
// jedisClient.expire(REDIS_USER_ROLE_KEY + ":" + userType, SSO_SESSION_EXPIRE);
// return BSLResult.ok(bslRole);
// }
// if (bslRoles != null && bslRoles.size() > 0) {
// StringBuffer sf = new StringBuffer();
// for (BslRole bslRole : bslRoles) {
// sf.append(bslRole.getNoOpenPages()).append("|");
// }
// String noOpenPages = sf.toString();
// jedisClient.set(REDIS_USER_ROLE_KEY + ":" + userType, noOpenPages);
// jedisClient.expire(REDIS_USER_ROLE_KEY + ":" + userType, SSO_SESSION_EXPIRE);
// return BSLResult.ok(noOpenPages);
// }
return BSLResult.build(ErrorCodeInfo.错误类型_状态校验错误, "没有权限");
}
/**
* 用户编号自生成六位
*/
@Override
public String queryNewUserId() {
long incr = jedisClient.incr(REDIS_NEXT_USER_ID_KEY);
String userId = String.format("%06d", incr);
return userId;
}
@Override
public BSLResult loginOut(QueryExample queryExample, HttpServletRequest request, HttpServletResponse response) {
// 1从cookie中取token
// String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
HttpSession session = request.getSession();
//将数据存储到session中
String token = String.valueOf(session.getAttribute("TT_TOKEN"));
jedisClient.del(REDIS_USER_SESSION_KEY + ":" + token);
jedisClient.del(REDIS_USER_ROLE_KEY + ":" + queryExample.getUserType());
// CookieUtils.deleteCookie(request, response, "TT_TOKEN");
//清除session
session.removeAttribute("TT_TOKEN");
return BSLResult.ok();
}
@Override
public List<BslUserInfo> exportToExcel() {
return bslUserInfoMapper.selectByExample(new BslUserInfoExample());
}
}
|
Markdown
|
UTF-8
| 3,722 | 3.15625 | 3 |
[] |
no_license
|
## Resources System ##
The final method of managing source data in FME Server is to use the system of tools called Resources.
---
### What are Resources? ###
"Resources" is an inbuilt file management system that allows data (and other files) to be published to an FME Server instance and used within all Server operations. It is accessed using Manage > Resources from the web interface menu.
The Resources web page looks like this:

Although there are a number of different folders data can be stored in, the Data folder is the most logical location:

In this window are options to upload either a selection of files or an entire folder. Additionally, new folders can be created, and existing data moved, copied, or deleted.
---
### Using Uploaded Data ###
Using uploaded data in a translation is very simple. Here, for example, a user has created a new subfolder in the resources file system (Home > Data > StreetLighting), and has uploaded some MapInfo data to it:

Now when the workspace is run, the end-user clicks the browse button and is able to select data from the Resources folders, like so:

In fact, it's even possible to set the output data folder to be a Resources folder too:

---
### Other Upload Methods ###
Besides the web interface, there are other ways of getting data into the Resources filesystem.
Firstly, the FME Server publishing wizard in FME Workbench allows this. Where the default method is to select the files and upload them to the same repository as the workspace, it is permitted to change the location to the resources filesystem:

Alternatively, FME Server resources actually exists on the operating system's filesystem, meaning the data can be copied there directly. The default location (on a Windows operating system) is C:\ProgramData\Safe Software\FME Server\resources:

Finally, the Resources system also allows connections to Amazon S3:

This allows data stored in S3 buckets to be used as the source for a translation on FME Server.
---
<!--Person X Says Section-->
<table style="border-spacing: 0px">
<tr>
<td style="vertical-align:middle;background-color:darkorange;border: 2px solid darkorange">
<i class="fa fa-quote-left fa-lg fa-pull-left fa-fw" style="color:white;padding-right: 12px;vertical-align:text-top"></i>
<span style="color:white;font-size:x-large;font-weight: bold;font-family:serif">Sister Intuitive says...</span>
</td>
</tr>
<tr>
<td style="border: 1px solid darkorange">
<span style="font-family:serif; font-style:italic; font-size:larger">
The Resources filesystem was (prior to FME2016) located within the FME Server installation folder on the operating system, but was moved in 2016 as the installation folder is (or should be) a restricted space off-limits to most users. To find it, try looking in %programdata%
</span>
</td>
</tr>
</table>
---
### Benefits for Data Management ###
The advantage of these Resources, compared to other methods, is that data can be uploaded and referenced by any workspace, without having to upload it every time. This is particularly useful when access to the file system is restricted (like on an FME Cloud system).
If the workspace author does have access to the file system, then Resources are still useful, as a Resources folder can be mapped and shared among many users as a physical drive.
|
C
|
UTF-8
| 815 | 3.640625 | 4 |
[
"MIT"
] |
permissive
|
/*
* Copyright(c) 2011-2023 The Maintainers of Nanvix.
* Licensed under the MIT License.
*/
#include <stddef.h>
/**
* @details The __strncpy() function copies not more than @p n characters
* (characters that follow a null character are not copied) from the
* array pointed to by @p s2 to the array pointed to by @p s1) If
* copying takes place between objects that overlap, the behavior is
* undefined.
*/
char *__strncpy(char *s1, const char *s2, size_t n)
{
char *p1 = s1; /* Indexes s1. */
const char *p2 = s2; /* Indexes s2. */
/* Copy string. */
while (n > 0) {
if (*p2 == '\0') {
break;
}
*p1++ = *p2++;
n--;
}
/* Fill with null bytes. */
while (n > 0) {
*p1++ = '\0';
n--;
}
return (s1);
}
|
Java
|
UTF-8
| 1,338 | 2.171875 | 2 |
[] |
no_license
|
package com.marketplace.wishlist.service;
import com.marketplace.wishlist.AbstractITCase;
import com.marketplace.wishlist.exception.BusinessException;
import com.marketplace.wishlist.model.Wish;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class WishlistLimitServiceCase extends AbstractITCase {
@Autowired
WishlistService wishlistService;
@Test
public void insertAndFetchWishSuccess() throws BusinessException {
UUID customerId = UUID.randomUUID();
for (int i = 0; i < 20; i++) {
wishlistService.addWish(Wish.builder()
.customerId(customerId)
.productId(UUID.randomUUID())
.build());
}
assertThrows(BusinessException.class, () ->
wishlistService.addWish(Wish.builder()
.customerId(customerId)
.productId(UUID.randomUUID())
.build()));
}
}
|
Markdown
|
UTF-8
| 1,724 | 2.8125 | 3 |
[] |
no_license
|
---
title: CS3STHLM 2020 Theme Smarter!
date: 2020-02-14 05:00:00
categories:
- blog
layout: blog
author: CS3STHLM Crew
pdf:
-
published: true
permalink: /blog/cs3sthlm-2020-theme-smarter/
---
<img src="{{ site.baseurl }}/assets/cs3sthlm-heart.png" class="blog-content-image-half" />
<h1 class="blog-title" itemprop="name headline">{{ page.title }}</h1>
## We have chosen ***Smarter!*** as the theme for the 2020 conference.
There are many reasons for this selection: "Smart" is used to describe many current things in the cyber industry – such as "SmartGrid", "Smart Meters", "Smart Cities" and "smart vehicles". Smarter is also what the adversaries have become, finding more exotic vulnerabilities, and launching attacks built with increasing domain knowledge and sophistication. We, as people working in this profession, must be smarter, and we must design and implement smarter methods, tactics and solutions to be able to detect and protect against these attacks.
At the same time, we cannot forget that we live in a complicated world where "stupid" still is a highly viable option: "Admin/admin" is still used as login combinations! End-of-life firewalls are still in use! Old bugs are forever days as updates are not done! And separation of sensitive infrastructure from the rest of the business is still not done!
We anticipate submissions from speaker candidates that will be describing new and smart solutions. We also expect presentations that analyses, or describes different attacks, on the stupid, on the broken, or even the smart.
No matter the mix of "smarter" or ”stupid” in presentations, trainings and hallway tracks, we know that all participants will be leaving CS3STHLM 2020 Smarter!
|
Java
|
UTF-8
| 613 | 2.796875 | 3 |
[] |
no_license
|
package Level3;
public class Solution_네트워크 {
static int n = 3;
static int[][] computers = {{1,1,0},{1,1,0},{0,0,1}};
public static void main(String[] args) {
int answer =0;
boolean[] visit = new boolean[n];
for(int i = 0; i < n;i++) {
if(!visit[i]) {
answer++;
dfs(i, visit, computers);
}
}
System.out.println(answer);
}
public static void dfs(int idx, boolean[] visit, int[][] computers) {
visit[idx] = true;
for(int i = 0 ; i < computers.length; i++) {
if(!visit[i] && computers[idx][i] == 1) {
dfs(i, visit, computers);
}
}
}
}
|
PHP
|
UTF-8
| 743 | 3.375 | 3 |
[] |
no_license
|
<?php
$cities = array(
'Germany' => 'Berlin',
'France' => 'Paris',
'Ukraine' => 'Kiev'
);
$object = new ArrayObject($cities);
$iterator = $object->getIterator();
$object['Russia'] = 'Moscow';
$object->append('Tokio');
while ($iterator->valid()) {
echo $iterator->key() .' '. $iterator->current() . '<br/>';
$iterator->next();
}
/********************/
$data = array(
'name' => 'John Doe',
'email' => 'john@domain.com'
);
/*
* access the object properties using an object notation
*/
$arrayObj = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
echo 'Full name: ' . $arrayObj->name . ' Email: ' . $arrayObj->email;
foreach ($arrayObj as $key => $value) {
echo 'Key: ' . $key . ' Value: ' . $value . '<br />';
}
|
C++
|
UTF-8
| 512 | 3.296875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int coord(int x,int y){
if(y==x){
int n=1;
while(x!=0 && x!=1){
n++;
x-=2;
}
if(x==1)
return (4*n-3);
else
return (4*n-4);
}
else if(y==(x-2)){
int n=1;
while(y!=0 && y!=1){
n++;
y-=2;
}
if(y==1)
return (4*n-1);
else
return (4*n-2);
}
return 0;
}
int main(){
int test;
cin>>test;
while(test--){
int x,y;
cin>>x>>y;
int res = coord(x,y);
if(res!=0)
cout<<res<<endl;
else
cout<<"No Number"<<endl;
}
}
|
Markdown
|
UTF-8
| 1,229 | 2.796875 | 3 |
[] |
no_license
|
# MuleSoft training: DevFundamentals w/Mule-4
The contents in these folders contain solution files for walkthroughs covered each day.
**Note**:
The projects in Day-1 thru Day-3 are built with AnypointStudio ver 7.4.1. Whereas the projects in Day-4 and Day-5 are built using newer version of Studio ver 7.4.2
<BR>
## How to import **Mule Application** solution into Studio?
- Download the solution .jar file from appropriate day's folder
- Start **Anypoint Studio**
- **Note**: If the Studio's worspace already contains a project with the same name that you plan to import, right-click on the prject and _delete_ it first (don't forget to select the _checkmark_ to delete it from the filesystem as well)
- Within **Package Explorer** section (top-left), right-click anywhere in white space, select **Import** to open the wizard
- Within **Import** wizard, exapand **Anypoint Studio > Packaged Mule application (jar)** and click **Next**
- Browse and select the .jar file that you downloaded, and click **Finish**
- Wait till all necessary dependencies are downloaded (progress is indicated at the bottom-right corner of Studio)
- That's it. Now, you are ready to either add more content or run and test the mule app
|
Java
|
UTF-8
| 81 | 1.804688 | 2 |
[] |
no_license
|
package myProject;
public interface IPlayer {
public IHand getHand();
}
|
Java
|
UTF-8
| 815 | 2.234375 | 2 |
[
"MIT"
] |
permissive
|
package com.example.fuseExample.transform;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class CvsAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
List<String> data = newExchange.getIn().getBody(List.class);
newExchange.getIn().setBody(data.get(1));
newExchange.getIn().setHeader("tag", data.get(0));
return newExchange;
} else {
String data1 = oldExchange.getIn().getBody(String.class);
List<String> data = newExchange.getIn().getBody(List.class);
oldExchange.getIn().setBody(data1 +" - " + data.get(1));
return oldExchange;
}
}
}
|
Java
|
UTF-8
| 1,142 | 2.421875 | 2 |
[] |
no_license
|
package com.example.a3671129.musidroid;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.TextView;
import l2i013.musidroid.model.InstrumentPart;
public class TempoChangeListener implements SeekBar.OnSeekBarChangeListener {
private TheApplication app;
private TextView tempoText;
private int tempo;
public TempoChangeListener(TheApplication app, TextView ct) {
super();
this.app = app;
this.tempoText = ct;
InstrumentPart ip = app.getInstrument();
tempo = app.getPartition().getTempo();
}
public void onProgressChanged(SeekBar sb, int n, boolean b) {
if (app != null) {
tempo = n;
tempoText.setText("Partition\t Tempo (" + tempo + ")");
}
else
{
Log.wtf("TempoChangeListener Methode onProgressChanged", "app NULL !");
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
tempoText.setText("Partition \t Tempo (" + tempo + ")");
}
public void onStopTrackingTouch(SeekBar seekBar) {
app.getPartition().setTempo(tempo);
}
}
|
Java
|
UTF-8
| 18,516 | 1.695313 | 2 |
[] |
no_license
|
/*
*
*/
package com.indra.iquality.dao.jdbctemplateimplem;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.indra.iquality.dao.DictionaryOfConceptsDAO;
import com.indra.iquality.helper.GenericTreeNode;
import com.indra.iquality.model.MasterAttributeDescription;
import com.indra.iquality.model.IndicatorDescription;
import com.indra.iquality.model.AttributeDescription;
import com.indra.iquality.model.DictionaryConcept;
import com.indra.iquality.singleton.Environment;
import oracle.sql.ROWID;
/**
* Implementation of {@link com.indra.iquality.dao.DictionaryOfConceptsDAO}
* using JDBC to connect to an Oracle DB.
*
* @author Ignacio N. Lucero Ascencio
* @version 0.5, 14-dic-2015
*
* The Class DictionaryOfConceptsDAOJDBCTemplateImpl.
*/
public class DictionaryOfConceptsDAOJDBCTemplateImpl extends AbstractDAOJDBCTemplateImpl
implements DictionaryOfConceptsDAO {
/** The Constant logger. */
private final static org.slf4j.Logger logger = LoggerFactory
.getLogger(DictionaryOfConceptsDAOJDBCTemplateImpl.class);
/*
* (non-Javadoc)
*
* @see
* com.indra.iquality.dao.DictionaryOfConceptsDAO#getAllConcepts(java.lang.
* String, int)
*/
@Override
public List<GenericTreeNode<DictionaryConcept>> getAllConcepts(String sistema, int software) {
logger.info("[getAllConcepts] : INIT");
String query = "WITH CONSULTA " + "AS "
+ "(select ID_PADRE, id_hijo, id_tipo, ID_SISTEMA, ID_SOFTWARE, ID_ORDEN,DESCRIPCION, id_fila_lk_met_fi_comp, ID_FILA_RE_MET_FI_COMP_TAB "
+ "from VS_MET_FI_ARBOL_COMP VS " + "), " + "FILTRO as "
+ "(SELECT DISTINCT ID_HIJO ID_HIJO_FILTRO,ID_SISTEMA,ID_SOFTWARE,ID_ORDEN,ID_TIPO FROM CONSULTA "
+ "start with ID_TIPO IN ('A','I','L') " + "connect by NOCYCLE " + "PRIOR ID_PADRE = ID_HIJO AND "
+ "prior ID_SOFTWARE = ID_SOFTWARE AND " + "prior ID_SISTEMA = ID_SISTEMA ), " + "FILTROHERM as "
+ "( " + "SELECT ID_HIJO_FILTRO,ID_SISTEMA,ID_SOFTWARE FROM FILTRO " + "UNION "
+ "SELECT C.ID_HIJO,C.ID_SISTEMA,C.ID_SOFTWARE FROM FILTRO F,VS_MET_FI_ARBOL_COMP C WHERE "
+ "F.ID_SOFTWARE=C.ID_SOFTWARE AND F.ID_SISTEMA=C.ID_SISTEMA AND F.ID_HIJO_FILTRO=C.ID_PADRE AND F.ID_TIPO='S' AND F.ID_ORDEN='1' AND C.ID_TIPO='S' AND C.ID_ORDEN<>'1' "
+ "), " + "ARBOL AS " + "( " + "select " + "DESCRIPCION as title, " + "null as tooltip, "
+ "link, VS.ID_PADRE, VS.ID_HIJO, VS.ID_SOFTWARE, VS.ID_SISTEMA, VS.ID_TIPO, VS.ID_ORDEN, vs.id_fila_lk_met_fi_comp, VS.ID_FILA_RE_MET_FI_COMP_TAB "
+ "from VS_MET_FI_ARBOL_COMP VS " + "left join " + "FILTROHERM "
+ "on (VS.ID_HIJO=FILTROHERM.ID_HIJO_FILTRO AND " + "VS.ID_SOFTWARE=FILTROHERM.ID_SOFTWARE AND "
+ "VS.ID_SISTEMA=FILTROHERM.ID_SISTEMA) "
+ "where ((ID_PADRE NOT LIKE '%ODS%' AND VS.ID_HIJO NOT LIKE '%ODS%') OR ID_PADRE IS NULL) AND ID_SN_MAESTRA = 'N' AND DESCRIPCION NOT LIKE '%Otros valores%' "
+ "AND DESCRIPCION NOT LIKE '%No informado%' " + ") " + "select case when connect_by_isleaf = 1 then 0 "
+ " when level = 1 then 1 " + " else -1 "
+ " end as status, "
+ " level, title, VS.ID_TIPO as tipo, vs.id_fila_lk_met_fi_comp as comp_rowid, VS.ID_FILA_RE_MET_FI_COMP_TAB as ct_rowid "
+ "from arbol VS " + "start with ID_PADRE is null " + "connect by NOCYCLE "
+ "VS.ID_PADRE = prior VS.ID_HIJO AND " + "VS.ID_SOFTWARE = prior VS.ID_SOFTWARE AND "
+ "VS.ID_SISTEMA = prior VS.ID_SISTEMA " + "ORDER SIBLINGS BY ID_ORDEN ASC, ID_TIPO ";
// Hago la query
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<GenericTreeNode<DictionaryConcept>> dictionaryConceptList = new ArrayList<GenericTreeNode<DictionaryConcept>>();
List<Map<String, Object>> dictionaryConceptNodeRows;
try {
dictionaryConceptNodeRows = jdbcTemplate.queryForList(query, new Object[] {});
} catch (Exception e) {
logger.error("[getAllConcepts] : Excepción <{}> | Ayuda: {} \n {}", e.getClass(), e.getMessage());
e.printStackTrace();
return new ArrayList<GenericTreeNode<DictionaryConcept>>();
}
// Mapeo los resultados a una lista
for (Map<String, Object> dictionaryConceptNodeRow : dictionaryConceptNodeRows) {
DictionaryConcept dictionaryConcept = new DictionaryConcept();
dictionaryConcept
.setStatus(helper.filterStringToInt(String.valueOf(dictionaryConceptNodeRow.get("status"))));
dictionaryConcept.setLevel(helper.filterStringToInt(String.valueOf(dictionaryConceptNodeRow.get("level"))));
dictionaryConcept
.setConcept(helper.filterNullString(String.valueOf(dictionaryConceptNodeRow.get("title"))));
dictionaryConcept
.setType((helper.conceptTypeStringToEnum(String.valueOf(dictionaryConceptNodeRow.get("tipo")))));
// Son ROWIDs the Oracle. Hay que filtrarlos de otra manera
if (dictionaryConceptNodeRow.get("comp_rowid") != null) {
dictionaryConcept.setCompRowID((((ROWID) (dictionaryConceptNodeRow.get("comp_rowid"))).stringValue()));
} else
dictionaryConcept.setCompRowID(Environment.DEFAULT_NULL_STRING);
if (dictionaryConceptNodeRow.get("ct_rowid") != null) {
dictionaryConcept.setCtRowID((((ROWID) (dictionaryConceptNodeRow.get("ct_rowid"))).stringValue()));
} else
dictionaryConcept.setCtRowID(Environment.DEFAULT_NULL_STRING);
GenericTreeNode<DictionaryConcept> dictionaryConceptNode = new GenericTreeNode<DictionaryConcept>(
dictionaryConcept);
dictionaryConceptList.add(dictionaryConceptNode);
}
logger.debug("[getAllConcepts] : found {} concepts", dictionaryConceptList.size());
logger.info("[getAllConcepts] : RETURN");
return dictionaryConceptList;
}
/*
* (non-Javadoc)
*
* @see
* com.indra.iquality.dao.DictionaryOfConceptsDAO#getDescriptionOfAttribute(
* java.lang.String, java.lang.String, java.lang.String, int)
*/
@Override
public AttributeDescription getDescriptionOfAttribute(String compRowID, String ctRowID, String sistema,
int software) {
logger.info("[getDescriptionOfAttribute] : INIT");
String queryBasicosYEntidad = "SELECT"
+ " VSMT.id_componente, VSMT.de_nombre as nombre, RESP.de_area as responsable,"
+ " VSMT.de_definicion as definicion, VSMT.de_comentario as comentario, VSMT.de_historico as historico,"
+ " VSMT.de_formula_usuario as mtd_obtencion, VSMT.de_formato as formato,"
+ " PERACT.de_periodo_act as periodo_act, TIPACT.de_tipo_actualizacion as tipo_act" + " FROM"
+ " VS_MET_FI_COMPONENTE_TABLA VSMT, lk_met_fi_area RESP,"
+ " lk_met_fi_periodo_act PERACT, lk_met_fi_tipo_actualizacion TIPACT" + " WHERE"
+ " VSMT.COMP_ROWID = ? AND VSMT.CT_ROWID = ?" + " AND VSMT.id_sistema = ? AND VSMT.id_software = ?"
+ " AND VSMT.id_software = RESP.id_software and VSMT.id_sistema = RESP.id_sistema"
+ " AND VSMT.id_area = RESP.id_area AND VSMT.id_software = PERACT.id_software"
+ " AND VSMT.id_sistema = PERACT.id_sistema and VSMT.id_periodo_act = PERACT.id_periodo_act"
+ " AND VSMT.id_software = TIPACT.id_software and VSMT.id_sistema = TIPACT.id_sistema"
+ " AND VSMT.id_tipo_actualizacion = TIPACT.id_tipo_actualizacion";
// Hago la query y mapeo a un objeto directamente
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
AttributeDescription da;
try {
da = jdbcTemplate.queryForObject(queryBasicosYEntidad,
new Object[] { compRowID, ctRowID, sistema, software }, new RowMapper<AttributeDescription>() {
@Override
public AttributeDescription mapRow(ResultSet rs, int rowNum) throws SQLException {
AttributeDescription da = new AttributeDescription();
da.setId(rs.getInt("id_componente"));
da.setName(rs.getString("nombre"));
da.setResponsible(rs.getString("responsable"));
da.setDefinition(rs.getString("definicion"));
da.setComments(rs.getString("comentario"));
da.setHistory(rs.getString("historico"));
da.setObtentionMethod(rs.getString("mtd_obtencion"));
da.setFormat(rs.getString("formato"));
da.setUodatePeriod(rs.getString("periodo_act"));
da.setUpdateType(rs.getString("tipo_act"));
return da;
}
});
} catch (Exception e) {
logger.error("[getDescriptionOfAttribute] : Excepción <{}> | Ayuda: {} \n {}", e.getClass(),
e.getMessage());
e.printStackTrace();
return new AttributeDescription();
}
logger.debug("[getDescriptionOfAttribute] : found description {}", da.toString());
logger.info("[getDescriptionOfAttribute] : RETURN");
return da;
}
/*
* (non-Javadoc)
*
* @see com.indra.iquality.dao.DictionaryOfConceptsDAO#
* getDescriptionOfMasterAttribute(java.lang.String, java.lang.String,
* java.lang.String, int)
*/
@Override
public MasterAttributeDescription getDescriptionOfMasterAttribute(String compRowID, String ctRowID, String sistema,
int software) {
logger.info("[getDescriptionOfMasterAttribute] : INIT");
// Preparo un maestro para retornar
// Lo creo con los campos que tiene de un atributo normal con
// getDescriptionOfAttribute
MasterAttributeDescription dam = new MasterAttributeDescription(
getDescriptionOfAttribute(compRowID, ctRowID, sistema, software));
// Obtengo los campos propios del maestro, que un atributo normal no
// tiene
String queryAtributosDelMaestro = "SELECT"
+ " VSMT.de_historico_lk as historico_maestro, PERACT.de_periodo_act as periodo_act_maestro,"
+ " TIPACT.de_tipo_actualizacion as tipo_act_maestro, VSMT.de_formula_usuario_lk as mtd_obtencion_maestro"
+ " FROM" + " VS_MET_FI_COMPONENTE_TABLA VSMT, LK_MET_FI_PERIODO_ACT PERACT,"
+ " LK_MET_FI_TIPO_ACTUALIZACION TIPACT" + " WHERE"
+ " VSMT.COMP_ROWID = ? AND VSMT.CT_ROWID = ? AND VSMT.id_sistema = ? AND VSMT.id_software = ?"
+ " AND VSMT.id_software = PERACT.id_software AND VSMT.id_sistema = PERACT.id_sistema"
+ " AND VSMT.id_periodo_act_lk = PERACT.id_periodo_act AND VSMT.id_software = TIPACT.id_software"
+ " AND VSMT.id_sistema = TIPACT.id_sistema AND VSMT.id_tipo_actualizacion_lk = TIPACT.id_tipo_actualizacion";
// Hago la query y mapeo a un objeto directamente
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
MasterAttributeDescription auxdam;
try {
auxdam = jdbcTemplate.queryForObject(queryAtributosDelMaestro,
new Object[] { compRowID, ctRowID, sistema, software },
new RowMapper<MasterAttributeDescription>() {
@Override
public MasterAttributeDescription mapRow(ResultSet rs, int rowNum) throws SQLException {
MasterAttributeDescription dam = new MasterAttributeDescription();
dam.setHistoryMaster(rs.getString("historico_maestro"));
dam.setUpdatePeriodMaster(rs.getString("periodo_act_maestro"));
dam.setUpdateTypeMaster(rs.getString("tipo_act_maestro"));
dam.setObtentionMethodMaster(rs.getString("mtd_obtencion_maestro"));
return dam;
}
});
} catch (Exception e) {
logger.error("[getDescriptionOfMasterAttribute] : Excepción <{}> | Ayuda: {} \n {}", e.getClass(),
e.getMessage());
e.printStackTrace();
return new MasterAttributeDescription();
}
// Agrego los campos obtenidos al atributo maestro que me había
// preparado
dam.setHistoryMaster(auxdam.getHistoryMaster());
dam.setUpdatePeriodMaster(auxdam.getUpdatePeriodMaster());
dam.setUpdateTypeMaster(auxdam.getUpdateTypeMaster());
dam.setObtentionMethodMaster(auxdam.getObtentionMethodMaster());
logger.debug("[getDescriptionOfMasterAttribute] : found description {}", dam.toString());
logger.info("[getDescriptionOfMasterAttribute] : RETURN");
return dam;
}
/*
* (non-Javadoc)
*
* @see
* com.indra.iquality.dao.DictionaryOfConceptsDAO#getDescriptionOfIndicator(
* java.lang.String, java.lang.String, java.lang.String, int)
*/
@Override
public IndicatorDescription getDescriptionOfIndicator(String compRowID, String ctRowID, String sistema,
int software) {
logger.info("[getDescriptionOfIndicator] : INIT");
String queryBasicosYEntidad = "SELECT" + " VSMT.id_componente,"
+ " VSMT.de_nombre as nombre, RESP.de_area as responsable, VSMT.de_definicion as definicion,"
+ " VSMT.de_comentario as comentario, VSMT.de_historico as historico,"
+ " VSMT.de_formula_usuario as mtd_obtencion, VSMT.de_unidad_medida as unidad_medida,"
+ " PERACU.de_periodo_acum as periodo_acumulado" + " FROM"
+ " VS_MET_FI_COMPONENTE_TABLA VSMT, LK_MET_FI_AREA RESP, LK_MET_FI_PERIODO_ACUM PERACU"
+ " WHERE VSMT.COMP_ROWID = ? AND VSMT.CT_ROWID = ? AND VSMT.id_sistema = ? AND VSMT.id_software = ?"
+ " AND VSMT.id_software = RESP.id_software and VSMT.id_sistema = RESP.id_sistema"
+ " AND VSMT.id_area = RESP.id_area AND VSMT.id_software = PERACU.id_software"
+ " AND VSMT.id_sistema = PERACU.id_sistema and VSMT.id_periodo_acum = PERACU.id_periodo_acum";
// Hago la query y mapeo a un objeto directamente
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
IndicatorDescription di;
try {
di = jdbcTemplate.queryForObject(queryBasicosYEntidad,
new Object[] { compRowID, ctRowID, sistema, software }, new RowMapper<IndicatorDescription>() {
@Override
public IndicatorDescription mapRow(ResultSet rs, int rowNum) throws SQLException {
IndicatorDescription di = new IndicatorDescription();
di.setId(rs.getInt("id_componente"));
di.setName(helper.filterNullString(rs.getString("nombre")));
di.setResponsible(helper.filterNullString(rs.getString("responsable")));
di.setDefinition(helper.filterNullString(rs.getString("definicion")));
di.setComments(helper.filterNullString(rs.getString("comentario")));
di.setHistory(helper.filterNullString(rs.getString("historico")));
di.setObtentionMethod(helper.filterNullString(rs.getString("mtd_obtencion")));
di.setMeasureUnit(helper.filterNullString(rs.getString("unidad_medida")));
di.setAcummulatedPeriod(helper.filterNullString(rs.getString("periodo_acumulado")));
return di;
}
});
} catch (Exception e) {
logger.error("[getDescriptionOfIndicator] : Excepción <{}> | Ayuda: {} \n {}", e.getClass(),
e.getMessage());
e.printStackTrace();
return new IndicatorDescription();
}
// Busco las certificaciones del indicador y se las agrego
List<Certification> certificaciones = getCertifications(di.getId(), sistema, software);
List<String> descripcionCertificaciones = new ArrayList<String>();
for (Certification c : certificaciones) {
descripcionCertificaciones.add(c.getDescripcion());
}
di.setCertificates(descripcionCertificaciones);
logger.debug("[getDescriptionOfIndicator] : found description {}", di.toString());
logger.info("[getDescriptionOfIndicator] : RETURN");
return di;
}
/**
* Gets the certifications of a component for a given system and software
* version.
*
* @param idComponente
* the identifier of the component
* @param sistema
* the system
* @param software
* the software version
* @return the certifications of the component
*/
private List<Certification> getCertifications(int idComponente, String sistema, int software) {
logger.info("[getCertifications] : INIT");
String queryBasicosYEntidad = "SELECT" + " COMP.ID_COMPONENTE," + " COMP.DE_NOMBRE," + " CERT.DE_CERTIFICACION"
+ " FROM LK_MET_FI_CERTIFICACION CERT" + " LEFT JOIN LK_MET_FI_COMPONENTE COMP"
+ " ON(COMP.ID_COMPONENTE = CERT.ID_COMPONENTE_HIJO AND" + " COMP.ID_SOFTWARE = CERT.ID_SOFTWARE AND"
+ " COMP.ID_SISTEMA = CERT.ID_SISTEMA)" + " WHERE" + " COMP.ID_COMPONENTE = ? AND"
+ " COMP.ID_SISTEMA = ? AND" + " COMP.ID_SOFTWARE = ?";
// Hago la query
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Certification> certList = new ArrayList<Certification>();
List<Map<String, Object>> certRows;
try {
certRows = jdbcTemplate.queryForList(queryBasicosYEntidad,
new Object[] { idComponente, sistema, software });
} catch (Exception e) {
logger.error("[getCertifications] : Excepción <{}> | Ayuda: {} \n {}", e.getClass(), e.getMessage());
e.printStackTrace();
return new ArrayList<Certification>();
}
// Mapeo a una lista
for (Map<String, Object> certRow : certRows) {
Certification cert = new Certification();
cert.setIdComponente(helper.filterStringToInt((String.valueOf(certRow.get("id_componente")))));
cert.setNombre(helper.filterNullString(String.valueOf(certRow.get("de_nombre"))));
cert.setDescripcion(helper.filterNullString(String.valueOf(certRow.get("de_certificacion"))));
certList.add(cert);
}
logger.debug("[getCertifications] : found {} certificates", certList.size());
logger.info("[getCertifications] : RETURN");
return certList;
}
/**
* The auxiliary Class for representing certifications.
*
* @author Ignacio N. Lucero Ascencio
* @version 0.5, 14-dic-2015
*
* The Class Certification.
*/
private class Certification {
/** The identifier of the component. */
private int idComponente;
/** The name of the component. */
private String nombre;
/** The description of the component. */
private String descripcion;
/**
* Gets the identifier of the component.
*
* @return the identifier of the component
*/
public int getIdComponente() {
return idComponente;
}
/**
* Sets the identifier of the component.
*
* @param idComponente
* the new identifier of the component
*/
public void setIdComponente(int idComponente) {
this.idComponente = idComponente;
}
/**
* Gets name of the component.
*
* @return name of the component
*/
public String getNombre() {
return nombre;
}
/**
* Sets name of the component
*
* @param nombre
* the new name of the component
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* Gets description of the component.
*
* @return description of the component
*/
public String getDescripcion() {
return descripcion;
}
/**
* Sets description of the component.
*
* @param descripcion
* the new description of the component
*/
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
}
}
|
Java
|
UTF-8
| 15,385 | 1.851563 | 2 |
[] |
no_license
|
package com.taca.boombuy.net;
import android.content.Context;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.taca.boombuy.dto.itemDTO;
import com.taca.boombuy.evt.OTTOBusTEST;
import com.taca.boombuy.modelReq.ReqBbLogIn;
import com.taca.boombuy.modelReq.ReqBbSearchBrand;
import com.taca.boombuy.modelReq.ReqBbSearchItem;
import com.taca.boombuy.modelReq.ReqBbSearchItemId;
import com.taca.boombuy.modelReq.ReqBbSignUp;
import com.taca.boombuy.Reqmodel.ReqHeader;
import com.taca.boombuy.modelReq.ReqSendFcm;
import com.taca.boombuy.modelReq.ReqUpdateToken;
import com.taca.boombuy.modelRes.ResBbSearchBrand;
import com.taca.boombuy.modelRes.ResBbSearchItem;
import com.taca.boombuy.modelRes.ResBbSearchItemCoupon;
import com.taca.boombuy.modelRes.ResBbSearchItemId;
import com.taca.boombuy.netmodel.FCMModel;
import com.taca.boombuy.netmodel.LoginModel;
import com.taca.boombuy.netmodel.SignUpModel;
import com.taca.boombuy.netmodel.UpdateTokenModel;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by jimin on 2017-01-20.
*/
public class NetworkTEST {
private static NetworkTEST ourInstance = new NetworkTEST();
public static NetworkTEST getInstance() {
return ourInstance;
}
private NetworkTEST() {
}
String url = "http://ec2-35-166-158-25.us-west-2.compute.amazonaws.com:3000/"; // 준범 서버
//String url = "http://ec2-35-165-170-210.us-west-2.compute.amazonaws.com:3000/"; // 지민 서버
///////////////////////////////////////////////////////////////////////////
// 통신 큐
RequestQueue requestQueue;
public RequestQueue getRequestQueue(Context context) {
if (requestQueue == null)
requestQueue = Volley.newRequestQueue(context);
return requestQueue;
}
public void bb_search_item_coupon(Context context, int bid){
ReqBbSearchItemId reqBbSearchItemCoupon = new ReqBbSearchItemId();
ReqHeader header = new ReqHeader();
header.setCode("상품 Bid 값으로 상품정보 검색");
reqBbSearchItemCoupon.setHeader(header);
reqBbSearchItemCoupon.setBody(bid);
try {
JSONObject json = new JSONObject(new Gson().toJson(reqBbSearchItemCoupon));
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url + "bb_search_item_coupon",
json,
new Response.Listener<JSONObject>(){
@Override
public void onResponse(JSONObject response) {
Log.i("COUPON RES" , response.toString());
ResBbSearchItemCoupon resBbSearchItemCoupon = new Gson().fromJson(response.toString(), ResBbSearchItemCoupon.class);
OTTOBusTEST.getInstance().getSearch_items_coupon_bus().post(resBbSearchItemCoupon);
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
}
});
getRequestQueue(context).add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
// 상품번호를 통해 상품 하나의 상세정보 가져오는 volley
public ArrayList<itemDTO> bb_search_item_Id(Context context, int id) {
ReqBbSearchItemId reqBbSearchItemId = new ReqBbSearchItemId();
ReqHeader header = new ReqHeader();
header.setCode("상품 Id 값으로 상품정보 검색");
reqBbSearchItemId.setHeader(header);
reqBbSearchItemId.setBody(id);
try {
JSONObject json = new JSONObject(new Gson().toJson(reqBbSearchItemId));
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url + "bb_search_item_Id",
json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("RESPONSE :", response.toString());
ResBbSearchItemId resBbSearchItemId = new Gson().fromJson(response.toString(), ResBbSearchItemId.class);
Log.i("SELECT FROM ID : ", resBbSearchItemId.toString());
OTTOBusTEST.getInstance().getSelected_item_detail_bus().post(resBbSearchItemId);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.i("SELECT FROM ID 위치", "실패" + error.getMessage());
}
}
);
getRequestQueue(context).add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
// 전역변수에 형태 정해주고 return list
return null;
}
///////////////////////////////////////////////////////////////////////////
// FCM 전송
public void sendFcm(Context context, ArrayList<FCMModel> cc) {
// 전송 : { header:{code:AD}, body:[{token:xx, content:xx}] }
// 응답 : { code:1, msg:"ok" }
// 1. 파라미터 구성
ReqSendFcm reqSendFcm = new ReqSendFcm();
ReqHeader reqHeader = new ReqHeader();
reqSendFcm.setHeader(reqHeader);
reqSendFcm.setBody(cc);
// 2. 요청객체 준비
try {
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(
Request.Method.POST,
url + "sendFcm",
new JSONObject(new Gson().toJson(reqSendFcm)),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// 4. 응답처리
Log.i("RES", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
// 3. 요청 (타임아웃 설정 추가 필요)
getRequestQueue(context).add(jsonObjectRequest);
} catch (Exception e) {
}
}
// users 회원가입
public void bb_Signup(Context context, SignUpModel signUpModel) {
// 전송 : { header:{code:AD}, body:[{phone:xx, password:xx, name:xx, token:xx, profile:xx}] }
// 응답 : { code:1, msg:"ok" }
// 1. 파라미터 구성
ReqBbSignUp reqBbSignUp = new ReqBbSignUp();
ReqHeader reqHeader = new ReqHeader();
reqBbSignUp.setHeader(reqHeader);
reqBbSignUp.setBody(signUpModel);
// 2. 요청객체 준비
try {
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(
Request.Method.POST,
url + "bb_Signup",
new JSONObject(new Gson().toJson(reqBbSignUp)),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// 4. 응답처리
Log.i("RES", "bb_Signup" + response.toString());
// 이벤트 발생 등록
OTTOBusTEST.getInstance().getSign_up_bus().post(response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
// 3. 요청 (타임아웃 설정 추가 필요)
getRequestQueue(context).add(jsonObjectRequest);
} catch (Exception e) {
}
}
// users 로그인
public void bb_Login(Context context, LoginModel lonInModel) {
// 전송 : { header:{code:AD}, body:[{uid:xx, name:xx, tel:xx}] }
// 응답 : { code:1, msg:"ok" }
// 1. 파라미터 구성
ReqBbLogIn reqBbLogIn = new ReqBbLogIn();
ReqHeader reqHeader = new ReqHeader();
reqBbLogIn.setHeader(reqHeader);
reqBbLogIn.setBody(lonInModel);
// 2. 요청객체 준비
try {
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(
Request.Method.POST,
url + "bb_Login",
new JSONObject(new Gson().toJson(reqBbLogIn)),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// 4. 응답처리
Log.i("RES", "bb_Login" + response.toString());
// 이벤트 발생 등록
OTTOBusTEST.getInstance().getSign_in_bus().post(response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
// 3. 요청 (타임아웃 설정 추가 필요)
getRequestQueue(context).add(jsonObjectRequest);
} catch (Exception e) {
}
}
// users token 업데이트
public void bb_Update_token(Context context, UpdateTokenModel updateTokenModel) {
// 전송 : { header:{code:AD}, body:[{uid:xx, name:xx, tel:xx}] }
// 응답 : { code:1, msg:"ok" }
// 1. 파라미터 구성
ReqUpdateToken reqUpdateToken = new ReqUpdateToken();
ReqHeader reqHeader = new ReqHeader();
reqUpdateToken.setHeader(reqHeader);
reqUpdateToken.setBody(updateTokenModel);
// 2. 요청객체 준비
try {
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(
Request.Method.POST,
url + "bb_Update_token",
new JSONObject(new Gson().toJson(reqUpdateToken)),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// 4. 응답처리
Log.i("RES", "bb_Update_token" + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
// 3. 요청 (타임아웃 설정 추가 필요)
getRequestQueue(context).add(jsonObjectRequest);
} catch (Exception e) {
}
}
public void bb_search_items(Context context) {
ReqBbSearchItem reqBbSearchItem = new ReqBbSearchItem();
ReqHeader header = new ReqHeader();
header.setCode("아이템 총 출력");
reqBbSearchItem.setHeader(header);
try {
JSONObject json = new JSONObject(new Gson().toJson(reqBbSearchItem));
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url + "bb_Search_Items",
json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("RESULT", response.toString());
ResBbSearchItem resBbSearchItem = new Gson().fromJson(response.toString(), ResBbSearchItem.class);
Log.i("RESULT RES", resBbSearchItem.toString());
OTTOBusTEST.getInstance().getSearch_items_bus().post(resBbSearchItem);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("RESULT FAIL", "실패:");
}
}
);
getRequestQueue(context).add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
public void bb_search_brands(Context context) {
ReqBbSearchBrand reqBbSearchBrand = new ReqBbSearchBrand();
ReqHeader header = new ReqHeader();
header.setCode("브랜드 총 출력");
reqBbSearchBrand.setHeader(header);
try {
JSONObject json = new JSONObject(new Gson().toJson(reqBbSearchBrand));
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url + "bb_Search_Brands",
json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("BRAND RESPONSE", response.toString());
ResBbSearchBrand resBbSearchBrand = new Gson().fromJson(response.toString(), ResBbSearchBrand.class);
OTTOBusTEST.getInstance().getSearch_brands_bus().post(resBbSearchBrand);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("실패", error.getMessage());
}
});
getRequestQueue(context).add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Java
|
UTF-8
| 977 | 2 | 2 |
[] |
no_license
|
package com.example.internetshop.controllers;
import com.example.internetshop.FormFilter;
import com.example.internetshop.entities.Product;
import com.example.internetshop.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class IndexController {
@Autowired
ProductRepository productRepository;
@GetMapping("/")
public String greetingForm(@RequestParam(required = false) String searchText, Model model) {
Iterable<Product> productsList = productRepository.findAll();
model.addAttribute("productsList", productsList);
return "index";
}
@PostMapping("/")
public String greetingSubmit(@ModelAttribute FormFilter formFilter, Model model) {
model.addAttribute("ff", formFilter);
return "result";
}
}
|
Markdown
|
UTF-8
| 9,184 | 2.984375 | 3 |
[] |
no_license
|
---
layout: post
title: 第二百一十七节 符富卷入了调查工作
category: 4
path: 2011-12-12-4-21700.md
tag: [normal]
---
万里辉已经习惯了符不二家有一屋子人的情景了。符不二是村长,家里等于是半个村公所。村里的百姓来办事的,说话的,甚至还要喊冤的。基本上每天川流不息。虽然村里盖了还算气派的村公所,但是老百姓还是习惯抬腿就上村长家来办事。
屋子里聚集这么一堆人中间站起个伏波军的士兵给他敬礼,才让他有点意外军队放假了么?
“这是符富,在伏波军当兵。”符不二赶紧介绍道,符富突然从军队里回来让他吃了一惊,这小子莫非是当了逃兵?这可要连累死他了!想到前阶段他还去专做过逃兵工作,又有个首长在这里,心里不由的一阵慌
再看符富穿着整齐,容光焕发,又带着大包小包,不是丧家之犬的模样,他心稍稍一宽。
“符富,”万里辉随口说道,“是你儿子?”
“啊”符不二一时间不知道说什么好,符富早不是他家的小厮了,当然更不是他的儿子,“是……符喜他们的哥哥。”
万里辉点点头,忽然想起来符富不就是当年符不二求他去要军饷的那个家养小厮么。为了这事他还平白无故的在吃了一个钉子。被魏爱文等人数落了一番。想到这里,万里辉的脸上就变得不大好看了。
众人一见有首长来,不便再在这里,纷纷都散了。
符富赶紧立正站好,一副“听候命令”的模样。
“既然是你家里人,不用这么拘束。”万里辉装作不在意的挥了挥手,又问,“你回家有没有去报到一下?”
“报告首长,还没有”
“快去!”万里辉摆出首长的架势来,他转眼一看符一金脸色红扑扑的,有点痴痴的看着符富,心里愈发不痛快起来。虽然他摇号买了一个级女仆之后就对符一金有点冷下来了,但是一直把符家的大女儿当作自己随时可以采摘的花朵,忽然发觉对方暗恋上了一个土著士兵,心里当然很不乐意。
“是!”符富也赶紧溜了出来,刚才聊天说话让他享受了一番众星捧月感受,把去驻在警那里报到给忘记了。照规矩士兵休假回家,到家后必须立刻向驻在警报到盖章,否则回部队之后没法销假。
驻在警的住家,在东村和西村交界的地方--当初修在这里是便于东村和西村的人能够同样方便的办事。驻在警的住所是由民政委员会出资修建的,两层小楼,楼上是驻在警的住家和宿舍,楼下是警察的办公室和临时拘留所。按照冉耀的警务规划,每个千人以上的村落均要配备两名驻在警。其中一人在当地长期安家落户,另一人由新进警察轮换担任。
驻在警除了维持当地治安,还直接负责轻微案件审理,由于这种执法最少需要两人,所以冉耀最终决定每个千人以上的标准村至少要有2名驻在警。他们同时还负责社情民意的收集,户籍管理和外来人口的管理。
军人探亲当然属于“外来人口”管理,符富赶紧到了“警察阁子”,因为驻在警的住所是一栋小楼,土著们就这样称呼了。
没想到推进去“警察阁子”里也有个“首长”,和万首长那占满泥巴的工作服不一样,他穿着整齐,看上去极有风度。正和驻在警在说话。
符富小心翼翼的敬了个礼,这才向驻在警出示休假证件因为他要在这里住三天以上,所以必须登记临时户口。
“急什么,没看到我和首长在说话”
把帽子推到脑后的黑衣服警察一边擦着脑上的汗一边训斥道。
“你先给他办好了,我们的事还得好一会。”说话的首长和颜悦色的说道。符富不由得看了他一眼,这是个三十来岁的首长,他的身材没有其他首长那么高大,但是同样健壮,长了一张不大会留下印象的大众脸。
符富忽然发觉:这个首长穿得是一身取下了兵种和军衔符号的海军制服,他也没有佩戴指挥刀。一个海军元老军官忽然跑到美洋村来干嘛呢?
很快办完了手续,盖了章,只听驻在警又在诉苦:“……您不知道,村里的事情实在太多,这村子里外来户和土著矛盾很大蒜皮的事情三天两头有,这不一堆的调查表要填……你老得等我一会,等办完了这些事马上就办,你老体谅一下……”
“一等兵!”符富刚要出去,就被首长叫住了。他赶紧站住,转身敬礼。
“你是本村人么?”
“报告长官:是的!”
“新移民还是土著?”
“报告长官:是土著。”
驻在警接话道:“这是符不二家的……”
“一等兵!你愿意帮我办事吗?”
“报告长官!为元老服务是我的荣誉!”符富按照套路大声的说着。
“稍息!不用搞得这么正式!”
“是,长官!”
“我是仲裁庭的许可。”许可在仲裁庭属于“借用”的身份,没有正式的头衔。他在马甲的要求下被暂时借到仲裁庭办理这次的破坏军婚案件,充当法官。
由于此案子是新得法律体系走入土著的开端,有必要慎重点对待。争取一个法权威和土著可预见的平衡,之后就可以考虑用临高自己的对土著法取代大明律了。马甲专召开了一次法学会的全会。就这个案件的法学理论、审理模式、适用法系和如何量刑进行了逐条的讨论,以确保这一案件具有“历史意义”。
新得法律必须体现的是统治阶级也就是元老院的意志。而元老院的终极目标是改造社会,也就是说,审判的目的是不简单的惩罚,而是在“移风易俗“上。
首先,大家一致认为在管辖权问题上,这个案子还是走普通的法院程序为好,不宜贸然搞军事法庭。这一方面要考虑社会效应和政治效果,另一方面没有诉讼法典,贸然走军事法院途径难以服人,于法无凭。
在会议上,法学会经过讨论认为形成三个基本观点:
第一,元老院并没有颁布相关的成文法。那么就应当本着从旧兼从轻的原则和罪刑法定的原则进行审判。那么,还是以本地通行的习惯法或者大明律为基础,进行裁判。
第二,应当立即在法庭审理后进行公开释法,增进土著百姓对元老们法学理念的了解。
第三,赶紧制订颁布相关的法律。不教而杀谓之虐。
大家认为,由于元老院至今没有公布过婚姻法或者民法典之类的法律,所以本案在没有成文法的情况下适用大明律定罪是恰当的,至于量刑上可以由法官裁量而由于临高法院系统应当讲政治,再加上这个案子的重要意义,可以考虑引入审判委员会制,将元老院内部的精神通过审委会讨论的方式转换为可被各方面接受的判决。军方要求严惩是有一定的合理的。
这样做一方面对外确立了法律系统在土著中的权威,另一方面确立了元老院对司法系统的政治领导与思想领导,在当前政治背景下是可以接受的。
总之,在审理中争取一个法律权威和土著可预见的平衡,之后再考虑用新得法律取代大明律。
指导思想既然已经明确,下一步就是具体的经办,马甲借调了在情报局工作的许可担任法官,由姬信担任免费的辩护律师,而公诉人由安熙来担任。
许可接到这个案子之后,决定亲自到事发地点,也就是海兵的家乡所在地来进行一番实地调查按理说这不是他的事情,但是安熙的办事能力实在让人不能放心。根据他从海军调取来的士兵档案,这个被人nr的士兵和奸夫都住在美洋村。
许可决定自己亲自出马到美洋村来进行实地调查,以确保这个案件的“事实清楚”,“证据确凿”。
“你认识这个人吗?”他说了戴了绿帽子水兵的名字。
“报告长官!认识,就是本村的。”
许可点点头:“不用报告,就一般的说话好了。”
“是!”符富说,“这是个福佬不,福建人。七八年前就到我们这里来安家落户了。开始是靠打短工过活,又开了几亩荒地……”
“他老婆是什么时候娶得?”
“是他从福建带来得。”
“没有孩子?”
“有过,都死了。”符富说。
“你看,一个出去好几年的士兵都比你消息灵通!”许可带着责备的神气对驻在警说道,“你到这里多久了?都在干什么?!”
“是,是,首长,小的……我,不是这村里的……”驻在警这下急得汗如雨下,“小的我刚来三个月……”
“好了,你自己反思反思工作效率问题!”许可原来还想就他一团糟的工作指出些问题来,但是想到自己不是警政部的元老,不宜直接动手指手画脚,便放缓了口气,“既然来了没多久,以后要多花点心思!”
|
Java
|
UTF-8
| 2,512 | 2.671875 | 3 |
[] |
no_license
|
package com.team5.game.tools;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GameState implements Serializable {
private static GameState instance;
private int difficulty;
private int currentHealth;
private float playerX;
private float playerY;
private boolean[] systemsBroken = new boolean[19];
private int systemsBrokenNumber;
private int infiltratorNumber;
private GameState() {}
public static void initialise() {
instance = new GameState();
instance.setDifficulty(Difficulty.difficulty);
instance.setCurrentHealth(Constants.MAX_HEALTH);
instance.setPlayerX(50 * Constants.TILE_SIZE);
instance.setPlayerY(95 * Constants.TILE_SIZE);
Arrays.fill(instance.getSystemsBroken(), false);
instance.setSystemsBrokenNumber(0);
instance.setInfiltratorNumber(Difficulty.getNoInfiltrators());
}
public static void initialise(GameState loadedGameState) {
instance = loadedGameState;
}
public static GameState getInstance() {
if (instance == null) {
throw new IllegalStateException("GameState has not been initialized");
}
return instance;
}
public int getDifficulty() {
return difficulty;
}
public void setDifficulty(int difficulty) {
this.difficulty = difficulty;
}
public int getHealth() {
return currentHealth;
}
public void setCurrentHealth(int healthRemaining) {
this.currentHealth = healthRemaining;
}
public float getPlayerX() {
return playerX;
}
public void setPlayerX(float playerX) {
this.playerX = playerX;
}
public float getPlayerY() {
return playerY;
}
public void setPlayerY(float playerY) {
this.playerY = playerY;
}
public boolean[] getSystemsBroken() {
return systemsBroken;
}
public void setSystemsBroken(boolean[] systemsBroken) {
this.systemsBroken = systemsBroken;
}
public void setSystemsBrokenNumber(int systemsBrokenNumber) {
this.systemsBrokenNumber = systemsBrokenNumber;
}
public int getSystemsBrokenNumber() {
return systemsBrokenNumber;
}
public int getInfiltratorNumber() {
return infiltratorNumber;
}
public void setInfiltratorNumber(int infiltratorNumber) {
this.infiltratorNumber = infiltratorNumber;
}
}
|
Java
|
UTF-8
| 736 | 1.8125 | 2 |
[] |
no_license
|
package pomPages.todoLy;
import controls.Button;
import controls.TextBox;
import org.openqa.selenium.By;
public class TodoistLogin {
public TextBox emailTextBox = new TextBox(By.xpath("//input[@class=\"input_email\"]"));
public Button registrarEmailButton = new Button(By.xpath("//button[@id=\"step_one_submit\"]"));
public TextBox nameTextBox = new TextBox(By.xpath("//input[@class=\"input_name\"]"));
public TextBox passTextBox = new TextBox(By.xpath("//input[@type=\"password\"]"));
public Button registrarButton = new Button(By.xpath("//button[@id=\"step_two_submit\"]"));
public Button abrirButton = new Button(By.xpath("//a[@class=\"tdo-button js-cta js-cta-finish\"]"));
public TodoistLogin(){}
}
|
Java
|
UTF-8
| 2,761 | 2.296875 | 2 |
[] |
no_license
|
package com.zhihuishu.springboot.springboothello;
import com.zhihuishu.springboot.springboothello.test.bean.Person;
import com.zhihuishu.springboot.springboothello.test.controller.HelloWorldController;
import org.junit.Before;
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.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootHelloApplicationTests {
private MockMvc mvc;
@Autowired
private ApplicationContext ioc;
@Autowired
private Person person;
/*@Autowired
private RedisTemplate redisTemplate;*/
/*@Test
public void redisTest(){
//redisTemplate.opsForValue().set("test:set","testValue1");
Object o = redisTemplate.opsForValue().get("test:set");
System.out.println(o);
}*/
/*@Test
public void springSessionTest(HttpSession session){
session.setAttribute("uid","123456789");
}*/
@Test
public void test1(){
//System.out.println(97 >>> 16);
String result = "/";
result = result.substring(0, result.length() - 1);
System.out.println("result"+result);
}
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void getHello() throws Exception {
ResultActions hello_world = mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
System.out.println(hello_world);
}
@Test
public void contextLoads() {
}
@Test
public void filterLetter(){
String s = "sf98 97&^%fdferf";
s = s.replaceAll("[^0-9]","");
System.out.println(s);
}
@Test
public void test(){
boolean b = ioc.containsBean("helloSevice");
System.out.println(b);
System.out.println(person);
}
@Autowired
private DataSource dataSource;
@Test
public void test2() throws SQLException{
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
|
PHP
|
UTF-8
| 3,227 | 2.8125 | 3 |
[] |
no_license
|
<?php
/**
* File for class DHLStructCancelPickupRequest
* @package DHL
* @subpackage Structs
* @author WsdlToPhp Team <contact@wsdltophp.com>
* @version 20150429-01
* @date 2016-03-21
*/
/**
* This class stands for DHLStructCancelPickupRequest originally named CancelPickupRequest
* Documentation : The data for cancelling a pickup order. The version of the webservice implementation for which the requesting client is developed.
* Meta informations extracted from the WSDL
* - from schema : {@link https://www.intraship.de/ws/1_0/ISService/DE/is_base_de.xsd}
* @package DHL
* @subpackage Structs
* @author WsdlToPhp Team <contact@wsdltophp.com>
* @version 20150429-01
* @date 2016-03-21
*/
class DHLStructCancelPickupRequest extends DHLWsdlClass
{
/**
* The Version
* @var DHLStructVersion
*/
public $Version;
/**
* The BookingConfirmationNumber
* Meta informations extracted from the WSDL
* - documentation : The confirmation number of the pickup order which should be cancelled. Use value from pickup response attribute 'ConfirmationNumber' to cancel respective pickup order.Note: only one pickup can be deleted at a time.
* @var string
*/
public $BookingConfirmationNumber;
/**
* Constructor method for CancelPickupRequest
* @see parent::__construct()
* @param DHLStructVersion $_version
* @param string $_bookingConfirmationNumber
* @return DHLStructCancelPickupRequest
*/
public function __construct($_version = NULL,$_bookingConfirmationNumber = NULL)
{
parent::__construct(array('Version'=>$_version,'BookingConfirmationNumber'=>$_bookingConfirmationNumber),false);
}
/**
* Get Version value
* @return DHLStructVersion|null
*/
public function getVersion()
{
return $this->Version;
}
/**
* Set Version value
* @param DHLStructVersion $_version the Version
* @return DHLStructVersion
*/
public function setVersion($_version)
{
return ($this->Version = $_version);
}
/**
* Get BookingConfirmationNumber value
* @return string|null
*/
public function getBookingConfirmationNumber()
{
return $this->BookingConfirmationNumber;
}
/**
* Set BookingConfirmationNumber value
* @param string $_bookingConfirmationNumber the BookingConfirmationNumber
* @return string
*/
public function setBookingConfirmationNumber($_bookingConfirmationNumber)
{
return ($this->BookingConfirmationNumber = $_bookingConfirmationNumber);
}
/**
* Method called when an object has been exported with var_export() functions
* It allows to return an object instantiated with the values
* @see DHLWsdlClass::__set_state()
* @uses DHLWsdlClass::__set_state()
* @param array $_array the exported values
* @return DHLStructCancelPickupRequest
*/
public static function __set_state(array $_array,$_className = __CLASS__)
{
return parent::__set_state($_array,$_className);
}
/**
* Method returning the class name
* @return string __CLASS__
*/
public function __toString()
{
return __CLASS__;
}
}
|
Markdown
|
UTF-8
| 4,925 | 2.71875 | 3 |
[] |
no_license
|
---
description: "Easiest Way to Make Quick Pumpkin Dog Biscuits"
title: "Easiest Way to Make Quick Pumpkin Dog Biscuits"
slug: 1464-easiest-way-to-make-quick-pumpkin-dog-biscuits
date: 2020-05-27T09:40:59.009Z
image: https://img-global.cpcdn.com/recipes/6540781627113472/751x532cq70/pumpkin-dog-biscuits-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/6540781627113472/751x532cq70/pumpkin-dog-biscuits-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/6540781627113472/751x532cq70/pumpkin-dog-biscuits-recipe-main-photo.jpg
author: Eliza Santiago
ratingvalue: 3
reviewcount: 14
recipeingredient:
- "2 3/4 cup allpurpose flour"
- "1/2 cup powdered milk"
- "1 tsp salt"
- "1/4 tsp garlic powder"
- "1 large egg"
- "6 tsp vegetable oil"
- "1/2 cup vegetable puree pumpkin spinach squash carrot ETC"
- "10 tbsp water IF NEEDED"
recipeinstructions:
- "**I used frozen leftover canned pumpkin from Thanksgiving for this batch. I also save the carrots and parsnips from my homemade chicken stock to make these biscuits. When my produce starts to look weepy rather than throw them away, I toss them in the freezer to cook and puree for these biscuits at a later date.**"
- "Preheat oven to 300°F."
- "Whisk together powdered milk, salt, garlic powder, egg, vegetable oil and vegetable puree."
- "**DEPENDING on water content of your choice of vegetable puree you MAY have to add some water to get all the flour incorporated.**"
- "Add flour in 3 to 4 batches. Knead dough on floured surface for minutes."
- "Roll out dough to 1/2-1/4 inch thickness."
- "Cut out biscuits using your choice of cutter. I used a shot glass for puppy sized treats."
- "Place on parchment paper lined baking sheet. Bake an oven 20 to 35 minutes or until crispy. Sometimes I leave them in the oven over night after baking to dry them out really well."
- "Your dogs will love these homemade treats AND you get the satisfaction of knowing what exactly your dog is eating!!"
categories:
- Recipe
tags:
- pumpkin
- dog
- biscuits
katakunci: pumpkin dog biscuits
nutrition: 288 calories
recipecuisine: American
preptime: "PT16M"
cooktime: "PT53M"
recipeyield: "2"
recipecategory: Dessert
---

Hey everyone, it is John, welcome to my recipe page. Today, I'm gonna show you how to prepare a special dish, pumpkin dog biscuits. One of my favorites food recipes. For mine, I will make it a little bit tasty. This is gonna smell and look delicious.
Pumpkin Dog Biscuits is one of the most well liked of current trending foods in the world. It's simple, it's quick, it tastes yummy. It's appreciated by millions daily. Pumpkin Dog Biscuits is something that I've loved my entire life. They're nice and they look fantastic.
To get started with this recipe, we must first prepare a few ingredients. You can have pumpkin dog biscuits using 8 ingredients and 9 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Pumpkin Dog Biscuits:
1. Make ready 2 3/4 cup all-purpose flour
1. Make ready 1/2 cup powdered milk
1. Get 1 tsp salt
1. Take 1/4 tsp garlic powder
1. Get 1 large egg
1. Prepare 6 tsp vegetable oil
1. Prepare 1/2 cup vegetable puree (pumpkin, spinach, squash, carrot, ETC.)
1. Get 10 tbsp water, IF NEEDED
<!--inarticleads2-->
##### Instructions to make Pumpkin Dog Biscuits:
1. **I used frozen leftover canned pumpkin from Thanksgiving for this batch. I also save the carrots and parsnips from my homemade chicken stock to make these biscuits. When my produce starts to look weepy rather than throw them away, I toss them in the freezer to cook and puree for these biscuits at a later date.**
1. Preheat oven to 300°F.
1. Whisk together powdered milk, salt, garlic powder, egg, vegetable oil and vegetable puree.
1. **DEPENDING on water content of your choice of vegetable puree you MAY have to add some water to get all the flour incorporated.**
1. Add flour in 3 to 4 batches. Knead dough on floured surface for minutes.
1. Roll out dough to 1/2-1/4 inch thickness.
1. Cut out biscuits using your choice of cutter. I used a shot glass for puppy sized treats.
1. Place on parchment paper lined baking sheet. Bake an oven 20 to 35 minutes or until crispy. Sometimes I leave them in the oven over night after baking to dry them out really well.
1. Your dogs will love these homemade treats AND you get the satisfaction of knowing what exactly your dog is eating!!
So that's going to wrap this up for this special food pumpkin dog biscuits recipe. Thank you very much for your time. I'm sure you will make this at home. There is gonna be interesting food in home recipes coming up. Remember to save this page in your browser, and share it to your family, friends and colleague. Thanks again for reading. Go on get cooking!
|
PHP
|
UTF-8
| 2,725 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Sobit\SudokuChecker\Sudoku;
use Sobit\SudokuChecker\Factory\SudokuBoxFactory;
use Sobit\SudokuChecker\Factory\SudokuColumnFactory;
use Sobit\SudokuChecker\Factory\SudokuRowFactory;
use Sobit\SudokuChecker\Helper\ArrayHelper;
use Sobit\SudokuChecker\Validator\DimensionValidator;
/**
* Class Sudoku
*/
class Sudoku
{
/**
* @var SudokuRowFactory
*/
private $rowFactory;
/**
* @var SudokuColumnFactory
*/
private $columnFactory;
/**
* @var SudokuBoxFactory
*/
private $boxFactory;
/**
* @var ArrayHelper
*/
private $arrayHelper;
/**
* @var SudokuRow[]
*/
private $rows;
/**
* @var SudokuColumn[]
*/
private $columns;
/**
* @var SudokuBox[]
*/
private $boxes;
/**
* @param array $sudoku
* @param SudokuRowFactory $srf
* @param SudokuColumnFactory $scf
* @param SudokuBoxFactory $sbf
* @param ArrayHelper $ah
*/
public function __construct(array $sudoku, SudokuRowFactory $srf, SudokuColumnFactory $scf, SudokuBoxFactory $sbf, ArrayHelper $ah)
{
$this->rowFactory = $srf;
$this->columnFactory = $scf;
$this->boxFactory = $sbf;
$this->arrayHelper = $ah;
$this->initRows($sudoku);
$this->initColumns($sudoku);
$this->initBoxes($sudoku);
}
/**
* @param array $sudoku
*/
private function initRows(array $sudoku)
{
for ($i = 0; $i < 9; $i++) {
$extractedRow = $this->arrayHelper->extract($sudoku, $i, 0, 1, 9);
$this->rows[] = $this->rowFactory->build($extractedRow);
}
}
/**
* @param array $sudoku
*/
private function initColumns(array $sudoku)
{
for ($i = 0; $i < 9; $i++) {
$extractedColumn = $this->arrayHelper->extract($sudoku, 0, $i, 9, 1);
$this->columns[] = $this->columnFactory->build($extractedColumn);
}
}
/**
* @param array $sudoku
*/
private function initBoxes(array $sudoku)
{
for ($i = 0; $i < 9; $i = $i + 3) {
for ($j = 0; $j < 9; $j = $j + 3) {
$extractedBox = $this->arrayHelper->extract($sudoku, $i, $j, 3, 3);
$this->boxes[] = $this->boxFactory->build($extractedBox);
}
}
}
/**
* @return SudokuRow[]
*/
public function getRows()
{
return $this->rows;
}
/**
* @return SudokuColumn[]
*/
public function getColumns()
{
return $this->columns;
}
/**
* @return SudokuBox[]
*/
public function getBoxes()
{
return $this->boxes;
}
}
|
Java
|
UTF-8
| 285 | 2.203125 | 2 |
[] |
no_license
|
import com.ssau.btc.sys.CurrentPriceProvider;
import org.junit.Test;
/**
* Author: Sergey42
* Date: 05.04.14 18:24
*/
public class CurrentPriceTest {
@Test
public void run() {
System.out.println(new CurrentPriceProvider().getCurrentPrice());
}
}
|
JavaScript
|
UTF-8
| 399 | 4.03125 | 4 |
[] |
no_license
|
// triangle.js
//
// Write a triangle on the console
for (let i = 0, pound = ""; i < 7; i++) {
console.log(pound += "#");
}
// NOTE: The above could also be done using the padStart method built into
// strings on an empty string (e.g. "".padStart(i,"#") == "#####") when i = 5)
// or with the repeat method (e.g. "#".repeat(4) = "####") but these methods
// are not introduced until chapter 4.
|
Java
|
UTF-8
| 1,005 | 3.375 | 3 |
[] |
no_license
|
package com.ocalessons.lesson13;
public class Lesson13 {
public void lesson13() {
System.out.println("Start Lesson 13");
int aa;
for (int i = 0; i < 9; i++) {
switchMounth(i);
}
}
public void switchMounth(int a) {
switch (a) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
default:
System.out.println("Fucking month");
}
}
}
|
C#
|
UTF-8
| 1,861 | 2.609375 | 3 |
[
"MS-PL"
] |
permissive
|
//===============================================================================================================
// System : Personal Data Interchange Classes
// File : CardKind.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 12/20/2019
// Note : Copyright 2019, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This enumerated type defines the various vCard kinds for the KindProperty class
//
// This code is published under the Microsoft Public License (Ms-PL). A copy of the license should be
// distributed with the code and can be found at the project website: https://github.com/EWSoftware/PDI.
// This notice, the author's name, and all copyright notices must remain intact in all applications,
// documentation, and source files.
//
// Date Who Comments
// ==============================================================================================================
// 12/20/2019 EFW Created the code
//===============================================================================================================
using System;
namespace EWSoftware.PDI.Properties
{
/// <summary>
/// This enumerated type defines the various vCard kinds for the <see cref="KindProperty"/> class
/// </summary>
[Serializable]
public enum CardKind
{
/// <summary>
/// No type defined
/// </summary>
None,
/// <summary>
/// An individual
/// </summary>
Individual,
/// <summary>
/// A group
/// </summary>
Group,
/// <summary>
/// An organization
/// </summary>
Organization,
/// <summary>
/// A location
/// </summary>
Location,
/// <summary>
/// Indicates some other type of vCard
/// </summary>
Other
}
}
|
Python
|
UTF-8
| 890 | 3.40625 | 3 |
[] |
no_license
|
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.bttn_clicks = 0
self.create_widgets()
def create_widgets(self):
self.lbl = Label(self, text="Click to increment!")
self.lbl.grid()
self.bttn = Button(self, text = "Total Clicks: 0",command = self.update_button)
self.bttn.grid()
def update_button(self):
self.bttn_clicks += 1
self.bttn["text"] = "Total Clicks: " + str(self.bttn_clicks)
#define a method to serve as the event handler
#the method should increment the attribute
#and update the text for the button as well!
# main
root = Tk()
root.title("Click Counter")
root.geometry("200x50")
root.resizable(width = FALSE, height = FALSE)
app = Application(root)
root.mainloop()
|
JavaScript
|
UTF-8
| 2,556 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
var App = {
foods: [],
dataUrl: 'http://joefearnley.com/slow-carb-search/data/foods.json',
init: function () {
this.fetchFoods();
},
fetchFoods: function() {
var self = this;
$.get(self.dataUrl).done(function(response) {
self.foods = response;
self.showForm();
self.bindEvents();
}).fail(function(response) {
console.log('Error fetching foods: ' + response.resposeText);
});
},
bindEvents: function () {
$('body').tooltip({ selector: '[data-toggle=tooltip]' });
$('form#search-form').on('keyup', this.handleFormKeyUp);
$('form#search-form').on('submit', this.handleFormSubmission);
$('#info-button').click(this.toggleInfoButton);
},
handleFormKeyUp: function (e) {
e.preventDefault();
var query = (this.value === undefined) ? $('#query').val() : this.value;
if(query === '') {
$('#results').html('');
}
},
handleFormSubmission: function (e) {
e.preventDefault();
var self = App;
var query = (this.value === undefined) ? $('#query').val() : this.value;
if(query === '') {
return false;
}
var context = self.search(query);
var html = $('#results-template').html();
var template = Handlebars.compile(html);
$('#results').html(template(context));
},
toggleInfoButton: function () {
$('#info').slideToggle(function () {
var icon = $('#info-button-icon');
if(icon.hasClass('fa-info-circle')) {
$('#info-button').addClass('open');
icon.removeClass('fa-info-circle').addClass('fa-close');
} else {
$('#info-button').removeClass('open');
icon.removeClass('fa-close').addClass('fa-info-circle');
}
});
},
showForm: function () {
$('#form').html($('#search-form-template').html());
},
search: function(query) {
var context = {
name: query,
allowed: false,
allowed_in_moderation: false
};
var results = App.foods.filter(function(food) {
return (query.toLowerCase() == food.name.toLowerCase());
});
if(results.length > 0) {
context.name = results[0].name;
context.allowed = true;
context.allowed_in_moderation = results[0].allowed_in_moderation;
}
return context;
}
};
|
PHP
|
UTF-8
| 1,952 | 2.671875 | 3 |
[] |
no_license
|
<?php
/**
* The primary tool for the plugin.
*
* @since {{VERSION}}
*/
defined( 'ABSPATH' ) || die();
class WCM_GAP_Tool {
/**
* WCM_GAP_Tool constructor.
*
* @since {{VERSION}}
*/
function __construct() {
add_action( 'current_screen', array( $this, 'screen_actions' ) );
add_action( 'wp_ajax_wcm_gap_grant_access_run', array( $this, 'ajax_batch_run' ) );
}
/**
* Fires actions only a given screen.
*
* @since {{VERSION}}
* @access private
*
* @param WP_Screen $screen
*/
function screen_actions( $screen ) {
if ( $screen->id === 'wc_membership_plan' ) {
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 1 );
add_action( 'admin_footer', array( $this, 'output_modal' ) );
}
}
/**
* Enqueues scripts.
*
* @since {{VERSION}}
* @access private
*/
function enqueue_scripts() {
wp_enqueue_style( 'wcm-gap' );
wp_enqueue_script( 'wcm-gap' );
}
/**
* Runs a batch import.
*
* @since {{VERSION}}
* @access private
*/
function ajax_batch_run() {
$limit = isset( $_REQUEST['limit'] ) ? $_REQUEST['limit'] : 100;
$offset = isset( $_REQUEST['offset'] ) ? $_REQUEST['offset'] : 0;
require_once WCM_GAP_DIR . 'core/wcm-gap-mock.php';
$grant_count = wcm_gap_mock_grant_access_to_membership( $limit, $offset );
wp_send_json_success( array(
'grant_count' => $grant_count,
) );
}
/**
* Retrieves number of rows in orders table to know how long this will take.
*
* @since {{VERSION}}
* @access private
*/
public static function get_total_orders() {
global $wpdb;
$count = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->prefix}woocommerce_order_items" );
return $count;
}
/**
* Outputs the modal HTML.
*
* @since {{VERSION}}
* @access private
*/
function output_modal() {
$redirect_to = get_edit_post_link( $_REQUEST['post'], 'redirect' );
include_once WCM_GAP_DIR . 'core/views/loading-modal.php';
}
}
|
Markdown
|
UTF-8
| 26,810 | 2.734375 | 3 |
[] |
no_license
|
---
layout: default
title: "Spring Boot Recipes"
---
# Spring Boot Recipes
{:.no_toc}
* TOC
{:toc}
## Overview
These are my notes from the book [Spring Boot 2 Recipes: A Problem-Solution Approach](https://www.amazon.ca/dp/1484239628). I highly recommend this book to anyone who is already somewhat familiar with the Spring Framework, but wants to get familiar with Spring Boot. Kudos to Marten Deinum on his great work. If you like what you see here in my notes, I highly encourage you to buy the book which has many more useful information and examples.
## Chapter 1 - Hello World
A Hello World in Spring Boot can be done as follows. Directory Layout:
```
.
├── pom.xml
└── src
└── main
└── java
└── biz
└── tugay
└── DemoApplication.java
```
pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>biz.tugay</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
```
DemoApplication.java
```java
package biz.tugay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx =
SpringApplication.run(DemoApplication.class, args);
System.out.println(ctx.getBeanDefinitionCount());
}
}
```
Note that when `spring-boot-starter` was added to dependencies, no version information was added. This is because `spring-boot-starter-parent` has default for core dependencies needed in a Spring Boot application, such as the Spring Framework, Logback for logging and Spring Boot itself.
`@SpringBootApplication` annotation is a combination of the following annotations:
- `@Configuration`
- `@ComponentScan`
- `@EnableAutoConfiguration`
### Limitting Scanned Packages
As simple as:
```java
@SpringBootApplication(scanBasePackages = {"biz.tugay.foo", "biz.tugay.bar"})
```
This may be needed when there are dependencies in your classpath that you do not want to be picked up.
## Chapter 2 - Spring Boot Basics
### Configuring a Bean using `@Component`
Any class annotated with the `@Component` annotation will be picked up by and instantiated by Spring Boot.
If we add the following class to our project, we do not need to change anything else, the message will be printed:
```java
package biz.tugay;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class MyFirstBean {
@Value("${biz.tugay.myCustomProperty}")
private String message;
@PostConstruct
public void printMessage() {
System.out.println(message);
}
}
```
Here, I also added `application.properties` file in `resources` folder:
```properties
biz.tugay.myCustomProperty=Hello World!
```
### Configuring a Bean using `@Bean` on a Factory Method
`@Bean` annotation on methods can be used to create beans from factory methods. Given again we have the same `application.properties` file from above, without using the `@Component` annotation, create a class as follows:
```java
package biz.tugay;
import org.springframework.beans.factory.annotation.Value;
public class MySecondBean {
private String message;
public void printMessage() {
System.out.println(message);
}
@Value("${biz.tugay.myCustomProperty}")
public void setMessage(String message) {
this.message = message;
}
}
```
And in our main class, we can create a bean from this class using a factory method:
```java
package biz.tugay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx =
SpringApplication.run(DemoApplication.class, args);
MySecondBean mySecondBean = ctx.getBean(MySecondBean.class);
mySecondBean.printMessage();
}
@Bean
public MySecondBean mySecondBean() {
return new MySecondBean();
}
}
```
This gives more power over bean creation, and also allows us to create beans from 3<sup>rd</sup> party libraries. For example, we could have a `RestTemplate` bean configured in a specific way using this approach, if we wanted to.
### Injecting Components
Using the [Constructor Injection](https://reflectoring.io/constructor-injection/) is the best practice, and the `@Autowired` annotation is not needed, if only a single constructor exists for a `@Component`. In other words, given `FooBaz` is a `Component`, it will already be injected in the following example:
```java
@Component
public class FooBar {
private final FooBaz fooBaz;
public FooBar(FooBaz fooBaz) {
this.fooBaz = fooBaz;
}
}
```
### Externalize Properties
We have already used the `application.properties` file above in our examples. The following is a rough hierarchy where the properties are read from:
1. Command line arguments
1. `application-{profile}.properties` outside the packaged application
1. `application.properties` outside the packaged application
1. `application-{profile}.properties` in the packaged application
1. `application.properties` in the packaged application
Simply having an `application.properties` where you have the `jar` file will override the `application.properties` bundled within the application, for example.
To make use of a specific profile, add `--spring.profile.active=` in command line. To override any arbirary propery in command line arguments, pass the desired value with `--propertyName=propertyValue`.
[Here](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config) is the full hierarchy if you are interested.
#### Example Making Use of Profiles
Given a project with the following directory layout:
```
.
├── pom.xml
└── src
└── main
├── java
│ └── biz
│ └── tugay
│ ├── DemoApplication.java
│ └── FooBar.java
└── resources
├── application-dev.properties
├── application-prod.properties
└── application.properties
```
And the file contents as follows:
pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>biz.tugay</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
```
DemoApplication.java
```java
package biz.tugay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext ctx =
SpringApplication.run(DemoApplication.class, args);
FooBar fooBar = ctx.getBean(FooBar.class);
System.out.println(fooBar.getFooBar());
}
}
```
FooBar.java
```java
package biz.tugay;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class FooBar {
@Value("${foo.bar}")
public String fooBar;
public String getFooBar() {
return fooBar;
}
}
```
Given all the `.properties` file contain a `foo.bar` key with a different value, application can either be started with the following VM arguments as follows `-Dspring.profiles.active=[dev|prod]` or program arguments using the double dash: `--spring.profiles.active=[dev|prod]` to pick up values from the properties file with the passed in suffix.
### Loading Properties from a Different Configuration File
Properties from arbitrary files can be loaded by loading them using another annotation: `@PropertySource`. Here is an example
```java
@PropertySource("classpath:your-external.properties")
```
__Heads Up!__ Give [Setting Custom Properties in Tests](https://reflectoring.io/spring-boot-test/#setting-custom-configuration-properties) a read to refresh your knowledge!
### Setting a Custom Property Value in a `SpringBootTest`
Did you know that you can do the following?
```java
@SpringBootTest(properties = {"foo.bar=overridden"})
@RunWith(SpringRunner.class)
public class FooBarTest {
```
__Heads Up!__ Give [Profiles with Spring Boot](https://reflectoring.io/spring-boot-profiles/) a read to refresh your knowledge!
### Integration Testing with Spring Boot
`@SpringBootTest` will make the test class load the context fully, and run the tests within the context. This is good for integration testing of beans. Unless a `@MockBean` is used in a class, the loaded context will be re-used. Here is an example to get you started:
```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBeanTest {
@Autowired
public MyBean myBean;
@Test
public void valMustBeExpectedValue() {
Assertions.assertThat(myBean.val()).isEqualTo(-1);
}
}
```
Check out [this](https://stackoverflow.com/a/44200907) answer to refresh your knowledge on the difference between `@Mock` and `@MockBean`. When running integration tests and there needs a requirement to mock a bean, you most likely want the `@MockBean` annotation.
## Chapter 3 - Spring MVC
Simply adding the `spring-boot-starter-web` dependency does a lot of work and changes how the application starts. Following is a simple hello world web application:
Directory Layout
```
.
├── pom.xml
└── src
└── main
└── java
└── biz
└── tugay
└── DemoApplication.java
```
pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>biz.tugay</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
```
DemoApplication.java
```java
package biz.tugay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
The default behaviour for `spring-boot-starter-web` is as follows:
1. Start an embedded Tomcat server on port 8080.
1. Register and enable default Servlet Filters.
1. Set up static resource handling for `.css`, `.js` and `favicon.ico` files.
1. Enable integration with WebJars (_What does this mean?_).
1. Setup basic error handling features.
1. Configure the `DispatcherServlet`
An example to create a Controller and return JSON would be as follows:
```java
package biz.tugay;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
static class ResponseDto {
public String message = "Hello World!";
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseDto hello() {
return new ResponseDto();
}
}
```
with a sample run:
```bash
curl -v localhost:8080
# * Trying ::1...
# * TCP_NODELAY set
# * Connected to localhost (::1) port 8080 (#0)
# > GET / HTTP/1.1
# > Host: localhost:8080
# > User-Agent: curl/7.64.1
# > Accept: */*
# >
# < HTTP/1.1 200
# < Content-Type: application/json;charset=UTF-8
# < Transfer-Encoding: chunked
# < Date: Sun, 14 Jun 2020 14:30:05 GMT
# <
# * Connection #0 to host localhost left intact
# {"message":"Hello World!"}
# * Closing connection 0
```
__Heads Up!__ Instead of `@RestController`, one can also use `@Controller` and put `@ResponseBody` on each request handling method. Using `@RestController` will implicitly add `@ResponseBody` to request handling methods. To refresh your knowledge on what `@ResponseBody` does, see [this](https://stackoverflow.com/a/28647129) answer, but in a nutshell:
> ..what the annotation means is that the returned value of the method will constitute the body of the HTTP response.
### Testing the Web Layer
Here is how we could test the `HelloController` we have above using `MockMvc`:
```java
@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private HelloService helloService;
@Before
public void before() {
Mockito.when(helloService.message()).thenReturn("hello world!");
}
@Test
public void testMessage() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(status().isOk())
.andReturn();
String body = mvcResult.getResponse().getContentAsString();
HelloController.ResponseDto responseDto
= new Gson().fromJson(body, HelloController.ResponseDto.class);
Assertions.assertThat(responseDto.message).isEqualTo("hello world!");
}
}
```
`@WebMvcTest` instructs the Spring Test framework to set up an application context for testing this specific controller. It will start a minimal Spring Boot application with only web-related beans like `@Controller`. It will also preconfigure the Spring Test Mock MVC support, which can be autowired.
## Spring Security
Adding the `spring-boot-starter-security` as a dependency automatically configures a basic security in a Spring Boot application. Default username and password can be overridden in `application.properties` file as follows:
```properties
spring.security.user.name=username
spring.security.user.password=password
```
### Hello World Example
pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>biz.tugay</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
DemoApplication.java
```java
package biz.tugay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
FooResource.java
```java
package biz.tugay;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("foo")
public class FooResource {
static class FooDto {
public String message = "Hello from Foo";
}
@GetMapping
public FooDto getFoo() {
return new FooDto();
}
}
```
Using `curl` with authentication:
```bash
curl -u username:password -v -H 'Connection:close' localhost:8080
# * Trying ::1...
# * TCP_NODELAY set
# * Connected to localhost (::1) port 8080 (#0)
# * Server auth using Basic with user 'username'
# > GET / HTTP/1.1
# > Host: localhost:8080
# > Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
# > User-Agent: curl/7.64.1
# > Accept: */*
# > Connection:close
# >
# < HTTP/1.1 200
# < Set-Cookie: JSESSIONID=4FE3C238BF46F14CF978CD9D34CEF083; Path=/; HttpOnly
# < X-Content-Type-Options: nosniff
# < X-XSS-Protection: 1; mode=block
# < Cache-Control: no-cache, no-store, max-age=0, must-revalidate
# < Pragma: no-cache
# < Expires: 0
# < X-Frame-Options: DENY
# < Content-Type: application/json;charset=UTF-8
# < Transfer-Encoding: chunked
# < Date: Sat, 27 Jun 2020 15:37:29 GMT
# < Connection: close
# <
# * Closing connection 0
# {"message":"Hello from Foo"}
```
And a subsequent request as follows will also work in bash:
```bash
curl --cookie "JSESSIONID=4FE3C238BF46F14CF978CD9D34CEF083" -v -H 'Connection:close' localhost:8080
```
A login form will also be made available in `http://localhost:8080/login` by Spring, by default.
### WebSecurityConfigurerAdapter
Spring Boot enables the default security settings when no explicit configuration through `WebSecurityConfigurerAdapter` exists.
### Configuring Authentication - In Memory
The following is an example of configuring in memory authentication. The first requirement is to define a `PasswordEncoder` in our main configuration class:
```java
// This is our @SpringBootApplication class
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
```
```java
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {
private final PasswordEncoder passwordEncoder;
public DemoSecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder) // this can be omitted
// spring will use the defined bean
.withUser("koraytugay")
.password(passwordEncoder.encode("password"))
.roles("USER");
}
}
```
The above will invalidate the default username:password, and user will require to provide `koraytugay:password` when logging in.
### Configuring Authenticated Paths And Required Authorization
Authorization can be configured by overriding yet another method found in the same class:
```java
@Override
protected void configure(HttpSecurity http) throws Exception {
// go from most restrictive to least restrictive
http
.authorizeRequests()
.antMatchers("/foo").hasRole("USER")
.antMatchers("/anon").permitAll()
.antMatchers("static/css", "static/js").permitAll()
.and().formLogin()
.and().httpBasic();
}
```
No login will be required when accessing `/anon` but authentication (together with required authorization) will be required when accessing `/foo`.
### Spring Security Details - AuthenticationProvider
When Spring Security performs authentication, it keeps track of the input and the output information in an `Authentication` object. The input is usually credentials and the output is a `Principal` object.
Spring Security comes with a concept called `AuthenticationProvider`, which is responsible for the main authentication being made. [Here](https://docs.spring.io/spring-security/site/docs/5.3.3.BUILD-SNAPSHOT/api/org/springframework/security/authentication/AuthenticationProvider.html) is the docs for this class, check it out. Both the method parameter and the return type is `Authentication`. This is like a data transfer object for Spring Security.
Typically a single application will have multiple authentication ways, such as form login and LDAP login and so on. Application will have multiple `AuthenticationProvider`s in such a case.
There is a special type in Spring Security - the `AuthenticationManager`, that coordinates all these providers. It too also takes an `Authentication` object and coordinates with the providers.
Spring Security also has a concept called `UserDetailsService`. This service returns all the information if the user is enabled or locked or expired and so on. This service returns an object of type `User`, to the `AuthenticationProvider`. Usually, the `User` returned from the `UserService` becomes directly the `Principal` of the `Authentication` object. Watch [this](https://youtu.be/caCJAJC41Rk?t=955) part to refresh your memory.
Finally, Spring Security saves the Authentication in ThreadLocal. In order to refresh how you can retrieve current user, read [this](https://dzone.com/articles/how-to-get-current-logged-in-username-in-spring-se) article.
### Default and Hardcoded UserDetailsService Example
It seems like we can bypass configuring any `AuthenticationProvider`s and simply define a single `UserDetailsService` which will become the service to be used by the one and only (and default) `AuthenticationProvider` we have. Here is an example:
DemoUserDetails.java
```java
public class DemoUserDetails implements UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority
= new SimpleGrantedAuthority("ROLE_USER");
return Collections.singletonList(simpleGrantedAuthority);
}
@Override
public String getPassword() {
// password encoded with BCryptPasswordEncoder
return "$2a$10$Y2Y82gMirzVZ9y04iHeeJuTfjqRVSFwXJkiheQ2nAE0GrzFpwNmZW";
}
@Override
public String getUsername() {
return "hardcoded-username";
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
```
DemoUserDetailsService.java
```java
@Service
public class DemoUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
return new DemoUserDetails();
}
}
```
DemoSecurityConfig.java
```java
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// go from most restrictive to least restrictive
http
.authorizeRequests()
.antMatchers("/foo").hasRole("USER")
.antMatchers("/anon").permitAll()
.antMatchers("static/css", "static/js").permitAll()
.and().formLogin()
.and().httpBasic();
}
}
```
With this configuration, when `/foo` is accessed, any login will work as long as the provided password in form is `pass`. We did not define any `AuthenticationProvider`s. Also note, we had to appen `ROLE_` in `getAuthorities`, although we call `hasRole("USER")` without the prefix. By simply implementing our own `UserDetailsService` we configured how Spring Security loads users. This class for example can hit a `Repository` class and query for entities.. A good resource I found was [this](https://www.marcobehler.com/guides/spring-security#_introduction).
To see how to configure multiple `AuthenticationProvider`s, see [this](https://www.baeldung.com/spring-security-multiple-auth-providers) page.
## References
- [Spring Framework Official Documentation](https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/index.html)
- [Spring Boot Official Documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/index.html)
- [One-Stop Guide to Profiles with Spring Boot](https://reflectoring.io/spring-boot-profiles/)
- [CSRF Explanation](https://www.marcobehler.com/guides/spring-security#_common_exploit_protections)
|
Python
|
UTF-8
| 270 | 3 | 3 |
[] |
no_license
|
class Solution:
def isSubsequence(self, short: str, long: str) -> bool:
if not short: return True
i = 0
for ch in long:
if ch == short[i]:
i += 1
if i == len(short): return True
return False
|
C++
|
UTF-8
| 480 | 2.5625 | 3 |
[] |
no_license
|
/*
TASK:White Eye
LANG: CPP
AUTHOR: KersW
SCHOOL: RYW
*/
#include<bits/stdc++.h>
using namespace std;
stack<int> st;
int main()
{
int n,m,i,j;
char a ;
scanf("%d %d",&n,&m);
for(i=0;i<n+m;i++){
scanf(" %c",&a);
if(a=='A'){
scanf("%d",&j);
while(!st.empty() && j>=st.top())
st.pop();
st.push(j);
}else{
printf("%d\n",st.size());
}
}
return 0;
}
|
Java
|
UTF-8
| 1,265 | 3.53125 | 4 |
[] |
no_license
|
package com.clear.thread;
/**
* ClassName DeadLock
*
* @author qml
* Date 2021/1/25 11:52
* Version 1.0
**/
public class DeadLock {
private static final String read_lock=new String();
private static final String write_lock=new String();
private void read(){
synchronized (read_lock){
System.out.println(Thread.currentThread().getName()+"得到读锁,下面获取写锁");
synchronized ((write_lock)){
System.out.println(Thread.currentThread().getName()+"读写锁都得到");
}
}
}
private void write(){
synchronized (write_lock){
System.out.println(Thread.currentThread().getName()+"得到写锁,下面获取读锁");
synchronized ((read_lock)){
System.out.println(Thread.currentThread().getName()+"读写锁都得到");
}
}
}
public static void main(String[] args) {
DeadLock deadLock = new DeadLock();
new Thread(()->{
while (true){
deadLock.read();
}
},"read-local").start();
new Thread(() -> {
while (true) {
deadLock.write();
}
}, "write-local").start();
}
}
|
Markdown
|
UTF-8
| 5,016 | 2.765625 | 3 |
[] |
no_license
|
# ViiMU - Varolii Member Utility
## About
This utility was created to allow you to ADD, UPDATE, DELETE members using data in csv format.
##Installation
Note - ViiMU requires suds. [SUDS](https://fedorahosted.org/suds/)
pip install suds
git clone https://github.com/tpe11etier/viimu.git
Once installed you'll need to rename viimu.props.example to viimu.props and enter the correct values for your site.
Logging is also controlled from this properties file. INFO should be fine, but if you really want **lots** of info, set it to DEBUG.
##Usage
Usage:
viimu.py [-f filename] [-a <action> <subaction>] [-s <sync>]
viimu.py -h | --help | -v | --version
Options:
-h --help show this help message and exit
-v --version show version and exit
-f <filename> filename to parse.
Note - filename is not required when querying contact methods(CMS)
and custom fields(CFS).
-a <action> <subaction> actions to perform. [QUERY, ADD, UPDATE, DELETE] [MEMBERS, CFS, CMS]
-s <sync> when using UPDATE, set to TRUE or FALSE. Note - defaults value is FALSE
False if the given members augment information in the Varolii Profiles database.
True if the given members replace the existing subscriptions in the Varolii Profiles database.
##Example Usage and Details
ViiMU will use the csv header row to create the [Member object](https://ws.envoyprofiles.com/WebService/EPAPI_1.0/object/Member.htm).
For that reason, the header needs to match **exactly**. For example. To create a Member, **Username** and **Password** are required attributes.
The csv column headers must be **Username** and **Password**. **USERName** or **PASSWORD** will not work.
---
###QUERY
QUERY is used to query members(MEMBERS), organization contact methods(CMS) and organization custom fields(CFS).
Contact methods can be queried and the return values will be used as the column header.
Note - Only Phone, Email, SMS and Fax are supported at this time.
[tonypelletier@tpelletiermac:viimu]$ ./viimu.py -a QUERY CMS
Phone_Office_0 (Work Phone)
Phone_Home_0 (Home Phone)
Phone_Cell_0 (Cell Phone)
Sms_None_0 (SMS)
Email_Office_0 (Work Email)
Email_Home_0 (Home Email)
AlphaPager_None_0 (Alpha Pager)
AlphaPager_None_0 (Alpha Pager Carrier)
Fax_Office_0 (Fax)
Custom fields can be queried and the return values will be used as the column header.
Note - In order to determine what column headers are custom fields, I am using **CF_** as a prefix.
Your Custom field headers should also include the **CF_**.
[tonypelletier@tpelletiermac:viimu]$ ./viimu.py -a QUERY CFS
CF_Seniority#
CF_STATUS
CF_Building
CF_Floor
CF_boolean
The member query is used to pass in a csv of members that you would like to delete. I made deleting members a two step process to avoid
accidental deletion.
Query members from a csv which writes out a json file that contains member Username's and MemberId's.
[tonypelletier@tpelletiermac:viimu]$ ./viimu.py -f members.csv -a QUERY MEMBERS
['BMarchand', 'TRask']
members.json has been successfully written out with active members found.
[tonypelletier@tpelletiermac:viimu]$ less members.json
[
{
"TRask": "kmhyhkj67",
"BMarchand": "kmhdtkj67"
}
]
members.json (END)
---
###DELETE
Delete the members using the json file.
[tonypelletier@tpelletiermac:viimu]$ ./viimu.py -f members.json -a DELETE
(ArrayOfstring){
string[] =
"kmhyhkj67",
"kmhdtkj67",
}
Are you sure you want to delete 2 users? yes/no: yes
Processing Deletes...
(ArrayOfboolean){
boolean[] =
True,
True,
}
---
###ADD
Add members using csv file passed in.
[tonypelletier@tpelletiermac:viimu]$ ./viimu.py -f members.csv -a ADD
(ArrayOfResponseEntry){
ResponseEntry[] =
(ResponseEntry){
Id = "k85jhkj67"
Warnings = ""
},
(ResponseEntry){
Id = "k85itkj67"
Warnings = ""
},
}
---
###UPDATE
Update members using csv file passed in. When updating members, you can also use the -s option with a value of TRUE or FALSE(Default).
FALSE if the given members augment information in the Varolii Profiles database.
TRUE if the given members replace the existing subscriptions in the Varolii Profiles database.
[tonypelletier@tpelletiermac:viimu]$ ./viimu.py -f members.csv -a UPDATE -s FALSE
['BMarchand', 'TRask']
(ArrayOfResponseEntry){
ResponseEntry[] =
(ResponseEntry){
Id = "k85jhkj67"
Warnings = ""
},
(ResponseEntry){
Id = "k85itkj67"
Warnings = ""
},
}
##TODO
* Document code
* Write test cases
* More logging
* py2exe?
* fix bugs
|
Java
|
WINDOWS-1251
| 2,413 | 2 | 2 |
[] |
no_license
|
package old.com.hps.july.sync.msaccess.adapters;
import java.sql.*;
import old.com.hps.july.sync.*;
import com.hps.july.cdbc.lib.CDBCResultSet;
/**
* @author Ildar
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
public class ForNRITableAdaptor extends SimpleAdaptor {
public ForNRITableAdaptor(SyncConnection argConNRI, SyncConnection argConNFS) {
super(argConNRI, argConNFS, "dbspositions", "_NRI_");
setColumnMap(new ForNRITableMap());
}
private class ForNRITableMap extends ColumnMap {
/**
*
*/
ForNRITableMap() {
super();
// addMap( MSAccess, NRI, isKey)
addMap("", "idrecord", true);
addMap("DAMPS", "dampsid", false);
addMap("GSM", "gsmid", false);
//addMap("%WLAM", "wlanid", false);
addMap("", "name", false);
addMap("2", "name2", false);
addMap("_", "apparattype", false);
addMap("", "containertype", false);
addMap("_", "placetype", false);
addMap("_", "apparatplace", false);
addMap("_", "oporaplace", false);
addMap("", "isouropora", false);
addMap("_", "oporatype", false);
addMap("_", "antennaplace", false);
addMap("", "heightopora", false);
addMap("_", "fiootvexpl", false);
addMap("", "tabnumotvexpl", false);
addMap("", "statebs", false);
addMap("", "datederrick", false);
addMap("", "dateonsitereview", false);
addMap("__", "lastupdmarshkarta", false);
addMap("_", "lastupdlistprohod", false);
addMap("_", "lastupdposition", false);
// , NRI
//addPredefinedColumnNRI("", "");
}
}
}
|
Java
|
UTF-8
| 649 | 2.875 | 3 |
[] |
no_license
|
class c8258096 {
private String encryptPassword(String password) throws NoSuchAlgorithmException {
StringBuffer encryptedPassword = new StringBuffer();
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.reset();
md5.update(password.getBytes());
byte digest[] = md5.digest();
for (int i = 0; i < digest.length; i++) {
String hex = Integer.toHexString(0xFF & digest[i]);
if (hex.length() == 1) {
encryptedPassword.append('0');
}
encryptedPassword.append(hex);
}
return encryptedPassword.toString();
}
}
|
Markdown
|
UTF-8
| 4,565 | 2.859375 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: include file
description: include file
services: logic-apps
author: ecfan
ms.service: logic-apps
ms.topic: include
ms.date: 05/15/2018
ms.author: estfan
ms.custom: include file
---
* If you're using Azure SQL Database, follow the steps under
[Connect to Azure SQL Database](#connect-azure-sql-db).
* If you're using SQL Server, follow the steps under
[Connect to SQL Server](#connect-sql-server).
<a name="connect-azure-sql-db"></a>
### Connect to Azure SQL Database
1. When the SQL trigger or action prompts you for connection information,
follow these steps:
1. Create a name for your connection.
2. Select your SQL server, and then select your database.
The database list appears only after you select your SQL server.
3. Provide your user name and password for your server.
You can find this information either in the Azure portal
under your SQL database properties or in your connection string:
"User ID=<*yourUserName*>"
<br>
"Password=<*yourPassword*>"
This example shows the connection information for a trigger,
but these steps work for actions too.

<br>
Asterisks (*) indicate required values.
| Property | Value | Details |
|----------|-------|---------|
| Connection Name | <*my-sql-connection*> | The name for your connection |
| SQL Server Name | <*my-sql-server*> | The name for your SQL server |
| SQL Database Name | <*my-sql-database*> | The name for your SQL database |
| Username | <*my-sql-username*> | The user name for accessing your database |
| Password | <*my-sql-password*> | The password for accessing your database |
||||
2. When you're done, choose **Create**.
3. After you create your connection, continue with
[Add SQL trigger](#add-sql-trigger) or [Add SQL action](#add-sql-action).
<a name="connect-sql-server"></a>
### Connect to SQL Server
Before you can select your gateway, make sure that you already
[set up your data gateway](https://docs.microsoft.com/azure/logic-apps/logic-apps-gateway-connection).
That way, your gateway appears in the gateways list when you create your connection.
1. When the SQL trigger or action prompts you for connection information,
follow these steps:
1. In the trigger or action, select **Connect via on-premises data gateway**
so that the SQL server options appear.
2. Create a name for your connection.
3. Provide the address for your SQL server, then provide the name for your database.
You can find this information in your connection string:
* "Server=<*yourServerAddress*>"
* "Database=<*yourDatabaseName*>"
4. Provide your user name and password for your server.
You can find this information in your connection string:
* "User ID=<*yourUserName*>"
* "Password=<*yourPassword*>"
5. If your SQL server uses Windows or Basic authentication, select the authentication type.
6. Select the name for your on-premises data gateway that you previously created.
If your gateway doesn't appear in the list, check that you correctly
[set up your gateway](https://docs.microsoft.com/azure/logic-apps/logic-apps-gateway-connection).
This example shows the connection information for a trigger,
but these steps work for actions too.

<br>
Asterisks (*) indicate required values.
| Property | Value | Details |
|----------|-------|---------|
| Connect via on-premises gateway | Select this option first for SQL Server settings. | |
| Connection Name | <*my-sql-connection*> | The name for your connection |
| SQL Server Name | <*my-sql-server*> | The name for your SQL server |
| SQL Database Name | <*my-sql-database*> | The name for your SQL database |
| Username | <*my-sql-username*> | The user name for accessing your database |
| Password | <*my-sql-password*> | The password for accessing your database |
| Authentication Type | Windows or Basic | Optional: The authentication type used by your SQL server |
| Gateways | <*my-data-gateway*> | The name for your on-premises data gateway |
||||
2. When you're done, choose **Create**.
3. After you create your connection, continue with
[Add SQL trigger](#add-sql-trigger) or [Add SQL action](#add-sql-action).
|
Python
|
UTF-8
| 116 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
def say_hello():
print('Hello')
class Astronaut:
name = 'José Jiménez'
jose = Astronaut()
say_hello()
# Hello
|
JavaScript
|
UTF-8
| 2,062 | 3.265625 | 3 |
[] |
no_license
|
/***************************
*
* CHILLI+GARLIC
* MODEL: Faves.js
*
***************************/
/***************************
*
* Faves object
* Methods:
* isFave(recipeID)
* persistFaves()
* restoresFaves()
* addFave
* removeFave
* Properties:
* faveList: array of fave objects
* objFave:
* id
* title
* author
* imageUrl
*
****************************/
export default class Faves {
constructor() {
this.faveList = [];
}
// Determine if specified recipe is in FaveList
isFave(recipeID) {
const faveIndex = this.faveList.findIndex(objFave => objFave.id === recipeID);
return faveIndex !== -1 ? true : false;
}
// Add recipe to Faves list
addFave(newFave) {
this.faveList.push(newFave);
// Persist the updated fave list in local storage
this.persistFaves();
}
// Remove recipe from Faves list
removeFave(recipeID) {
// Find the entry in the array for this id and remove it with splice
const indexToDel = this.faveList.findIndex(objFave => objFave.recipeID === recipeID);
this.faveList.splice(indexToDel, 1);
// Persist the updated fave list in local storage
this.persistFaves();
}
// Clear all faves
clear() {
this.faveList = [];
// Persist the updated fave list in local storage
this.persistFaves();
}
// Persist the search object by turning it into a string and storing in session storage
persistFaves() {
localStorage.setItem('faves', JSON.stringify(this.faveList));
}
// Retrieve search from storage, parse then restore search object details
restoreFaves() {
const arrLocalFaves = JSON.parse(localStorage.getItem('faves'));
// If the retrieved fave list is not null or 0, restore to current Faves object
if (arrLocalFaves && arrLocalFaves.length > 0) {
this.faveList = arrLocalFaves;
}
}
}
|
PHP
|
UTF-8
| 2,492 | 2.765625 | 3 |
[] |
no_license
|
<?php
include("class_mysql.php");
$db = new MYSQL();
//// GET SUBCATEGORIES
if(isset($_GET['cat_id']) && is_numeric($_GET['cat_id']))
{
if($db->connect_db())
{
$cat_id = $db->escape_chars($_GET['cat_id']);
$sql = "SELECT * FROM subcategories WHERE cat_id ='".$cat_id."' ORDER BY subcat_name";
$result = $db->query($sql);
if(mysqli_num_rows($result)==0)
{
echo "None";
}
else
{
$data = "";
while($row = mysqli_fetch_array($result))
{
$data .="<subcategory>";
$data .="<name>".$row['subcat_name']."</name>";
$data .="<id>".$row['subcat_id']."</id>";
$data .="</subcategory>";
}
header('Content-Type: application/xml; charset=ISO-8859-1');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
echo "<answer>";
echo $data;
echo "</answer>";
}
}
else
{
echo "";
}
}
elseif(isset($_GET['getCat']) && is_numeric($_GET['getCat']) && isset($_GET['last']) && is_numeric($_GET['last']))
{
if($db->connect_db())
{
$cat_id = $db->escape_chars($_GET['getCat']);
$sql_posts = "SELECT * FROM posts";
if($cat_id!=0)
$sql_posts .=" WHERE post_cat_id = ".$cat_id." AND post_id > ".$_GET['last'];
if(isset($_GET['getSub']) && is_numeric($_GET['getSub']) && $_GET['getSub']!=0)
{
$subcat_id = $db->escape_chars($_GET['getSub']);
$sql_posts .=" AND post_subcat_id =".$subcat_id;
}
$sql_posts .=" ORDER BY post_date DESC LIMIT 0,10";
if($result = $db->query($sql_posts))
{
$data = "";
$i = 0;
while($row = mysqli_fetch_array($result))
{
$data .= "<message>";
$data .= "<postid>".$row['post_id']."</postid>";
$data .= "<title>".$row['post_title']."</title>";
if($i==0)
$data .= "<message>".$row['post_content']."</message>";
else
$data .= "<message>".strip_tags(substr($row['post_content'],0,150))."</message>";
$data .= "<seotitle>".$row['post_page_link']."</seotitle>";
$data .= "<authorid>".$row['post_author_id']."</authorid>";
$data .= "<authorname>".$row['post_author_name']."</authorname>";
$data .= "<date>".$row['post_date']."</date>";
$data .="</message>";
$i++;
}
header('Content-Type: application/xml; charset=ISO-8859-1');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
echo "<posts>";
echo "<number>".mysqli_num_rows($result)."</number>";
echo $data;
echo "</posts>";
}
else
{
echo "";
}
}
else
{
echo "Server connection problem.";
}
}
?>
|
C
|
UTF-8
| 4,352 | 4.21875 | 4 |
[] |
no_license
|
/*
NAME-Saurav ROLL-1601CS41 DATE-21st march 2017
The aim of the program is to implement a singely linked list and sort it using its height and weight
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//defining the strucure of the node
typedef struct node {
char roll[10];
int ht;
int wt;
struct node *nextht;
struct node *nextwt;
};
//some global variables to be used
struct node *headwt,*headht,*prev=NULL;
int counter=0;
//function to insert a node into the linked list
void insert_node(struct node *x , char temp_roll[],int tht, int twt){
//for the first element i.e. the head
if(prev==NULL){
headht=x;
strcpy(headht->roll,temp_roll);
headht->ht=tht;
headht->wt=twt;
headht->nextht=NULL;
headht->nextwt=NULL;
prev=headht;
headwt=x;
strcpy(headwt->roll,temp_roll);
headwt->ht=tht;
headwt->wt=twt;
headwt->nextht=NULL;
headwt->nextwt=NULL;
prev=headwt;
}
//for the rest of the elements
else{
strcpy(x->roll,temp_roll);
x->ht=tht;
x->wt=twt;
x->nextht=NULL;
x->nextwt=NULL;
prev->nextht=x;
prev->nextwt=x;
prev=x;
}
}
//bubble sort in terms of height
void sort_ht(struct node *h){
int num_nodes = counter;
int count;
//looping and pairwise swapping if necessary
for (count = 0; count < num_nodes; count++) {
struct node* current = headht;
struct node* next = current->nextht;
struct node* previous = NULL;
while(next != NULL) {
if (current->ht > next->ht) {
if (current == headht){
headht = next;
} else {
previous->nextht = next;
}
current->nextht = next->nextht;
next->nextht = current;
previous = next;
next = current->nextht;
}
else {
previous = current;
current = current->nextht;
next = current->nextht;
}
}
}
}
//bubble sort in terms of weight
void sort_wt(struct node *h){
int num_nodes = counter;
int count;
for (count = 0; count < num_nodes; count++) {
struct node* current = headwt;
struct node* next = current->nextwt;
struct node* previous = NULL;
while(next != NULL) {
if (current->wt > next->wt) {
if (current == headwt){
headwt = next;
} else {
previous->nextwt = next;
}
current->nextwt = next->nextwt;
next->nextwt = current;
previous = next;
next = current->nextwt;
}
else {
previous = current;
current = current->nextwt;
next = current->nextwt;
}
}
}
}
//to print the list in desired way
void printNameList(struct node *h , int option){
//sorting using height
if (option==0)
{
sort_ht(h);
printf("Sorted using height:");
struct node *ptr=headht;
while (ptr !=NULL)
{
printf("%s ",ptr->roll);
ptr=ptr->nextht;
}
printf("\n");
}
//sorting using weight
else
{
sort_wt(h);
printf("Sorted using weight:");
struct node *ptr=headwt;
while (ptr !=NULL)
{
printf("%s ",ptr->roll);
ptr=ptr->nextwt;
}
printf("\n");
}
}
int main(){
//the number of elements
int n;
printf("Enter the number of elements:");
scanf("%d",&n);
//temporary variables to store the data
char temp_roll[10];
int tht,twt;
//looping n times and inserting the nodes
int i;
for ( i = 0; i < n; i++)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
printf("Enter the data:");
scanf("%s %d %d",temp_roll,&tht,&twt);
insert_node(temp,temp_roll,tht,twt);
counter++;
}
//printing after sorting using ht
printNameList(headht,0);
//Printing after sorting using wt
printNameList(headwt,1);
return 0;
}
|
SQL
|
UTF-8
| 4,116 | 3.890625 | 4 |
[] |
no_license
|
-- Организация
-- id первичный ключ
-- name название организации
-- full_name полное название организации
-- inn ИНН
-- kpp КПП
-- address адрес
-- phone телефон
-- is_active признак активности
-- version оптимистичная блокировка
CREATE TABLE IF NOT EXISTS organization (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (50) NOT NULL,
full_name VARCHAR (100) NOT NULL,
inn VARCHAR (12) NOT NULL,
kpp VARCHAR (9) NOT NULL,
address VARCHAR (200) NOT NULL,
phone VARCHAR (20),
is_active BOOLEAN DEFAULT FALSE,
version INTEGER
);
-- Оффис
-- id первичный ключ
-- org_id внешний ключ к организации
-- name название
-- address адрес
-- phone телефон
-- is_active признак активности
-- version оптимистичная блокировка
CREATE TABLE IF NOT EXISTS office (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
org_id INTEGER NOT NULL,
name VARCHAR (50),
address VARCHAR (200),
phone VARCHAR (20),
is_active BOOLEAN DEFAULT FALSE,
version INTEGER
);
ALTER TABLE office ADD FOREIGN KEY (org_id) REFERENCES organization(id);
CREATE INDEX IX_office_org_id ON office (org_id);
-- Сотрудник
-- id первичный ключ
-- office_id внешний ключ к офису
-- first_name имя
-- last_name фамилия
-- middle_name отчество
-- second_name второе имя
-- position должность
-- phone телефон
-- document_id внешний ключ к документу
-- citizenship_id внешний ключ к стране
-- is_identified признак идентификации
-- version оптимистичная блокировка
CREATE TABLE IF NOT EXISTS employer (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
office_id INTEGER,
first_name VARCHAR (50) NOT NULL,
last_name VARCHAR (50),
middle_name VARCHAR (50),
second_name VARCHAR (50),
position VARCHAR (50) NOT NULL,
phone VARCHAR (50),
document_id INTEGER,
citizenship_id INTEGER,
is_identified BOOLEAN DEFAULT FALSE,
version INTEGER
);
ALTER TABLE employer ADD FOREIGN KEY (office_id) REFERENCES office(id);
CREATE INDEX IX_employer_office_id ON employer (office_id);
-- Документ
-- id первичный ключ
-- type_id внешний ключ к типу документа
-- number номер документа
-- date дата выдачи
CREATE TABLE IF NOT EXISTS document (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
type_id INTEGER NOT NULL,
number VARCHAR (20),
date DATE
);
ALTER TABLE employer ADD FOREIGN KEY (document_id) REFERENCES document(id);
CREATE INDEX IX_document_id ON employer (document_id);
-- Тип документа
-- id первичный ключ
-- code код типа
-- name название
CREATE TABLE IF NOT EXISTS document_type (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
code VARCHAR (2) NOT NULL,
name VARCHAR (100) NOT NULL
);
ALTER TABLE document ADD FOREIGN KEY (type_id) REFERENCES document_type(id);
CREATE INDEX IX_document_type_id ON document (type_id);
-- Страна
-- id первичный ключ
-- code код страны
-- name название
CREATE TABLE IF NOT EXISTS country (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
code VARCHAR (3) NOT NULL UNIQUE,
name VARCHAR (100) NOT NULL
);
ALTER TABLE employer ADD FOREIGN KEY (citizenship_id) REFERENCES country(id);
CREATE INDEX IX_employer_citizenship_id ON employer (citizenship_id);
|
Markdown
|
UTF-8
| 807 | 3.46875 | 3 |
[] |
no_license
|
## jQuery namespace ('jQuery' and '\$')
jQuery is the starting point for writing any jQuery code. It can be used as a function jQuery(...) or a variable jQuery.foo. \$ is an alias for jQuery and the two can usually be interchanged for each other (except where
`jQuery.noConflict()`; has been used - see Avoiding namespace collisions).
Assuming we have this snippet of HTML -
`<div id="demo_div" class="demo"></div>`
Now we might want to add some text on the div content using jQuery. To do that we can either use jQuery function or \$ -
`jQuery('#demo_div').text('Demo text');`
or
`$('#demo_div').text('Demo text');`
Both will result the same final HTML -
`<div id="demo_div" class="demo">Demo text</div>`
As `$` is more concise than jQuery it is generally the preferred method of writing jQuery.
|
Markdown
|
WINDOWS-1252
| 7,345 | 3.15625 | 3 |
[] |
no_license
|
---
title: "**Peer Assessment 1 in Reproducible Research**"
output: html_document
---
- Author: GL
- Date: 05/16/2015
## 1. Introduction
It is now possible to collect a large amount of data about personal movement using activity monitoring devices such as a Fitbit, Nike Fuelband, or Jawbone Up. These type of devices are part of the quantified self movement C a group of enthusiasts who take measurements about themselves regularly to improve their health, to find patterns in their behavior, or because they are tech geeks. But these data remain under-utilized both because the raw data are hard to obtain and there is a lack of statistical methods and software for processing and interpreting the data.
This assignment makes use of data from a personal activity monitoring device. This device collects data at 5 minute intervals through out the day. The data consists of two months of data from an anonymous individual collected during the months of October and November, 2012 and include the number of steps taken in 5 minute intervals each day.
## 2. Solutions
### 2.1 Loading and preprocessing the data
Load the data and transform the data (if necessary) into a format suitable the analysis.
```r
mydata <- read.csv("activity.csv")
```
### 2.2 Mean total number of steps taken per day
Calculate the total number of steps taken per day and analyze the results by drawing histograms.
```r
## Sort data in terms of date
dataPerDay <- split(mydata, mydata$date)
stepsPerDay <- lapply(dataPerDay, function(xx)
{ sum( xx$steps, na.rm = TRUE ) })
## Draw the histogram
library(ggplot2)
stepsPerDay <- t( as.data.frame(stepsPerDay))
stepsPerDay <- as.data.frame(stepsPerDay)
colnames(stepsPerDay) <- "totalSteps"
q <- ggplot(stepsPerDay, aes(x = totalSteps))
q + geom_histogram(position = 'identity', alpha = 0.5, fill = "red") +
labs(x = "Total Steps per Day", y = "Freqency") +
labs(title = "Histogram of the total number of steps taken each day")
```

```r
## Calculate mean and median steps per day
mymean <- round( mean( t(as.vector(stepsPerDay)) ) )
mymedian <- median(t(as.vector(stepsPerDay)))
```
**The mean and median of the total number of steps taken per day are 9354 and 10395, respectively.**
### 2.3 The average daily activity pattern
Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis).
```r
## Sort data in terms of date and calculate the average per interval
dataDaily <- split(mydata, mydata$interval)
stepsDaily <- lapply(dataDaily, function(xx)
{ mean( xx$steps, na.rm = TRUE ) })
## build a data.frame of myDailyPattern as the output
myDailyPattern <- rbind( as.data.frame(stepsDaily),
as.integer(names(stepsDaily)))
myDailyPattern <- t(myDailyPattern)
colnames(myDailyPattern) <- c("average","interval")
myDailyPattern <- as.data.frame(myDailyPattern)
## Draw a plot using ggplot2
library(ggplot2)
q <- ggplot(myDailyPattern, aes(x = interval, y = average))
q + geom_line() + labs( title = "Averaged Step Numbers as a Function of Interval", x = "5-min Interval", y = "Averaged Step Numbers")
```

```r
## Determine the interval corresponding to the maximum averaged step number
maxIndex <- which.max(myDailyPattern$average)
maxInterval <- myDailyPattern$interval[maxIndex]
```
**The interval of 835, on average across all the days in the dataset, contains the maximum number of steps.**
### 2.4 Imputing missing values
There are a number of days/intervals where there are missing values (coded as NA). The presence of missing days may introduce bias into some calculations or summaries of the data.
```r
rowNA <- is.na( mydata$steps )
numNA <- sum( as.integer(rowNA) )
## The strategy is to use the averaged step values calcualted in Section 2.3 to replace the missing values
filledData <- lapply(dataDaily, function(xx) {
dateChecker <- which( is.na(xx$steps) == TRUE )
b <- as.integer( (xx$interval[1])/5 + 1)
xx[dateChecker,"steps"] <- round( myDailyPattern[ b,"average"] )
xx
})
## Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day.
library(ggplot2)
myfilledData <- unsplit(filledData, mydata$interval)
dataPerDay2 <- split(myfilledData, myfilledData$date)
stepsPerDay2 <- lapply(dataPerDay2, function(xx)
{ sum( xx$steps, na.rm = TRUE ) })
stepsPerDay2 <- t( as.data.frame(stepsPerDay2))
stepsPerDay2 <- as.data.frame(stepsPerDay2)
colnames(stepsPerDay2) <- "totalSteps"
q <- ggplot(stepsPerDay2, aes(x = totalSteps))
q + geom_histogram(position = 'identity', alpha = 0.5, fill = "red") +
labs(x = "Total Steps per Day", y = "Freqency") +
labs(title = "Histogram of the total number of steps taken each day")
```

```r
mymean2 <- round( mean( t(as.vector(stepsPerDay2)) ) )
mymedian2 <- median(t(as.vector(stepsPerDay2)))
```
**The mean and median of the total number of steps taken per day are 1.0282 × 10<sup>4</sup> and 1.0395 × 10<sup>4</sup>, respectively.**
### 2.5 Differences in activity patterns between weekdays and weekends
```r
## Create a new factor variable in the dataset with two levels C weekday and weekend indicating whether a given date is a weekday or weekend day.
myWeekdays <- weekdays(as.Date(myfilledData$date))
dayChecker <- myWeekdays == "" | myWeekdays == ""
activity <- rep(x = "Weekday", times = length(dayChecker))
a <- which( dayChecker == TRUE )
activity[a] <- "Weekend"
activity <- as.factor(activity)
myfilledData2 <- cbind(myfilledData, activity)
## Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). See the README file in the GitHub repository to see an example of what this plot should look like using simulated data.
dataA <- subset(myfilledData2, dayChecker)
dataB <- subset(myfilledData2, !dayChecker)
dataDailyA <- split(dataA, dataA$interval)
stepsDailyA <- lapply(dataDailyA, function(xx)
{ mean( xx$steps ) })
dataDailyB <- split(dataB, dataB$interval)
stepsDailyB <- lapply(dataDailyB, function(xx)
{ mean( xx$steps ) })
## build a data.frame of myDailyPattern as the output
myDailyPatternA <- rbind( as.data.frame(stepsDailyA),
as.integer(names(stepsDailyA)))
myDailyPatternA <- t(myDailyPatternA)
colnames(myDailyPatternA) <- c("average","interval")
myDailyPatternA <- as.data.frame(myDailyPatternA)
myDailyPatternB <- rbind( as.data.frame(stepsDailyB),
as.integer(names(stepsDailyB)))
myDailyPatternB <- t(myDailyPatternB)
colnames(myDailyPatternB) <- c("average","interval")
myDailyPatternB <- as.data.frame(myDailyPatternB)
## Draw a plot
par(mfrow = c(2,1))
plot(x = myDailyPatternA$interval, y = myDailyPatternA$average, type = "l")
plot(x = myDailyPatternB$interval, y = myDailyPatternB$average, type = "l")
```

|
Python
|
UTF-8
| 455 | 3.734375 | 4 |
[] |
no_license
|
# Tree walking
import os
for dirpath, dirname, files in os.walk("mydir"):
print(dirpath, " : ", dirname, " : ", files)
def printdirandfile(dirname):
for dirpath, dirnames, files in os.walk(dirname):
print(dirpath)
for file in files:
print(" L ", file)
for d in dirnames:
printdirandfile(d)
print("-------------------------")
printdirandfile("mydir")
|
Java
|
UTF-8
| 2,595 | 2.21875 | 2 |
[] |
no_license
|
package io.github.tanu31195.audionirvana;
public class Earphone {
private String model;
private String type;
private String back;
private boolean wireless;
private boolean portable;
private String comfort;
private String sound;
private String noiseCancelling;
private String frequencyRange;
private String impedance;
private String durability;
private boolean waterProof;
private String cost;
private String url;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBack() {
return back;
}
public void setBack(String back) {
this.back = back;
}
public boolean isWireless() {
return wireless;
}
public void setWireless(boolean wireless) {
this.wireless = wireless;
}
public boolean isPortable() {
return portable;
}
public void setPortable(boolean portable) {
this.portable = portable;
}
public String getComfort() {
return comfort;
}
public void setComfort(String comfort) {
this.comfort = comfort;
}
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
public String getNoiseCancelling() {
return noiseCancelling;
}
public void setNoiseCancelling(String noiseCancelling) {
this.noiseCancelling = noiseCancelling;
}
public String getFrequencyRange() {
return frequencyRange;
}
public void setFrequencyRange(String frequencyRange) {
this.frequencyRange = frequencyRange;
}
public String getImpedance() {
return impedance;
}
public void setImpedance(String impedance) {
this.impedance = impedance;
}
public String getDurability() {
return durability;
}
public void setDurability(String durability) {
this.durability = durability;
}
public boolean isWaterProof() {
return waterProof;
}
public void setWaterProof(boolean waterProof) {
this.waterProof = waterProof;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
Swift
|
UTF-8
| 2,351 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
//
// Container.swift
// Bright
//
// Created by Roman on 29.06.2020.
//
import AppKit
import Swinject
import RxSwift
import SwiftUI
private struct DisplayBrightnessServiceEnvironmentKey: EnvironmentKey {
static var defaultValue: DisplayBrightnessService?
}
extension EnvironmentValues {
var displayBrightnessService: DisplayBrightnessService? {
get { self[DisplayBrightnessServiceEnvironmentKey.self] }
set { self[DisplayBrightnessServiceEnvironmentKey.self] = newValue }
}
}
class MainContainer: ObservableObject {
public static let shared: MainContainer = {
return MainContainer()
}()
public let container: Container = {
let container = Container()
container.register(NSApplication.self) { _ in NSApp }.inObjectScope(.container)
container.register(AppService.self) { c in AppService(appInstance: c.resolve(NSApplication.self)!) }.inObjectScope(.container)
container.register(BrightnessSerivce.self) { _ in BrightnessSerivce() }.inObjectScope(.container)
container.register(DisplayService.self) { _ in DisplayService(brightnessService: BrightnessSerivce()) }.inObjectScope(.container)
container.register(WindowService.self) { _ in WindowService( ) }.inObjectScope(.container)
container.register(MediaKeyTapService.self) { _ in MediaKeyTapService() }.inObjectScope(.container)
container.register(DisplayBrightnessService.self) { c in DisplayBrightnessService(
brightnessService: c.resolve(BrightnessSerivce.self)!,
displayService: c.resolve(DisplayService.self)!
) }.inObjectScope(.container)
container.register(UserInterfaceService.self) { c in UserInterfaceService(
windowService: c.resolve(WindowService.self)!,
displayBrightnessService: c.resolve(DisplayBrightnessService.self)!
)}.inObjectScope(.container)
container.register(MediaKeyObserver.self) { c in MediaKeyObserver.init(
mediaKeyservice: c.resolve(MediaKeyTapService.self)!,
appService: c.resolve(AppService.self)!,
displayBrightnessService: c.resolve(DisplayBrightnessService.self)!
) }.inObjectScope(.container)
return container
}()
private init() {}
}
|
Python
|
UTF-8
| 1,544 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
"""
Requirements Files Extensions
=============================
By default ``pip-compile-multi`` compiles ``*.txt`` from ``*.in`` files.
While this is a common naming pattern, each project can use it's own:
.. code-block:: text
-i, --in-ext TEXT File extension of input files
-o, --out-ext TEXT File extension of output files
"""
import os
from .base import BaseFeature, ClickOption
class InputExtension(BaseFeature):
"""Override input file extension."""
OPTION_NAME = 'in_ext'
CLICK_OPTION = ClickOption(
long_option='--in-ext',
short_option='-i',
default="in",
is_flag=False,
help_text='File extension of input files.',
)
def compose_input_file_name(self, base_name):
"""Compose file name given environment name.
>>> InputExtension().compose_input_file_name('base')
'base.in'
"""
return '{0}.{1}'.format(base_name, self.value)
class OutputExtension(BaseFeature):
"""Override output file extension."""
OPTION_NAME = 'out_ext'
CLICK_OPTION = ClickOption(
long_option='--out-ext',
short_option='-o',
default="txt",
is_flag=False,
help_text='File extension of output files.',
)
def compose_output_file_path(self, in_path):
"""Compose file name given environment name.
>>> OutputExtension().compose_output_file_path('sub/base.in')
'sub/base.txt'
"""
return '{0}.{1}'.format(os.path.splitext(in_path)[0], self.value)
|
Ruby
|
UTF-8
| 1,743 | 2.671875 | 3 |
[] |
no_license
|
class AlignmentCodonCost < ActiveRecord::Base
belongs_to :alignment_codon
belongs_to :condition
belongs_to :cost_type
validates_presence_of :alignment_codon_id, :condition_id, :cost_type_id, :mean
validates_uniqueness_of :alignment_codon_id, :scope => [:condition_id, :cost_type_id]
def self.create_from_codon(codon)
# Each group of condition and cost
costs_by_condition_and_type = AminoAcidCost.all :group => ["condition_id"," , ","cost_type_id"]
# Weights for each amino acid
frequencies = codon.amino_acid_frequencies.map(&:frequency)
costs_by_condition_and_type.each do |cost|
costs = codon.amino_acid_frequencies.map do |freq|
AminoAcidCost.find(:first, :conditions => {
:amino_acid_id => freq.amino_acid_id,
:condition_id => cost.condition_id,
:cost_type_id => cost.cost_type_id
}).estimate
end
aac = AlignmentCodonCost.new(
:alignment_codon_id => codon.id,
:condition_id => cost.condition_id,
:cost_type_id => cost.cost_type_id,
:mean => self.weighted_mean(costs,frequencies)
)
aac.save
end
end
def self.weighted_mean(observations,weights)
# Degrade gracefully if no observations are passed...
return nil if observations.size < 1
# ...or the number of observations does not match the number of weights
return nil unless observations.size == weights.size
# Return the observation if there is only one
return observations.first if observations.size < 2
weighted_sum = 0
observations.each_index {|i| weighted_sum += weights[i].to_f * observations[i]}
weighted_sum / weights.inject {|sum,x| sum += x}
end
end
|
Java
|
UTF-8
| 1,174 | 2.46875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.mytaxi.domainobject;
import javax.persistence.*;
@Entity
@Table(name = "manufacture")
public class ManufatureDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "pk_manufatureId")
private Long id;
@Column(name = "ManufactureName")
private String name;
@Column
private String model;
@Column
private String modelYear;
public ManufatureDO() {
}
public ManufatureDO(Long id, String name, String model, String modelYear) {
this.id = id;
this.name = name;
this.model = model;
this.modelYear = modelYear;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModelYear() {
return modelYear;
}
public void setModelYear(String modelYear) {
this.modelYear = modelYear;
}
}
|
Markdown
|
UTF-8
| 1,373 | 2.84375 | 3 |
[
"Apache-2.0"
] |
permissive
|
[](https://jitpack.io/#snarks/OpenRange)
# OpenRange
Open ended version of Kotlin's `ClosedRange` class
## Usage
Get a range that covers the value `512` _and lower_:
```kotlin
val range: OpenRange<Int> = lessOrEqual(512)
assertTrue(0 in range)
assertTrue(512 in range)
assertFalse(1024 in range)
assertEquals("<=512", "$range")
```
Get a range that covers values _lower than_ `512` _(exclusive)_:
```kotlin
val range: OpenRange<Int> = lessThan(512)
assertTrue(0 in range)
assertFalse(512 in range)
assertFalse(1024 in range)
assertEquals("<512", "$range")
```
Get a range that covers the value `512` _and higher_:
```kotlin
val range: OpenRange<Int> = moreOrEqual(512)
assertFalse(0 in range)
assertTrue(512 in range)
assertTrue(1024 in range)
assertEquals(">=512", "$range")
```
Get a range that covers values _higher than_ `512` _(exclusive)_:
```kotlin
val range: OpenRange<Int> = moreThan(512)
assertFalse(0 in range)
assertFalse(512 in range)
assertTrue(1024 in range)
assertEquals(">512", "$range")
```
## Adding OpenRange to your Project
You can add this project as a dependency via [JitPack](https://jitpack.io/).
```gradle
repositories {
...
maven { url "https://jitpack.io" }
}
dependencies {
compile 'io.github.snarks:OpenRange:1.0.1'
}
```
(_`com.github.snarks` will also work_)
|
Markdown
|
UTF-8
| 512 | 2.890625 | 3 |
[] |
no_license
|
- [x] Start stage 1 of the project:heart:
- [x] Complete stage 1 of the project
- [x] Finish my changes
- [x] Push my commits to GitHub
- [x] Start stage 2 of the project
- [X] Complete stage 2
- [X] Start stage 3 of the project
- [X] Complete stage 3
- [X] Start stage 4 of the project
- [X] Complete stage 4. P.S. I almost gave up. :weary:
- [X] Start stage 5 of the project
- [X] Complete stage 5
- [X] Project completed.
- [X] Delete unnecessary files.
- [X] Can't wait to tick all of these. :dizzy_face:
|
Java
|
UTF-8
| 2,884 | 2.96875 | 3 |
[] |
no_license
|
package org.seeker.swing.stock.util;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
@SuppressWarnings("serial")
public class TableTools extends JFrame {
// 声明控件
public Vector<String> title, row;
public Vector<Vector<String>> data;
private List<String> rs;
// 带结果集构造方法
public TableTools(List<String> rs) {
this.rs = rs;
}
// 传送查询出来的表头
public Vector<String> toTitle() {
// // 处理结果
// ResultSetMetaData rmd = rs.getMetaData();
title = new Vector<String>();
data = new Vector<Vector<String>>();
// 标题栏
// for (int i = 1; i <= rmd.getColumnCount(); i++) {
// title.add(rmd.getColumnName(i));
// // System.out.println(rmd.getColumnName(i));
title.add("测试");
// }
return title;
}
// 传入每次更新的二维集合
public Vector<Vector<String>> toData() {
// 处理结果
// ResultSetMetaData rmd = rs.getMetaData();
data = new Vector<Vector<String>>();
// 处理结果
// while (rs.next()) {
// row = new Vector<String>();
// for (int j = 1; j <= rmd.getColumnCount(); j++) {
// row.add(rs.getString(j));
// System.out.println(rs.getString(j));
// }
// data.add(row);
// }
return data;
}
// 自动分配列宽的函数
public void toTable(JTable table) {
JTableHeader header = table.getTableHeader(); // 表头
int rowCount = table.getRowCount(); // 表格的行数
TableColumnModel cm = table.getColumnModel(); // 表格的列模型
for (int i = 0; i < cm.getColumnCount(); i++) { // 循环处理每一列
TableColumn column = cm.getColumn(i); // 第i个列对象
int width = (int) header.getDefaultRenderer().getTableCellRendererComponent(table, column.getIdentifier(), false, false, -1, i).getPreferredSize().getWidth(); // 用表头的绘制器计算第i列表头的宽度
for (int row = 0; row < rowCount; row++) { // 循环处理第i列的每一行,用单元格绘制器计算第i列第row行的单元格宽度
int preferedWidth = (int) table.getCellRenderer(row, i).getTableCellRendererComponent(table, table.getValueAt(row, i), false, false, row, i).getPreferredSize().getWidth();
width = Math.max(width, preferedWidth); // 取最大的宽度
}
column.setPreferredWidth(width + table.getIntercellSpacing().width); // 设置第i列的首选宽度
}
table.doLayout(); // 按照刚才设置的宽度重新布局各个列
}
// 将查询出来的结果转换成集合存储
public Vector<String> toRow() {
// 处理结果
row = new Vector<String>();
row.add("----请选择----");
row.addAll(rs);
// 处理结果
// while (rs.next()) {
// row.add(rs.getString(1));
// }
return row;
}
}
|
Java
|
UTF-8
| 838 | 2.578125 | 3 |
[] |
no_license
|
import java.net.URL;
import java.net.URLClassLoader;
public class PluginManager {
private final String pluginRootDirectory;
public PluginManager(String pluginRootDirectory) {
this.pluginRootDirectory = pluginRootDirectory;
}
public Plugin load(String pluginName, String pluginClassName) {
URL[] classLoaderUrls;
Plugin downloaded_class = new MyPlugin();
try {
classLoaderUrls = new URL[]{new URL("file:/" + pluginRootDirectory + "/" + pluginName + "/")};
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
downloaded_class = (Plugin) urlClassLoader.loadClass(pluginClassName).getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return downloaded_class;
}
}
|
Java
|
UTF-8
| 2,195 | 2.15625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014-2021 Web Firm Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webfirmframework.wffweb.tag.html;
import static org.junit.Assert.*;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import com.webfirmframework.wffweb.tag.html.attribute.Name;
import com.webfirmframework.wffweb.tag.html.attribute.global.Id;
import com.webfirmframework.wffweb.tag.html.stylesandsemantics.Div;
import com.webfirmframework.wffweb.tag.html.stylesandsemantics.Span;
import com.webfirmframework.wffweb.tag.htmlwff.NoTag;
public class AbstractHtmlRepositoryTest {
@SuppressWarnings("serial")
@Test
public void testGetAllNestedChildrenIncludingParent() {
final Html html = new Html(null) {{
new Body(this) {{
new Div(this, new Id("one")) {{
new Span(this, new Id("two")) {{
new H1(this, new Id("three"));
new H2(this, new Id("three"));
new NoTag(this, "something");
}};
new H3(this, new Name("name1"));
}};
}};
}};
{
final Set<AbstractHtml> set =AbstractHtmlRepository.getAllNestedChildrenIncludingParent(false, html).collect(Collectors.toSet());
assertEquals(8, set.size());
}
{
final Set<AbstractHtml> set =AbstractHtmlRepository.getAllNestedChildrenIncludingParent(true, html).collect(Collectors.toSet());
assertEquals(8, set.size());
}
}
}
|
Java
|
UTF-8
| 3,028 | 1.820313 | 2 |
[] |
no_license
|
package com.nieyue.controller.test;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.nieyue.controller.ManagerController;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:config/spring-dao.xml","classpath:config/spring-service.xml","classpath:config/springmvc-servlet.xml"})
public class UserControllerTest {
@Resource
ManagerController managerController;
@Resource
WebApplicationContext wac;
MockHttpServletRequest request=new MockHttpServletRequest();
MockHttpServletResponse response=new MockHttpServletResponse();
MockMvc mvc;
@Before
public void setUp(){
this.mvc=MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testTest1() {
fail("Not yet implemented");
}
@Test
public void testTest2() {
fail("Not yet implemented");
}
@Test
public void testSelectUserByID() {
fail("Not yet implemented");
}
@Test
public void xsdfsdfsd() throws Exception {
Integer type=1;//0是get
String url="";
//String url="/1000.xml";
//String url="/manager/login?managerPhone=15111336587&managerPassword=123456";//退款
//String url="/news/delete/review";//删除去重
//url="/news/grab?url=http://t.kejixun.com/list/6&mode=热点";//新闻抓取
//for (int i = 0; i < 100; i++) {
// url="/news/grab?url=http://3g.k.sohu.com/t/n"+Integer.valueOf(152233000+i)+"&mode=新浪";//新闻抓取
//url="/news/list?pageNum=11&pageSize=10&type=热点&orderName=news_id&orderWay=asc";//list
//url="/news/list?pageNum=11&pageSize=10&type=首页&orderName=news_id&orderWay=asc";//list
url="/news/list/random?pageSize=10";//list
if(type.equals(0)){
this.mvc.perform(get(url))
//.andExpect(status().isOk())
.andDo(print());
return;
}
this.mvc.perform(post(url))
//.andExpect(status().isOk())
.andDo(print());
//}
}
@Test
public void testModel() {
fail("Not yet implemented");
}
@Test
public void testJs() {
fail("Not yet implemented");
}
@Test
public void testRp() {
fail("Not yet implemented");
}
}
|
JavaScript
|
UTF-8
| 1,406 | 2.859375 | 3 |
[] |
no_license
|
import gsap from "gsap";
export default class Image {
constructor(el) {
this.DOM = {
el: el
};
this.next = false;
this.arrImage = [];
this.DOM.image1 = this.DOM.el.querySelector("img:nth-child(1)");
this.DOM.image2 = this.DOM.el.querySelector("img:nth-child(2)");
this.DOM.images = this.DOM.el.querySelectorAll("img");
[...this.DOM.images].forEach((a) => {
this.arrImage.push(a);
});
this.evtClick();
}
evtClick() {
this.arrImage.forEach((image) => {
image.addEventListener("click", () => {
if (!this.next) {
this.next = true;
this.show();
this.timeout(1300);
}
});
});
}
show() {
setTimeout(() => {
this.arrImage.splice(this.arrImage.length, 0, this.arrImage[0]);
this.insertInTheHTML();
this.removeClass();
this.arrImage.shift();
}, 1000);
this.addClass();
}
removeClass() {
this.arrImage[0].classList.remove("active-img");
}
addClass() {
if (this.arrImage[1].className !== "active-img") {
this.arrImage[1].classList.add("active-img");
}
}
insertInTheHTML() {
if (this.DOM.el) {
this.DOM.el.appendChild(this.arrImage[0]);
} else {
console.error(`"${this.id}" n'est pas un id valide`);
}
}
timeout(time) {
setTimeout(() => {
this.next = false;
}, time);
}
}
|
Shell
|
UTF-8
| 249 | 2.8125 | 3 |
[] |
no_license
|
#!/bin/bash
if [[ $(uname -a) =~ Android ]]; then
curl -s "https://www.dict.cc/german-english/$1.html" \
|html2text \
|sed -n '/Tabular\ list/,/back\ to\ top/p' \
|less
else
google -w "https://www.dict.cc/german-english/$1.html"
fi
|
Java
|
UTF-8
| 338 | 2.34375 | 2 |
[] |
no_license
|
package cs160_wk9_le2;
public class Player {
//members
public String name;
public PlayerClass playerClass;
int health;
String race;
int xp;
Milestone[] completedMilestones;
//constructor
public Player(String n, PlayerClass pC, int h, String r, int x) {
name = n;
playerClass = pC;
health = h;
race = r;
xp = x;
}
}
|
C#
|
UTF-8
| 6,434 | 2.640625 | 3 |
[] |
no_license
|
using System.Text.RegularExpressions;
using DocHound.Interfaces;
using Markdig;
using Markdig.Extensions.AutoIdentifiers;
namespace DocHound.TopicRenderers.Markdown
{
public class MarkdownTopicRenderer : ITopicRenderer
{
public string RenderToHtml(TopicInformation topic, string imageRootUrl = "", ISettingsProvider settings = null)
{
if (string.IsNullOrEmpty(topic.OriginalContent)) return string.Empty;
return MarkdownToHtml(topic, imageRootUrl, settings);
}
private string MarkdownToHtml(TopicInformation topic, string imageRootUrl, ISettingsProvider settings)
{
// TODO: This uses all images as external links. We may need to handle that differently
var markdown = topic.OriginalContent;
markdown = markdown.Replace(";
markdown = markdown.Replace("background: url('", "background: url('" + imageRootUrl);
markdown = markdown.Replace("src=\"", "src=\"" + imageRootUrl);
var builder = new MarkdownPipelineBuilder();
BuildPipeline(builder, settings, markdown);
var pipeline = builder.Build();
var html = Markdig.Markdown.ToHtml(markdown, pipeline);
if (settings.GetSetting<bool>(SettingsEnum.UseFontAwesomeInMarkdown))
html = ParseFontAwesomeIcons(html);
return html;
}
public static Regex FontAwesomeIconRegEx = new Regex(@"@icon-.*?[\s|\.|\,|\<]");
/// <summary>
/// Post processing routine that post-processes the HTML and
/// replaces @icon- with fontawesome icons
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
protected string ParseFontAwesomeIcons(string html)
{
var matches = FontAwesomeIconRegEx.Matches(html);
foreach (Match match in matches)
{
var iconblock = match.Value.Substring(0, match.Value.Length - 1);
var icon = iconblock.Replace("@icon-", "");
html = html.Replace(iconblock, "<i class=\"fa fa-" + icon + "\"></i> ");
}
return html;
}
protected virtual MarkdownPipelineBuilder BuildPipeline(MarkdownPipelineBuilder builder, ISettingsProvider settings, string markdown)
{
if (settings.GetSetting<bool>(SettingsEnum.UseAbbreviations)) builder = builder.UseAbbreviations();
if (settings.GetSetting<bool>(SettingsEnum.UseAutoIdentifiers)) builder = builder.UseAutoIdentifiers(AutoIdentifierOptions.GitHub);
//if (settings.GetSetting<bool>(SettingsEnum.UseAutoLinks)) builder = builder.UseAutoLinks();
if (settings.GetSetting<bool>(SettingsEnum.UseCitations)) builder = builder.UseCitations();
if (settings.GetSetting<bool>(SettingsEnum.UseCustomContainers)) builder = builder.UseCustomContainers();
if (settings.GetSetting<bool>(SettingsEnum.UseEmojiAndSmiley)) builder = builder.UseEmojiAndSmiley();
if (settings.GetSetting<bool>(SettingsEnum.UseEmphasisExtras)) builder = builder.UseEmphasisExtras();
if (settings.GetSetting<bool>(SettingsEnum.UseFigures)) builder = builder.UseFigures();
if (settings.GetSetting<bool>(SettingsEnum.UseFootnotes)) builder = builder.UseFootnotes();
if (settings.GetSetting<bool>(SettingsEnum.UseGenericAttributes) && !settings.GetSetting<bool>(SettingsEnum.UseMathematics)) builder = builder.UseGenericAttributes();
if (settings.GetSetting<bool>(SettingsEnum.UseGridTables)) builder = builder.UseGridTables();
if (settings.GetSetting<bool>(SettingsEnum.UseListExtras)) builder = builder.UseListExtras();
//if (settings.GetSetting<bool>(SettingsEnum.UseMathematics)) builder = builder.UseMathematics();
if (settings.GetSetting<bool>(SettingsEnum.UseMathematics)) builder = builder.UseMathJax();
if (settings.GetSetting<bool>(SettingsEnum.UseMediaLinks)) builder = builder.UseMediaLinks();
if (settings.GetSetting<bool>(SettingsEnum.UsePipeTables)) builder = builder.UsePipeTables();
if (settings.GetSetting<bool>(SettingsEnum.UsePragmaLines)) builder = builder.UsePragmaLines();
if (settings.GetSetting<bool>(SettingsEnum.UseSmartyPants)) builder = builder.UseSmartyPants();
if (settings.GetSetting<bool>(SettingsEnum.UseTaskLists)) builder = builder.UseTaskLists();
if (settings.GetSetting<bool>(SettingsEnum.UseYamlFrontMatter)) builder = builder.UseYamlFrontMatter();
var containsMermaid = markdown.Contains("```mermaid");
var containsNomnoml = markdown.Contains("```nomnoml");
var useDiagrams = containsMermaid || containsNomnoml;
if (useDiagrams)
{
// We need to check to make sure that it isn't specifically disabled
if (settings.IsSettingSpecified(SettingsEnum.UseDiagramsNomnoml) && !settings.GetSetting<bool>(SettingsEnum.UseDiagramsNomnoml))
useDiagrams = false;
if (settings.IsSettingSpecified(SettingsEnum.UseDiagramsMermaid) && !settings.GetSetting<bool>(SettingsEnum.UseDiagramsMermaid))
useDiagrams = false;
if (useDiagrams) // If we auto-use, we need to set the diagram settings to true in this instance, so subsequent processing will work correctly
{
if (containsMermaid)
settings.OverrideSetting(SettingsEnum.UseDiagramsMermaid, true);
if (containsNomnoml)
settings.OverrideSetting(SettingsEnum.UseDiagramsNomnoml, true);
}
}
else
useDiagrams = settings.GetSetting<bool>(SettingsEnum.UseDiagramsMermaid) || settings.GetSetting<bool>(SettingsEnum.UseDiagramsNomnoml);
if (useDiagrams) builder = builder.UseDiagrams();
return builder;
}
public string GetTemplateName(TopicInformation topic, string suggestedTemplateName, ISettingsProvider settings = null) => suggestedTemplateName;
public string RenderToJson(TopicInformation topic, string imageRootUrl = "", ISettingsProvider settings = null) => string.Empty;
}
}
|
Python
|
UTF-8
| 4,184 | 3.171875 | 3 |
[] |
no_license
|
import math
import itertools
from raise_helper import *
from position import Position, BB_AMT, SB_AMT
class Player:
def __init__(self, pos):
self.pos = pos
self.stack = 100
self.folded = False
self.has_option = True
invested = {
Position.BB: BB_AMT,
Position.SB: SB_AMT,
}
self.invested = invested.get(pos, 0)
def raise_to(self, amt):
extra_invested = self.call(amt)
self.has_option = True
return extra_invested
def call(self, amt):
extra_invested = max(amt-self.invested, 0)
self.stack -= extra_invested
self.invested = amt
self.has_option = True
return extra_invested
def fold(self):
self.folded = True
self.has_option = False
def check(self):
self.call(0)
def available(self):
return not self.folded and self.has_option
def __str__(self):
return str(self.pos).split(".")[1]
class Game:
MAX_PLAYERS = 6
def __init__(self, num_players):
self.num_players_rem = self.num_players = min(num_players, Game.MAX_PLAYERS)
print("Initializing game with {} players".format(self.num_players))
ommited_players = Game.MAX_PLAYERS - self.num_players
positions = [x for x in Position][ommited_players:]
self.players = []
self.player_idx = 0
# BB is encoded as a bet
self.pot = SB_AMT
self.bet = BB_AMT
for position in positions:
p = Player(position)
self.players.append(p)
print(position)
print("Currently in pot {}".format(self.total_pot()))
def get_cur_player(self):
return self.players[self.player_idx]
def next_player(self):
while True:
self.player_idx = (self.player_idx+1) % len(self.players)
if self.players[self.player_idx].available():
break
return self.players[self.player_idx]
def total_pot(self):
return self.pot + self.bet
def fold(self):
p = self.get_cur_player()
print("{} folded".format(p))
if self.num_players_rem == 2:
raise ValueError("No more remaining players")
p.fold()
self.num_players_rem -= 1
def raise_to_amt(self, amt):
p = self.get_cur_player()
self.pot += self.bet
self.bet = p.raise_to(amt)
def raise_by_percent(self, percent):
try:
int(percent)
except:
raise NameError("Invalid Raise Size")
p = self.get_cur_player()
raise_amt = calc_raise_size(percent, self.bet, self.pot-p.invested)
print("Raising by {}% = {}x".format(percent, raise_amt))
self.raise_to_amt(raise_amt)
def call(self):
p = self.get_cur_player()
self.pot += p.call(self.bet)
print("{} calls. Total in pot is {}.".format(p, self.total_pot()))
def rewind(self):
pass
def parse_action(self, s):
action = "".join(itertools.takewhile(str.isalpha, s))
size = "".join(itertools.takewhile(str.isnumeric, s[len(action):]))
if len(size) != 0:
size = int(size)
actions = {
'r': lambda : self.raise_by_percent(size),
'c': self.call,
'f': self.fold,
'back': self.rewind
}
if action not in actions:
raise NameError("Invalid Action")
return actions[action]
def start(self):
player = None
while True:
player = self.get_cur_player()
s = input("What's {}'s action?\n".format(player))
try:
f = self.parse_action(s)
f()
except NameError as e:
print(e)
continue
except ValueError as e:
print(e)
break
self.next_player()
class GameDriver:
def __init__(self, num_players):
self.history = []
history.append(Game(num_players))
if __name__ == "__main__":
n = int(input("How many handed?\n"))
g = Game(n)
g.start()
|
C++
|
UTF-8
| 798 | 3.421875 | 3 |
[
"Apache-2.0"
] |
permissive
|
// dynamic programming | coin change | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
const int MAX = 100;
int coinWays(int amt, std::vector<int>& coins)
{
// init the dp table
std::vector<int> dp(MAX, 0);
int n = coins.size();
dp[0] = 1; // base case
for (int j = 0; j < n; ++j)
for (int i = 1; i <= amt; ++i)
if (i - coins[j] >= 0)
// if coins[j] < i then add no. of ways -
// - to form the amount by using coins[j]
dp[i] += dp[i - coins[j]];
//final result at dp[amt]
return dp[amt];
}
int main()
{
std::vector<int> coins = {1, 2, 3}; // coin denominations
int amount = 4; // amount
std::cout << coinWays(amount, coins) << "\n";
return 0;
}
|
C#
|
UTF-8
| 2,274 | 2.71875 | 3 |
[] |
no_license
|
using System;
using System.Threading;
using System.Windows.Media;
namespace Lab7.Model
{
internal class PlayerThread : IDisposable
{
private bool _isPlay;
private bool _isStop;
private bool _isInterrupt;
private readonly AutoResetEvent _ar = new AutoResetEvent(false);
private readonly Player _player;
private MediaPlayer _mediaPlayer;
public Item PlayingItem { get; }
public PlayerThread(Item item, Player player)
{
PlayingItem = item;
_player = player;
}
public void Pause()
{
_isStop = true;
_isPlay = false;
_ar.Set();
}
public void Play()
{
_isStop = false;
_isPlay = true;
_ar.Set();
}
public void Start()
{
Play();
ThreadPool.QueueUserWorkItem(Run);
}
public void Interrupt()
{
_isInterrupt = true;
_ar.Set();
}
void m_MediaEnded(object sender, EventArgs e) => Interrupt();
private void Run(object state)
{
_mediaPlayer = new MediaPlayer();
_mediaPlayer.Open(new Uri(PlayingItem.FileName));
_mediaPlayer.MediaEnded += m_MediaEnded;
while (true)
{
if (_isInterrupt) break;
_ar.WaitOne();
if (_isPlay)
{
_mediaPlayer.Play();
_isPlay = false;
}
if (!_isStop) continue;
_mediaPlayer.Pause();
_isStop = false;
}
Dispose();
}
public override string ToString()
{
return PlayingItem.Name;
}
public void Dispose()
{
_ar.Dispose();
if (_mediaPlayer != null)
{
_mediaPlayer.Stop();
_mediaPlayer.Close();
_mediaPlayer = null;
}
_player.PlayNowList.Remove(this);
}
}
}
//Thread, ThreadPool, Blocking, Semaphore, Task, Asynqawait, TPL
|
PHP
|
UTF-8
| 4,510 | 2.921875 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Dress;
class DressController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$vestiti = Dress::all();
$data = [
'vestiti' => $vestiti
];
return view('dresses.index', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('dresses.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// a questo punto mi salvo i dati della request nel form (riga 45)
$data = $request -> all();
$request->validate([
'name' => 'required|unique:dresses|max:255',
'color' => 'required|max:20',
'size' => 'required|max:4',
'description' => 'required',
'price' => 'required|numeric',
'season' => 'required'
]);
//METODOLOGIA 1 - PER PASSARE I DATI DEL FORM
/* $new_dress = new Dress();
$new_dress->name = $data['name'];
$new_dress->color = $data['color'];
$new_dress->size = $data['size'];
$new_dress->description = $data['description'];
$new_dress->price = $data['price'];
//A questo punto ci si definisce un metodo, proprio per salvare:
$new_dress->save();
//Come faccio a rimuoverlo senza che mi faccia una copia e a rimandare l'utente al suo vestito?
//in questo modo mi fa ritornare alla pagine dei vestiti e posso visualizzare quindi il vestito appena creato
return redirect()->route('vestiti.index'); */
//FINE METODOLOGIA 1
//METODOLOGIA 2 - PER PASSARE I DATI DEL FORM
/* Controllare il Dress.php perché bisogna aggiungere il fill anche di là */
$new_dress = new Dress();
$new_dress->fill($data);
$new_dress->save(); // N.B: l'id viene assegnato solo dopo che ho effettuato questa operazione, ovvero il salvataggio, e così anche per il timestamp
return redirect()->route('vestiti.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id) //E se io tolgo l'id dalle parentesi? A cosa serve nelle parentesi l'id?
{
$data = Dress::find($id); //Questo serve per trovare lo specifico id, ma non potevo trovarlo anche senza?
if($id) { //ovvero: SE esiste $id, allora fammi questo... (in questo caso mi ritorna il mio vestito, ma solo perché ho chiamato a riga 55)
$vestito = Dress::find($id); //SELECT id FROM dress WHERE
$data = [
'vestito' => $vestito
];
return view('dresses.show', $data);
}
abort(404); //Perché non funziona?
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Dress $vestiti)
{
//
//primo metodo:
//$dress_to_update = Dress::findOrFail($id); //è un find, la differenza con l'altro è che se
//non esiste mi ritorna un errore
//Secondo metodo: molto più corto, a riga 112 nella parentesi non serve inserire l'id ma solo quell'istanza e poi usarla
//@dd($vestiti);
return view('dresses.edit', compact('vestiti'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Dress $vestiti)
{
//
$data = $request -> all();
$vestiti->update($data);
return redirect()->route('vestiti.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Dress $vestiti)
{
//
$vestiti->delete();
return redirect()->route('vestiti.index');
}
}
|
SQL
|
UTF-8
| 11,158 | 3.6875 | 4 |
[] |
no_license
|
-- 获取2020年的客户项目负责人数据
drop temporary table if exists test.cusitem_person;
create temporary table if not exists test.cusitem_person
select
start_dt
,end_dt
,concat(bi_cuscode,item_code,cbustype) as matchid
,areadirector
,cverifier
from edw.x_cusitem_person
where start_dt >= '2020-01-01';
alter table test.cusitem_person add index (start_dt),add index (end_dt),add index (matchid);
-- 实际收入处理
-- 19-20年收入 最终客户是multi的 改为ccuscode 不取健康检测, 不取杭州贝生 分组聚合 不取非销售数据 210112补充
drop temporary table if exists test.bonus_base;
create temporary table if not exists test.bonus_base
select
a.cohr
,a.ddate
,case
when a.finnal_ccuscode = 'multi' then a.ccuscode
else a.finnal_ccuscode
end as ccuscode
,a.cinvcode
,b.item_code
,b.business_class as cbustype
,sum(a.isum) as isum
,concat( if(a.finnal_ccuscode = 'multi',a.ccuscode,a.finnal_ccuscode),b.item_code,b.business_class) as matchid
,a.if_xs
from pdm.invoice_order as a
left join edw.map_inventory as b
on a.cinvcode = b.bi_cinvcode
where a.item_code != 'JK0101' and year(ddate) >= 2019
and a.cohr != '杭州贝生'
group by a.cohr,a.ddate,a.ccuscode,a.finnal_ccuscode,a.cinvcode,a.if_xs;
alter table test.bonus_base add index (ddate),add index (matchid);
-- 计划收入处理
drop temporary table if exists test.bonus_base_budget;
create temporary table if not exists test.bonus_base_budget
select
a.cohr
,a.ddate
,a.bi_cuscode as ccuscode
,a.bi_cinvcode as cinvcode
,b.item_code
,b.business_class as cbustype
,sum(a.isum_budget) as isum_budget
,concat( a.bi_cuscode,b.item_code,b.business_class) as matchid
from edw.x_sales_budget_20 as a
left join edw.map_inventory as b
on a.bi_cinvcode = b.bi_cinvcode
where a.cohr != '杭州贝生'
group by a.cohr,a.ddate,a.bi_cuscode,a.bi_cinvcode;
alter table test.bonus_base_budget add index (ddate),add index (matchid);
-- 明细匹配人员数据(19年人员 用20年客户同期的人员)
drop table if exists report.bonus_base_person;
create table if not exists report.bonus_base_person
-- 先取2020年实际数据
select
a.cohr
,a.ddate
,c.sales_dept
,case
when a.if_xs is null then c.sales_region_new
else '其他'
end as sales_region_new
,c.province
,case
when c.province in ("浙江省","安徽省","福建省","江苏省","山东省","湖南省") then "六省"
else "非六省"
end as mark_province
,a.ccuscode
,c.bi_cusname
,a.cinvcode
,a.item_code
,a.cbustype
,b.areadirector
,b.cverifier
,cast('act' as char(10)) as 'if_act'
,a.isum
,cast(0 as decimal(18,4)) as isum_budget
from test.bonus_base as a
left join test.cusitem_person as b
on a.matchid = b.matchid
and a.ddate >= b.start_dt and a.ddate <= b.end_dt
left join edw.map_customer as c
on a.ccuscode = c.bi_cuscode
where a.ddate >= '2020-01-01'
and a.isum !=0 ; -- 收入是0的数据不取
-- 取2019年实际数据
insert into report.bonus_base_person
select
a.cohr
,a.ddate
,c.sales_dept
,case
when a.if_xs is null then c.sales_region_new
else '其他'
end as sales_region_new
,c.province
,case
when c.province in ("浙江省","安徽省","福建省","江苏省","山东省","湖南省") then "六省"
else "非六省"
end as mark_province
,a.ccuscode
,c.bi_cusname
,a.cinvcode
,a.item_code
,a.cbustype
,b.areadirector
,b.cverifier
,cast('act' as char(10)) as 'if_act'
,a.isum
,cast(0 as decimal(18,4)) as isum_budget
from test.bonus_base as a
left join test.cusitem_person as b
on a.matchid = b.matchid
and date_add(a.ddate,interval 1 year) >= b.start_dt and date_add(a.ddate,interval 1 year) <= b.end_dt -- a表日期加一年
left join edw.map_customer as c
on a.ccuscode = c.bi_cuscode
where a.ddate >= '2019-01-01' and a.ddate <= '2019-12-31'
and a.isum != 0 ; -- 收入是0的数据不取
-- 取2020年计划数据
insert into report.bonus_base_person
select
a.cohr
,a.ddate
,c.sales_dept
,c.sales_region_new
,c.province
,case
when c.province in ("浙江省","安徽省","福建省","江苏省","山东省","湖南省") then "六省"
else "非六省"
end as mark_province
,a.ccuscode
,c.bi_cusname
,a.cinvcode
,a.item_code
,a.cbustype
,b.areadirector
,b.cverifier
,cast('budget' as char(10)) as 'if_act'
,cast(0 as decimal(18,4)) as isum
,a.isum_budget
from test.bonus_base_budget as a
left join test.cusitem_person as b
on a.matchid = b.matchid
and a.ddate >= b.start_dt and a.ddate <= b.end_dt
left join edw.map_customer as c
on a.ccuscode = c.bi_cuscode
where a.ddate >= '2020-01-01'
and a.isum_budget != 0; -- 计划收入是0的数据不取
-- 非省区客户,手动维护 -- 210112更新 已经通过pdm.invoice_order 区分是否销售负责的数据
-- update report.bonus_base_person set areadirector = '非省区客户' , cverifier = '非省区客户' where bi_cusname = "浙江迪安深海冷链物流有限公司";
-- update report.bonus_base_person set areadirector = '非省区客户' , cverifier = '非省区客户' where bi_cusname = "杭州优客互动网络科技有限公司";
-- 20200717更新 这家客户是销售负责 update report.bonus_base_person set areadirector = '非省区客户' , cverifier = '非省区客户' where bi_cusname = "湖南文吉健康管理有限公司";
-- update report.bonus_base_person set areadirector = '非省区客户' , cverifier = '非省区客户' where bi_cusname = "浙江玺诺医疗器械有限公司";
-- update report.bonus_base_person set areadirector = '非省区客户' , cverifier = '非省区客户' where bi_cusname = "杭州方回春堂同心中医门诊部有限公司";
-- 根据20年奖金方案 聚合减少数据量
drop temporary table if exists report.bonus_base_cal_;
create temporary table if not exists report.bonus_base_cal_
select
year(a.ddate) as year_
,month(a.ddate) as month_
,a.sales_dept
,a.sales_region_new
,a.province
,a.mark_province
,a.areadirector
,a.cverifier
-- 新品要品增量奖,需刨除2020下半年补充的几个重点项目(杰毅NIPT、CNV_seq、LDT甄元、博圣自有软件、东方海洋VD) 谷晓丽 2020-12-24 邮件
,case
when month(a.ddate) <= 6 then c.cinv_key_2020
when month(a.ddate) > 6 and c.cinv_key_2020 = '杰毅麦特NIPT' then null
when month(a.ddate) > 6 and c.cinv_key_2020 = '甄元LDT' then null
when month(a.ddate) > 6 and c.cinv_key_2020 = '服务_软件' then null
when month(a.ddate) > 6 and c.cinv_key_2020 = '东方海洋VD' then null
when month(a.ddate) > 6 and c.item_code = 'CQ0706' then null -- CNV-seq
else c.cinv_key_2020
end as cinv_key_2020
,ifnull(c.screen_class,"筛查") as screen_class
,c.equipment
,sum(isum) as isum
,sum(isum_budget) as isum_budget
from report.bonus_base_person as a
left join edw.map_inventory as c
on a.cinvcode = c.bi_cinvcode
group by year_,month_,a.sales_region_new,a.province,a.areadirector,a.cverifier,cinv_key_2020,c.screen_class,c.equipment;
alter table report.bonus_base_cal_ add index (areadirector),add index(cverifier);
-- ehr离职人员档案 最后工作日期+1 钉钉群 销售奖金工作群 谷晓丽确认 2020-10-22
drop table if exists report.bonus_base_ehr;
create table if not exists report.bonus_base_ehr
select
name
,employeestatus
,TransitionType
,date_add(lastworkdate, interval 1 day) as lastworkdate_add1
,year(date_add(lastworkdate, interval 1 day)) as year_
,month(date_add(lastworkdate, interval 1 day)) as month_
from pdm.ehr_employee
where employeestatus = '离职' and year(lastworkdate) = 2020;
alter table report.bonus_base_ehr add index (name);
-- 根据20年奖金方案 聚合减少数据量
drop table if exists report.bonus_base_cal;
create table if not exists report.bonus_base_cal
select
a.year_
,a.month_
,a.sales_dept
,a.sales_region_new
,a.province
,a.mark_province
,a.areadirector
,a.cverifier
,a.cinv_key_2020
,a.screen_class
,a.equipment
,a.isum
,a.isum_budget
,b.TransitionType as TransitionType_area
,b.lastworkdate_add1 as lastworkdate_area
,b.month_ as month_area
,c.TransitionType as TransitionType_cver
,c.lastworkdate_add1 as lastworkdate_cver
,c.month_ as month_cver
from report.bonus_base_cal_ as a
left join report.bonus_base_ehr as b
on a.areadirector = b.name
left join report.bonus_base_ehr as c
on a.cverifier = c.name
;
-- 以下2020-10-23 彭丽电话确认 源数据中不改确认空
-- -- 被动离职的, 改 确认空
-- update report.bonus_base_cal set areadirector = '确认空' where TransitionType_area = '被动离职';
-- update report.bonus_base_cal set cverifier = '确认空' where TransitionType_cver = '被动离职';
--
-- -- 主动离职的, 根据最后工作日期判断
-- -- 1. 最后工作日期在Q1, 改 确认空
-- update report.bonus_base_cal set areadirector = '确认空'
-- where TransitionType_area != '主动离职' and lastworkdate_area is not null
-- and month_area <= 3;
--
-- update report.bonus_base_cal set cverifier = '确认空'
-- where TransitionType_cver != '主动离职' and lastworkdate_cver is not null
-- and month_cver <= 3;
--
-- -- 2. 最后工作日期在Q2 , Q1不变, 其余改 确认空
-- update report.bonus_base_cal set areadirector = '确认空'
-- where (TransitionType_area = '主动离职' or TransitionType_area is null )and lastworkdate_area is not null
-- and month_area > 3 and month_area <= 6 and month_ >3;
--
-- update report.bonus_base_cal set cverifier = '确认空'
-- where (TransitionType_cver = '主动离职' or TransitionType_cver is null ) and lastworkdate_cver is not null
-- and month_cver > 3 and month_cver <= 6 and month_ >3;
--
-- -- 3. 最后工作日期在Q3 , Q1-Q2不变, 其余改 确认空
-- update report.bonus_base_cal set areadirector = '确认空'
-- where (TransitionType_area = '主动离职' or TransitionType_area is null ) and lastworkdate_area is not null
-- and month_area > 6 and month_area <= 9 and month_ >6;
--
-- update report.bonus_base_cal set cverifier = '确认空'
-- where (TransitionType_cver = '主动离职' or TransitionType_cver is null ) and lastworkdate_cver is not null
-- and month_cver > 6 and month_cver <= 9 and month_ >6;
--
-- -- 4. 最后工作日期在Q4 , Q1-Q3不变, 其余改 确认空
-- update report.bonus_base_cal set areadirector = '确认空'
-- where (TransitionType_area = '主动离职' or TransitionType_area is null ) and lastworkdate_area is not null
-- and month_area > 9 and month_area <= 12 and month_ >9;
--
-- update report.bonus_base_cal set cverifier = '确认空'
-- where (TransitionType_cver = '主动离职' or TransitionType_cver is null ) and lastworkdate_cver is not null
-- and month_cver > 9 and month_cver <= 12 and month_ >9;
|
Markdown
|
UTF-8
| 1,178 | 3.328125 | 3 |
[] |
no_license
|
# cs546-Final-Project
## Setup:
Bring terminal to root project folder. Run "npm install" to get requisite packages.
Run "node ./tasks/seed.js" to seed the database with example posts.
Run "npm start" to start the web server, and connect in a browser by going to localhost:3000.
## Usage:
Homepage("/") - This page will display the last 10 posts submitted to the site. Use buttons at bottom of page to cycle to older posts.
Sign Up ("/signup") - This allows users to create an account. Must provide a unique username.
Log in ("/login") - If you already have an account, provide your credentials here.
Create a Post ("/create") - Create a post to be displayed on the site. Must be logged in, or will redirect to the login page.
Random ("/random") - This page will redirect you automatically to a random post on the site.
My Profile ("/user/{id}") - This will show a user's authored posts and their favorites.
Post ("/post/{id}") - This page will show a single post, and if logged in, will display a button to add a post as a favorite.
Logout ("logout") - This will end the user's session and redirect them to the homepage.
|
C++
|
UTF-8
| 3,434 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
/*=============================================================================
Win32ConsoleStream.cpp
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
#include "Core/IO/ConsoleStream.h"
#include "Core/Exception/ArgumentNullException.h"
#include "Core/Exception/ArgumentOutOfRangeException.h"
#include "Win32Platform.h"
namespace SonataEngine
{
typedef ConsoleStream Win32ConsoleStream;
Win32ConsoleStream* Win32ConsoleStream::StandardInput = new Win32ConsoleStream(StdConsoleType_Input);
Win32ConsoleStream* Win32ConsoleStream::StandardOutput = new Win32ConsoleStream(StdConsoleType_Output);
Win32ConsoleStream* Win32ConsoleStream::StandardError = new Win32ConsoleStream(StdConsoleType_Error);
Win32ConsoleStream::ConsoleStream() :
Stream()
{
_ConsoleType = (StdConsoleType)0;
_handle = INVALID_HANDLE_VALUE;
}
Win32ConsoleStream::ConsoleStream(StdConsoleType type) :
Stream()
{
_ConsoleType = type;
if (type == StdConsoleType_Input)
_handle = ::GetStdHandle(STD_INPUT_HANDLE);
else if (type == StdConsoleType_Output)
_handle = ::GetStdHandle(STD_OUTPUT_HANDLE);
else if (type == StdConsoleType_Error)
_handle = ::GetStdHandle(STD_ERROR_HANDLE);
else
_handle = INVALID_HANDLE_VALUE;
}
Win32ConsoleStream::~ConsoleStream()
{
}
bool Win32ConsoleStream::CanRead() const
{
if ((HANDLE)_handle == INVALID_HANDLE_VALUE)
return false;
return (_ConsoleType == StdConsoleType_Input);
}
bool Win32ConsoleStream::CanWrite() const
{
if ((HANDLE)_handle == INVALID_HANDLE_VALUE)
return false;
return ((_ConsoleType == StdConsoleType_Output) || (_ConsoleType == StdConsoleType_Error));
}
bool Win32ConsoleStream::CanSeek() const
{
return false;
}
int32 Win32ConsoleStream::GetLength() const
{
return 0;
}
void Win32ConsoleStream::SetLength(int32 value)
{
}
int32 Win32ConsoleStream::GetPosition() const
{
return 0;
}
void Win32ConsoleStream::SetPosition(int32 value)
{
}
void Win32ConsoleStream::Close()
{
if ((HANDLE)_handle != INVALID_HANDLE_VALUE)
{
_ConsoleType = (StdConsoleType)0;
_handle = INVALID_HANDLE_VALUE;
}
}
void Win32ConsoleStream::Flush()
{
}
int32 Win32ConsoleStream::Seek(int32 offset, SeekOrigin origin)
{
return 0;
}
bool Win32ConsoleStream::IsEOF() const
{
return false;
}
byte Win32ConsoleStream::ReadByte()
{
byte value;
return (Read(&value, 1) == -1 ? -1 : value);
}
int32 Win32ConsoleStream::Read(byte* buffer, int32 count)
{
if (buffer == NULL)
{
throw ArgumentNullException("buffer");
}
if (count < 0)
{
throw ArgumentOutOfRangeException("count");
}
if ((HANDLE)_handle == INVALID_HANDLE_VALUE)
{
return -1;
}
if (!CanRead())
{
return -1;
}
DWORD dwNumberOfBytesRead;
if (::ReadFile((HANDLE)_handle, buffer, count, &dwNumberOfBytesRead, NULL) == FALSE)
{
return -1;
}
return dwNumberOfBytesRead;
}
void Win32ConsoleStream::WriteByte(byte value)
{
Write(&value, 1);
}
int32 Win32ConsoleStream::Write(const byte* buffer, int32 count)
{
if (buffer == NULL)
{
throw ArgumentNullException("buffer");
}
if (count < 0)
{
throw ArgumentOutOfRangeException("count");
}
if ((HANDLE)_handle == INVALID_HANDLE_VALUE)
{
return -1;
}
if (!CanWrite())
{
return -1;
}
DWORD dwNumberOfBytesWritten;
if (::WriteFile((HANDLE)_handle, buffer, count, &dwNumberOfBytesWritten, NULL) == FALSE)
{
return -1;
}
return dwNumberOfBytesWritten;
}
}
|
Java
|
UTF-8
| 5,106 | 2.296875 | 2 |
[] |
no_license
|
package org.softuni.main.casebook.handlers.dynamic;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.softuni.main.casebook.annotations.ApplicationRequestHandler;
import org.softuni.main.casebook.annotations.Get;
import org.softuni.main.casebook.annotations.Post;
import org.softuni.main.database.models.User;
import org.softuni.main.database.repositories.UserRepository;
import org.softuni.main.javache.WebConstants;
import org.softuni.main.javache.http.HttpCookie;
import org.softuni.main.javache.http.HttpCookieImpl;
import org.softuni.main.javache.http.HttpRequest;
import org.softuni.main.javache.http.HttpResponse;
import org.softuni.main.javache.http.HttpSession;
import org.softuni.main.javache.http.HttpSessionImpl;
import org.softuni.main.javache.http.HttpSessionStorage;
@ApplicationRequestHandler
public class UsersHandler extends BaseDynamicHandler {
protected UsersHandler(HttpSessionStorage sessionStorage) {
super(sessionStorage);
}
@Get(route = "/register")
public HttpResponse register(HttpRequest request, HttpResponse response) {
return this.view("register", request, response);
}
@Post(route = "/register")
public HttpResponse registerConfirm(HttpRequest request, HttpResponse response) {
UserRepository userRepository = new UserRepository();
String username = request.getBodyParameters().get("username");
String password = request.getBodyParameters().get("password");
userRepository.doAction("create", username.toString(), password.toString());
userRepository.dismiss();
return this.redirect("/", request, response);
}
@Get(route = "/login")
public HttpResponse login(HttpRequest request, HttpResponse response) {
return this.view("login", request, response);
}
@Post(route = "/login")
public HttpResponse loginConfirm(HttpRequest request, HttpResponse response) {
UserRepository userRepository = new UserRepository();
String username = request.getBodyParameters().get("username");
String password = request.getBodyParameters().get("password");
User user = (User) userRepository.doAction("findByUsername", username);
if(user == null) {
return this.redirect("/login", request, response);
} else if (!user.getPassword().equals(password)) {
return this.redirect("/login", request, response);
}
String sessionId = UUID.randomUUID().toString();
HttpSession session = new HttpSessionImpl(sessionId);
session.addAttribute("user-id", user.getId());
this.sessionStorage.setSessionData(session.getId(), session);
response.addCookie(new HttpCookieImpl(WebConstants.SERVER_SESSION_TOKEN, session.getId()));
userRepository.dismiss();
return this.redirect("/home", request, response);
}
@Post(route = "/logout")
public HttpResponse logout(HttpRequest request, HttpResponse response) {
if(!this.isLoggedIn(request)) {
return this.redirect("/login", request, response);
}
HttpCookie cookie = request.getCookies().get(WebConstants.SERVER_SESSION_TOKEN);
this.sessionStorage.getSessionData(cookie.getValue()).invalidate();
this.sessionStorage.removeSession(cookie.getValue());
response.addCookie(new HttpCookieImpl("Javache", "token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"));
return this.redirect("/", request, response);
}
@Get(route = "/profile")
public HttpResponse profile(HttpRequest request, HttpResponse response) {
if (!this.isLoggedIn(request)) {
return this.redirect("/login", request, response);
}
UserRepository repository = new UserRepository();
User user = this.getCurrentUser(request, repository);
StringBuilder friendsHtml = new StringBuilder();
friendsHtml.append("<ul class=\"list-group\">");
for (User friend : user.getFriends()) {
friendsHtml.append("<li class=\"list-group-item\">").append(friend.getUsername()).append("</li>");
}
friendsHtml.append("</ul>");
this.viewData.remove("username");
this.viewData.remove("friends");
this.viewData.putIfAbsent("username", user.getUsername());
this.viewData.putIfAbsent("friends", friendsHtml.toString());
repository.dismiss();
return this.view("profile", request, response);
}
@Post(route = "/add-friend")
public HttpResponse addFriend(HttpRequest request, HttpResponse response) {
if (!this.isLoggedIn(request)) {
return this.redirect("/login", request, response);
}
UserRepository userRepository = new UserRepository();
User currentUser = this.getCurrentUser(request, userRepository);
userRepository.doAction("addFriend", currentUser.getUsername(), request.getBodyParameters().get("friend"));
userRepository.dismiss();
return this.redirect("/profile", request, response);
}
}
|
C
|
GB18030
| 17,735 | 2.59375 | 3 |
[] |
no_license
|
#include "header.h"
#include <stdio.h>
#include<string.h>
#define N 6
operatedata userdata;
extern char *wday[] ;
extern struct tt * p;
FILE *number;
int vipnumber=N;
people * VipList()
{
FILE *fp;
int i;
if((fp=fopen("vip.txt","r"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
people * head,*node,*tail;
head=(people *)malloc(sizeof(people));
tail=head;
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(i=0;i<vipnumber;i++)
{
node=(people *)malloc(sizeof(people));
fscanf(fp,"%s %s %d",node->ID,node->name,&node->vip);
tail->next=node;
tail=node;
}
tail->next=NULL;
head=head->next;
fclose(fp);
return head;
}
void Find()
{
FILE *fp;
FILE *invip;
int i,j;
int choice;
char choice2;
char temp;
char target[20];
people *head,*change;
head=VipList();
fp=fopen("vip.txt","w");
change=head;
printf("Ա֤вѯ:\n");
scanf("%s",target);
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(i=0;i<vipnumber;i++)
{
if(strcmp(target,head->name)==0||strcmp(target,head->ID)==0)
{
printf("ԱϢ\n");
printf(":");
printf("%s\n",head->name);
stpcpy(userdata.user,head->name);
printf("֤:");
printf("%s\n",head->ID);
stpcpy(userdata.ID,head->ID);
printf("vip:");
printf("%d\n",head->vip);
if(head->vip>=5)
{
printf("ûԱֿɻȡƷǷҪͨԱֻȡƷ?(1 OR 0) 1һ0˳\n");
scanf("%d",&choice);
while(!(choice==1 || choice==0))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
if(choice==1)
{
system("cls");
printf("***********************************************\n");
printf("*---------------------------------------------*\n");
printf("*| |*\n");
printf("*| Ʒ |*\n");
printf("*| |*\n");
printf("*| 1.ȯ80Ԫ 5 |*\n");
printf("*| 2.ororȯ 2 |*\n");
printf("*| 3.Ƶ 2 |*\n");
printf("*| 4.Ʒ 1 |*\n");
printf("*| 5.һ˵ |*\n");
printf("*| |*\n");
printf("*| |*\n");
printf("*---------------------------------------------*\n");
printf("***********************************************\n");
printf("ҪһƷ:(1-4)\n");
scanf("%d",&choice);
while(!(choice==1 || choice==2|| choice==3|| choice==4))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
// /*
userdata.vipchoice=choice;
switch(choice)
{
case 1:
printf("ϲѳɹһ:ȯ80Ԫ\n");
head->vip-=5;
userdata.vippoint=head->vip;
break;
case 2:
printf("ϲѳɹһ:ororȯ\n");
head->vip-=2;
userdata.vippoint=head->vip;
break;
case 3:
printf("ϲѳɹһ:Ƶ\n");
head->vip-=2;
userdata.vippoint=head->vip;
break;
case 4:
printf("ϲѳɹһ:Ʒ\n");
head->vip-=1;
userdata.vippoint=head->vip;
break;
}
Timeget();
if((invip=fopen("OperateData.txt","a"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
fprintf(invip,"%d%d%d\t%s\t%dʱ:%d:%d\t֤Ϊ:%svipû:%s,һƷ%d,ĿǰVIPΪ:%d\n",(p->tm_year),(p->tm_mon), p->tm_mday,wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec,userdata.ID,userdata.user,userdata.vipchoice,userdata.vippoint);
fclose(invip);
}
else
{
break;
}
}
else
{
printf("ûԱĻв㻻ȡƷԱֿͨסʱȡ\n");
}
break;
}
else
{
head=head->next;
}
}
if(i==vipnumber)
{
printf("!\n");
}
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(j=0;j<vipnumber;j++)
{
fprintf(fp,"%s %s %d\n",change->ID,change->name,change->vip);
change=change->next;
}
fclose(fp);
printf("ѯ,Ƿ²ѯ(1)(0)һ(2):\n");
scanf("%d",&choice);
while(!(choice==1 || choice==0|| choice==2))
{
printf("ȷ\n");
scanf("%d",&choice);
}
switch(choice)
{
case 1: Find();break;
case 0: welcome();break;
case 2: VipService();break;
}
}
void change1()
{
int choice;
int i,j;
FILE *fp;
FILE *invip;
people *head,*change;
char target[20];
char now_name[20];
char now_ID[20];
int now_vip;
head=VipList();
change=head;
if((fp=fopen("vip.txt","w"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
printf("Ҫĵvipû֤\n");
scanf("%s",target);
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(i=0;i<vipnumber;i++)
{
if(strcmp(target,head->name)==0||strcmp(target,head->ID)==0)
{
printf("ԱϢ\n");
printf(":");
printf("%s\n",head->name);
stpcpy(userdata.user,head->name);
printf("֤:");
printf("%s\n",head->ID);
stpcpy(userdata.ID,head->ID);
printf("vip:");
printf("%d\n",head->vip);
printf("ѡҪĵϢ(1-3):1.֤\t2.\t3.VIP\n");
scanf("%d",&choice);
while(!(choice==2 || choice==1|| choice==3))
{
printf("ѡȷѡ:\n");
}
switch(choice)
{
case 1:
printf("ĺ֤:\n");
scanf("%s",now_ID);
stpcpy(head->ID,now_ID);
printf("ĺϢΪ:\n֤:%s\n:%s\n",head->ID,head->name);
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(j=0;j<vipnumber;j++)
{
fprintf(fp,"%s %s %d\n",change->ID,change->name,change->vip);
change=change->next;
}
fclose(fp);
Timeget();
if((invip=fopen("OperateData.txt","a"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
fprintf(invip,"%d%d%d\t%s\t%dʱ:%d:%d\tvipû:%s֤Ϣ%s\n",(p->tm_year),(p->tm_mon), p->tm_mday,wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec,head->name,head->ID);
fclose(invip);
printf("(1)һ(2)?(1-2):\n");
scanf("%d",&choice);
while((!choice==2 || choice==1))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
switch (choice)
{
case 1:
change1();
break;
case 2:
VipService();
break;
}
case 2:
printf("ĺ:\n");
scanf("%s",now_name);
stpcpy(head->name,now_name);
printf("ĺϢΪ:\n֤:%s\n:%s\n",head->ID,head->name);
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(j=0;j<vipnumber;j++)
{
fprintf(fp,"%s %s %d\n",change->ID,change->name,change->vip);
change=change->next;
}
fclose(fp);
Timeget();
if((invip=fopen("OperateData.txt","a"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
fprintf(invip,"%d%d%d\t%s\t%dʱ:%d:%d\t֤Ϊ%svipûϢ%s\n",(p->tm_year),(p->tm_mon), p->tm_mday,wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec,head->ID,head->name);
fclose(invip);
printf("(1)һ(2)?(1-2):\n");
scanf("%d",&choice);
while(!(choice==2 || choice==1))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
switch (choice)
{
case 1:
change1();
break;
case 2:
VipService();
break;
}
case 3:
printf("ĺvip:\n");
scanf("%d",&now_vip);
head->vip=now_vip;
printf("ĺϢΪ:\n֤:%s\n:%s\nvip:%d\n",head->ID,head->name,head->vip);
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
for(j=0;j<vipnumber;j++)
{
fprintf(fp,"%s %s %d\n",change->ID,change->name,change->vip);
change=change->next;
}
fclose(fp);
Timeget();
if((invip=fopen("OperateData.txt","a"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
fprintf(invip,"%d%d%d\t%s\t%dʱ:%d:%d\tvipû:%svipϢ:%d\n",(p->tm_year),(p->tm_mon), p->tm_mday,wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec,head->name,head->vip);
fclose(invip);
printf("(1)һ(2)?(1-2):\n");
scanf("%d",&choice);
while(!(choice==2 || choice==1))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
switch (choice)
{
case 1:
change1();
break;
case 2:
VipService();
break;
}
}
}
else
{
head=head->next;
}
}
if(i==vipnumber)
{
printf("!\n");
}
for(;change->next!=NULL;)
{
fprintf(fp,"%s %s %d\n",change->ID,change->name,change->vip);
change=change->next;
}
fclose(fp);
printf("ѯ,Ƿ²ѯ(1)(0)߷һ(2):\n");
scanf("%d",&choice);
while(!(choice==1 || choice==0))
{
printf("ȷ\n");
scanf("%d",&choice);
}
switch(choice)
{
case 1: Find();break;
case 0: welcome();break;
}
}
void vipcreat()
{
FILE *fp;
FILE *op;
int choice;
char new_ID[20];
char new_name[20];
int new_point=0;
if((fp=fopen("vip.txt","a"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
vipnumber+=1;
number=fopen("number.txt","w");
fprintf(number,"%d",vipnumber);
fclose(number);
printf("û֤\n");
scanf("%s",new_ID);
printf("û:\n");
scanf("%s",new_name);
fprintf(fp,"%s %s %d\n",new_ID,new_name,new_point);
fclose(fp);
Timeget();
if((op=fopen("OperateData.txt","a"))==NULL)
{
printf("ļʧ\n");
exit(0);
}
fprintf(op,"%d%d%d\t%s\t%dʱ:%d:%d\tvipû:%s,֤Ϊ:%s\n",(p->tm_year),(p->tm_mon), p->tm_mday,wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec,new_name,new_ID);
fclose(op);
printf("ɹ!һ?(1-2)\n");
while((!scanf("%d",&choice)&&(choice==2 || choice==1)))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
switch (choice)
{
case 1:
vipcreat();
break;
case 2:
VipService();
break;
}
}
void VipService()
{
int choice;
system("cls");
printf("*******************************************\n");
printf("*-----------------------------------------*\n");
printf("*| |*\n");
printf("*| |*\n");
printf("*| 1.ԱϢҼƷһ |*\n");
printf("*| 2.ԱϢ |*\n");
printf("*| 3.Ա˻ |*\n");
printf("*| 4.˵ |*\n");
printf("*| |*\n");
printf("*| |*\n");
printf("*-----------------------------------------*\n");
printf("*******************************************\n");
printf("ѡ(1-4):\n");
scanf("%d",&choice);
while(!(choice==2 || choice==1||choice==3||choice==4))
{
printf("ѡȷѡ:\n");
scanf("%d",&choice);
}
switch(choice)
{
case 1:
Find();
break;
case 2:
change1();
break;
case 3:
vipcreat();
break;
case 4:
welcome();
break;
}
}
/*
void vipsearch(char *target )
{
int i,j;
FILE *fp;
FILE *invip;
people *head,*change;
number=fopen("number.txt","r");
fscanf(number,"%d",&vipnumber);
fclose(number);
head=VipList();
change=head;
fp=fopen("vip.txt","w");
change=head;
for(i=0;i<vipnumber;i++)
{
if(strcmp(target,head->ID)==0)
{
printf("ûΪVIPûÿסVIP˴εס2֡\n");
head->vip+=2;
}
else
{
head=head->next;
}
}
if(i==vipnumber)
{
printf("ûvipûƵṩvipעṦܡ\n");
}
for(j=0;j<vipnumber;j++)
{
fprintf(fp,"%s %s %d\n",change->ID,change->name,change->vip);
change=change->next;
}
fclose(fp);
}
*/
|
Go
|
UTF-8
| 2,429 | 2.703125 | 3 |
[] |
no_license
|
// storeResultsFunctionTesting
package main
import (
"database/sql"
"errors"
"fmt"
//"strconv"
_ "github.com/go-sql-driver/mysql"
)
type Submission struct {
courseName string
assignmentName string
userName string
userID int
sourceName string // without .cpp, call this submission name..?
numTestCases int
compiled bool
results string
maxRuntime int
compilerOptions string
submissionNum int
}
const DB_USER_NAME string = "dbadmin"
const DB_PASSWORD string = "EX0evNtl"
const DB_NAME string = "pest"
const SHELL_NAME string = "ksh"
//------------------------------------------------------------------------------
func storeResults(results Submission) error {
db, err := sql.Open("mysql", DB_USER_NAME+":"+DB_PASSWORD+"@unix(/var/run/mysql/mysql.sock)/"+DB_NAME)
if err != nil {
return errors.New("No connection")
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Println("Failed to connect to the database.")
return errors.New("Failed to connect to the database.")
}
//printResults(results)
updateStatement, err := db.Prepare("update Submissions set Compile=(?), Results=(?) where Student=(?) and SubmissionNumber=(?) and AssignmentName=(?)")
if err != nil {
//fmt.Println("Failed to prepare.")
return errors.New("Failed to prepare.")
}
res, err := updateStatement.Exec(results.compiled, results.results, results.userID, results.submissionNum, results.assignmentName)
//res, err := updateStatement.Exec(results.compiled, results.results, results.userID, results.submissionNum, results.assignmentName, results.numTestCases)
if err != nil {
//fmt.Println("Update failed.")
return errors.New("Update failed.")
}
rowsAffected, _ := res.RowsAffected()
if rowsAffected != 1 {
//fmt.Println("Could not store results into database. Please try again.")
return errors.New("Could not store results into database. Please try again.")
}
return nil
}
//------------------------------------------------------------------------------
func main() {
results := Submission{}
results.submissionNum = 0
results.courseName = "TerwilligerCS15501SP17"
results.assignmentName = "0"
results.compiled = true
results.results = "TEST: Some results..."
results.userID = 11111
//fmt.Println("Test...")
storeResults(results)
}
|
Python
|
UTF-8
| 476 | 3.75 | 4 |
[] |
no_license
|
#!/usr/bin/env python
#
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
#
from euler.util import is_palindrome
def run():
L = []
for i in reversed(range(100, 1000)):
for j in reversed(range(100, 1000)):
if is_palindrome(i * j):
L.append(i * j)
print max(L)
|
C
|
UTF-8
| 1,746 | 3.21875 | 3 |
[] |
no_license
|
/*
** main.c for main in /home/pion_b/CPE_2015_getnextline
**
** Made by Virgile Pion
** Login <pion_b@epitech.net>
**
** Started on Mon Jan 4 10:53:25 2016 Virgile Pion
** Last update Sun Jan 22 01:34:39 2017 Virgile
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include "get_next_line.h"
int my_strlen(char *str)
{
int i;
i = 0;
if (str == NULL)
return (0);
while (str[i])
i++;
return (i);
}
static char *my_strncpy(char *dest, char *src, int n)
{
int i;
i = 0;
while (src[i] != '\0' && i < n)
{
dest[i] = src[i];
i++;
}
if (n < i)
dest[i] = '\0';
return (dest);
}
static char *add(char *line, char *buf, int *start, int nbread)
{
char *next;
int back;
back = (line != 0) ? (my_strlen(line)) : (0);
if ((next = malloc((back + nbread + 1) * sizeof(*next))) == NULL)
return (NULL);
if (line != 0)
my_strncpy(next, line, back);
else
my_strncpy(next, "", back);
next[back + nbread] = 0;
my_strncpy(next + back, buf + *start, nbread);
if (line)
free(line);
*start = *start + (nbread + 1);
return (next);
}
char *get_next_line(const int fd)
{
static char buf[READ_SIZE];
static int nbbuf = 0;
static int start;
char *line;
int nbread;
line = 0;
nbread = 0;
while (1)
{
if (nbbuf <= start && (start = 0) == 0)
{
if (!(nbbuf = read(fd, buf, READ_SIZE)))
return (line);
if (((nbread = 0) == 0) && nbbuf == -1)
return (NULL);
}
if (buf[start + nbread] == '\n')
return (line = add(line, buf, &start, nbread));
if (start + nbread == nbbuf - 1 \
&& (line = add(line, buf, &start, nbread + 1)) == NULL)
return (NULL);
nbread++;
}
}
|
JavaScript
|
UTF-8
| 289 | 2.796875 | 3 |
[] |
no_license
|
// console.log(this);
const kibria = {
id: 101,
name: "Rj Kibriya",
major: 'mathematics',
isRich: false,
money: 5000,
treatDey: function (expense, boksis) {
this.money = this.money - expense - boksis
console.log(this);
return this.money
}
}
|
Ruby
|
UTF-8
| 763 | 3.25 | 3 |
[] |
no_license
|
class User
attr_reader :age
def initialize(hash)
@name = hash[:name]
@age = hash[:age]
end
def name
if @name
@name
else
puts "a girl has no name"
end
end
def plants
self.user_plants.map do |user_plant|
user_plant.plant
end
end
def user_plants
user_plants= UserPlant.all.select do |user_plant|
user_plant.user == self
end
end
def which_days
# user_plants.map{|up| up.day}.uniq
user_plants.map do |up|
up.day
end.uniq
end
def add_plant(name, type, height)
Plant.new({name: name, type: type, height: height, user: self})
end
end
|
Python
|
UTF-8
| 2,379 | 3.546875 | 4 |
[] |
no_license
|
#crawl web https://www.udacity.com/cs101x/index.html
import urllib
import time
#1) get the urls of a web page
def geturls(url): # get the first/next link in source code of variable "page"
page = urllib.urlopen(url).read()
linklist = []
start_link = page.find('<a href=')
while start_link != -1:
start_quote = page.find('"http', start_link) #start search for " from psoition "startling"
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote] #+1 so as to not capture the " ie start at HTTP
linklist.append(url)
start_link= page.find('<a href=',end_quote)
return linklist
def crawl_the_web(url,max_pages):
start_time = time.time() # Check execution time of this program
to_crawl = [url]
final_list_of_crawled_urls = []
index = ["init",["init"]]
while to_crawl: # while this list is not empty
if len(final_list_of_crawled_urls) < max_pages:
url = to_crawl.pop()
linklist = geturls(url)
for link in linklist:
if link not in final_list_of_crawled_urls :
final_list_of_crawled_urls.append(link)
else:
linklist.remove(link) # dont store duplicates
for link in linklist:
to_crawl.append(link) # any new links found, go and crawl them
else:
break
while final_list_of_crawled_urls:
for link in final_list_of_crawled_urls:
url = final_list_of_crawled_urls.pop()
try: # some pages reject urlopen
content = urllib.urlopen(url).read()
except:
print "exception" , url
words = content.split()
less_words = words[5:6]
index.append([less_words,[url]] ) # slow and basic but works to prove the point.
print("--- %s seconds ---" % (time.time() - start_time)) # execution time
print index
# return (final_list_of_crawled_urls)
print crawl_the_web("http://www.reddit.com",5)
|
Python
|
UTF-8
| 1,070 | 2.8125 | 3 |
[] |
no_license
|
from tkinter import *
from tkinter import filedialog,messagebox
root = Tk()
root.geometry('300x300')
root.title('encrypt/decrypt')
def encdec():
f1 = filedialog.askopenfile(mode='r', filetype=[ ('png file', '*.png'),('jpg file', '*.jpg'), ('mp3 file', '*.mp3'), ('video file', '*.mp4'), ('mkv file', '*.mkv'), ('gif file', '*.gif')])
if f1 is not None:
# print(f1)
image = f1.name
# print(image)
key = e.get()
e.delete(0,END)
fl = open(image,'rb')
img = fl.read()
fl.close()
img = bytearray(img)
for index,values in enumerate(img):
img[index] = values^int(key)
f11= open(image,'wb')
f11.write(img)
f11.close()
messagebox.showinfo('Congratulations',"Process completed successfully")
b = Button(root,text="encrypt/decrypt",font="luicida 10 bold",command=encdec)
b.place(x=90,y=30)
e = Entry(root)
e.place(x=60,y=80)
e.config(show="*")
l = Label(root,text='Integer Key only',font='luicida 15 bold')
l.place(x=50,y=120)
root.mainloop()
|
C++
|
UTF-8
| 197 | 2.921875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int Count(int x){
for (int i=1;i<=16;i=i<<1){
x=x^(x>>i);
}
return x&1;
}
int main(){
int x;
while (cin>>x){
cout<<Count(x)<<endl;
}
return 0;
}
|
Java
|
UTF-8
| 1,162 | 3.828125 | 4 |
[] |
no_license
|
package data_structure.queue;
public class ListQueue<T> {
private QueueNode<T> front;
private QueueNode<T> rear;
public ListQueue() {
this.front = null;
this.front = null;
}
public void enQueue(T item) {
QueueNode<T> node = new QueueNode<>(item);
if(isEmpty()){
front = node;
}else{
rear.next = node;
}
rear = node;
}
public T deQueue() {
if(isEmpty()){
throw new ArrayIndexOutOfBoundsException();
}else{
T item = front.data;
front = front.next;
if(front == null){
rear = null;
}
return item;
}
}
public T peek() {
if(isEmpty()){
throw new ArrayIndexOutOfBoundsException();
}else{
return front.data;
}
}
public void clear() {
if(isEmpty()) {
System.out.println("Queue is already empty!");
}
else {
front = null;
rear = null;
}
}
public boolean isEmpty() {
return front == null;
}
}
|
Java
|
UTF-8
| 907 | 2.59375 | 3 |
[] |
no_license
|
package com.howie.java.request;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* Created with IntelliJ IDEA
*
* @Author yuanhaoyue swithaoy@gmail.com
* @Description
* @Date 2018-04-21
* @Time 20:25
*/
@RestController
@RequestMapping("/requestController1")
public class RequestController1 {
/**
* 线程安全
*
* 缺点:request对象的获取只能从controller开始,如果使用request对象的地方在函数调用层级比较深的地方,
* 那么整个调用链上的所有方法都需要添加request参数
*/
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request) {
return request.getRequestURI();
}
}
|
C#
|
UTF-8
| 1,089 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
using CreateUserFields.Domain;
using SimpleQuery;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreateUserFields.Infra
{
public class SettingRepository : ISettingRepository
{
private IDataConnection _dataConnection;
public SettingRepository(IDataConnection dataConnection)
{
_dataConnection = dataConnection;
}
public Setting GetSetting()
{
var setting = _dataConnection.DbConnection.Select<Setting>(c => c.Language == "English").LastOrDefault();
if (setting == null)
{
setting = new Setting { Language = "English" };
Save(setting);
}
return setting;
}
public void Save(Setting setting)
{
if (setting.Id == 0)
_dataConnection.DbConnection.Insert(setting);
else
_dataConnection.DbConnection.Update(setting);
}
}
}
|
Python
|
UTF-8
| 1,120 | 3.3125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import sys
S = 4
x_won = "X won"
o_won = "O won"
draw = "Draw"
not_completed = "Game has not completed"
def solve(board):
ways = []
ways.append([ (j, j) for j in xrange(S) ])
ways.append([ (j, S - j - 1) for j in xrange(S) ])
for i in xrange(S):
ways.append([ (i, j) for j in xrange(S) ])
ways.append([ (j, i) for j in xrange(S) ])
completed = True
for way in ways:
x = True
o = True
for pos in way:
c = board[pos[0]][pos[1]]
if c == 'X':
o = False
if c == 'O':
x = False
if c == '.':
completed = False
x = False
o = False
if x:
return x_won
if o:
return o_won
if completed:
return draw
return not_completed
T = int(sys.stdin.readline())
for t in xrange(T):
if t > 0:
sys.stdin.readline()
board = []
for i in xrange(S):
board.append(sys.stdin.readline())
res = solve(board)
print "Case #%d: %s" % (t + 1, res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.