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
|
|---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 907
| 2.859375
| 3
|
[] |
no_license
|
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
const int MAX = 100;
int Table[MAX][MAX];
int result[MAX][MAX];
vector <int> myGraph[MAX];
void DFS(int start, bool check[]) {
check[start] = true;
printf("start : %d\n", start);
for(int j=0; j<myGraph[start].size(); j++) {
int node = myGraph[start][j];
if(!check[node]) {
result[start][node] = 1;
DFS(node, check);
}
}
}
int main()
{
int N;
scanf("%d", &N);
bool check[N];
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
scanf("%d", &Table[i][j]);
if(Table[i][j] == 1) {
myGraph[i].push_back(j);
myGraph[j].push_back(i);
}
}
}
for(int i=0; i<N; i++) {
memset(check, false, sizeof(bool)*(N));
DFS(i, check);
}
printf("======================\n");
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
|
Java
|
UTF-8
| 2,541
| 2.125
| 2
|
[] |
no_license
|
package rest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import javax.annotation.Priority;
import javax.crypto.KeyGenerator;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;
import dao.SessionDAO;
import dao.UserDAO;
import dto.UserDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.impl.crypto.MacProvider;
import logic.CDIOException.DALException;
import logic.CDIOException.InvalidLoginException;
@Provider
@JWTTokenNeeded
public class RESTSession implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
System.out.println("Admin");
try {
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authorizationHeader == null) {
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
return;
}
String token = authorizationHeader.substring("Bearer".length()).trim();
Claims claims = Jwts.parser()
.setSigningKey(RESTLogin.getKey())
.parseClaimsJws(token).getBody();
System.out.println("validated as user: " + claims.getId() + " with roles: " + claims.get("roles"));
ArrayList<String> roles = (ArrayList<String>) claims.get("roles");
if (roles == null || !Arrays.asList(roles).contains("Administrator")) {
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
} catch(ExpiredJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
e.printStackTrace();
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
}
|
Markdown
|
UTF-8
| 7,763
| 2.75
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# Machine Learning Model Inference
## Summary
This tutorial describes how to use within the ImFusion framework a deep learning model that has been trained independently from Python.
The C++ plugin included in this repo will define a demo algorithm that runs such a model in the Suite.

## Requirements and Build Instructions
- Installed ImFusion SDK with ImageMathPlugin and TorchPlugin (or OnnxRuntimePlugin)
- Qt5 (at least the version that the ImFusion SDK comes with)
- CMake version 3.2 or newer
Use CMake to generate build/project files for your build system of choice.
If you are using Visual Studio the CMake scripts will automatically configure the generated Solution with the correct environment parameters so that you can launch the ImFusion Suite including your plugin directly from Visual Studio.
If the ImFusion Suite does not pick up the built plugin on start, configure the `IMFUSION_PLUGIN_PATH` environment variable to contain .dll/.so directory.
The two main deep learning engines supported in the ImFusion framework are [Torch](https://pytorch.org/) and [ONNXRuntime](https://onnxruntime.ai/) (experimental).
To make sure that you have the appropriate plugins (`TorchPlugin`, `OnnxRuntimePlugin`) installed with the Suite/SDK, you can start the ImFusion Suite or Console and look at the log window:
```
ImFusionLib Version x.x.x built on yyyy-mm-dd.
[OnnxRuntimePlugin] Providers: CUDAExecutionProvider
[OnnxRuntimePlugin] Providers: CPUExecutionProvider
[Framework] Available Plugins: [...], ImFusionML, OnnxRuntimePlugin, TorchPlugin [...]
```
## Step 1: Exporting trained models from PyTorch
### As Torch traced model
The currently supported version of PyTorch is 1.8 (or 1.5 for older versions of our SDK, or Windows VS2017 installers).
Exporting the model with a different version of PyTorch may lead to incompatibility errors.
```python
# For 3D volumes
dummy_input = torch.rand(1, 1, 64, 64, 64) # batch x channels x slices x height x width
# For 2D images
dummy_input = torch.rand(1, 3, 256, 256) # batch x channels x height x width
traced_script_module = torch.jit.trace(model, dummy_input)
traced_script_module.save("traced_model.pt")
```
### As ONNX model
```python
# For 3D volumes
dummy_input = torch.rand(1, 1, 64, 64, 64) # batch x channels x slices x height x width
# For 2D images
dummy_input = torch.rand(1, 3, 256, 256) # batch x channels x height x width
# Define dynamic axes (that can be resized at inference time)
input_dynamic_axes = {0: 'batch', 2: 'width', 3: 'height', 4: 'depth'}
input_dynamic_axes = {dim: name for dim, name in input_dynamic_axes.items() if dim < len(dummy_input.shape)}
torch.onnx.export(model, dummy_input, "traced_model.onnx", input_names=['input'], dynamic_axes={'input': input_dynamic_axes})
```
Other models exported as ONNX (for instance converted from TensorFlow) can be used as long as they follow the same convention as described above.
## Step 2: Preparing the YAML model file
Once you have exported your model in a suitable format, you need to create a model configuration file with the YAML format.
This file will contain all the necessary information for the ImFusion framework to run it on an input image.
The section below shows an example of such a file.
```yaml
Version: 4.0
Type: NeuralNetwork
Name: Name of the model (no practical purpose)
Description: Description of the model (no practical purpose)
Engine: torch # Could be onnx
ModelFile: traced_model.pt # Path to the actual model file (could be a onnx file)
ForceCPU: false # Set it to true if you want to perform the inference on the CPU instead of the GPU
Verbose: false # Print many info messages
MaxBatchSize: 1 # Maximum number of images to run through the network simulatenously
LabelNames: [FirstObject, SecondObject] # Names of the different labels encoded as channels of the output tensor
#############################################################################################
# Sequence of preprocessing operations run before the network
# (all available operations are available in the Python documentation of the SDK)
#############################################################################################
PreProcessing:
- MakeFloat: {} # First convert to float
- BakeTransformation: {} # If the image has a matrix, apply the transformation to the image
- Resample: # Resample to a fixed resolution of 1.5mm
resolution: 1.5
- NormalizePercentile: # Normalize image intensities based on the image percentile
min: 0.001
max: 0.999
clip: false
#############################################################################################
# For pixelwise (fully convolutional) models, it might be necessary to split the input in sub-images
# because of GPU memory constraints, especially for 3D volumes.
# Each of those images will be fed into the network and the predictions will be recombined.
# This section can be removed for imagewise models.
#############################################################################################
Sampling:
# Maximum size of the sub-image (set to -1 if you never want to split the image)
- MaxSizeSubdivision: 96
# Some network architectures require each sub-image dimension to be a multiple of this number
- DimensionDivisor: 16
# Recommended for real-time applications when speed is paramount
- SkipUnpadding: false
# Sub-images are extracted with overlap in order to avoid border effect - this is the size in pixels of this overlap
- PixelsOverlap: 32
# Weigh the different contributions at each pixel of overlap regions based on their position
- RecombineWeighted: true
# Repeat border values or mirror pad when extracting sub-images at to the border
- MirrorPadding: false
#############################################################################################
# Sequence of preprocessing operations run
# after the network and the recombination of the sub-images
# (all available operations are available in the Python documentation of the SDK)
#############################################################################################
PostProcessing:
- ResampleToInput: {} # Resample the prediction image back to the original image
- ArgMax: {} # Convert the multi-channel probability map to a label map
```
## Step 3a: Executing a model in the ImFusion Suite
The algorithm that runs a Machine Learning model in the Suite is `Run Machine Learning Model`.
It is available in the *Machine Learning* sub-menu of the algorithm list.
Select the path to the YAML model configuration file, and click on _Compute_.
## Step 3b: Executing a model from the ImFusion SDK
The aforementioned algorithm is a UI wrapper of the class `MachineLearningModel` which is available via our C++ SDK.
For more details, have a look at the source code of this sample plugin (in particular `RunPretrainedModelAlgorithm`), which consists in running a segmentation model after pre-processing the input.
In order to reproduce what is shown in the screenshot, build the `MachineLearningInferencePlugin` and start the ImFusionSuite.
Open the image `horse.png`, and select the new algorithm called _My Demo Machine Learning Algorithm_ in the _Machine Learning_ sub-menu.
Select the `demo_model.yaml` and click on Compute.
The segmentation model `demo_model_traced.pt` has been generated via the Python script `generate_demo_model.py`.
The expected input of this algorithm is a 2D RGB images with intensities between [0;255]. The applied pre- and post-processing operations are defined in the YAML file `demo_model.yaml`.
|
JavaScript
|
UTF-8
| 444
| 3.234375
| 3
|
[] |
no_license
|
function Prisoner(index) {
this.index = index;
this.left = this.right = null;
}
Prisoner.prototype.release = function() {
this.left.right = this.right;
this.right.left = this.left;
this.left = this.right = null;
}
Prisoner.prototype.isLonely = function() {
return this.left === this.right &&
this.left === this;
}
Prisoner.prototype.shout = function(n) {
if(n === 3) {
this.release();
}
}
|
Java
|
UTF-8
| 1,031
| 3.296875
| 3
|
[] |
no_license
|
package com.company;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
double[] num = {12.3, 32.5, -13.5, 5.6, 9.5, -6.7, 8.3, 2.1, -23.5, 24.6, -12.3, -35.7, -18.4, 32.6, 14.7};
int positive = 0;
double summa = 0;
boolean negative = false;
for (double r : num) {
if (r < 0) {
negative = true;
continue;
} else if (negative && r > 0) {
summa += r;
positive++;
}
System.out.println(summa);
System.out.println(positive);
System.out.println("Avarage summery " + summa / positive);
}
for (int i = 0; i < num.length; i++) {
double h = num[i];
int a = i - 1;
while (a >= 0 && h < num[a]) {
num[a + 1] = num[a];
a--;
}
num[a+1]= h;
System.out.println(Arrays.toString(num));
}
}
}
|
Ruby
|
UTF-8
| 738
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
class Callapi::Routes::HelperMethodCreator
POSTFIX = '_call'
def initialize(call_class)
@call_class = call_class
@call_class_name = call_class.to_s
end
def create
call_class = @call_class
Object.send(:define_method, helper_method_name) do |*args|
call_class.new(*args)
end
end
def helper_method_base_name
class_name = @call_class_name.dup
class_name.scan(/(::)?((\w)+)Param/).map { |matched_groups| matched_groups[1] }.compact.each do |pattern|
class_name.sub!(pattern, "By#{pattern}")
class_name.sub!('Param', '')
end
class_name
end
def helper_method_name
SuperString.underscore(helper_method_base_name).gsub('/', '_').gsub('callapi_', '') + POSTFIX
end
end
|
Java
|
UTF-8
| 603
| 2.25
| 2
|
[] |
no_license
|
package ru.netology;
import com.github.javafaker.Faker;
import lombok.Value;
import java.time.LocalDate;
import java.util.Locale;
public class DataGenerator {
private DataGenerator() {
}
@Value
public static class Registration {
private Registration (){}
public static UserInfo getRegistrationInfo() {
Faker faker = new Faker(new Locale("ru"));
return new UserInfo(
faker.name().fullName(),
faker.phoneNumber().phoneNumber(),
faker.address().city()
);
}
}
}
|
C#
|
UTF-8
| 616
| 2.96875
| 3
|
[] |
no_license
|
using Newtonsoft.Json;
using System.IO;
namespace ShipCollections
{
public class ShipType
{
/// <summary>
/// 艦種を識別する一意な値です。
/// </summary>
public int Id { get; set; }
/// <summary>
/// 艦船の種類を表す名前です。
/// </summary>
public string Name { get; set; }
public static ShipType[] LoadAll()
{
var json = File.ReadAllText("Assets/ShipTypes.json");
var types = JsonConvert.DeserializeObject<ShipType[]>(json);
return types;
}
}
}
|
Python
|
UTF-8
| 465
| 2.8125
| 3
|
[] |
no_license
|
#!/usr/bin/python
from common import *
goal = 'welcome to code jam'
mod = 10000
def testcase(x):
line = readline()
counts = [0] * len(goal)
for c in line:
for i in xrange(len(goal)):
if goal[i] == c:
if i > 0:
counts[i] = (counts[i] + counts[i - 1]) % mod
else:
counts[i] += 1
writeline("Case #%d: %04d" % (x, counts[-1]))
run_tests(sys.argv, testcase)
|
Ruby
|
UTF-8
| 594
| 3.484375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Artist
attr_reader :name, :import
@@all = []
def self.all
@@all
end
def self.find_or_create_by_name(import)
found_artist = @@all.find{|a| a.name == import}
if found_artist
found_artist
else
self.new(import)
end
end
def initialize(name)
@name = name
@@all << self
@songs = []
# binding.pry
end
def name=(name)
@name = name
# binding.pry
end
def add_song(song)
@songs << song
song.artist = self
end
def songs
@songs
# binding.pry
end
def print_songs
@songs.each do |a|
puts a.name
end
end
end
|
Java
|
UTF-8
| 256
| 1.804688
| 2
|
[] |
no_license
|
package com.yt.pulltorefresh.i;
import com.yt.pulltorefresh.recyclerview.BaseAdapterHelper;
/**
* ACCommonAdapter
* 扩展的Adapter接口规范
*/
public interface I_Adapter<T> {
void bindData(BaseAdapterHelper helper, int position, T item);
}
|
Ruby
|
UTF-8
| 162
| 3.078125
| 3
|
[] |
no_license
|
def compute(one, two)
first = one.split('')
second = two.split('')
count = 0
first.zip(second).each {|x, y| count += 1 if x != y }
count
end
|
JavaScript
|
UTF-8
| 181
| 3.203125
| 3
|
[] |
no_license
|
let order = (str) => {
newStr = str.split("");
for (var i = 0; i < newStr.length; i++) {
newStr = newStr.sort();
}
console.log((newStr = newStr.join("")));
};
order("prem");
|
Python
|
UTF-8
| 2,526
| 2.546875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import urllib.request as ur
import urllib.parse as up
import lxml.etree as le
import re
from faker import Factory
# url = 'https://so.csdn.net/so/search/s.do?p={page}&q={keyword}&t=blog&viparticle=&domain=&o=&s=&u=&l=&f=&rbg=0'
url = 'https://so.csdn.net/so/search/all'
user_agent = Factory.create()
def getResponse(url, keyword, page):
dict = {'q': keyword, 'p': page, 't': 'all', 's': 0, 'tm': 0, 'lv': -1, 'ft': 0}
data = up.urlencode(dict).encode('utf-8')
req = ur.Request(
url=url,
data=data,
headers={
'User-Agent': user_agent.user_agent()
# 'User-Agent':'Mozilla/5.0 (compatible; MSIE 5.0; Windows NT 5.01; Trident/5.1)',
# 'Mozilla/5.0 (Windows NT 5.01) AppleWebKit/534.0 (KHTML, like Gecko) Chrome/31.0.883.0 Safari/534.0'
},
method='GET'
)
# 【字符串对象】= 【字节对象】.decode('utf‐8','ignore')
# 这个时候 response就是一个字符对象 ,保存的时候就不可以用wb
response = ur.urlopen(req).read().decode('utf-8')
# print(response)
print(user_agent.user_agent())
return response
if __name__ == '__main__':
# keyword = input('关键词')
# pn_start = int(input('起始页'))
# pn_end = int(input('终止页'))
keyword = 'python'
pn_start = 1
pn_end = 1
# 中文操作
data = up.urlencode(
{'q': keyword}
)
print(keyword)
for page in range(pn_start, pn_end + 1):
# 访问1级页面
response = getResponse(url=url, page=page, keyword=data)
print(response)
# 二级页面,博客的链接
with open('1.html', 'w', encoding='utf-8') as f:
f.write(response)
hrefs = le.HTML(response).xpath(
'//dl[@class="search-list J_search"]/a/@href') # //span[@class="mr16"]/../../dt/div/a[1]/@href
# 遍历二级页面
print(hrefs)
for href in hrefs:
response_blog = getResponse(
url=href,
)
# 文件名称
title = le.HTML(response_blog).xpath('//h1[@class="title-article"]/text()')[0]
# 文件名称除去非法字符
title = re.sub(
r'[/\\:*"<>|? ]', '', title
)
# 文件路径
filepath = 'blog/%s.html' % title
# 文件写入
with open(filepath, 'w', encoding='utf-8') as f:
f.write(response_blog)
print(title)
|
PHP
|
UTF-8
| 1,327
| 2.828125
| 3
|
[] |
no_license
|
<div class="main">
<ul id="content">
<div id="pageContentCenter">
<h2>Il mio Profilo:</h2>
<?php
$mysqli = database::getInstance()->databaseConnection();
if (!isset($mysqli)) {
$mysqli->close();
return false;
}
$stmt = $mysqli->stmt_init();
$username = $_SESSION['username'];
$arrChartData[] = array();
$sql = "SELECT email, name, surname, street, number, city, state FROM user WHERE username= '$username'";
;
$res = $mysqli->query($sql) or trigger_error($mysqli->error . "[$sql]");
while ($row = $res->fetch_row()) {
$email = $row[0];
$name = $row[1];
$surname = $row[2];
$street = $row[3];
$number = $row[4];
$city = $row[5];
$state = $row[6];
}
$mysqli->close();
?>
<div id="text">
<p>Nome: <?php echo $name . " " . $surname ?> </p>
<p>Email: <?php echo $email; ?> </p>
<p>Indirizzo: <?php echo $street . " " . $number . ", " . $city . ", " . $state; ?> </p>
</div>
</div>
</ul>
</div>
|
Python
|
UTF-8
| 1,898
| 4.09375
| 4
|
[] |
no_license
|
'''
Problem
You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all
available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide
will consist of the two integers indicating the positions of the items in your list (smaller number first).
Input
The first line of input gives the number of cases, N. N test cases follow. For each test case there will be:
One line containing the value C, the amount of credit you have at the store.
One line containing the value I, the number of items in the store.
One line containing a space separated list of I integers. Each integer P indicates the price of an item in the store.
Each test case will have exactly one solution.
Output
For each test case, output one line containing "Case #x: " followed by the indices of the two items whose price adds up to the store
credit. The lower index should be output first.
'''
test=int(input())
have=test
result1=[None]*test
result2=[None]*test
count=0
while(test>0):
c=int(input()) #get credit value
l=int(input()) #get prices
line=input()
x=line.split(' ')
dict1={} #store the prices in a dictionary
for i in range(0,l):
dict1[i+1]=x[i]
for i in range(0,l):
done=-1
value=c-int(x[i]) #get the expeted output
v=str(value)
for j in range(i+2,l+1): #get the key value of the difference if it exists
if(dict1[j]==v):
result1[count]=i+1
result2[count]=j
count=count+1
done=0
break
if(done==0):
break
test=test-1
for i in range(0,have):
print('Case #{0}: {1} {2}'.format(i+1,result1[i],result2[i]))
|
Java
|
UTF-8
| 2,520
| 2.4375
| 2
|
[] |
no_license
|
package com.slack.geekbrainswork.ai.data.api;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
private static final String BASE_URL = "http://yrsoft.cu.cc:8080/";
public static ApiInterface getApiInterface() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.build();
return retrofit.create(ApiInterface.class);
}
public static ApiInterface getApiInterface(final String token) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Auth-Token", token)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.addInterceptor(logging)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(httpClient)
.build();
return retrofit.create(ApiInterface.class);
}
}
|
C++
|
WINDOWS-1258
| 2,462
| 3
| 3
|
[] |
no_license
|
#include "Create.h"
Create::Create()
{
//ctor
}
void Create::menu()
{
int opc;
do
{
cout<<"Set instrucciones"<<endl<<endl
<<"Que desea hacer?"<<endl
<<op_tipoR<<"( Tipo R"<<endl
<<op_tipoI<<"( Tipo I"<<endl
<<op_tipoJ<<"( Tipo J"<<endl
<<op_salir<<"( Salir"<<endl
<<"Seleccione: ";
cin>>opc;
cin.ignore();
system("CLS");
switch(opc)
{
case op_tipoR:
tipoR();
break;
case op_tipoI:
tipoI();
break;
case op_tipoJ:
tipoJ();
break;
case op_salir:
cout<<"Adios..."<<endl;
break;
default:
cout<<"Te equivocaste"<<endl;
system("PAUSE");
system("CLS");
break;
}
}while(opc != op_salir);
}
void Create::tipoR()
{
ofstream salida("archivo.txt", ios::app);
Instruccion ins;
int Op, Rd, Rs, Rt, Sh;
cout<<"Instruccion Tipo R "<<endl<<endl;
ins.setOpcode();
cout<<"Registro fuente: ";
cin>>Rs;
ins.setRs(Rs);
cout<<"Registro Temporal: ";
cin>>Rt;
ins.setRt(Rt);
cout<<"Registro destino: ";
cin>>Rd;
ins.setRd(Rd);
ins.setShamt();
ins.setFunct();
if(!salida.is_open())
{
cout<<"Error al cargar el archivo"<<endl;
}
else
{
salida <<ins;
salida.close();
}
}
void Create::tipoI()
{
ofstream salida("archivo.txt", ios::app);
Instruccion ins;
int Rd, Rs, Inm;
cout<<"Instruccion Tipo I "<<endl<<endl;
cout<<"Ingrese los siguientes datos "<<endl<<endl;
ins.setOpcode();
cout<<"Registro fuente: ";
cin>>Rs;
ins.setRs(Rs);
cout<<"Registro destino: ";
cin>>Rd;
ins.setRd(Rd);
cout<<"Inmediato: ";
cin>>Inm;
ins.setInmediaro(Inm);
if(!salida.is_open())
{
cout<<"Error al cargar el archivo"<<endl;
}
else
{
salida <<ins;
salida.close();
}
}
void Create::tipoJ()
{
ofstream salida("archivo.txt", ios::app);
Instruccion ins;
int Op, Dir;
cout<<"Instruccion Tipo J "<<endl<<endl;
ins.setOpcode();
cout<<"Direccion: ";
cin>>Dir;
ins.setDir(Dir);
if(!salida.is_open())
{
cout<<"Error al cargar el archivo"<<endl;
}
else
{
salida <<ins;
salida.close();
}
}
|
Go
|
UTF-8
| 979
| 3.4375
| 3
|
[] |
no_license
|
package main
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 || len(matrix[0]) == 0 {
return nil
}
m, n := len(matrix)-1, len(matrix[0])-1
l, r, t, b := 0, n, 0, m
var res []int
for l <= r && t <= b {
// fmt.Println("l", l, "r", r, "t", t, "b", b)
edges := listEdges(matrix, l, r, t, b)
res = append(res, edges...)
l++
r--
t++
b--
}
return res
}
func listEdges(matrix [][]int, left, right, top, bottom int) (ret []int) {
for i := left; i <= right; i++ {
ret = append(ret, matrix[top][i])
}
for i := top + 1; i <= bottom; i++ {
ret = append(ret, matrix[i][right])
}
if left < right && top < bottom { // 之所以要做不带等号的判断,是因为如果left == right, top == bottom,下面的两循环其实重复了上面的循环,所以不再执行
for i := right - 1; i > left; i-- {
ret = append(ret, matrix[bottom][i])
}
for i := bottom; i > top; i-- {
ret = append(ret, matrix[i][left])
}
}
return
}
|
Swift
|
UTF-8
| 1,118
| 4.6875
| 5
|
[] |
no_license
|
//: [Previous](@previous)
import Foundation
//: ### Turple
//: Declare a constant typle that contains three Int values followed by a String. Use this to represent a date (month, day, year) followed by an emoji or word you might associte with that day
let halloween: (month: Int, day: Int, year: Int, means: String)
halloween = (10, 31, 2018, "👻")
//: Create another tuple, but this time name the constituent components, Give them names related to the date that they contain: month, day,year, emoji
let piaDay = (month: 3, day: 14, year: 1592, emoji: "🥧")
//: In one line. read the day and emoji value into two constants. You'll need to employ the underscore to ignore the month and year
let (_, day, _, emoji) = piaDay
day
emoji
//: Up until now, you're only seen constant tuples. But you can create variable tuples, too. Create one more tuple, like in the exercises above, but this time use var instead of let, Now change the emoji to a new value.
var brithday = (month: 5, day:24, year: 2018)
brithday.day = 20
// brithday.day = "20" error, Turple 是有类型推断的
brithday
//: [Next](@next)
|
Python
|
UTF-8
| 1,127
| 4.1875
| 4
|
[] |
no_license
|
def print_stars(count = 10):
print("*"*count)
print_stars()
print_stars(20)
def slice_list(list_to_slice, upper_bound):
"""Returns slice of list if upper bound is valid"""
if (len(list_to_slice) > upper_bound):
print('Slicing...')
return list_to_slice[:upper_bound]
else:
print('Value too high...', upper_bound)
return None
some_nums = [2,6,4,2,22,54,12,8,-1]
print('Value returned ', slice_list(some_nums, 4))
print(slice_list(some_nums, 4))
print(slice_list(some_nums, 12))
print(slice_list(some_nums, 20))
#error if no () at end of function
# File ".\functions.py", line 1
# def print_stars:
# ^
# SyntaxError: invalid syntax
# error with print_stars(20)
# Traceback (most recent call last):
# File ".\functions.py", line 5, in <module>
# print_stars(20)
# TypeError: print_stars() takes 0 positional arguments but 1 was given
#adding print(slice_list(some_nums, 20))
# **********
# ********************
# Slicing...
# Value returned [2, 6, 4, 2]
# Slicing...
# [2, 6, 4, 2]
# Value too high... 12
# None
# Value too high... 20
# None
|
Java
|
UTF-8
| 16,130
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package imageRecognition.openCV;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.lwjgl.util.vector.Vector3f;
import prevAutopilot.SimpleAutopilot;
public class ImageProcessor {
/* ImageProcessor constructor */
public ImageProcessor(SimpleAutopilot autopilot) {
this.autopilot = autopilot;
// rotate the cube to be in alignment with the world frame
alignCube();
// places the cube 5 meter in front of the camera
translate(0, 0, -5);
}
private final SimpleAutopilot autopilot;
//Getters for the AutoPilot config
public float getHorizontalAngleOfView() {
return autopilot.getConfig().getHorizontalAngleOfView();
}
public float getVerticalAngleOfView() {
return autopilot.getConfig().getVerticalAngleOfView();
}
public int getImageWidth() {
return autopilot.getConfig().getNbColumns();
}
public int getImageHeight() {
return autopilot.getConfig().getNbRows();
}
//Getters for the AutoPilot input
public byte[] getImage() {
return autopilot.getInput().getImage();
}
public float getHeading() {
return autopilot.getInput().getHeading();
}
public float getPitch() {
return autopilot.getInput().getPitch();
}
public float getRoll() {
return autopilot.getInput().getRoll();
}
/* Private static methods used for calculating the image properties */
/**
* Returns a byte[] array of the RGB values of the given BufferedImage.
*/
public static byte[] bufferedImageToByteArray(BufferedImage image) {
// get width and height of the image
int width = image.getWidth();
int height = image.getHeight();
// every int in this array consists of a red, green, blue and alpha component
int[] pixelArray = image.getRGB(0, 0, width, height, null, 0, width);
// create byte array to store the RGB values separately
byte[] bytes = new byte[pixelArray.length*3];
// for every pixel, place the RGB values in the byte array separately
for (int i=0; i < pixelArray.length; i++) {
bytes[i*3] = (byte) ((pixelArray[i] >> 16) & 0xFF); // red
bytes[i*3 + 1] = (byte) ((pixelArray[i] >> 8) & 0xFF); // green
bytes[i*3 + 2] = (byte) ((pixelArray[i] >> 0) & 0xFF); // blue
}
return bytes;
}
/**
* Returns a list with the HSV values of the given byteArray.
*/
public static List<float[]> byteArrayToHSVList(byte[] byteArray) {
List<float[]> colorHSVList = new ArrayList<float[]>();
for (int i=0; i < byteArray.length; i+=3) {
float[] hsv = new float[3];
Color.RGBtoHSB(byteArray[i],byteArray[i+1],byteArray[i+2],hsv);
hsv[0] = Math.round(hsv[0]*100.0);
hsv[1] = Math.round(hsv[1]*100.0);
hsv[2] = Math.round(hsv[2]*100.0);
colorHSVList.add(hsv);
}
return colorHSVList;
}
/**
* Returns a matrix with the HSV values of every pixel.
*/
public static float[][][] createMatrixOfHSVList(List<float[]> colorHSVList) {
float [][][] HSVList = new float [200][200][3];
int l = 0;
for (int y=0; y < HSVList.length; y++) {
for (int x=0; x < HSVList.length; x++) {
HSVList[x][y][0] = colorHSVList.get(l)[0];
HSVList[x][y][1] = colorHSVList.get(l)[1];
HSVList[x][y][2] = colorHSVList.get(l)[2];
l += 1;
}
}
return HSVList;
}
/**
* Returns all the different HS colors, which represent a cube. Only a cube color if V-value is lower than 50.
*/
public static List<double[]> getAllDifferentHSVColors(List<float[]> colorHSVList){
List<double[]> differentColorsHSVList = new ArrayList<double[]>();
for (int i = 0; i < colorHSVList.size(); i++) {
if ( !(colorHSVList.get(i)[0] == 0.0 && colorHSVList.get(i)[1] == 0.0 && colorHSVList.get(i)[2] == 0.0 )) {
int teller = 0;
for (int j = 0; j < differentColorsHSVList.size(); j++) {
if ( (differentColorsHSVList.get(j)[0] == colorHSVList.get(i)[0]) && (differentColorsHSVList.get(j)[1] == colorHSVList.get(i)[1])){
teller+=1;
}
}
if ( (teller == 0) && (colorHSVList.get(i)[2] == 45 || colorHSVList.get(i)[2] == 20 || colorHSVList.get(i)[2] == 40 || colorHSVList.get(i)[2] == 25 || colorHSVList.get(i)[2] == 35|| colorHSVList.get(i)[2] == 30)) {
if (! ((colorHSVList.get(i)[0] == 63 || colorHSVList.get(i)[0] == 64) && (colorHSVList.get(i)[1] == 99|| colorHSVList.get(i)[1] == 98))) {
differentColorsHSVList.add(new double[]{colorHSVList.get(i)[0],colorHSVList.get(i)[1],colorHSVList.get(i)[2]});
}
}
}
}
return differentColorsHSVList;
}
/**
* Returns the center of mass of the given cube
*/
static double[] getType0CenterOfMass(float[ ][ ][ ] HSVList, double[] color) {
// variables to store the total x and y coordinates
long xCoord = 0; long yCoord= 0; int amount = 0;
// iterate over every x,y coordinate and add the coordinates if their value equals 255
int x; int y;
for (x = 0; x < HSVList.length; x++) {
for (y = 0; y < HSVList.length; y++) {
if (HSVList[x][y][0] == color[0] && HSVList[x][y][1] == color[1] ) {
xCoord += x; yCoord += y; amount++;
}
}
}
// calculate the coordinates
double[] coordinates = new double[2];
coordinates[0] = (int) Math.round(xCoord / (float) amount);
coordinates[0] = (coordinates[0] - 100.0) / 100.0;
coordinates[1] = (int) Math.round(yCoord / (float) amount);
coordinates[1] = (100.0 - coordinates[1]) / 100.0;
return coordinates;
}
/**
* Returns the center of mass of the given cube
*/
static int getAmountOfPixels(float[ ][ ][ ] HSVList, double[] color) {
// variables to store the total x and y coordinates
int amount = 0;
// iterate over every x,y coordinate and add the coordinates if their value equals 255
int x; int y;
for (x = 0; x < HSVList.length; x++) {
for (y = 0; y < HSVList.length; y++) {
if (HSVList[x][y][0] == color[0] && HSVList[x][y][1] == color[1] ) {
amount++;
}
}
}
return amount;
}
// Focal length of the simulated pinhole camera
private static double f = 100 / Math.tan(Math.PI / 3);
private double x = 0;
private double y = 0;
private double z = 0;
public double[] getPosition() {
return new double[]{x, y, z};
}
public double getDistance() {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
}
private List<double[]> corners = Arrays.asList(new double[]{-2.5, 2.5, -2.5}, new double[]{-2.5, 2.5, 2.5},
new double[]{ 2.5, 2.5, 2.5}, new double[]{ 2.5, 2.5, -2.5}, new double[]{-2.5, -2.5, -2.5},
new double[]{-2.5, -2.5, 2.5}, new double[]{ 2.5, -2.5, 2.5}, new double[]{ 2.5, -2.5, -2.5});
//private List<double[]> corners = Arrays.asList(new double[]{1, 0, 0}, new double[]{0, 1, 0},
// new double[]{-1, 0, 0}, new double[]{-1.5, 0, 0}, new double[]{-2.59, 2.59, 0}, new double[]{2.59, -2.59, 0});
public List<double[]> getCorners() {
return this.corners;
}
// Setters
/**
* Rotate the cube
*/
public void rotate(double heading, double pitch, double roll) {
double x; double y; double z;
heading = -heading;
pitch = -pitch;
roll = -roll;
for (double[] point : getCorners()) {
x = point[0]; y = point[1]; z = point[2];
/* Without roll
point[0] = x*Math.cos(heading) + z*Math.sin(heading);
point[1] = y*Math.cos(pitch) - (z*Math.cos(heading) - x*Math.sin(heading))*Math.sin(pitch);
point[2] = y*Math.sin(pitch) + (z*Math.cos(heading) - x*Math.sin(heading))*Math.cos(pitch);
*/
double a = x * (Math.cos(heading)*Math.cos(roll) - Math.sin(heading)*Math.sin(pitch)*Math.sin(roll)) + y * (-Math.cos(pitch)*Math.sin(roll)) + z * (Math.cos(roll)*Math.sin(heading) + Math.cos(heading)*Math.sin(pitch)*Math.sin(roll));
double b = x * (Math.cos(heading)*Math.sin(roll) + Math.cos(roll)*Math.sin(heading)*Math.sin(pitch)) + y * (Math.cos(pitch)*Math.cos(roll)) + z * (Math.sin(heading)*Math.sin(roll) - Math.cos(heading)*Math.cos(roll)*Math.sin(pitch));
double c = x * (-Math.cos(pitch)*Math.sin(heading)) + y * (Math.sin(pitch))+ z * (Math.cos(heading) * Math.cos(pitch));
// heading (y-axis)
x = x*Math.cos(heading) + z*Math.sin(heading);
z = -x*Math.sin(heading) + z*Math.cos(heading);
// pitch (x-axis)
y = y*Math.cos(pitch) - z*Math.sin(pitch);
z = y*Math.sin(pitch) + z*Math.cos(pitch);
// roll (z-axis)
x = x*Math.cos(roll) - y*Math.sin(roll);
y = x*Math.sin(roll) + y*Math.cos(roll);
// -> -roll ! ! !
if (a != x || b != y || c != z) {
//System.out.println(roll);
//System.out.println(String.valueOf(x) + " - " + String.valueOf(y) + " - " + String.valueOf(z));
//System.out.println(String.valueOf(a) + " - " + String.valueOf(b) + " - " + String.valueOf(c));
}
point[0] = a;
point[1] = b;
point[2] = c;
}
}
/**
* Aligns the cube with the world frame
*/
private void alignCube() {
this.rotate(getHeading(), getPitch(), getRoll());
}
/**
* Translates the imaginary cube, coordinates are in drone frame
*/
public void translate(double deltaX, double deltaY, double deltaZ) {
for (double[] point : getCorners()) {
point[0] += deltaX;
point[1] += deltaY;
point[2] += deltaZ;
}
x += deltaX;
y += deltaY;
z += deltaZ;
}
// Calculations
/**
* Returns a list of the corners, projected using a pinhole camera
*/
private List<double[]> getProjectedCorners() {
List<double[]> projectedCorners = new ArrayList<>();
// project all points
for (double[] point : getCorners()) {
projectedCorners.add(new double[]{-ImageProcessor.f * point[0] / point[2], -ImageProcessor.f * point[1] / point[2]});
}
return projectedCorners;
}
/**
* Returns the convext hull of the given 2D coordinate list. The first and last coordinate are the same.
*/
public List<double[]> getConvextHull() {
List<double[]> corners = getProjectedCorners();
// map all double[] coordinates onto Point objects
Map<Point, double[]> map = new HashMap<Point, double[]>();
Point point;
for (double[] corner : corners) {
point = new Point((int) Math.round(corner[0] * 1000000), (int) Math.round(corner[1] * 1000000));
map.put(point, corner);
}
// use the Point objects to get the convex hull
List<Point> convexHullPoints = GrahamScan.getConvexHull(new ArrayList<Point>(map.keySet()));
// get the double[] coordinates from the convex hull Point list
List<double[]> convexHullCoordinates = new ArrayList<>();
for (Point p : convexHullPoints) {
convexHullCoordinates.add(map.get(p));
}
return convexHullCoordinates;
}
/**
* Returns the signed area of the given convex hull.
*/
private double getProjectedSingedArea(List<double[]> convexHull) {
double cubeArea = 0;
for (int i = 0; i < convexHull.size() - 1; i++) {
cubeArea += convexHull.get(i)[0] * convexHull.get(i+1)[1];
cubeArea -= convexHull.get(i)[1] * convexHull.get(i+1)[0];
}
return cubeArea / 2;
}
/**
* Returns the signed area of the projection of the cube.
*/
private double getProjectedSingedArea() {
return getProjectedSingedArea(getConvextHull());
}
/**
* Returns how much percent of the image, the projected cubes area is.
*/
public double getProjectedAreaPercentage(float horAngleOfView, float verAngleOfView) {
// calculate cube area
double cubeArea = Math.abs(getProjectedSingedArea());
// calculate total image area
double width = 2 * ImageProcessor.f * Math.tan(horAngleOfView);
double height = 2 * ImageProcessor.f * Math.tan(verAngleOfView);
double totalArea = width * height;
return cubeArea / totalArea;
}
/**
* Returns the center of mass of the projection of the cube. (0, 0) is the center of the image,
* (-1, y) the left border, (1, y) the right border, (x, -1) the bottom border, (x, 1) the top border.
*/
public double[] getProjectedAreaCenterOfMass(float horAngleOfView, float verAngleOfView) {
List<double[]> convexHull = getConvextHull();
double singedArea = getProjectedSingedArea(convexHull);
double cx = 0;
double cy = 0;
for (int i = 0; i < convexHull.size() - 1; i++) {
cx += (convexHull.get(i)[0] + convexHull.get(i+1)[0]) * (convexHull.get(i)[0]*convexHull.get(i+1)[1] - convexHull.get(i+1)[0]*convexHull.get(i)[1]);
cy += (convexHull.get(i)[1] + convexHull.get(i+1)[1]) * (convexHull.get(i)[0]*convexHull.get(i+1)[1] - convexHull.get(i+1)[0]*convexHull.get(i)[1]);
}
cx /= (singedArea * 6);
cy /= (singedArea * 6);
return new double[]{cx / 100, cy / 100};
}
// public void saveAsImage(String imageName, Mat surface) {
// Mat image = surface.clone();
//
// List<double[]> convexHull = getConvextHull();
// org.opencv.core.Point p0;
// org.opencv.core.Point p1;
// for (int i = 0; i < convexHull.size() - 1; i++) {
// p0 = new org.opencv.core.Point((int) (convexHull.get(i)[0]+100), (int) (-convexHull.get(i)[1]+100));
// p1 = new org.opencv.core.Point((int) (convexHull.get(i+1)[0]+100), (int) (-convexHull.get(i+1)[1]+100));
// Imgproc.line(image, p0, p1, new Scalar(255, 255, 255));
// }
//
// List<double[]> punten = getProjectedCorners();
// for (int i = 0; i < punten.size(); i++) {
// //Imgproc.circle(image, new org.opencv.core.Point((int) (punten.get(i)[0]+100), (int) (-punten.get(i)[1]+100)), 1, new Scalar(120, 120, 120));
// //Imgproc.circle(image, new org.opencv.core.Point((int) (punten.get(i)[0]+100), (int) (-punten.get(i)[1]+100)), 0, new Scalar(0, 0, 0));
// }
// Imgcodecs.imwrite("res/" + imageName + ".png", image);
// }
public List<Vector3f> getCoordinatesOfCube() {
List<Vector3f> listWithCoordinatesOfCubes = new ArrayList<Vector3f>();
// calculate positions of cubes
// create a list with the HSV values
List<float[]> colorHSVList = byteArrayToHSVList(getImage());
// create a matrix
float [][][] HSVList = createMatrixOfHSVList(colorHSVList);
// create a list with all the different HSV colors.
List<double[]> differentColorsHSVList = getAllDifferentHSVColors(colorHSVList);
for (int i = 0; i < differentColorsHSVList.size(); i++){
double[] color = differentColorsHSVList.get(i);
// Get center of mass (of the 2D red cube)
double[] centerOfMass = getType0CenterOfMass(HSVList, color);
// Get red area in image
int redArea = getAmountOfPixels(HSVList, color);
// Get red area percentage
double percentage = redArea / ((float) 200*200);
// create imaginary cube
ImaginaryCube imaginaryCube = new ImaginaryCube(0.0, 0.0, 0.0);
double[] imCenterOfMass; double deltaX=10; double deltaY=10;
double imPercentage; double ratio = 10;
int iterations = 0;
while (deltaX > 0.005 || deltaY > 0.005 || ratio > 1.025 || ratio < 0.975) {
iterations++;
if (iterations > 700) {
break;
}
// get difference between the centers of mass
imCenterOfMass = imaginaryCube.getProjectedAreaCenterOfMass((float) (120.0 / 180 * Math.PI), (float) (120.0 / 180 * Math.PI));
deltaX = (centerOfMass[0] - imCenterOfMass[0]);
deltaY = (centerOfMass[1] - imCenterOfMass[1]);
imaginaryCube.translate(deltaX * 3, deltaY * 3, 0);
// get the ration between the projected areas
imPercentage = imaginaryCube.getProjectedAreaPercentage((float) (120.0 / 180 * Math.PI), (float) (120.0 / 180 * Math.PI));
ratio = imPercentage / percentage;
imaginaryCube.translate(0, 0, (1 - ratio)*0.1);
}
Vector3f Coordinates = new Vector3f();
Coordinates.set((float)imaginaryCube.getPosition()[0], (float) (imaginaryCube.getPosition()[1]+2.32), (float) (imaginaryCube.getPosition()[2]-(5.0)));
listWithCoordinatesOfCubes.add(Coordinates);
}
return listWithCoordinatesOfCubes;
}
}
|
C#
|
UTF-8
| 2,304
| 3.625
| 4
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
class ThreeInOne
{
static void Main()
{
SolveTask1();
SolveTask2();
SolveTask3();
}
static void SolveTask1()
{
int[] points = Console.ReadLine().Split(',').Select(ch => int.Parse(ch)).ToArray();
Dictionary<int, int> occurs = new Dictionary<int, int>();
for (int i = 0; i < points.Length; i++)
if (!occurs.ContainsKey(points[i]) && points[i] <= 21) occurs.Add(points[i], 1);
else if (points[i] <= 21) occurs[points[i]]++;
occurs = occurs.OrderByDescending(i => i.Key).ToDictionary(k => k.Key, k => k.Value);
Console.WriteLine(occurs.ElementAt(0).Value == 1 ? Array.IndexOf(points, occurs.ElementAt(0).Key) : -1);
}
static void SolveTask2()
{
List<int> sizes = Console.ReadLine().Split(',').Select(ch => int.Parse(ch)).ToList();
int f = int.Parse(Console.ReadLine());
sizes.Sort();
int index = sizes.Count - 1, bitesOfCakeCount = 0;
while (index >= 0)
{
bitesOfCakeCount += sizes[index];
index -= f + 1;
}
Console.WriteLine(bitesOfCakeCount);
}
static void SolveTask3()
{
int[] coins = Console.ReadLine().Split(' ').Select(ch => int.Parse(ch)).ToArray();
int steps = 0;
int g1 = coins[0], s1 = coins[1], b1 = coins[2];
int g2 = coins[3], s2 = coins[4], b2 = coins[5];
while (g2 > g1)
{
g1++;
s1 -= 11;
steps++;
}
while (s2 > s1)
{
if (g1 > g2)
{
g1--;
s1 += 9;
}
else
{
s1++;
b1 -= 11;
}
steps++;
}
while (b2 > b1)
{
if (s1 > s2)
{
s1--;
b1 += 9;
}
else if (g1 > g2)
{
g1--;
s1 += 9;
}
else
{
Console.WriteLine(-1);
return;
}
steps++;
}
Console.WriteLine(steps);
}
}
|
JavaScript
|
UTF-8
| 564
| 2.734375
| 3
|
[] |
no_license
|
$('form').submit(function(e) {
e.preventDefault();
this.reset();
});
$('.submit-button').on('click', function() {
let title = $('.movie-title').val();
let rating = $('.rating').val();
$('body').append('<ul class="the-list"></ul>');
$('.the-list').eq(-1).append('<li class="new-item">' + title + ' Rating: ' + rating + ' ' + '</li>');
$('.new-item').eq(-1).append('<input type="button" value="remove" id="drop-it">');
$('.rating').empty();
});
$('body').on('click', '.new-item', function() {
console.log('you clicked remove!');
$(this).remove();
});
|
Java
|
UTF-8
| 3,494
| 2.5
| 2
|
[] |
no_license
|
package ua.training.model.entities;
import java.sql.Timestamp;
import java.util.Objects;
public class TaxReport {
private int id;
private Taxpayer taxpayer;
private Inspector inspector;
private TaxReportForm form;
private TaxReportType type;
private TaxReportStatus status;
private String message;
private Timestamp date;
public TaxReport(){}
public TaxReport(int id, Taxpayer taxpayer, Inspector inspector, TaxReportForm form, TaxReportType type, TaxReportStatus status, String message, Timestamp date) {
this.id = id;
this.taxpayer = taxpayer;
this.inspector = inspector;
this.form = form;
this.type = type;
this.status = status;
this.message = message;
this.date = date;
}
public TaxReport(Taxpayer taxpayer, Inspector inspector, TaxReportForm form, TaxReportType type, TaxReportStatus status, String message, Timestamp date) {
this.taxpayer = taxpayer;
this.inspector = inspector;
this.form = form;
this.type = type;
this.status = status;
this.message = message;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Taxpayer getTaxpayer() {
return taxpayer;
}
public void setTaxpayer(Taxpayer taxpayer) {
this.taxpayer = taxpayer;
}
public Inspector getInspector() {
return inspector;
}
public void setInspector(Inspector inspector) {
this.inspector = inspector;
}
public TaxReportForm getForm() {
return form;
}
public void setForm(TaxReportForm form) {
this.form = form;
}
public TaxReportType getType() {
return type;
}
public void setType(TaxReportType type) {
this.type = type;
}
public TaxReportStatus getStatus() {
return status;
}
public void setStatus(TaxReportStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaxReport taxReport = (TaxReport) o;
return id == taxReport.id &&
taxpayer.equals(taxReport.taxpayer) &&
inspector.equals(taxReport.inspector) &&
form.equals(taxReport.form) &&
type.equals(taxReport.type) &&
status.equals(taxReport.status) &&
Objects.equals(message, taxReport.message) &&
date.equals(taxReport.date);
}
@Override
public int hashCode() {
return Objects.hash(id, taxpayer, inspector, form, type, status, message, date);
}
@Override
public String toString() {
return "TaxReport{" +
"id=" + id +
", taxpayer=" + taxpayer +
", inspector=" + inspector +
", form=" + form +
", type=" + type +
", status=" + status +
", message='" + message + '\'' +
", date=" + date +
'}';
}
}
|
TypeScript
|
UTF-8
| 2,243
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
/**
* @class
* Resize command for figures. Can be execute/undo/redo via a CommandStack.
*
* @inheritable
* @author Andreas Herz
* @extends draw2d.command.Command
*/
import Command from "./Command";
import Configuration from "../Configuration";
class CommandResize extends Command {
private figure: any;
private oldWidth: any;
private oldHeight: any;
private newWidth: number | undefined;
private newHeight: number | undefined;
/**
* Create a new resize Command objects which can be execute via the CommandStack.
*
* @param {draw2d.Figure} figure the figure to resize
* @param {Number} [width] the current width
* @param {Number} [height] the current height
*/
constructor(figure: { getWidth: () => any; getHeight: () => any; }, width: any, height: any) {
super(Configuration.i18n.command.resizeShape)
this.figure = figure
if (typeof width === "undefined") {
this.oldWidth = figure.getWidth()
this.oldHeight = figure.getHeight()
}
else {
this.oldWidth = width
this.oldHeight = height
}
}
/**
*
* Set the new dimension of the element.
*
* @param {Number} width the new width.
* @param {Number} height the new height of the element.
**/
setDimension (width: number, height: number) {
this.newWidth = width | 0
this.newHeight = height | 0
}
/**
*
* Returns [true] if the command can be execute and the execution of the
* command modify the model. A CommandMove with [startX,startX] == [endX,endY] should
* return false. <br>
* the execution of the Command doesn't modify the model.
*
* @returns {Boolean}
**/
canExecute () {
// return false if we doesn't modify the model => NOP Command
return this.newWidth !== this.oldWidth || this.newHeight !== this.oldHeight
}
/**
*
* Execute the command the first time
*
**/
execute () {
this.redo()
}
/**
*
* Undo the command
*
**/
undo () {
this.figure.setDimension(this.oldWidth, this.oldHeight)
}
/**
*
* Redo the command after the user has undo this command
*
**/
redo () {
this.figure.setDimension(this.newWidth, this.newHeight)
}
}
export default CommandResize;
|
Python
|
UTF-8
| 1,426
| 3.203125
| 3
|
[
"BSD-3-Clause-Clear"
] |
permissive
|
from typing import Mapping
from mediaman.distribution import Bin, Item
def fast_serpent(bins: Mapping[str, int], items: Mapping[str, int]):
"""
Assign a poor distribution of items to bins, very quickly.
@param bins Mapping of bin identifier to bin size
@param items Mapping of item identifier to item size
@return distribution Mapping of bin identifier to set of item identifiers
"""
distribution = {k: set() for k in bins}
range_distribution = {k: set() for k in bins}
bin_queue = [Bin(k, v) for k, v in bins.items()]
print(bin_queue)
items_queue = sorted((Item(k, v) for k, v in items.items()), key=lambda item: item.n)
step = len(bin_queue)
total = len(items_queue)
start_offset = -1
for start_offset in range(step):
for bin in bin_queue:
item_range = range(start_offset, total, step)
for i in item_range:
item = items_queue[i]
if item.n > bin.n:
# print(f"{item} can't fit in {bin}")
break
bin.n -= item.n
range_distribution[bin.id].add(range(start_offset, i, step))
print(bin_queue)
print(range_distribution)
for (bin_id, ranges) in range_distribution.items():
items = set(items_queue[i].id for range in ranges for i in range)
distribution[bin_id].update(items)
return distribution
|
Go
|
UTF-8
| 999
| 2.625
| 3
|
[] |
no_license
|
package mysql
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB = &gorm.DB{}
func Init2(user string, password string, host string, db string, connMaxLifetime int, maxIdleConns int, mxOpenConns int) {
link := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", user, password, host, db)
DB, err := gorm.Open(mysql.New(mysql.Config{
DSN: link, // DSN data source name
}), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
panic("connect mysql error ="+err.Error())
}
sqlDB, err := DB.DB()
if err != nil {
panic("connect mysql error ="+err.Error())
}
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(maxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(mxOpenConns)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(connMaxLifetime * time.Millisecond)
}
|
JavaScript
|
UTF-8
| 3,559
| 4.15625
| 4
|
[] |
no_license
|
// This program demonstrates several Array and Object methods and examples of their use with an abstraction of a real-world object
// The Tarot Major Arcana is a data-set uniquely appropriate for these examples for several reasons:
// Each card has a proper name and a Roman numeral value, a natural key-value pair for an object structure
// This example uses data from Rider-Waite tarot deck
const majorArcana = {
"The Fool": 0,
"The Magician": 1,
"The High Priestess": 2,
"The Empress": 3,
"The Emperor": 4,
"The Hierophant": 5,
"The Lovers": 6,
"The Chariot": 7,
"Strength": 8,
"The Hermit": 9,
"Wheel of Fortune": 10,
"Justice": 11,
"The Hanged Man": 12,
"Death": 13,
"Temperance": 14,
"The Devil": 15,
"The Tower": 16,
"The Star": 17,
"The Moon": 18,
"The Sun": 19,
"Judgement": 20,
"The World": 21
};
console.log(majorArcana);
// This method prevents majorArcana from being mutated (sorry to non-fans of Rider-Waite!)
Object.freeze(majorArcana);
// Objects can be iterated over with a for...in statement, a loop method unique to the Object class.
for (card in majorArcana) {
console.log(`${card} is number ${majorArcana[card]}.`)
}
// Objects can be converted into arrays with built-in methods from the global Object class.
// If a user does not know the names of Tarot cards, they may find any aribitrary card by selecting a number between 0 and 21 to reference its array index.
// That can be found with a chain operator
// Return an array, where every element is a sub-array whose elements are the key and value of each card
const entriesArray = Object.entries(majorArcana);
console.log(entriesArray);
console.log(entriesArray[4][0]); // The Emperor
// Since the Major Arcana is already zero-indexed, let's eliminate the need of chain operators
// Return an array where each element is the key of each property
const keysArray = Object.keys(majorArcana);
console.log(keysArray);
// Thus, reference any "key element" by its index to get its name
console.log(keysArray[6]); // The Lovers
console.log(keysArray[8]); // Strength
console.log(keysArray[14]); // Temperance
// The Major Arcana values are usually represented by Roman numerals. This representation uses Arabic numerals.
// Let us recreate the Major Arcana with Roman numerals!
// The Romans didn't have 0 but we will use it in our array literal
const romanArray = [
"O",
"I",
"II",
"III",
"IV",
"V",
"VI",
"VII",
"VIII",
"IX",
"X",
"XI",
"XII",
"XIII",
"XIV",
"XV",
"XVI",
"XVII",
"XVIII",
"XIX",
"XX",
"XXI"
];
// Easily make an array of numbers using values from the original object
// Return an array where each element is the value of each property
const numbersArray = Object.values(majorArcana);
console.log(numbersArray);
// We will store our entries in a new array
const newEntriesArray = [];
// And populate it with sub-arrays whose elements are the name and roman numeral
// This is my favorite part of the program :)
numbersArray.forEach( v => {
newEntriesArray.push([keysArray[v], romanArray[v]]);
}
);
console.log(newEntriesArray);
// The above output looks a lot like entriesArray!
// Indeed, every element is a sub-array whose elements are the key and value of each card
// Hence, we can create a proper Object from newEntriesArray, by using the reverse of Object.entries
// Return an object with properties taken from an array's key-value sub-arrays.
const romanArcana = Object.fromEntries(newEntriesArray);
// Behold!
for (card in romanArcana) {
console.log(`${card} is number ${romanArcana[card]}.`)
}
|
Swift
|
UTF-8
| 20,499
| 2.65625
| 3
|
[] |
no_license
|
//
// ExhibitsViewModel.swift
// Exhibit Finder
//
// Created by Kate Duncan-Welke on 8/21/20.
// Copyright © 2020 Kate Duncan-Welke. All rights reserved.
//
import Foundation
import UIKit
public class ExhibitsViewModel {
weak var alertDelegate: AlertDisplayDelegate?
weak var exhibitDelegate: ExhibitLoadDelegate?
var dateFormatter = DateFormatter()
// get string from date
func getStringDate(from date: Date) -> String {
var timeDateFormatter = DateFormatter()
timeDateFormatter.dateFormat = "yyyy-MM-dd 'at' hh:mm a"
let createdDate = timeDateFormatter.string(from: date)
return createdDate
}
// turn date into string to pass into search
func getDate(from stringDate: String?) -> Date {
dateFormatter.dateFormat = "yyyy-MM-dd"
var currentDate = Date()
guard let shortenedDate = stringDate?.dropLast(11), let createdDate = dateFormatter.date(from: String(shortenedDate)) else {
return currentDate
}
return createdDate
}
public func loadExhibitions() {
DataManager<Exhibits>.fetch() { [unowned self] result in
switch result {
case .success(let response):
DispatchQueue.main.async {
guard let response = response.first?.exhibits else {
self.alertDelegate?.displayAlert(with: "Connection failed", message: "Data response failed, please try again later.")
return
}
for exhibit in response {
let closeDate = self.getDate(from: exhibit.closingDate)
// disclude museums outside of Washington DC
if exhibit.museum != "Cooper Hewitt, Smithsonian Design Museum" && exhibit.museum != "Air and Space Museum Udvar-Hazy Center" && exhibit.museum != "American Indian Museum Heye Center" {
// only add exhibit if closedate is in the future
if closeDate >= Date() || exhibit.closingDate == nil {
ExhibitManager.exhibitsList.append(exhibit)
// add exhibit to exhibit dictionary
ReminderManager.exhibitDictionary[exhibit.id] = exhibit
// if exhibit is in reminder dictionary, add to list of exhibits that have reminders
if ReminderManager.reminderDictionary[exhibit.id] != nil {
// add to array of exhibits that have reminder
ReminderManager.exhibitsWithReminders.append(exhibit)
} else {
// nothing
}
}
}
}
for exhibit in ExhibitManager.exhibitsList {
if let urlString = exhibit.imgUrl, let url = URL(string: urlString) {
ReminderManager.urls[exhibit.id] = url
}
}
self.exhibitDelegate?.loadExhibits(success: true)
}
case .failure(let error):
DispatchQueue.main.async {
switch error {
case Errors.networkError:
self.alertDelegate?.displayAlert(with: "Networking failed", message: "\(Errors.networkError.localizedDescription)")
default:
self.alertDelegate?.displayAlert(with: "Networking failed", message: "\(Errors.otherError.localizedDescription)")
}
self.exhibitDelegate?.loadExhibits(success: false)
}
}
}
}
func setData(type: DataType, searchText: String?) {
ExhibitManager.currentType = type
if searchText != "" {
if let search = searchText {
ExhibitManager.isSearching = true
switch type {
case .exhibitsOnly:
ExhibitManager.currentSource = ExhibitManager.exhibitsList
case .exhibitsWithReminders:
ExhibitManager.currentSource = ReminderManager.exhibitsWithReminders
}
ExhibitManager.searchResults = ExhibitManager.currentSource.filter({(exhibit: Exhibit) -> Bool in
return (exhibit.exhibit?.lowercased().contains(search.lowercased()))! || (exhibit.info?.lowercased().contains(search.lowercased()))! || (exhibit.closingDate?.contains(search.lowercased()) ?? false)
})
}
ExhibitManager.currentSource = ExhibitManager.searchResults
} else {
ExhibitManager.isSearching = false
switch type {
case .exhibitsOnly:
ExhibitManager.currentSource = ExhibitManager.exhibitsList
case .exhibitsWithReminders:
ExhibitManager.currentSource = ReminderManager.exhibitsWithReminders
}
}
}
func retrieveSource() -> [Exhibit] {
if ExhibitManager.isSearching {
return ExhibitManager.searchResults
} else {
switch ExhibitManager.currentType {
case .exhibitsOnly:
return ExhibitManager.exhibitsList
case .exhibitsWithReminders:
return ReminderManager.exhibitsWithReminders
}
}
}
func getRows(isFiltering: Bool, segment: Int, section: Int) -> Int {
var data = retrieveSource()
if isFiltering && segment == 1 {
let result = ReminderManager.reminderDictionary[data[section].id]
if result?.time != nil && result?.location != nil {
return 2
} else {
return 1
}
} else if isFiltering {
return data.count
} else if segment == 0 {
return data.count
} else {
if ReminderManager.reminders.isEmpty {
return 1
} else {
let result = ReminderManager.reminderDictionary[data[section].id]
if result?.time != nil && result?.location != nil {
return 2
} else {
return 1
}
}
}
}
func setSource(index: Int) {
if index == 0 {
ExhibitManager.currentType = .exhibitsOnly
} else {
ExhibitManager.currentType = .exhibitsWithReminders
}
}
public func setCurrentIndex(index: IndexPath) {
ExhibitManager.currentIndex = index
}
public func getCurrentIndex() -> IndexPath? {
return ExhibitManager.currentIndex
}
public func isListEmpty() -> Bool {
return ExhibitManager.exhibitsList.isEmpty
}
public func isSearchEmpty() -> Bool {
return ExhibitManager.searchResults.isEmpty
}
public func searchCount() -> Int {
return ExhibitManager.exhibitsList.count
}
public func deleteFromSearch(index: Int) {
ExhibitManager.searchResults.remove(at: index)
}
public func getReminderForExhibit(indexPath: IndexPath) -> Reminder? {
var exhibit: Exhibit
if ExhibitManager.isSearching {
switch ExhibitManager.currentType {
case .exhibitsOnly:
exhibit = ExhibitManager.searchResults[indexPath.row]
case .exhibitsWithReminders:
exhibit = ExhibitManager.searchResults[indexPath.section]
}
} else {
switch ExhibitManager.currentType {
case .exhibitsOnly:
exhibit = ExhibitManager.exhibitsList[indexPath.row]
case .exhibitsWithReminders:
exhibit = ReminderManager.exhibitsWithReminders[indexPath.section]
}
}
if let result = ReminderManager.reminderDictionary[exhibit.id] {
ReminderManager.currentReminder = result
} else {
ReminderManager.currentReminder = nil
}
return ReminderManager.currentReminder
}
public func hasTitle(section: Int) -> String? {
switch ExhibitManager.currentType {
case .exhibitsOnly:
return nil
case .exhibitsWithReminders:
if !ExhibitManager.currentSource.isEmpty {
return ExhibitManager.currentSource[section].exhibit
} else {
return nil
}
}
}
public func getImageUrl(index: IndexPath) -> URL? {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let url = ReminderManager.urls[ExhibitManager.currentSource[selection].id] {
return url
} else {
return nil
}
}
public func getTitle(index: IndexPath) -> String {
switch ExhibitManager.currentType {
case .exhibitsOnly:
if let title = ExhibitManager.currentSource[index.row].exhibit {
let decoded = title.decodingHTMLEntities()
return String.removeHTMLWithoutSpacing(from: decoded)
} else {
return "No title"
}
case .exhibitsWithReminders:
guard let result = ReminderManager.reminderDictionary[ExhibitManager.currentSource[index.section].id] else { return "" }
var currentDate = Date()
if (result.time != nil && result.location != nil && index.row == 0) || (result.time != nil && result.location == nil) {
guard let date = result.time else { return "" }
let calendar = Calendar.current
let components = DateComponents(year: Int(date.year), month: Int(date.month), day: Int(date.day), hour: Int(date.hour), minute: Int(date.minute))
guard let dateToUse = calendar.date(from: components) else { return "" }
if let invalid = result.invalidDate {
if dateToUse < currentDate || invalid < currentDate {
return "This reminder has expired"
} else {
let stringDate = getStringDate(from: dateToUse)
return "For \(stringDate)"
}
} else {
if dateToUse < currentDate {
return "This reminder has expired"
} else {
let stringDate = getStringDate(from: dateToUse)
return "For \(stringDate)"
}
}
} else {
if let radius = result.location?.radius {
return "Within \(Int(radius)) foot radius of museum"
} else {
return ""
}
}
}
}
public func getTitleForTimeReminder(index: IndexPath) -> String {
guard let result = ReminderManager.currentReminder else { return "" }
var currentDate = Date()
if (result.time != nil && result.location != nil && index.row == 0) || (result.time != nil && result.location == nil) {
guard let date = result.time else { return "" }
let calendar = Calendar.current
let components = DateComponents(year: Int(date.year), month: Int(date.month), day: Int(date.day), hour: Int(date.hour), minute: Int(date.minute))
guard let dateToUse = calendar.date(from: components) else { return "" }
if let invalid = result.invalidDate {
if dateToUse < currentDate || invalid < currentDate {
return "This reminder has expired"
} else {
let stringDate = getStringDate(from: dateToUse)
return "For \(stringDate)"
}
} else {
if dateToUse < currentDate {
return "This reminder has expired"
} else {
let stringDate = getStringDate(from: dateToUse)
return "For \(stringDate)"
}
}
}
return ""
}
public func getTitleForLocationReminder(index: IndexPath) -> String {
guard let result = ReminderManager.currentReminder else { return "" }
if let radius = result.location?.radius {
return "Within \(Int(radius)) foot radius of museum"
} else {
return ""
}
}
public func getMuseum(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let museum = ExhibitManager.currentSource[selection].museum {
return museum
} else {
return "No museum listed"
}
}
public func getInfo(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let data = ExhibitManager.currentSource[selection].infoBrief {
let decoded = data.decodingHTMLEntities()
return String.removeHTMLWithoutSpacing(from: decoded)
} else {
return "No description available"
}
}
public func getVerboseInfo(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let data = ExhibitManager.currentSource[selection].info {
let decoded = data.decodingHTMLEntities()
return String.removeHTML(from: decoded)
} else {
return "No description available"
}
}
public func getOpenDate(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let open = ExhibitManager.currentSource[selection].openingDate?.dropLast(11) {
return "\(open)"
} else {
return "No info"
}
}
public func getCloseDate(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let close = ExhibitManager.currentSource[selection].closingDate?.dropLast(11) {
return "\(close)"
} else if (ExhibitManager.currentSource[selection].closeText?.contains("Indefinitely")) != nil {
return "Indefinite"
} else {
return "No info"
}
}
public func getLocation(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let location = ExhibitManager.currentSource[selection].location {
return "Location: \(location)"
} else {
return "No specific location"
}
}
public func hasReminder(index: IndexPath) -> String {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
// there is a reminder
if let result = ReminderManager.reminderDictionary[ExhibitManager.currentSource[selection].id] {
switch ExhibitManager.currentType {
case .exhibitsOnly:
return "Reminder"
case .exhibitsWithReminders:
if (result.time != nil && result.location != nil && index.row == 0) || (result.time != nil && result.location == nil) {
return "Time"
} else if (result.time != nil && result.location != nil && index.row == 1) || (result.time == nil && result.location != nil) {
return "Location"
} else {
return ""
}
}
} else { // there is no reminder
switch ExhibitManager.currentType {
case .exhibitsOnly:
return "No reminder"
case .exhibitsWithReminders:
return ""
}
}
}
public func reminderImage(index: IndexPath) -> UIImage? {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
// there is a reminder
if let result = ReminderManager.reminderDictionary[ExhibitManager.currentSource[selection].id] {
switch ExhibitManager.currentType {
case .exhibitsOnly:
if result.time != nil && result.location != nil {
return UIImage(named: "both25")
} else if result.time != nil && result.location == nil {
return UIImage(named: "clockicon25")
} else if result.time == nil && result.location != nil {
return UIImage(named: "locationicon25")
} else {
return nil
}
case .exhibitsWithReminders:
if (result.time != nil && result.location != nil && index.row == 0) || (result.time != nil && result.location == nil) {
return UIImage(named: "clockicon25")
} else if (result.time != nil && result.location != nil && index.row == 1) || (result.time == nil && result.location != nil) {
return UIImage(named: "locationicon25")
} else {
return nil
}
}
} else { // there's no reminder and therefore no image
return nil
}
}
public func getURL(index: IndexPath) -> URL? {
var selection: Int
switch ExhibitManager.currentType {
case .exhibitsOnly:
selection = index.row
case .exhibitsWithReminders:
selection = index.section
}
if let stringUrl = ExhibitManager.currentSource[selection].exhibitURL, let generatedUrl = URL(string: stringUrl) {
return generatedUrl
} else {
return nil
}
}
func hasConnection() -> Bool {
return NetworkMonitor.connection
}
func setUpNetworkMonitor() {
NetworkMonitor.monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
print("connection successful")
NetworkMonitor.connection = true
} else if path.status == .unsatisfied {
print("no connection")
NetworkMonitor.connection = false
}
}
let queue = DispatchQueue(label: "Monitor")
NetworkMonitor.monitor.start(queue: queue)
}
}
|
Python
|
UTF-8
| 4,225
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
import random
from player import Player
from evaluator import Evaluator
from card import Card
from deck import Deck
from itertools import combinations
evaluator = Evaluator()
WORST_SCORE = 7462
class Simon(Player):
def bet(self, game_view):
score = 0
opponent_score = self.estimate_opponent_score(game_view)
my_win_chance = self.my_win_chance(game_view, opponent_score)
# print("Estimated opponent score:", opponent_score, "My estimated win chance:", my_win_chance)
# TODO: Detect bluffing
# TODO: Bluff
if my_win_chance > 0.5:
target_bet = game_view.minimum_bet + game_view.minimum_raise * 2
return min(target_bet, game_view.chips[self.name])
else:
# Don' fold if we don't have to
if game_view.minimum_bet == 0:
return 0
return None
def estimate_opponent_score(self, game_view):
"""Return my best guess of the best hand of all my opponents."""
score = WORST_SCORE
for i in range(len(game_view.players_in_hand) - 1):
score = min(score, random.randint(WORST_SCORE / 2, WORST_SCORE))
return score
def my_win_chance(self, game_view, opponent_score):
"""Return the chance I have of beating the score."""
if len(game_view.community_cards) == 0: # before flop
return self.my_win_chance_before_flop(game_view.hole_cards, opponent_score) # after flop
elif len(game_view.community_cards) == 3:
return self.my_win_chance_after_flop(game_view.hole_cards, game_view.community_cards, opponent_score)
elif len(game_view.community_cards) == 4: # after turn
return self.my_win_chance_after_river(game_view.hole_cards, game_view.community_cards, opponent_score)
else: # after river
return evaluator.evaluate(game_view.community_cards, game_view.hole_cards)
def my_win_chance_before_flop(self, hole_cards, opponent_score):
"""Return how good a set of hole cards are with no other information."""
# too hard to go through and evaluate all possibilities, but we can have a pretty good guess
score = 0
card_ranks = [Card.get_rank_int(card) for card in hole_cards]
if card_ranks[0] == card_ranks[1]:
score += 0.1 * (card_ranks[0] / 13.0) ** 2
else:
score += 0.1 * (card_ranks[0] / 13.0) ** 2
score += 0.1 * (card_ranks[1] / 13.0) ** 2
return 0.5 + 0.5 * evaluator.get_five_card_rank_percentage(opponent_score)
def my_win_chance_after_flop(self, hole_cards, community_cards, opponent_score):
"""Return how good a set of hole cards are with given the flop."""
wins = 0
deck = self.get_remaining_deck(hole_cards + community_cards)
for cards in combinations(deck, 2):
score = evaluator.evaluate(hole_cards, community_cards + list(cards))
if score < opponent_score:
wins += 1
elif score == opponent_score:
wins += 0.5
return wins / len(deck)
def my_win_chance_after_river(self, hole_cards, community_cards, opponent_score):
"""Return how good a set of hole cards are with given the flop and river."""
wins = 0
deck = self.get_remaining_deck(hole_cards + community_cards)
for card in deck:
score = evaluator.evaluate(hole_cards, community_cards + [card])
if score < opponent_score:
wins += 1
elif score == opponent_score:
wins += 0.5
return wins / len(deck)
def my_win_chance_after_turn(self, hole_cards, community_cards, opponent_score):
"""Return how good a set of hole cards are with given the flop and river."""
score = evaluator.evaluate(game_view.community_cards, game_view.hole_cards)
return int(score > opponent_score)
def get_remaining_deck(self, known_cards):
"""Returns array of all cards remaining in the deck."""
known_cards = set(known_cards)
deck = Deck.GetFullDeck()
deck = filter(lambda card: card not in known_cards, deck)
return list(deck)
|
C
|
UTF-8
| 441
| 3.8125
| 4
|
[] |
no_license
|
#include <stdio.h>
int main ()
{
int n, i, j;
int arr[10];
printf ("Enter the number of elements in the array: \t");
scanf ("%d", &n);
printf ("The elements are: ");
for (i = 0; i < n; i++) {
scanf ("%d", &arr[i]);
printf("Element you want to search: \t");
scanf("%d",&j);
for (i = 0; i < n ; i++)
if(arr[i] == j){
printf("Element %d is at position %d.",j,i+1);}
else if (i==n)
printf("The element isn't there in the array.");} }
return 0;}
|
Python
|
UTF-8
| 389
| 3.59375
| 4
|
[] |
no_license
|
from random import randint
class LuckyBall:
def __init__(self):
self.nums = []
while len(self.nums) < 6:
rand_num = randint(1, 69)
if rand_num not in self.nums:
self.nums.append(rand_num)
def __getitem__(self, index):
return self.nums[index]
def __len__(self):
return len(self.nums)
|
Python
|
UTF-8
| 38
| 2.8125
| 3
|
[] |
no_license
|
summa = 102
summa %= 20
print(summa)
|
Java
|
UTF-8
| 7,649
| 2.265625
| 2
|
[] |
no_license
|
package rasa;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class ReadXML {
public static Column read_column(Column ColObj,Element colElement)
{
ColObj.Name = colElement.getElementsByTagName("Name").item(0).getTextContent();
ColObj.PosTag = colElement.getElementsByTagName("PosTag").item(0).getTextContent();
ColObj.Type = colElement.getElementsByTagName("Type").item(0).getTextContent();
ColObj.VarType = colElement.getElementsByTagName("VarType").item(0).getTextContent();
Node ValueNode = colElement.getElementsByTagName("ValueList").item(0);
Element ValueElement = (Element) ValueNode;
NodeList ValueList = ValueElement.getElementsByTagName("value");
ArrayList<String> ValList = new ArrayList<String>();
for(int k=0; k<ValueList.getLength(); k++) {
Node value = ValueList.item(k);
ValList.add(value.getTextContent());
}
ColObj.ValueList = ValList;
Node PrefixNode = colElement.getElementsByTagName("Prefix").item(0);
Element PrefixElement = (Element) PrefixNode;
NodeList PrefixList = PrefixElement.getElementsByTagName("prefix");
ArrayList<String> PreList = new ArrayList<String>();
for(int k=0; k<PrefixList.getLength(); k++) {
Node prefix = PrefixList.item(k);
PreList.add(prefix.getTextContent());
}
ColObj.Prefix = PreList;
Node PostNode = colElement.getElementsByTagName("Postfix").item(0);
Element PostfixElement = (Element) PostNode;
NodeList PostfixList = PostfixElement.getElementsByTagName("postfix");
ArrayList<String> PostList = new ArrayList<String>();
for(int k=0; k<PostfixList.getLength(); k++) {
Node postfix = PostfixList.item(k);
PostList.add(postfix.getTextContent());
}
ColObj.Postfix = PostList;
Node SynonymNode = colElement.getElementsByTagName("Synonym").item(0);
Element SynonymElement = (Element) SynonymNode;
NodeList SynonymList = SynonymElement.getElementsByTagName("synonym");
ArrayList<String> SynList = new ArrayList<String>();
for(int k=0; k<SynonymList.getLength(); k++) {
Node synonym = SynonymList.item(k);
SynList.add(synonym.getTextContent());
}
ColObj.Synonym = SynList;
Node VerbNode = colElement.getElementsByTagName("VerbList").item(0);
Element VerbElement = (Element) VerbNode;
NodeList VerbList = VerbElement.getElementsByTagName("verb");
ArrayList<Verb> VerList = new ArrayList<Verb>();
for(int k=0; k<VerbList.getLength(); k++)
{
Verb VerbObj = new Verb();
Node verb = VerbList.item(k);
Element verbElement = (Element) verb;
VerbObj.VerbName = verbElement.getElementsByTagName("VerbName").item(0).getTextContent();
VerbObj.VerbType = verbElement.getElementsByTagName("VerbType").item(0).getTextContent();
VerList.add(VerbObj);
}
ColObj.VerbList = VerList;
Node AdjectiveNode = colElement.getElementsByTagName("AdjectiveList").item(0);
Element AdjectiveElement = (Element) AdjectiveNode;
NodeList AdjectiveList = AdjectiveElement.getElementsByTagName("adjective");
ArrayList<Adjective> AdjList = new ArrayList<Adjective>();
for(int k=0; k<AdjectiveList.getLength(); k++)
{
Adjective AdjObj = new Adjective();
Node adjective = AdjectiveList.item(k);
Element adjectiveElement = (Element) adjective;
//VerbObj.VerbName = verbElement.getElementsByTagName("VerbName").item(0).getTextContent();
//VerbObj.VerbType = verbElement.getElementsByTagName("VerbType").item(0).getTextContent();
AdjList.add(AdjObj);
}
ColObj.AdjectiveList = AdjList;
Node PrepositionNode = colElement.getElementsByTagName("PrepositionList").item(0);
Element PrepositionElement = (Element) PrepositionNode;
NodeList PrepositionList = PrepositionElement.getElementsByTagName("preposition");
ArrayList<Preposition> PrepList = new ArrayList<Preposition>();
for(int k=0; k<PrepositionList.getLength(); k++)
{
Preposition PrepObj = new Preposition();
Node preposition = PrepositionList.item(k);
Element prepositionElement = (Element) preposition;
//VerbObj.VerbName = verbElement.getElementsByTagName("VerbName").item(0).getTextContent();
//VerbObj.VerbType = verbElement.getElementsByTagName("VerbType").item(0).getTextContent();
PrepList.add(PrepObj);
}
ColObj.PrepositionList = PrepList;
return ColObj;
}
public static void tree_reader(Element n, Nodes x, int q) {
NodeList a = n.getElementsByTagName("Level"+Integer.toString(q));
//System.out.println(a.getLength());
for(int i=0;i<a.getLength();i++) {
Node b = a.item(i);
Element b1 = (Element) b;
x.add_child(b1.getElementsByTagName("Name").item(0).getTextContent());
//System.out.println(b1.getElementsByTagName("Name").item(0).getTextContent());
if(b.getNodeType() == Node.ELEMENT_NODE) {
tree_reader((Element) b,x.children.get(x.children.size()-1),q+1);
}
}
//System.out.println("hi"+a.getLength());
}
public static void main(String argv[]) {
Schema SchemaObj = new Schema();
try {
File fXmlFile = new File("src/rasa/Schema.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
Node RelationNode = doc.getElementsByTagName("RelationList").item(0);
Element RelationElement = (Element) RelationNode;
NodeList RelationList = RelationElement.getElementsByTagName("relation");
ArrayList<Relation> RelList = new ArrayList<Relation>();
for (int i = 0; i < RelationList.getLength(); i++) {
Relation RelObj = new Relation();
Node relation = RelationList.item(i);
Element relElement = (Element) relation;
Column ColObj = new Column();
Node PrimaryDetails = relElement.getElementsByTagName("PrimaryDetails").item(0);
Element colElement = (Element) PrimaryDetails;
ColObj = read_column(ColObj, colElement);
RelObj.PrimaryDetails = ColObj;
Node ColumnNode = relElement.getElementsByTagName("ColumnList").item(0);
Element ColumnElement = (Element) ColumnNode;
NodeList ColumnList = ColumnElement.getElementsByTagName("column");
ArrayList<Column> ColList = new ArrayList<Column>();
for(int j=0; j<ColumnList.getLength(); j++) {
Column ColObj1 = new Column();
Node column = ColumnList.item(j);
Element colElement1 = (Element) column;
ColObj1 = read_column(ColObj1, colElement1);
ColList.add(ColObj1);
}
RelObj.ColumnList = ColList;
RelList.add(RelObj);
}
SchemaObj.RelationList = RelList;
NodeList n = doc.getElementsByTagName("Hierarchy");
if(n.item(0).getNodeType() == Node.ELEMENT_NODE) {
Element hnode = (Element) n.item(0);
NodeList root = hnode.getElementsByTagName("RootNode");
if(n.item(0).getNodeType() == Node.ELEMENT_NODE) {
Element rnode = (Element) root.item(0);
SchemaObj.Hierarchy.name = rnode.getElementsByTagName("Name").item(0).getTextContent();
//System.out.println(rnode.getElementsByTagName("Name").item(0).getTextContent());
tree_reader(rnode,SchemaObj.Hierarchy,1);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
|
Java
|
UTF-8
| 971
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
package juice.animation;
import juice.animation.easing.EasingType;
final public class Key {
public interface FrameCallback {
void call(int frame, double[] values);
}
public interface EndCallback {
void call();
}
//=========================================================================
int frame;
double[] values;
EasingType easingType = EasingType.LINEAR;
FrameCallback frameCallback;
EndCallback endCallback;
public Key frame(int f) {
this.frame = f;
return this;
}
public Key values(double[] v) {
this.values = v;
return this;
}
public Key eachFrame(FrameCallback c) {
this.frameCallback = c;
return this;
}
public Key atEnd(EndCallback c) {
endCallback = c;
return this;
}
public Key easing(EasingType e) {
this.easingType = e;
return this;
}
}
|
C#
|
UTF-8
| 11,689
| 2.984375
| 3
|
[] |
no_license
|
using System;
using System.Threading;
using WATKit.Controls;
using WATKit.Exceptions;
namespace WATKit
{
/// <summary>
/// Provides extension methods for wait operations within the fluent automation api
/// </summary>
/// <remarks>
/// These methods provide support for waiting on an automation control
/// to become available and/or visible when it represents a proxy or for a real control
/// to become unavailable, hidden, enabled or disabled
/// </remarks>
public static class FluentAutomationWaitExtensions
{
/// <summary>
/// Sets up a new wait operation
/// </summary>
/// <param name="owner">The automation control owning the wait settings</param>
/// <returns>
/// The new wait settings to support fluent usage
/// </returns>
public static WaitSettings Wait(this AutomationControl owner)
{
owner.WaitSettings = new WaitSettings
{
WaitRoot = owner,
WaitTime = TimeSpan.Zero
};
return owner.WaitSettings;
}
/// <summary>
/// Sets the operation to wait for the existence of the control.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The original wait settings to support fluent usage</returns>
public static WaitSettings UntilExists(this WaitSettings waitSettings)
{
waitSettings.WaitType = WaitType.Exists;
return waitSettings;
}
/// <summary>
/// Sets the operation to wait for the control to no longer exist.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The original wait settings to support fluent usage</returns>
public static WaitSettings UntilNotExists(this WaitSettings waitSettings)
{
waitSettings.WaitType = WaitType.NotExists;
return waitSettings;
}
/// <summary>
/// Sets the operation to wait for the control to be visible.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The original wait settings to support fluent usage</returns>
public static WaitSettings UntilVisible(this WaitSettings waitSettings)
{
waitSettings.WaitType = WaitType.Visible;
return waitSettings;
}
/// <summary>
/// Sets the operation to wait for the control to become hidden.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The original wait settings to support fluent usage</returns>
public static WaitSettings UntilHidden(this WaitSettings waitSettings)
{
waitSettings.WaitType = WaitType.Hidden;
return waitSettings;
}
/// <summary>
/// Sets the operation to wait for the control to be enabled.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The original wait settings to support fluent usage</returns>
public static WaitSettings UntilEnabled(this WaitSettings waitSettings)
{
waitSettings.WaitType = WaitType.Enabled;
return waitSettings;
}
/// <summary>
/// Sets the operation to wait for the control to become disabled.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The original wait settings to support fluent usage</returns>
public static WaitSettings UntilDisabled(this WaitSettings waitSettings)
{
waitSettings.WaitType = WaitType.Disabled;
return waitSettings;
}
/// <summary>
/// Executes and indefinite wait operation.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <returns>The control owning the wait settings</returns>
public static AutomationControl Indefinitely(this WaitSettings waitSettings)
{
return ExecuteWait(waitSettings, TimeSpan.Zero);
}
/// <summary>
/// Executes a wait operation that will timeout if not successful
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> a TimeoutException will be thrown on timeout without success.</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
public static AutomationControl TimeoutAfter(this WaitSettings waitSettings, TimeSpan timeout, bool throwExceptionOnTimeout = false)
{
return ExecuteWait(waitSettings, timeout, throwExceptionOnTimeout);
}
/// <summary>
/// Executes a wait operation
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> a TimeoutException will be thrown on timeout without success.</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
private static AutomationControl ExecuteWait(WaitSettings waitSettings, TimeSpan timeout, bool throwExceptionOnTimeout = false)
{
if(waitSettings.WaitType == WaitType.NotSet)
{
throw new WaitTypeNotSetException();
}
waitSettings.WaitTime = timeout;
switch(waitSettings.WaitType)
{
case WaitType.Enabled:
case WaitType.Disabled:
return ExecuteIsEnabledWait(waitSettings, throwExceptionOnTimeout);
case WaitType.Visible:
case WaitType.Hidden:
return ExecuteIsVisibleWait(waitSettings, throwExceptionOnTimeout);
case WaitType.Exists:
case WaitType.NotExists:
return ExecuteExistsWait(waitSettings, throwExceptionOnTimeout);
default:
return waitSettings.WaitRoot;
}
}
/// <summary>
/// Executes a wait on the existence of the target automation control.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> throw an exception if the timeout expires.</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
private static AutomationControl ExecuteExistsWait(WaitSettings waitSettings, bool throwExceptionOnTimeout)
{
var stateToWaitFor = waitSettings.WaitType == WaitType.NotExists;
var control = waitSettings.WaitRoot;
SpinWait.SpinUntil(() =>
{
control = control.FindSettings.AsDefault();
return control.IsProxy == stateToWaitFor;
}, waitSettings.ActualTimeOut);
if(throwExceptionOnTimeout && control.IsProxy != stateToWaitFor)
{
throw new TimeoutException("Wait operation timed out before the required existence was achieved");
}
waitSettings.WaitRoot.AutomationElement = control.AutomationElement;
return waitSettings.WaitRoot;
}
/// <summary>
/// Executes a wait on the IsVisible state of the target automation control.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> throw an execption if the timeout expires.</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
private static AutomationControl ExecuteIsVisibleWait(WaitSettings waitSettings, bool throwExceptionOnTimeout)
{
var expectedState = waitSettings.WaitType == WaitType.Visible;
if(waitSettings.WaitRoot.IsVisible == expectedState)
{
return waitSettings.WaitRoot;
}
if(waitSettings.WaitRoot.AutomationElement != null && waitSettings.WaitRoot.AutomationElement.Current.FrameworkId == "WPF")
{
return ExecuteWpfVisiblityWait(waitSettings, throwExceptionOnTimeout, expectedState);
}
return ExecuteWinFormsVisibilityWait(waitSettings, throwExceptionOnTimeout, expectedState);
}
/// <summary>
/// Executes a wait on the IsVisible state of a WinForms automation control.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> [throw exception on timeout].</param>
/// <param name="stateToWaitFor">The visibility state to wait for</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
private static AutomationControl ExecuteWinFormsVisibilityWait(WaitSettings waitSettings, bool throwExceptionOnTimeout, bool stateToWaitFor)
{
var control = waitSettings.WaitRoot;
SpinWait.SpinUntil(() =>
{
control = control.FindSettings.AsDefault();
return control.IsVisible == stateToWaitFor;
}, waitSettings.ActualTimeOut);
if(throwExceptionOnTimeout && control.IsVisible != stateToWaitFor)
{
throw new TimeoutException("Wait operation timed out before the required visibility was achieved");
}
waitSettings.WaitRoot = control;
return waitSettings.WaitRoot;
}
/// <summary>
/// Executes a wait on the IsVisible state of a WPF automation control.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> [throw exception on timeout].</param>
/// <param name="stateToWaitFor">The visibility state to wait for</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
private static AutomationControl ExecuteWpfVisiblityWait(WaitSettings waitSettings, bool throwExceptionOnTimeout, bool stateToWaitFor)
{
var control = waitSettings.WaitRoot;
var element = control.AutomationElement;
SpinWait.SpinUntil(() =>
{
return control.IsVisible == stateToWaitFor;
}, waitSettings.ActualTimeOut);
if(throwExceptionOnTimeout && control.IsVisible != stateToWaitFor)
{
throw new TimeoutException("Wait operation timed out before the required visibility was achieved");
}
return waitSettings.WaitRoot;
}
/// <summary>
/// Executes a wait on the IsEnabled state of the target automation control.
/// </summary>
/// <param name="waitSettings">The wait settings.</param>
/// <param name="throwExceptionOnTimeout">if set to <c>true</c> throw an exception if the timeout expires.</param>
/// <returns>
/// The control owning the wait settings
/// </returns>
/// <exception cref="TimeoutException">Thrown if the timeout period is reached before the expected state is true</exception>
private static AutomationControl ExecuteIsEnabledWait(WaitSettings waitSettings, bool throwExceptionOnTimeout = false)
{
var expectedState = waitSettings.WaitType == WaitType.Enabled;
if(waitSettings.WaitRoot.IsEnabled == expectedState)
{
return waitSettings.WaitRoot;
}
SpinWait.SpinUntil(() => waitSettings.WaitRoot.IsEnabled == expectedState, waitSettings.ActualTimeOut);
if(throwExceptionOnTimeout && waitSettings.WaitRoot.IsEnabled != expectedState)
{
throw new TimeoutException("Wait operation timed out before the required enabled state was achieved");
}
return waitSettings.WaitRoot;
}
}
}
|
Python
|
UTF-8
| 113
| 3.203125
| 3
|
[] |
no_license
|
nlista=[1,2,3,4]
nlistalen=len(nlista)
for i in range(0,nlistalen,1):
nlista.append(nlista[i])
print(nlista)
|
Python
|
UTF-8
| 927
| 3.5625
| 4
|
[] |
no_license
|
class Solution:
def search(self, nums: List[int], target: int) -> bool:
# (0) edge case
if len(nums) == 0:
return False
# (1) two pointers and while loop
l = 0
r = len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if nums[mid] == target:
return True
if nums[mid] == nums[l] == nums[r]: # remove the duplicate
l += 1
r -= 1
elif nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return False
# Time: O(n)
# Space: O(1)
|
Python
|
UTF-8
| 1,777
| 2.9375
| 3
|
[] |
no_license
|
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
num_words = 2000
num_tags = 12
num_departments = 4
# 输入
body_input = keras.Input(shape=(None,),name='body')
title_input = keras.Input(shape=(None,),name='title')
tag_input = keras.Input(shape=(num_tags,),name='tag')
# 嵌入点
body_feat = layers.Embedding(num_words,64)(body_input)
title_feat = layers.Embedding(num_words,64)(title_input)
# 特征提取层
body_feat = layers.LSTM(32)(body_feat)
title_feat = layers.LSTM(128)(title_feat)
print(body_feat.shape)
print(title_feat.shape)
features = layers.concatenate([title_feat,body_feat,tag_input])
print(features.shape)
# 分类层
priority_pred = layers.Dense(1,activation='sigmoid',name='priority')(features)
department_pred = layers.Dense(num_departments,activation='softmax', name='department')(features)
# 构建模型
model = keras.Model(inputs=[body_input, title_input, tag_input],
outputs=[priority_pred, department_pred])
model.summary()
model.compile(optimizer=keras.optimizers.RMSprop(1e-3),
loss={'priority': 'binary_crossentropy',
'department': 'categorical_crossentropy'},
loss_weights=[1., 0.2])
import numpy as np
# 载入输入数据
title_data = np.random.randint(num_words, size=(1280, 10))
body_data = np.random.randint(num_words, size=(1280, 100))
tag_data = np.random.randint(2, size=(1280, num_tags)).astype('float32')
# 标签
priority_label = np.random.random(size=(1280, 1))
department_label = np.random.randint(2, size=(1280, num_departments))
# 训练
history = model.fit(
{'title': title_data, 'body':body_data, 'tag':tag_data},
{'priority':priority_label, 'department':department_label},
batch_size=32,
epochs=5
)
|
Python
|
UTF-8
| 18,802
| 3.1875
| 3
|
[] |
no_license
|
import pdb
import time
import sys
class GameState:
"""
Blackjack Game state
"""
def __init__(self, HandType, Value, OppCard):
# if you add other members add them to the hash and eq as well
self.HandType = HandType
# [ "HardFresh", "HardStaleAce", "HardStale", "AceFresh", "Pair" ]
self.OppCard = OppCard
self.Value = Value
def __hash__(self):
return hash((self.OppCard,
self.Value,
self.HandType))
def __eq__(self, other):
return (self.OppCard,
self.Value,
self.HandType) == (other.OppCard,
other.Value,
other.HandType)
def printme(self):
print("State (Type: %s, Value: %d, OppCard: %d) : " % (self.HandType, self.Value, self.OppCard), end='')
# maps states to float values
def InitializeValueDict():
ValueDict = {}
StateSet = []
for summ in range(2,22):
for opp in range(1,11):
StateSet.append(GameState("HardFresh", summ, opp))
StateSet.append(GameState("HardStaleAce", summ, opp))
StateSet.append(GameState("HardStale", summ, opp))
for summ in range(2,11):
for opp in range(1,11):
StateSet.append(GameState("AceFresh", summ, opp))
for summ in range(1,11):
for opp in range(1,11):
StateSet.append(GameState("Pair", summ, opp))
for state in StateSet:
ValueDict[state] = 0
return ValueDict
def PerformValueIteration( ValueActionDict, ValueDict, p):
for state in ValueDict.keys():
if state.HandType == "HardFresh":
PerformValueIterationHardFresh(ValueActionDict, ValueDict, state, p)
elif state.HandType == "HardStale":
PerformValueIterationHardStale(ValueActionDict, ValueDict, state, p)
elif state.HandType == "Pair":
PerformValueIterationPair(ValueActionDict, ValueDict, state, p)
elif state.HandType == "AceFresh":
PerformValueIterationAceFresh(ValueActionDict, ValueDict, state, p)
else:
PerformValueIterationHardStaleAce(ValueActionDict, ValueDict, state, p)
def IsPolicySame( OldValueDict, NewValueDict):
epsilon = 1e-11
for state in OldValueDict:
if abs(OldValueDict[state] - NewValueDict[state]) > epsilon:
#print("Returning false")
return False
return True
def GetFinalPayoff(MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh):
if acefresh and (MyHandValue==11):
if (NumDealerCards==2) and DealerHasAce and (DealerHandValue==11):
return 0
else:
return 1.5
if WeHaveAce:
if MyHandValue+10 <= 21:
MyHandValue = MyHandValue + 10
if DealerHasAce:
if DealerHandValue+10 <= 21:
DealerHandValue = DealerHandValue + 10
if MyHandValue > 21:
return -1
if DealerHandValue > 21:
return 1
if DealerHandValue > MyHandValue:
return -1
if MyHandValue > DealerHandValue:
return 1
if (NumDealerCards==2) and DealerHasAce and (DealerHandValue==21):
return -1
if DealerHandValue == MyHandValue:
return 0
else:
print("Damn")
return 0
def GetStandValueHardStale(p, MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards = 1, acefresh = False): # both values count aces as 1
# base case - dealer stands
if DealerHasAce:
if (DealerHandValue + 10 >= 17 and DealerHandValue + 10 <= 21):
return GetFinalPayoff(MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh)
elif DealerHandValue >= 17:
return GetFinalPayoff(MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh)
else:
if (DealerHandValue >= 17):
return GetFinalPayoff(MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh)
if (MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh) in MemoizationDict:
return MemoizationDict[(MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh)]
#deal more (hit)
np = (1-p)/9.0
TotalReward = 0
for DealerCard in range(2,10): # no ace
TotalReward += np * GetStandValueHardStale(p, MyHandValue, WeHaveAce, DealerHandValue + DealerCard, DealerHasAce, NumDealerCards = NumDealerCards + 1, acefresh = acefresh)
TotalReward += p * GetStandValueHardStale(p, MyHandValue, WeHaveAce, DealerHandValue + 10, DealerHasAce, NumDealerCards = NumDealerCards + 1, acefresh = acefresh)
# Dealer Ace
TotalReward += np * GetStandValueHardStale(p, MyHandValue, WeHaveAce, DealerHandValue + 1, True, NumDealerCards = NumDealerCards + 1, acefresh = acefresh)
MemoizationDict[(MyHandValue, WeHaveAce, DealerHandValue, DealerHasAce, NumDealerCards, acefresh)] = TotalReward
return TotalReward
def GetStandValue(state, p):
# handle ace
# First convert the state to the form where only the total, ace presence and freshness matters
if state.HandType == "HardStaleAce":
if state.OppCard == 1:
ret = GetStandValueHardStale(p, state.Value, True, state.OppCard, True)
else:
ret = GetStandValueHardStale(p, state.Value, True, state.OppCard, False)
elif state.HandType == "AceFresh":
if state.OppCard == 1:
ret = GetStandValueHardStale(p, state.Value+1, True, state.OppCard, True, acefresh = True)
else:
ret = GetStandValueHardStale(p, state.Value+1, True, state.OppCard, False, acefresh = True)
else:
if state.OppCard == 1:
ret = GetStandValueHardStale(p, state.Value, False, state.OppCard, True)
else:
ret = GetStandValueHardStale(p, state.Value, False, state.OppCard, False)
# print("Returning ", ret)
return ret
def ReferenceValueDict(ValueDict, state):
if state.Value > 21:
return -1
elif state not in ValueDict:
print("Logical Error: State (Type: %s, Value: %d, OppCard: %d)not in dict" % (state.HandType, state.Value, state.OppCard))
return 0
else:
return ValueDict[state]
def PerformValueIterationHardFresh(ValueActionDict, ValueDict, state, p):
# [ "HardFresh", "HardStaleAce", "HardStale", "AceFresh", "Pair" ]
np = (1-p)/9.0
cards = [2,3,4,5,6,7,8,9]
# print("HardFresh")
# state.printme()
# for action Hit
HitValue = 0
for card in cards:
NewState = GameState("HardStale", state.Value + card, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardStale", state.Value + 10, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("HardStaleAce", state.Value + 1, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# for action Stand
state_temp = GameState("HardStale", state.Value, state.OppCard)
StandValue = GetStandValue(state_temp, p)
# for action Double
DoubleValue = 0
for card in cards:
NewState = GameState("HardStale", state.Value + card, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
# to handle face cards
NewState = GameState("HardStale", state.Value + 10, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * p
# to handle ace
NewState = GameState("HardStaleAce", state.Value + 1, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
ValueDict[state] = max(HitValue, StandValue, DoubleValue)
if ValueDict[state] == HitValue:
ValueActionDict[state] = "H"
elif ValueDict[state] == StandValue:
ValueActionDict[state] = "S"
else:
ValueActionDict[state] = "D"
def PerformValueIterationHardStale(ValueActionDict, ValueDict, state, p):
# [ "HardFresh", "HardStaleAce", "HardStale", "AceFresh", "Pair" ]
np = (1-p)/9.0
cards = [2,3,4,5,6,7,8,9]
# print("HardStale")
# state.printme()
# for action Hit
HitValue = 0
for card in cards:
NewState = GameState("HardStale", state.Value + card, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardStale", state.Value + 10, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("HardStaleAce", state.Value + 1, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# for action Stand
StandValue = GetStandValue(state, p)
ValueDict[state] = max(HitValue, StandValue)
if ValueDict[state] == HitValue:
ValueActionDict[state] = "H"
elif ValueDict[state] == StandValue:
ValueActionDict[state] = "S"
def PerformValueIterationPair(ValueActionDict, ValueDict, state, p):
# TODO: Handle Ace pair
ActionList = ["Hit","Stand","Double","Split"]
np = (1-p)/9.0
cards = [2,3,4,5,6,7,8,9]
# print("Pair")
# state.printme()
if(state.Value != 1):
# for action Hit
HitValue = 0
for card in cards:
NewState = GameState("HardStale", 2 * state.Value + card, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardStale", 2 * state.Value + 10, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("HardStaleAce", 2 * state.Value + 1, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# for action Stand
state_temp = GameState("HardStale", 2 * state.Value, state.OppCard)
StandValue = GetStandValue(state_temp, p)
# for action Double
DoubleValue = 0
for card in cards:
NewState = GameState("HardStale", 2 * state.Value + card, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
# to handle face cards
NewState = GameState("HardStale", 2 * state.Value + 10, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * p
# to handle ace
NewState = GameState("HardStaleAce", 2 * state.Value + 1, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
SplitValue = 0
for card in cards:
if card != state.Value:
NewState = GameState("HardFresh", state.Value + card, state.OppCard)
SplitValue += 2 * ReferenceValueDict(ValueDict, NewState) * np
else:
NewState = GameState("Pair", state.Value, state.OppCard)
SplitValue += 2 * ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardFresh", state.Value + 10, state.OppCard)
SplitValue += 2 * ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("AceFresh", state.Value, state.OppCard)
SplitValue += 2 * ReferenceValueDict(ValueDict, NewState) * np
ValueDict[state] = max(HitValue, StandValue, DoubleValue, SplitValue)
if ValueDict[state] == HitValue:
ValueActionDict[state] = "H"
elif ValueDict[state] == StandValue:
ValueActionDict[state] = "S"
elif ValueDict[state] == DoubleValue:
ValueActionDict[state] = "D"
else:
ValueActionDict[state] = "P"
else:
# for action Hit
HitValue = 0
for card in cards:
NewState = GameState("HardStaleAce", 2 * state.Value + card, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardStaleAce", 2 * state.Value + 10, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("HardStaleAce", 2 * state.Value + 1, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# for action Stand
state_temp = GameState("HardStaleAce", 2 * state.Value, state.OppCard)
StandValue = GetStandValue(state_temp, p)
# for action Double
DoubleValue = 0
for card in cards:
NewState = GameState("HardStaleAce", 2 * state.Value + card, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
# to handle face cards
NewState = GameState("HardStaleAce", 2 * state.Value + 10, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * p
# to handle ace
NewState = GameState("HardStaleAce", 2 * state.Value + 1, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
# for action split
SplitValue = 0
for card in cards:
NewState = GameState("HardStaleAce", state.Value + card, state.OppCard)
SplitValue += 2 * GetStandValue(NewState, p) * np
# to handle face cards
NewState = GameState("HardStaleAce", state.Value + 10, state.OppCard)
SplitValue += 2 * GetStandValue(NewState, p) * p
# to handle ace
NewState = GameState("HardStaleAce", 2 * state.Value, state.OppCard)
SplitValue += 2 * GetStandValue(NewState, p) * np
ValueDict[state] = max(HitValue, StandValue, DoubleValue, SplitValue)
if ValueDict[state] == HitValue:
ValueActionDict[state] = "H"
elif ValueDict[state] == StandValue:
ValueActionDict[state] = "S"
elif ValueDict[state] == DoubleValue:
ValueActionDict[state] = "D"
else:
ValueActionDict[state] = "P"
def PerformValueIterationAceFresh(ValueActionDict, ValueDict, state, p):
# [ "HardFresh", "HardStaleAce", "HardStale", "AceFresh", "Pair" ]
np = (1-p)/9.0
cards = [2,3,4,5,6,7,8,9]
# print("AceFresh")
# state.printme()
# for action Hit
HitValue = 0
for card in cards:
NewState = GameState("HardStaleAce", 1 + state.Value + card, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardStaleAce", 1 + state.Value + 10, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("HardStaleAce", 1 + state.Value + 1, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# for action Stand
StandValue = GetStandValue(state, p)
# for action Double
DoubleValue = 0
for card in cards:
NewState = GameState("HardStaleAce", 1 + state.Value + card, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
# to handle face cards
NewState = GameState("HardStaleAce", 1 + state.Value + 10, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * p
# to handle ace
NewState = GameState("HardStaleAce", 1 + state.Value + 1, state.OppCard)
DoubleValue += 2 * GetStandValue(NewState, p) * np
ValueDict[state] = max(HitValue, StandValue, DoubleValue)
if ValueDict[state] == HitValue:
ValueActionDict[state] = "H"
elif ValueDict[state] == StandValue:
ValueActionDict[state] = "S"
elif ValueDict[state] == DoubleValue:
ValueActionDict[state] = "D"
def PerformValueIterationHardStaleAce(ValueActionDict, ValueDict, state, p):
# [ "HardFresh", "HardStaleAce", "HardStale", "AceFresh", "Pair" ]
np = (1-p)/9.0
cards = [2,3,4,5,6,7,8,9]
# print("HardStaleAce")
# state.printme()
# for action Hit
HitValue = 0
for card in cards:
NewState = GameState("HardStaleAce", state.Value + card, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# to handle face cards
NewState = GameState("HardStaleAce", state.Value + 10, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * p
# to handle ace
NewState = GameState("HardStaleAce", state.Value + 1, state.OppCard)
HitValue += ReferenceValueDict(ValueDict, NewState) * np
# for action Stand
StandValue = GetStandValue(state, p)
ValueDict[state] = max(HitValue, StandValue)
if ValueDict[state] == HitValue:
ValueActionDict[state] = "H"
elif ValueDict[state] == StandValue:
ValueActionDict[state] = "S"
if __name__ == '__main__':
MemoizationDict = {}
ValueDict = InitializeValueDict()
ValueActionDict = InitializeValueDict()
p = float(sys.argv[1])
iteration = 0
while True:
NewValueDict = ValueDict.copy()
NewValueActionDict = ValueActionDict.copy()
# print("Iteration ", iteration)
iteration += 1
PerformValueIteration(ValueActionDict, NewValueDict, p)
# print(NewValueDict.values())
# print(ValueDict.values())
if IsPolicySame(ValueDict, NewValueDict):
break
ValueDict = NewValueDict
ValueActionDict = NewValueActionDict
for summ in range(5,20):
print(summ, "\t", end="",sep="")
for opp in range(2,11):
state = GameState("HardFresh", summ, opp)
print(ValueActionDict[state]," ",end='',sep="")
state = GameState("HardFresh", summ, 1)
print(ValueActionDict[state])
for summ in range(2,10):
print("A%d\t" %(summ), end='')
for opp in range(2,11):
state = GameState("AceFresh", summ, opp)
print(ValueActionDict[state]," ",end='',sep="")
state = GameState("AceFresh", summ, 1)
print(ValueActionDict[state])
for summ in range(2,11):
print("%d%d\t" %(summ,summ), end='')
for opp in range(2,11):
state = GameState("Pair", summ, opp)
print(ValueActionDict[state]," ",end='',sep="")
state = GameState("Pair", summ, 1)
print(ValueActionDict[state])
print("AA\t" , end='')
for opp in range(2,11):
state = GameState("Pair", 1, opp)
print(ValueActionDict[state]," ",end='',sep="")
state = GameState("Pair", 1, 1)
print(ValueActionDict[state],end="")
# for state in StateSet:
# ValueDict[state] = 0
# for state in ValueDict:
# state.printme()
# print(ValueActionDict[state])
# print("MemoizationDict\n",MemoizationDict.values())
|
Python
|
UTF-8
| 434
| 4.28125
| 4
|
[] |
no_license
|
# def square(num)
# return num * num
# print(square(9))
def square(num): return num * num
square2 = lambda num: num * num
add = lambda a, b: a + b
# use when you are passing a function into another function as a parameter
# a function without a name for a one time use. Its a single line
# Write a lambda that accepts a single number and cubes it. Save it in a variable called cube.
cube = lambda num: num ** 3
print(cube(2))
#8
|
PHP
|
UTF-8
| 328
| 2.765625
| 3
|
[] |
no_license
|
<?php
function clear_string($cl_str){
$cl_str = strip_tags($cl_str); // Удаляем HTML и PHP теги
$cl_str = mysql_real_escape_string($cl_str); // Экранируем спец.символы
$cl_str = trim($cl_str); // Удаление лишних пробелов
return $cl_str;
}
?>
|
C#
|
UTF-8
| 3,419
| 3.28125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace 动态解打劫房屋问题
{
/*
打劫房屋问题
【问题】假设你是一个专业的窃贼,准备沿着一条街打劫房屋。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警。
给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,你最多可以得到多少钱 在不触动报警装置的情况下。
【递归思路】问题可以描述为,抢劫所有的房屋,使得抢劫的钱最多。 那么,这个问题的最优解,可以由子问题的最优解构造:除了当前房屋以外,抢劫剩余房屋获得的最多的钱,那么对于当前房屋会有两种策略,抢劫或者不抢劫。 所以,抢劫所有房屋获得的做多的钱 = max(抢劫当下房屋的钱+抢劫剩余n-2个房屋获得的最多的钱, 抢劫剩余n-1个房屋获得的钱)
递归问题可以描述为:从0位置开始到结束位置打劫的最高收益,它等于打劫当前房屋+从下下个位置开始打劫的最高收益 或者 从下个位置开始打劫的最高收益的 两者的最大值。
*/
class Program
{
static void Main(string[] args)
{
var arr = new int[] {89,56,12,36,12,55,63,10 };//89+36+55+10
var max = Recursion(arr, arr.Length-1 );
var arr2 = new int[arr.Length];
for (var i = 0; i < arr2.Length; i++)
{
arr2[i] = int.MinValue;
}
Console.WriteLine(max);
var max2 = Dy(arr,arr2, arr.Length - 1);
Console.WriteLine(max2);
var max3 = Dy2(arr);
Console.WriteLine(max3);
Console.ReadKey();
}
static int Recursion(int[]arr,int n)
{
if (n < 0)
return 0;
return Math.Max(Recursion(arr, n - 1), arr[n] + Recursion(arr, n - 2));
}
static int Dy(int[] arr, int[]arr2,int n)
{
if (n < 0)
return 0;
if (arr2[n] != Int32.MinValue)
return arr2[n];
arr2[n] = Math.Max(Dy(arr,arr2, n - 1), arr[n] + Dy(arr, arr2,n - 2));
return arr2[n];
}
/*
【动态规划思路】状态是打劫前n个房屋的最大收益f(n),状态转移方程式:f(n) = max{f(n-1), A[n]+f(n-2)}。 即打劫前n个房屋的最大收益是是否选择打劫当前房屋这个决定产生的两个结果的最大值。
复制代码
*/
static int Dy2(int[] arr)
{
if (arr == null || arr.Length == 0)
return 0;
if (arr.Length == 1)
return arr[0];
var arr3 = new int[arr.Length];
arr3[0] = arr[0];
arr3[1] = Math.Max(arr[1], arr3[0]);
if (arr.Length == 2)
return arr3[1];
for (var i = 2; i < arr.Length; i++)
{
arr3[i] = Math.Max(arr3[i - 1], arr[i] + arr3[i - 2]);
}
return arr3[arr3.Length - 1];
}
}
}
|
Python
|
UTF-8
| 1,421
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
#
# @lc app=leetcode id=142 lang=python3
#
# [142] Linked List Cycle II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
# To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
# Note: Do not modify the linked list.
# Example 1:
# Input: head = [3,2,0,-4], pos = 1
# Output: tail connects to node index 1
# Explanation: There is a cycle in the linked list, where tail connects to the second node.
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
# Accepted
# 16/16 cases passed (52 ms)
# Your runtime beats 85.48 % of python3 submissions
# Your memory usage beats 5.13 % of python3 submissions (16.7 MB)
if not head or not head.next:
return None
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow == fast:
break
if not fast or not fast.next:
return None
while head != fast:
head, fast = head.next, fast.next
return fast
# @lc code=end
|
JavaScript
|
UTF-8
| 369
| 2.734375
| 3
|
[] |
no_license
|
const animationBar = document.querySelector('.animation-bar')
const content = document.querySelector('.content');
document.addEventListener('scroll', function(e) {
const percentageDocScrolled = document.documentElement.scrollTop/(content.offsetHeight - document.documentElement.clientHeight) *100
animationBar.style.width = `${percentageDocScrolled}%` ;
});
|
Python
|
UTF-8
| 630
| 3.6875
| 4
|
[] |
no_license
|
def maxLista(l):
if len(l)==0:
return 0
max=0
for i in range (0,len(l)):
if l[i]>max:
max=l[i]
return max
def minLista(l):
if len(l)==0:
return 0
min=l[0]
for i in range (0,len(l)):
if l[i]<min:
min=l[i]
return min
def medLista(l):
if len(l)==0:
return 0
med=0
for i in range (0,len(l)):
med += l[i]
return med/len(l)
if __name__ == "__main__":
lista=[4,7,11]
print("Máximo: ",maxLista(lista))
print("Mínimo: ",minLista(lista))
print("Media: ",medLista(lista))
|
Markdown
|
UTF-8
| 3,255
| 3.359375
| 3
|
[] |
no_license
|
# Goal
In this tutorial, you will learn Simple thresholding, Adaptive thresholding, Otsu's thresholding etc.
You will learn these functions : cv.threshold, cv.adaptiveThreshold etc.
https://docs.opencv.org/trunk/d7/d4d/tutorial_py_thresholding.html
# Simple Thresholding
First argument is the source image, which should be a grayscale image. Second argument is the threshold value which is used to classify the pixel values. Third argument is the maxVal which represents the value to be given if pixel value is more than (sometimes less than) the threshold value.

# Adaptive Thresholding
In the previous section, we used a global value as threshold value. But it may not be good in all the conditions where image has different lighting conditions in different areas. In that case, we go for adaptive thresholding. In this, the algorithm calculate the threshold for a small regions of the image. So we get different thresholds for different regions of the same image and it gives us better results for images with varying illumination.
Adaptive Method - It decides how thresholding value is calculated.
cv.ADAPTIVE_THRESH_MEAN_C : threshold value is the mean of neighbourhood area.
cv.ADAPTIVE_THRESH_GAUSSIAN_C : threshold value is the weighted sum of neighbourhood values where weights are a gaussian window.
Block Size - It decides the size of neighbourhood area.
C - It is just a constant which is subtracted from the mean or weighted mean calculated.
ADAPTIVE_THRESH_MEAN_C
Python: cv.ADAPTIVE_THRESH_MEAN_C
the threshold value T(x,y) is a mean of the 𝚋𝚕𝚘𝚌𝚔𝚂𝚒𝚣𝚎×𝚋𝚕𝚘𝚌𝚔𝚂𝚒𝚣𝚎 neighborhood of (x,y) minus C
ADAPTIVE_THRESH_GAUSSIAN_C
Python: cv.ADAPTIVE_THRESH_GAUSSIAN_C
the threshold value T(x,y) is a weighted sum (cross-correlation with a Gaussian window) of the 𝚋𝚕𝚘𝚌𝚔𝚂𝚒𝚣𝚎×𝚋𝚕𝚘𝚌𝚔𝚂𝚒𝚣𝚎 neighborhood of (x,y) minus C . The default sigma (standard deviation) is used for the specified blockSize .
# Otsu’s Binarization
otsu又叫最大类间方差。主要是找到一个阈值,使整个图像中前景与背景这两部分差别最大,(这方法主要用于分割其实)
In global thresholding, we used an arbitrary value for threshold value, right? So, how can we know a value we selected is good or not? Answer is, trial and error method. But consider a bimodal image (In simple words, bimodal image is an image whose histogram has two peaks). For that image, we can approximately take a value in the middle of those peaks as threshold value, right ? That is what Otsu binarization does. So in simple words, it automatically calculates a threshold value from image histogram for a bimodal image. (For images which are not bimodal, binarization won’t be accurate.)
For this, our cv.threshold() function is used, but pass an extra flag, cv.THRESH_OTSU. For threshold value, simply pass zero. Then the algorithm finds the optimal threshold value and returns you as the second output, retVal. If Otsu thresholding is not used, retVal is same as the threshold value you used.
|
C++
|
WINDOWS-1251
| 5,343
| 2.859375
| 3
|
[] |
no_license
|
#pragma once
#include "Tagged.h"
namespace Demo
{
namespace Core
{
//------------------------------------------------------------
class _DemoExport Controller : public Tagged<Controller>
{
public:
DEFINE_CLASS_SHARED_PTR(Controller)
DEFINE_TAGGED
//--------------------------------//
class traits
{
public:
typedef type_traits< Controller >::ptr child_ctr_t;
typedef type_traits< child_ctr_t >::cref child_ctr_in;
typedef type_traits< Controller >::ptr parent_ctr_t;
typedef type_traits< parent_ctr_t >::cref parent_ctr_in;
//Child Controllers are added to Set container,
//thus index of child can change with time
typedef Demo::set< child_ctr_t >::type child_ctr_container;
typedef Ogre::SetIterator<child_ctr_container> child_ctr_oit;
typedef Ogre::ConstSetIterator<child_ctr_container> child_ctr_ocit;
};
//--------------------------------//
Controller();
virtual ~Controller();
/*=======================================================================
|
| .
|
========================================================================*/
virtual void CloseController();
/*=======================================================================
|
| m_childCtrContainer
========================================================================*/
virtual void OperateController();
/*=======================================================================
|
| .( )
| _isActive.
========================================================================*/
virtual void SetActiveController( bool );
/*=======================================================================
| /
|
========================================================================*/
/*=======================================================================
| this' pChild
| this , false
========================================================================*/
virtual bool ConnectChildController( traits::child_ctr_in pChild );
/*=======================================================================
| this' pChild
========================================================================*/
virtual void DisconnectChildController( traits::child_ctr_in pChild );
virtual void DisconnectAllChildControllers();
/*=======================================================================
| this' Parent |
========================================================================*/
void disconnectFromParentController();
inline traits::parent_ctr_t getParentController()const { return m_pParentController; }
inline void setInitializeController() { mInitializedController = true; }
inline bool isInitializedController()const { return mInitializedController; }
inline bool isActiveController()const { return mActiveController; }
traits::child_ctr_oit getChildControllerIterator() {return traits::child_ctr_oit(m_childCtrContainer);}
traits::child_ctr_ocit getChildControllerIterator()const {return traits::child_ctr_ocit(m_childCtrContainer);}
protected:
/*=======================================================================
| this pParent
| this false
========================================================================*/
virtual bool ConnectingToParentController( traits::parent_ctr_in pParent );
/*=======================================================================
| this pParent
========================================================================*/
virtual void DisconnectingFromParentController();
traits::child_ctr_container m_childCtrContainer;
traits::parent_ctr_t m_pParentController;
private:
Controller( const Controller& );
Controller& operator=( const Controller& );
bool mInitializedController;
bool mActiveController;
};
//------------------------------------------------------------
}
}
|
PHP
|
UTF-8
| 987
| 4.0625
| 4
|
[] |
no_license
|
<?php
class Solution {
static $dp = [];
/**
* @param Integer $n
* @return Integer
*/
function climbStairs($n) {
self::$dp[1] = 1;
self::$dp[2] = 2;
if (isset(self::$dp[$n])) {
return self::$dp[$n];
}
self::$dp[$n] = $this->climbStairs($n - 1) + $this->climbStairs($n - 2);
return self::$dp[$n];
}
function climbStairs2($n) {
if ($n <= 2) {
return $n;
}
// 当前下标往前两位,如果当前坐标为3,则pre_2指向1
$pre_2 = 1;
// 当前下标往前两位,如果当前坐标为3,则pre_1指向2
$pre_1 = 2;
//3的是结果是3
$result = $pre_2 + $pre_1;
//从4开始进入循环
for ($i = 3; $i < $n; $i++) {
$lastResult = $result;
$result += $pre_1;
$pre_1 = $lastResult;
}
return $result;
}
}
echo (new Solution())->climbStairs2(5);
|
C++
|
UTF-8
| 974
| 2.59375
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <stdio.h>
using namespace std;
#define int long long
int MOD = 1000000007;
string removeZeros(string T) {
reverse(T.begin(), T.end());
while ((int)T.size() > 0 && T.back() == '0')T.pop_back();
reverse(T.begin(), T.end());
return T;
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
string S;
cin >> S;
int res = 0;
for (int i = 0; i < S.size(); i++) {
res = max(res, (int)(S[i] - '0'));
}
vector<string> X(res, string(S.size(), '0'));
for (int i = 0; i < res; i++) {
for (int j = 0; j < S.size(); j++) {
if (i < (int)(S[j] - '0')) {
X[i][j] = '1';
}
}
}
cout << res << endl;
for (int i = 0; i < res; i++) {
if (i > 0)cout << " ";
cout << removeZeros(X[i]);
}
cout << endl;
}
|
Java
|
UTF-8
| 6,182
| 2.421875
| 2
|
[] |
no_license
|
package com.pj.magic.gui.panels;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.table.TableColumnModel;
import org.springframework.beans.factory.annotation.Autowired;
import com.pj.magic.gui.component.MagicToolBar;
import com.pj.magic.gui.component.MagicToolBarButton;
import com.pj.magic.gui.dialog.SearchBadStocksDialog;
import com.pj.magic.gui.tables.MagicListTable;
import com.pj.magic.gui.tables.models.ListBackedTableModel;
import com.pj.magic.model.BadStock;
import com.pj.magic.model.Unit;
import com.pj.magic.model.search.BadStockSearchCriteria;
import com.pj.magic.service.BadStockService;
import com.pj.magic.service.SupplierService;
public class BadStockInventoryListPanel extends StandardMagicPanel {
@Autowired
private BadStockService badStockService;
@Autowired
private SupplierService supplierService;
private MagicListTable table;
private BadStockTableModel tableModel = new BadStockTableModel();
private SearchBadStocksDialog searchBadStocksDialog;
public BadStockInventoryListPanel() {
setTitle("Bad Stock Inventory List");
}
@Override
protected void initializeComponents() {
table = new MagicListTable(tableModel);
focusOnComponentWhenThisPanelIsDisplayed(table);
initializeTable();
}
private void initializeTable() {
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(PRODUCT_CODE_COLUMN_INDEX).setPreferredWidth(40);
columnModel.getColumn(PRODUCT_DESCRIPTION_COLUMN_INDEX).setPreferredWidth(200);
columnModel.getColumn(AVAILABLE_QTY_CSE_COLUMN_INDEX).setPreferredWidth(40);
columnModel.getColumn(AVAILABLE_QTY_TIE_COLUMN_INDEX).setPreferredWidth(40);
columnModel.getColumn(AVAILABLE_QTY_CTN_COLUMN_INDEX).setPreferredWidth(40);
columnModel.getColumn(AVAILABLE_QTY_DOZ_COLUMN_INDEX).setPreferredWidth(40);
columnModel.getColumn(AVAILABLE_QTY_PCS_COLUMN_INDEX).setPreferredWidth(40);
}
public void updateDisplay() {
List<BadStock> products = badStockService.getAllAvailableBadStocks();
tableModel.setItems(products);
if (!products.isEmpty()) {
table.changeSelection(0, 0, false, false);
}
if (searchBadStocksDialog != null) {
searchBadStocksDialog.resetDisplay();
}
}
@Override
protected void layoutMainPanel(JPanel mainPanel) {
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = c.weighty = 1.0;
c.gridx = c.gridy = 0;
mainPanel.add(new JScrollPane(table), c);
}
@Override
protected void registerKeyBindings() {
registerEscapeKeyAsBack();
}
@Override
protected void doOnBack() {
getMagicFrame().switchToBadStockMenuPanel();
}
@Override
protected void addToolBarButtons(MagicToolBar toolBar) {
toolBar.add(new MagicToolBarButton("search", "Search", e -> searchBadStocks()));
}
private void searchBadStocks() {
if (searchBadStocksDialog == null) {
searchBadStocksDialog = new SearchBadStocksDialog(supplierService);
searchBadStocksDialog.resetDisplay();
}
searchBadStocksDialog.setVisible(true);
BadStockSearchCriteria criteria = searchBadStocksDialog.getSearchCriteria();
if (criteria != null) {
tableModel.setItems(badStockService.search(criteria));
if (tableModel.hasItems()) {
table.selectFirstRowThenFocus();
} else {
showMessage("No matching records");
}
}
}
private static final int PRODUCT_CODE_COLUMN_INDEX = 0;
private static final int PRODUCT_DESCRIPTION_COLUMN_INDEX = 1;
private static final int AVAILABLE_QTY_CSE_COLUMN_INDEX = 2;
private static final int AVAILABLE_QTY_TIE_COLUMN_INDEX = 3;
private static final int AVAILABLE_QTY_CTN_COLUMN_INDEX = 4;
private static final int AVAILABLE_QTY_DOZ_COLUMN_INDEX = 5;
private static final int AVAILABLE_QTY_PCS_COLUMN_INDEX = 6;
private static final String[] COLUMN_NAMES = {"Code", "Description", "CSE", "TIE", "CTN", "DOZ", "PCS"};
private class BadStockTableModel extends ListBackedTableModel<BadStock> {
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
BadStock badStock = getItem(rowIndex);
switch (columnIndex) {
case PRODUCT_CODE_COLUMN_INDEX:
return badStock.getProduct().getCode();
case PRODUCT_DESCRIPTION_COLUMN_INDEX:
return badStock.getProduct().getDescription();
case AVAILABLE_QTY_CSE_COLUMN_INDEX:
return badStock.getUnitQuantity(Unit.CASE);
case AVAILABLE_QTY_TIE_COLUMN_INDEX:
return badStock.getUnitQuantity(Unit.TIE);
case AVAILABLE_QTY_CTN_COLUMN_INDEX:
return badStock.getUnitQuantity(Unit.CARTON);
case AVAILABLE_QTY_DOZ_COLUMN_INDEX:
return badStock.getUnitQuantity(Unit.DOZEN);
case AVAILABLE_QTY_PCS_COLUMN_INDEX:
return badStock.getUnitQuantity(Unit.PIECES);
default:
return null;
}
}
@Override
protected String[] getColumnNames() {
return COLUMN_NAMES;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case AVAILABLE_QTY_CSE_COLUMN_INDEX:
case AVAILABLE_QTY_TIE_COLUMN_INDEX:
case AVAILABLE_QTY_CTN_COLUMN_INDEX:
case AVAILABLE_QTY_DOZ_COLUMN_INDEX:
case AVAILABLE_QTY_PCS_COLUMN_INDEX:
return Number.class;
default:
return super.getColumnClass(columnIndex);
}
}
}
}
|
C++
|
UTF-8
| 3,171
| 2.640625
| 3
|
[
"Zlib"
] |
permissive
|
#include "NativeMemory.hpp"
#include <Main.h>
#include <Psapi.h>
namespace GTA
{
using namespace System::Collections::Generic;
static MemoryAccess::MemoryAccess()
{
const uintptr_t patternAddress = FindPattern(EntityPoolOpcodePattern, EntityPoolOpcodeMask);
// 3 bytes are opcode and its first argument, so we add it to get relative address to patternAddress. 7 bytes are length of opcode and its parameters.
sAddressEntityPool = reinterpret_cast<MemoryPool **>(*reinterpret_cast<int *>(patternAddress + 3) + patternAddress + 7);
}
int MemoryAccess::HandleToIndex(int Handle)
{
return Handle >> 8; // == Handle / 256
}
uintptr_t MemoryAccess::GetAddressOfEntity(int Handle)
{
return *reinterpret_cast<uintptr_t*>(GetAddressOfItemInPool(*sAddressEntityPool, Handle) + 8);
}
array<int> ^MemoryAccess::GetEntityHandleList()
{
return GetListOfHandlesInPool(*sAddressEntityPool);
}
float MemoryAccess::GetVehicleRPM(int handle)
{
uintptr_t addr = GetAddressOfEntity(handle);
if (addr == 0)
{
return 0.0f;
}
return *(float*)(addr + 2004);
}
float MemoryAccess::GetVehicleAcceleration(int handle)
{
uintptr_t addr = GetAddressOfEntity(handle);
if (addr == 0)
{
return 0.0f;
}
return *(float*)(addr + 2020);
}
float MemoryAccess::GetVehicleSteering(int handle)
{
uintptr_t addr = GetAddressOfEntity(handle);
if (addr == 0)
{
return 0.0f;
}
return *(float*)(addr + 2212);
}
uintptr_t MemoryAccess::FindPattern(const char *pattern, const char *mask)
{
MODULEINFO modInfo = { 0 };
GetModuleInformation(GetCurrentProcess(), GetModuleHandle(nullptr), &modInfo, sizeof(MODULEINFO));
const char *start_offset = reinterpret_cast<const char *>(modInfo.lpBaseOfDll);
const uintptr_t size = static_cast<uintptr_t>(modInfo.SizeOfImage);
intptr_t pos = 0;
const uintptr_t searchLen = static_cast<uintptr_t>(strlen(mask) - 1);
for (const char *retAddress = start_offset; retAddress < start_offset + size; retAddress++)
{
if (*retAddress == pattern[pos] || mask[pos] == '?')
{
if (mask[pos + 1] == '\0')
{
return (reinterpret_cast<uintptr_t>(retAddress) - searchLen);
}
pos++;
}
else
{
pos = 0;
}
}
return 0;
}
uintptr_t MemoryAccess::GetAddressOfItemInPool(MemoryPool *PoolAddress, int Handle)
{
if (PoolAddress == nullptr)
{
return 0;
}
const int index = HandleToIndex(Handle);
const int flag = PoolAddress->BoolAdr[index]; // flag should be equal to 2 if everything is ok
// parity check? (taken from ScriptHookDotNet for IV
if (flag & 0x80 || flag != (Handle & 0xFF))
{
return 0;
}
return (PoolAddress->ListAddr + index * PoolAddress->ItemSize);
}
array<int> ^MemoryAccess::GetListOfHandlesInPool(MemoryPool *PoolAddress)
{
if (PoolAddress == nullptr)
{
return nullptr;
}
List<int> ^handles = gcnew List<int>();
for (int i = 0; i < PoolAddress->MaxCount; i++)
{
int val = static_cast<int>(PoolAddress->BoolAdr[i]); // parity value, important to cast it to int
if ((val & 0x80) == 0)
{
val = (i << 8) | val;
handles->Add(val);
}
}
return handles->ToArray();
}
}
|
Markdown
|
UTF-8
| 150
| 3.140625
| 3
|
[] |
no_license
|
# ML-Python
My first python linear regression project for finding demand for bikes in a location based on climate, season, temperature, day, type,etc
|
Java
|
UTF-8
| 4,390
| 2.609375
| 3
|
[] |
no_license
|
package by.bsuir.cinema.controller;
import by.bsuir.cinema.entity.user.User;
import by.bsuir.cinema.exception.ProjectException;
import by.bsuir.cinema.jframe.admin.AdminMenuFrame;
import by.bsuir.cinema.jframe.client.SignUpFrame;
import by.bsuir.cinema.logic.UserLogic;
import by.bsuir.cinema.jframe.client.UserMenuFrame;
import by.bsuir.cinema.util.Encryption;
import javax.swing.*;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Starter {
private static final int X = 650;
private static final int Y = 300;
private static final int WIDTH = 1000;
private static final int HEIGHT = 300;
public static User user;
public JPanel authorizationPanel;
private JButton signIn;
private JLabel authtorlabel;
private JLabel login;
private JLabel password;
private JTextField loginText;
private JPasswordField passwordField;
private JButton signUpButton;
private static Socket connection;
private static OutputStream output;
private static DataOutputStream dataOutputStream;
public static void main(String[] args) throws IOException {
connection = new Socket(InetAddress.getByName("127.0.0.1"), 3351);
output = connection.getOutputStream();
dataOutputStream = new DataOutputStream(output);
JFrame authorizationFrame = new JFrame("Авторизация");
authorizationFrame.setBounds(X, Y, WIDTH, HEIGHT);
authorizationFrame.setContentPane(new Starter(authorizationFrame, dataOutputStream).authorizationPanel);
authorizationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
authorizationFrame.pack();
authorizationFrame.setVisible(true);
}
public Starter(JFrame authorizationFrame, DataOutputStream output) {
signIn.addActionListener(e -> {
try {
user = UserLogic.findUser(loginText.getText(), Encryption.encryptPassword(passwordField.getText()));
} catch (ProjectException e1) {
e1.printStackTrace();
}
if (user != null) {
switch (user.getType()) {
case ADMIN:
authorizationFrame.dispose();
openAdminMenu(dataOutputStream);
break;
case CLIENT:
authorizationFrame.dispose();
openUserMenu(dataOutputStream);
break;
default:
JOptionPane.showMessageDialog(null,
"Ошибка");
break;
}
} else {
JOptionPane.showMessageDialog(null,
"Такого пользователя нет");
}
});
signUpButton.addActionListener(e -> {
authorizationFrame.dispose();
openSignUpMenu(dataOutputStream);
});
}
private void openAdminMenu(DataOutputStream dataOutputStream) {
JFrame frame = new JFrame("Меню администратора");
frame.setBounds(650, 300, 15000, 300);
frame.setContentPane(new AdminMenuFrame(frame, dataOutputStream).adminMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
new Thread(new AdminMenuFrame(dataOutputStream)).start();
}
private void openUserMenu(DataOutputStream dataOutputStream) {
JFrame frame = new JFrame("Меню пользователя");
frame.setBounds(650, 300, 15000, 300);
frame.setContentPane(new UserMenuFrame(frame, dataOutputStream).userMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
new Thread(new UserMenuFrame(dataOutputStream)).start();
}
private void openSignUpMenu(DataOutputStream dataOutputStream) {
JFrame frame = new JFrame("Меню регистрации");
frame.setBounds(650, 300, 15000, 300);
frame.setContentPane(new SignUpFrame(frame, dataOutputStream).signUpPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
|
Java
|
UTF-8
| 2,983
| 2.8125
| 3
|
[] |
no_license
|
/*
* Copyright (C) 2010 Grupo Integrado de Ingeniería
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* MinimizingObjectiveComparator.java
*
* Created on 21 de diciembre de 2006, 11:39
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package es.udc.gii.common.eaf.algorithm.fitness.comparator;
import es.udc.gii.common.eaf.algorithm.population.multiobjective.MONSGA2Individual;
/**
* This class compares two individuals considering only one of the objective
* values of each individual. Lesser values are better, i.e. it minimizes a
* given objective.
*
* @author Grupo Integrado de Ingeniería (<a href="http://www.gii.udc.es">www.gii.udc.es</a>)
* @since 1.0
*/
public class MinimizingTranslatedObjectiveComparator<T extends MONSGA2Individual>
extends FitnessComparator<T> {
/**
* Objective index of the objective under comparison.
*/
private int objectiveIndex;
public MinimizingTranslatedObjectiveComparator() {
this.objectiveIndex = 0;
}
/**
* Compares one single objective value of two individuals. Which objective
* is compared is given by an index returned by #getObjectiveIndex. For
* example, if this index is 2, then the two individuals are compared
* against the third objective value (indices start by 0). Lesser values
* are considered better.
*
* @param o1 - First individual.
* @param o2 - Second individual.
* @return -1 if o1 is better than o2, 1 if o2 is better than o1 and 0 if
* both individual have the same objective value for the given objective
* index.
*/
@Override
public int compare(T o1, T o2) {
double o1Value = o1.getTranslatedObjectives().get(objectiveIndex);
double o2Value = o2.getTranslatedObjectives().get(objectiveIndex);
if (o1Value < o2Value) {
return -1;
} else if(o1Value > o2Value) {
return 1;
} else {
return 0;
}
}
public void setObjectiveIndex(int index) {
this.objectiveIndex = index;
}
public int getObjectiveIndex() {
return objectiveIndex;
}
@Override
public String toString() {
return "Minimizing Objective Value Comparator (current: " +
this.objectiveIndex + "th ojective)";
}
}
|
Python
|
UTF-8
| 5,489
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pycompss.api.parameter import FILE_IN, FILE_OUT
from pycompss.api.api import compss_wait_on, compss_delete_object
from pycompss.api.task import task
from ddf_library.utils import create_stage_files, save_stage_file, \
read_stage_file, generate_info, merge_schema
import numpy as np
import sys
def parallelize(data, settings):
"""
Method to split the data in nfrag parts. This method simplifies
the use of chunks.
:param data: The np.array or list to do the split.
:param settings: A dictionary with:
- nfrag: A number of partitions;
:return: A list of pandas DataFrame.
:Note: the result may be unbalanced when the number of rows is too small
"""
nfrag = settings['nfrag']
n_rows = len(data)
# sizes = _generate_distribution1(n_rows, nfrag) # only when n >> nfrag
sizes = _generate_distribution2(n_rows, nfrag)
cols = data.columns.tolist()
data.reset_index(drop=True, inplace=True)
result = create_stage_files(nfrag)
info = []
begin = 0
for i, (n, out) in enumerate(zip(sizes, result)):
partition = data.iloc[begin:begin+n]
begin += n
partition.reset_index(drop=True, inplace=True)
save_stage_file(out, partition)
info.append(generate_info(partition, i))
if len(result) != nfrag:
raise Exception("Error in parallelize function.")
output = {'key_data': ['data'], 'key_info': ['schema'],
'data': result, 'schema': info}
return output
def _generate_distribution1(n_rows, nfrag):
"""
Each fragment will have the same number of rows, except
in fragments at end and that doesnt have more available data.
"""
size = n_rows / nfrag
size = int(np.ceil(size))
sizes = [size for _ in range(nfrag)]
return sizes
def _generate_distribution2(n_rows, nfrag):
"""Data is divided among the partitions."""
size = n_rows / nfrag
size = int(np.ceil(size))
sizes = [size for _ in range(nfrag)]
i = 0
while sum(sizes) > n_rows:
i += 1
sizes[i % nfrag] -= 1
sizes = sorted(sizes, reverse=True)
return sizes
# def import_to_ddf(df_list, parquet=False, schema=None):
# """
# In order to import a list of DataFrames in DDF abstraction, we need to
# check the schema of each partition.
#
# :param df_list: a List of Pandas DataFrames
# :param parquet: if data is saved in parquet files
# :param schema: A list of columns names, data types and size in each fragment
# :return: a List of Pandas DataFrames and a schema
# """
#
# nfrag = len(df_list)
#
# if parquet:
# if schema is None:
# schema = [_get_schema(df_list[f], f) for f in range(nfrag)]
# else:
# outs_files = create_stage_files(nfrag)
# schema = [0 for _ in range(nfrag)]
# for f in range(nfrag):
# schema[f] = _import_to_ddf(df_list[f], outs_files[f], f)
# df_list = outs_files
#
# info_agg = merge_reduce(merge_schema, schema)
# compss_delete_object(schema)
#
# info_agg = compss_wait_on(info_agg)
# schema = _check_schema(info_agg)
#
# output = {'key_data': ['data'], 'key_info': ['schema'],
# 'data': df_list, 'schema': schema}
# return output
def import_to_ddf(df_list, parquet=False, schema=None):
"""
In order to import a list of DataFrames in DDF abstraction, we need to
check the schema of each partition.
:param df_list: a List of Pandas DataFrames
:param parquet: if data is saved in parquet files
:param schema: A list of columns names, data types and size in each fragment
:return: a List of Pandas DataFrames and a schema
"""
nfrag = len(df_list)
if parquet:
if schema is None:
schema = [_get_schema(df_list[f], f) for f in range(nfrag)]
else:
outs_files = create_stage_files(nfrag)
schema = [0 for _ in range(nfrag)]
for f in range(nfrag):
schema[f] = _import_to_ddf(df_list[f], outs_files[f], f)
df_list = outs_files
info_agg = merge_schema(schema)
compss_delete_object(schema)
info_agg = compss_wait_on(info_agg)
info = _check_schema(info_agg)
# output = {'key_data': ['data'], 'key_info': ['schema'],
# 'data': df_list, 'schema': schema}
return df_list, info
def _check_schema(info):
if not isinstance(info, dict):
raise Exception(info)
memory = info['memory']
human_readable = _human_bytes(sum(memory))
avg = _human_bytes(np.mean(memory))
median = _human_bytes(np.median(memory))
print("Memory size of a "
"partition: avg({}), median({})".format(avg, median))
print("Total size of pandas in memory: ", human_readable)
return info
def _human_bytes(size):
"""Return the given bytes as a human friendly KB, MB, GB, or TB string"""
power = 2**10
n = 0
power_of_n = {0: 'B', 1: 'KB', 2: 'MB', 3: 'GB', 4: 'TB'}
while size > power:
size /= power
n += 1
value = "{:.2f} {}".format(size, power_of_n[n])
return value
@task(returns=1, data_out=FILE_OUT)
def _import_to_ddf(df, data_out, f):
info = generate_info(df, f)
save_stage_file(data_out, df)
return info
@task(data_input=FILE_IN, returns=1)
def _get_schema(data_input, f):
df = read_stage_file(data_input)
info = generate_info(df, f)
return info
|
Java
|
UTF-8
| 1,878
| 3.5625
| 4
|
[] |
no_license
|
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class SpriteSheet {
public BufferedImage sheet = null;
public BufferedImage[][] spriteArray = null;
public int sheetCol = 0;
public int sheetRow = 0;
SpriteSheet() {
}
SpriteSheet(String fileName, int sheetCol, int sheetRow){
//Creates file based off of imageFile
File file = new File(fileName);
//Makes a bufferedImage of the image inside the file using ImageIO
try{
sheet = ImageIO.read(file);
}catch(Exception e){
System.out.println("ERROR: couldn't load file (" + fileName + ")");
System.exit(42);
}
this.sheetCol = sheetCol;
this.sheetRow = sheetRow;
spriteArray = getSprites(this.sheetCol, this.sheetRow);
}
//Returns the entire sheet
public BufferedImage getImage(){
return sheet;
}
//Creates a 2D array of all the sprites in our SpriteSheet an returns it
public BufferedImage[][] getSprites(int sheetCol, int sheetRow){
//Our 2 dimensional array
BufferedImage[][] spriteArray = new BufferedImage[sheetCol][sheetRow];
//spriteCol represents our number of Sprite's per row
//spriteRow represents how many rows we have of images
//represents each sprite's dimensions based off given spriteCol and spriteRow
int imgW = sheet.getWidth() / sheetCol;
int imgH = sheet.getHeight() / sheetRow;
//For each sprite in the sheet get its image and store it into the corresponding position in the array
for(int i = 0; i < sheetCol; i++){
for(int j = 0; j < sheetRow; j++){
//getSubimage takes (x,y) position of image and (width, height) of image on the sheet and returns the bufferedImage
spriteArray[i][j] = sheet.getSubimage(i * imgW, j * imgH, imgW, imgH);
}
}
return spriteArray;
}
}
|
Java
|
UTF-8
| 1,645
| 1.929688
| 2
|
[] |
no_license
|
package com.hapmon.mapreduce.aspects;
public class JobDto {
private String jobName;
private String jobId;
private long totalExecutionTime;
private long mapperExecutionTime;
private long reducerExecutionTime;
private String mapperName;
private String reducerName;
private String hostName;
public String getMapperName() {
return mapperName;
}
public void setMapperName(String mapperName) {
this.mapperName = mapperName;
}
public String getReducerName() {
return reducerName;
}
public void setReducerName(String reducerName) {
this.reducerName = reducerName;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public long getTotalExecutionTime() {
return totalExecutionTime;
}
public void setTotalExecutionTime(long totalExecutionTime) {
this.totalExecutionTime = totalExecutionTime;
}
public long getMapperExecutionTime() {
return mapperExecutionTime;
}
public void setMapperExecutionTime(long mapperExecutionTime) {
this.mapperExecutionTime = mapperExecutionTime;
}
public long getReducerExecutionTime() {
return reducerExecutionTime;
}
public void setReducerExecutionTime(long reducerExecutionTime) {
this.reducerExecutionTime = reducerExecutionTime;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
}
|
PHP
|
UTF-8
| 1,226
| 2.5625
| 3
|
[] |
no_license
|
<?php session_start();?>
<?php
// Tout début du code PHP. Situé en haut de la page web
ini_set("display_errors",0);error_reporting(0);
?>
<h1>Liste des comediens</h1>
<a data-rel="dialog" data-transition="pop" href="index.php?action=addCP">Ajout d'un comédien</a><br/><br/>
<ul data-role="listview" class="ui-listview-outer">
<?php foreach($contacts as $info){ ?>
<div data-role="collapsible" >
<h2>
<?php $oneComedien = Passerelle::getOneComedien($info->getIdCom());
echo $oneComedien->getNomC();
echo ' ';
echo $oneComedien->getPrenomC();
?>
</div>
<?php $idCom=$info->getIdCP();
$idCom=$idCom+0;
var_dump($idCom=$info->getIdCP());
?>
<?php echo "<a rel=\"external\" href=\"javascript:deleteEntryCP($idCom)\">Supprimer cette saisie</a>"; ?>
<?php echo $_SESSION['comedien'] = $comedien->getIdP();?>
<?php var_dump($_SESSION['comedien']);?>
<?php }?>
</ul>
|
JavaScript
|
UTF-8
| 871
| 2.859375
| 3
|
[] |
no_license
|
import React, { Component } from 'react'
export default class App extends Component {
constructor() {
super()
this.state = {
message: 'Hello World'
}
}
render() {
return (
<div>
<h2>當前計數: {this.state.message}</h2>
<button onClick={e => this.changeTest()}>改變文本</button>
</div>
)
}
componentDidUpdate() {
console.log(this.state.message, "update")
}
changeTest() {
// this.setState({
// message: "你好阿"
// })
// console.log(this.state.message)
// 如何獲取異步更新後的state
// 回調 or componentDidUpdate
this.setState({
message: "你好阿"
}, () => {
console.log(this.state.message)
})
}
}
//異步更新的兩個原因
// 1. 同步更新性能較差
// 2. 保持props和state維持同步(同步渲染render)
|
PHP
|
UTF-8
| 2,959
| 2.671875
| 3
|
[] |
no_license
|
<?
require_once $_SERVER['DOCUMENT_ROOT' ] . "/src/classes/CCore/globals.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/src/classes/CError/CError.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/src/classes/CRes/CRes.php";
class CStatus
{
public $id = false;
public $entity = false;
public $type = false;
public $title = false;
public $description = false;
public function __construct($id, $entity, $type, $title, $description)
{
$this->id = $id;
$this->entity = $entity;
$this->type = $type;
$this->title = $title;
$this->description = $description;
}
}
class CStatuses
{
public $project_id = false;
public $statuses = false;
public static $table = 'statuses';
public function table(){ return self::$table; }
public function __construct($project_id)
{
if(!is_numeric($project_id))
throw new CError('project_id not numeric',
PROJECT_ID_NOT_NUMERIC);
global $DB;
$q = "SELECT * FROM {$this->table()} WHERE `PROJECT_ID`={$project_id};";
$rows = $DB->CQuery($q)->FetchByKey();
if(!$rows)
{
throw new CError("No statuses for project_id : {$project_id}",
MYSQL_EMPTY_RESULT);
}
$this->statuses = [];
foreach($rows as $row)
{
$id = $row['ID'];
$title = $row['TITLE'];
$entity = $row['ENTITY'];
$type = $row['TYPE'];
$description = $row['DESCRIPTION'];
if(!isset($this->statuses[$entity]))
$this->statuses[$entity] = [];
$this->statuses[$entity][$type] = new CStatus($id, $entity, $type, $title, $description );
}
}
public function get($entity, $type) : CStatus
{
if(!isset($this->statuses[$entity]))
throw new CError("No entity: [{$entity}]",
NO_ENTITY_IN_STATUSES);
if(!isset($this->statuses[$entity][$type]))
throw new CError("No type: [{$type}] for entity : {$entity}",
NO_TYPE_IN_STATUSES);
return $this->statuses[$entity][$type];
}
public function get_by_id($status_id) : CStatus
{
$res = false;
foreach($this->statuses as $entity=>$types)
foreach($types as $status)
if($status->id == $status_id)
{
$res = $status;
break;
}
if(!$res)
throw new CError("No status with status_id: {$status_id}",
NO_STATUS_WITH_ID);
return $res;
}
public function get_ids($entity,$statuses)
{
$ids = [];
foreach($statuses as $status)
$ids[] = $this->get($entity,$status)->id;
return $ids;
}
}
|
C#
|
UTF-8
| 27,299
| 2.6875
| 3
|
[] |
no_license
|
/*==============================================================================================================================
| Author Ignia, LLC
| Client Ignia, LLC
| Project Topics Library
\=============================================================================================================================*/
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using OnTopic.Attributes;
using OnTopic.Internal.Diagnostics;
using OnTopic.Querying;
namespace OnTopic.Data.Transfer.Interchange {
/*============================================================================================================================
| CLASS: TOPIC EXTENSIONS
\---------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// The <see cref="TopicExtensions"/> class provides extension methods for <see cref="Topic"/> for converting entities to
/// and from <see cref="TopicData"/> data transfer objects.
/// </summary>
/// <remarks>
/// The serialization and deserialization of <see cref="TopicData"/> is intended to be a simple, fast, and predictable
/// process since it's simply translating the JSON representation into a .NET class. By contrast, converting a <see
/// cref="TopicData"/> graph into a <see cref="Topic"/> graph—or vice versa—requires far more care. As such, these extension
/// methods should really be viewed as the heart of the import/export process; this is where all of the business logic,
/// user options, and safety checks will take place.
/// </remarks>
public static class TopicExtensions {
/*==========================================================================================================================
| RESERVED ATTRIBUTE KEYS
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Represents attribute keys that should not be stored in the <see cref="TopicData.Attributes"/> collection.
/// </summary>
private static string[] ReservedAttributeKeys { get; } = new string[] {
"Key",
"ParentID",
"ContentType",
"TopicID"
};
/*==========================================================================================================================
| EXPORT
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Exports a <see cref="Topic"/> entity—and, potentially, its descendants—into a <see cref="TopicData"/> data transfer
/// object.
/// </summary>
/// <param name="topic">The source <see cref="Topic"/> to operate off of.</param>
/// <param name="options">An optional <see cref="ExportOptions"/> object to specify export settings.</param>
public static TopicData Export(this Topic topic, [NotNull]ExportOptions? options = null) {
/*------------------------------------------------------------------------------------------------------------------------
| Validate topic
\-----------------------------------------------------------------------------------------------------------------------*/
Contract.Requires(topic, nameof(topic));
/*------------------------------------------------------------------------------------------------------------------------
| Establish default options
\-----------------------------------------------------------------------------------------------------------------------*/
if (options is null) {
options = new();
}
options.ExportScope ??= topic.GetUniqueKey();
/*------------------------------------------------------------------------------------------------------------------------
| Set primary properties
\-----------------------------------------------------------------------------------------------------------------------*/
var topicData = new TopicData {
Key = topic.Key,
UniqueKey = topic.GetUniqueKey(),
ContentType = topic.ContentType
};
/*------------------------------------------------------------------------------------------------------------------------
| Set attributes
\-----------------------------------------------------------------------------------------------------------------------*/
var attributes = topic.Attributes.Where(a =>
!ReservedAttributeKeys.Any(r =>
r.Equals(a.Key, StringComparison.OrdinalIgnoreCase)
)
);
foreach (var attribute in attributes) {
var attributeValue = getAttributeValue(attribute);
if (String.IsNullOrEmpty(attributeValue)) {
continue;
}
topicData.Attributes.Add(
new() {
Key = attribute.Key,
Value = attributeValue,
LastModified = attribute.LastModified
}
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Set topic references
\-----------------------------------------------------------------------------------------------------------------------*/
foreach (var reference in topic.References) {
if (
!options.IncludeExternalAssociations &&
!(reference.Value?.GetUniqueKey().StartsWith(options.ExportScope, StringComparison.InvariantCultureIgnoreCase)?? true)
) {
continue;
}
topicData.References.Add(
new() {
Key = reference.Key,
Value = reference.Value?.GetUniqueKey(),
LastModified = reference.LastModified
}
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Set relationships
\-----------------------------------------------------------------------------------------------------------------------*/
foreach (var relationship in topic.Relationships) {
var relationshipData = new KeyValuesPair() {
Key = relationship.Key,
};
foreach (var relatedTopic in relationship.Values) {
if (
options.IncludeExternalAssociations ||
relatedTopic.GetUniqueKey().StartsWith(options.ExportScope, StringComparison.InvariantCultureIgnoreCase)
) {
relationshipData.Values.Add(relatedTopic.GetUniqueKey());
}
}
if (relationshipData.Values.Count > 0) {
topicData.Relationships.Add(relationshipData);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Recurse over children
\-----------------------------------------------------------------------------------------------------------------------*/
foreach (var childTopic in topic.Children) {
if (
options.IncludeChildTopics ||
topic.ContentType is "List" ||
options.IncludeNestedTopics &&
childTopic.ContentType is "List"
) {
topicData.Children.Add(
childTopic.Export(options)
);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Return topic
\-----------------------------------------------------------------------------------------------------------------------*/
return topicData;
/*------------------------------------------------------------------------------------------------------------------------
| Get attribute value
\-----------------------------------------------------------------------------------------------------------------------*/
string? getAttributeValue(AttributeRecord attribute) =>
options.TranslateLegacyTopicReferences && attribute.Key.EndsWith("ID", StringComparison.InvariantCultureIgnoreCase)?
GetUniqueKey(topic, attribute.Value, options) :
attribute.Value;
}
/*==========================================================================================================================
| IMPORT
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Imports a <see cref="TopicData"/> data transfer object—and, potentially, its descendants—into an existing <see
/// cref="Topic"/> entity.
/// </summary>
/// <param name="topic">The source <see cref="Topic"/> to operate off of.</param>
/// <param name="topicData">The source <see cref="TopicData"/> graph to import into the <paramref name="topic"/>.</param>
/// <param name="options">An optional <see cref="ImportOptions"/> object to specify import settings.</param>
public static void Import(this Topic topic, TopicData topicData, [NotNull]ImportOptions? options = null) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish cache
\-----------------------------------------------------------------------------------------------------------------------*/
var unresolvedAssociations = new List<UnresolvedAssociation>();
/*------------------------------------------------------------------------------------------------------------------------
| Handle first pass
\-----------------------------------------------------------------------------------------------------------------------*/
topic.Import(topicData, options, unresolvedAssociations);
/*------------------------------------------------------------------------------------------------------------------------
| Attempt to resolve outstanding assocations
\-----------------------------------------------------------------------------------------------------------------------*/
foreach (var association in unresolvedAssociations) {
//Attempt to find the target association
var target = topic.GetByUniqueKey(association.TargetTopicKey);
//If the association STILL can't be resolved, skip it
if (target is null) {
continue;
}
//Wire up relationships
else if (association.AssociationType is AssociationType.Relationship) {
association.SourceTopic.Relationships.SetValue(association.Key, target);
}
//Wire up topic references
else {
association.SourceTopic.References.SetValue(association.Key, target);
}
}
}
/// <summary>
/// Imports a <see cref="TopicData"/> data transfer object—and, potentially, its descendants—into an existing <see
/// cref="Topic"/> entity. Track unmatched relationships.
/// </summary>
/// <remarks>
/// <para>
/// While traversing a topic graph with many new topics, scenarios emerge where the topic graph cannot be fully
/// reconstructed since the relationships and referenced topics may refer to new topics that haven't yet been imported.
/// To mitigate that, this overload accepts and populates a cache of such associations, so that they can be recreated
/// afterwards.
/// </para>
/// <para>
/// This does <i>not</i> address the scenario where implicit topic pointers (i.e., attributes ending in <c>Id</c>)
/// cannot be resolved because the target topics haven't yet been saved—and, therefore, the <see cref="Topic.
/// GetUniqueKey"/> cannot be translated to a <see cref="Topic.Id"/>. There isn't any obvious way to address this via
/// <see cref="Import(Topic, TopicData, ImportOptions?)"/> directly.
/// </para>
/// </remarks>
/// <param name="topic">The target <see cref="Topic"/> to write data to.</param>
/// <param name="topicData">The source <see cref="TopicData"/> to import data from.</param>
/// <param name="options">An optional <see cref="ImportOptions"/> object to specify import settings.</param>
/// <param name="unresolvedAssociations">A list of associations that could not be resolved on the first </param>
private static void Import(
this Topic topic,
TopicData topicData,
[NotNull]ImportOptions? options,
List<UnresolvedAssociation> unresolvedAssociations
) {
/*------------------------------------------------------------------------------------------------------------------------
| Validate topic
\-----------------------------------------------------------------------------------------------------------------------*/
Contract.Requires(topic, nameof(topic));
Contract.Requires(topicData, nameof(topicData));
/*------------------------------------------------------------------------------------------------------------------------
| Establish default options
\-----------------------------------------------------------------------------------------------------------------------*/
if (options is null) {
options = new() {
Strategy = ImportStrategy.Add
};
};
/*------------------------------------------------------------------------------------------------------------------------
| Detect mismatches
\-----------------------------------------------------------------------------------------------------------------------*/
if (topic.GetUniqueKey() != topicData.UniqueKey) {
throw new ArgumentException(
$"A topic with the unique key of '{topicData.UniqueKey}' cannot be created under a topic with the unique key of " +
$"{topic.GetUniqueKey()}."
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Set primary properties
\-----------------------------------------------------------------------------------------------------------------------*/
if (options.OverwriteContentType) {
topic.ContentType = topicData.ContentType;
}
#pragma warning disable CS0618 // Type or member is obsolete
if (topicData.DerivedTopicKey?.Length > 0 && !topicData.References.Contains("BaseTopic")) {
topicData.References.Add(
new() {
Key = "BaseTopic",
Value = topicData.DerivedTopicKey
}
);
}
#pragma warning restore CS0618 // Type or member is obsolete
/*------------------------------------------------------------------------------------------------------------------------
| Migrate legacy topic references
>-------------------------------------------------------------------------------------------------------------------------
| Previous versions of the OnTopic Data Transfer library identified attributes that ended with `Id` and had a value that
| mapped to a `topic.Id` and translated their values to `topic.GetUniqueKey()` so that they could be translated back to
| topic references. As of OnTopic 5 and OnTopic Data Transfer 3, this functionality is now formalized as `topic.
| References`. The following provides legacy support for this encoding by migrating these attributes to `topicData.
| References`, thus allowing them to be handled the same way as other topic references.
\-----------------------------------------------------------------------------------------------------------------------*/
foreach (var attribute in topicData.Attributes.ToList()) {
if (
attribute.Value is not null &&
attribute.Key.EndsWith("ID", StringComparison.InvariantCultureIgnoreCase) &&
attribute.Value.StartsWith("Root", StringComparison.InvariantCultureIgnoreCase)
) {
var referenceKey = attribute.Key.Substring(0, attribute.Key.Length-2);
if (referenceKey is "Topic") {
referenceKey = "BaseTopic";
}
if (!topicData.References.Contains(referenceKey)) {
attribute.Key = referenceKey;
topicData.Attributes.Remove(attribute);
topicData.References.Add(attribute);
}
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Set attributes
\-----------------------------------------------------------------------------------------------------------------------*/
//First delete any unmatched records, if appropriate
if (options.DeleteUnmatchedAttributes) {
var unmatchedAttributes = topic.Attributes.Where(a1 =>
!ReservedAttributeKeys.Contains(a1.Key) &&
!topicData.Attributes.Any(a2 => a1.Key == a2.Key)
);
foreach (var attribute in unmatchedAttributes.ToArray()) {
topic.Attributes.Remove(attribute);
};
}
//Update records based on the source collection
foreach (var attribute in topicData.Attributes) {
if (useCustomMergeRules(attribute)) continue;
var matchedAttribute = topic.Attributes.FirstOrDefault(a => a.Key == attribute.Key);
if (matchedAttribute is not null && isStrategy(ImportStrategy.Add)) continue;
if (matchedAttribute?.LastModified >= attribute.LastModified && isStrategy(ImportStrategy.Merge)) continue;
topic.Attributes.SetValue(
attribute.Key,
attribute.Value
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle special rules for LastModified(By) attribute
\-----------------------------------------------------------------------------------------------------------------------*/
if (topic.Attributes.IsDirty()) {
if (options.LastModifiedStrategy is LastModifiedImportStrategy.Current or LastModifiedImportStrategy.System) {
topic.Attributes.SetValue("LastModified", DateTime.Now.ToString(CultureInfo.CurrentCulture));
}
switch (options.LastModifiedByStrategy) {
case LastModifiedImportStrategy.Current:
topic.Attributes.SetValue("LastModifiedBy", options.CurrentUser);
break;
case LastModifiedImportStrategy.System:
topic.Attributes.SetValue("LastModifiedBy", "System");
break;
}
if (topic.Attributes.GetValue("LastModified", null) is null) {
topic.Attributes.SetValue("LastModified", DateTime.Now.ToString(CultureInfo.CurrentCulture));
}
if (topic.Attributes.GetValue("LastModifiedBy", null) is null) {
topic.Attributes.SetValue("LastModifiedBy", options.CurrentUser);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Set relationships
\-----------------------------------------------------------------------------------------------------------------------*/
//First delete any unmatched records, if appropriate
if (options.DeleteUnmatchedRelationships) {
foreach (var relationship in topic.Relationships) {
topic.Relationships.Clear(relationship.Key);
}
}
//Update records based on the source collection
foreach (var relationship in topicData.Relationships) {
foreach (var relatedTopicKey in relationship.Values) {
var relatedTopic = topic.GetByUniqueKey(relatedTopicKey);
if (relationship.Key is not null && relatedTopic is not null) {
topic.Relationships.SetValue(relationship.Key, relatedTopic);
}
else {
unresolvedAssociations.Add(new(AssociationType.Relationship, relatedTopicKey, topic, relatedTopicKey));
}
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Set topic references
\-----------------------------------------------------------------------------------------------------------------------*/
//First delete any unmatched records, if appropriate
if (options.DeleteUnmatchedReferences) {
var unmatchedReferences = topic.References.Where(a1 =>
!topicData.References.Any(a2 => a1.Key == a2.Key)
);
foreach (var reference in unmatchedReferences.ToArray()) {
topic.References.Remove(reference);
};
}
//Update records based on the source collection
foreach (var reference in topicData.References) {
var matchedReference = topic.References.FirstOrDefault(a => a.Key == reference.Key);
if (matchedReference is not null && isStrategy(ImportStrategy.Add)) continue;
if (matchedReference?.LastModified >= reference.LastModified && isStrategy(ImportStrategy.Merge)) continue;
var referencedTopic = topic.GetByUniqueKey(reference.Key);
if (reference.Value is null || referencedTopic != null) {
topic.References.SetValue(
reference.Key,
referencedTopic
);
}
else {
unresolvedAssociations.Add(new(AssociationType.Reference, reference.Key, topic, reference.Value));
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Recurse over children
\-----------------------------------------------------------------------------------------------------------------------*/
//First delete any unmatched records, if appropriate
if (options.DeleteUnmatchedChildren || options.DeleteUnmatchedNestedTopics) {
foreach (var child in topic.Children.Where(t1 => !topicData.Children.Any(t2 => t1.Key == t2.Key)).ToArray()) {
if (
topic.ContentType is "List" && options.DeleteUnmatchedNestedTopics ||
topic.ContentType is not "List" && options.DeleteUnmatchedChildren
) {
topic.Children.Remove(child);
}
};
}
//Update records based on the source collection
foreach (var childTopicData in topicData.Children) {
var childTopic = topic?.Children.GetValue(childTopicData.Key);
if (childTopic is null) {
childTopic = TopicFactory.Create(childTopicData.Key, childTopicData.ContentType, topic);
}
childTopic.Import(childTopicData, options, unresolvedAssociations);
}
/*------------------------------------------------------------------------------------------------------------------------
| Is strategy?
\-----------------------------------------------------------------------------------------------------------------------*/
bool isStrategy(params ImportStrategy[] strategies) => strategies.Contains<ImportStrategy>(options!.Strategy);
/*------------------------------------------------------------------------------------------------------------------------
| Is custom merge rules?
\-----------------------------------------------------------------------------------------------------------------------*/
bool useCustomMergeRules(RecordData attribute) =>
(attribute.Key is "LastModified" && options!.LastModifiedStrategy is not LastModifiedImportStrategy.Inherit) ||
(attribute.Key is "LastModifiedBy" && options!.LastModifiedByStrategy is not LastModifiedImportStrategy.Inherit);
}
/*==========================================================================================================================
| GET UNIQUE KEY
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Given a <c>TopicID</c>, lookup the topic in the topic graph and return the fully-qualified value. If no value can be
/// found, the original <c>TopicID</c> is returned.
/// </summary>
/// <remarks>
/// Note that this function is <i>exclusively</i> required for maintaining backward compatibility the <see cref="
/// ExportOptions.TranslateLegacyTopicReferences"/> option/ With the release of OnTopic 5.0.0, and OnTopic Data Transfer
/// 2.0.0, implementers should prefer the use of <see cref="Topic.References"/>. The <see cref="GetUniqueKey(Topic,
/// String?, ExportOptions)"/> method continues to be included primarily for backward compatibility with legacy database
/// configurations.
/// </remarks>
/// <param name="topic">The source <see cref="Topic"/> to operate off of.</param>
/// <param name="topicId">The <see cref="Topic.Id"/> to retrieve the <see cref="Topic.GetUniqueKey"/> for.</param>
/// <param name="options">An optional <see cref="ExportOptions"/> object to specify export settings.</param>
private static string? GetUniqueKey(Topic topic, string? topicId, ExportOptions options) {
/*------------------------------------------------------------------------------------------------------------------------
| Ignore empty or non-numeric values
\-----------------------------------------------------------------------------------------------------------------------*/
if (String.IsNullOrEmpty(topicId) || !Int32.TryParse(topicId, out var id)) {
return topicId;
}
/*------------------------------------------------------------------------------------------------------------------------
| Establish scope
\-----------------------------------------------------------------------------------------------------------------------*/
var uniqueKey = topic.GetRootTopic().FindFirst(t => t.Id == id)?.GetUniqueKey();
var exportScope = options.IncludeExternalAssociations? "Root" : options.ExportScope;
/*------------------------------------------------------------------------------------------------------------------------
| Return in-scope values
\-----------------------------------------------------------------------------------------------------------------------*/
if (uniqueKey?.StartsWith(exportScope, StringComparison.InvariantCultureIgnoreCase)?? false) {
return uniqueKey;
}
/*------------------------------------------------------------------------------------------------------------------------
| Default to null
\-----------------------------------------------------------------------------------------------------------------------*/
return null;
}
} //Class
} //Namespace
|
PHP
|
UTF-8
| 1,791
| 2.875
| 3
|
[] |
no_license
|
<?php
include('database.txt');
try
{
$dbh = new PDO('mysql:host='.$server.';port='.$port.';dbname='.$dbname, $user, $pass);
} catch (PDOException $e) {
print $e->getMessage();
exit;
}
$boss_id = $_GET['boss_id'];
?>
<html>
<head>
<title>Daniel Order</title>
</head>
<body bgcolor="white">
<?php
$query = "SELECT * FROM rest.boss WHERE boss_id=".$boss_id;
$result = $dbh->query($query);
if (!$result)
{
print "1 execution error: </br>";
$error = $dbh->errorInfo();
print($error[2]);
exit;
}
$row = $result->fetch();
$boss_name = $row['boss_name'];
?>
<h1>Welcome!!! <?php print $boss_name; ?>!!!</h1>
<h2>Choose a restaurant to edit.</h2>
<?php
$query2 = "SELECT * FROM rest.rests WHERE boss_id=".$boss_id;
?>
<font size="5">
<select name='rest' form="select">
<?php
$result = $dbh->query($query2);
if (!$result)
{
print "execution error: </br>";
$error = $dbh->errorInfo();
print($error[2]);
exit;
}
while($row = $result->fetch())
{
print "<option value=".$row['rest_name'].">".$row['rest_name']."</option>";
}
//$dbh = null;
?>
</select>
<br>
<br>
<?php
print "<form action='bos_resman_trans.php?boss_id=".$boss_id."' method='post' id='select'>";
print "<input name='sub_but' type='submit' value='Submit'>";
print " ";
print "<input name='sub_but' type='submit' value='I want to edit my information'>";
print " ";
print "<input name='sub_but' type='submit' value='Open a new restaurant!'>";
print " ";
print "<input name='sub_but' type='submit' value='Log out!'>";
print "</form>";
$dbh=null;
?>
</font>
</body>
</html>
|
PHP
|
UTF-8
| 15,352
| 2.546875
| 3
|
[] |
no_license
|
<?php
require_once('../classes/db.class.php');
require_once('../classes/ralph.php');
$db = new db_class;
// Open up the database connection.
if (!$db->connect())
$db->print_last_error(false);
if(isset($_POST['submit'])) {
/*
foreach($_POST as $value){
print "<pre>";
print $value;
print "</pre>";
}
*
*/
$filterString = "";
$locaties=array();
//----------------------------------
$postcodeGebieden = array();
$pcSQL = "SELECT * FROM user_postcode";
$pcResult = mysql_query($pcSQL);
while($pcRows = mysql_fetch_array($pcResult))
{
$postcodeGebieden[$pcRows['id']] = $pcRows['postcodegebied'];
}
//----------------------------------
//----------------------------------
$ervaringen = array();
$ervaringSQL = "SELECT * FROM user_ervaring";
$ervaringResult = mysql_query($ervaringSQL);
while($ervaringRows = mysql_fetch_array($ervaringResult))
{
$ervaringen[$ervaringRows['id']] = $ervaringRows['ervaring'];
}
//----------------------------------
//----------------------------------
$samenstellingen = array();
$samenstellingSQL = "SELECT * FROM user_samenstellingen";
$samenstellingResult = mysql_query($samenstellingSQL);
while($samenstellingRows = mysql_fetch_array($samenstellingResult))
{
$samenstellingen[$samenstellingRows['id']] = $samenstellingRows['samenstelling'];
}
//----------------------------------
//----------------------------------
$gesl = array();
$geslSQL = "SELECT * FROM user_geslacht";
$geslResult = mysql_query($geslSQL);
while($geslRows = mysql_fetch_array($geslResult))
{
$gesl[$geslRows['id']] = $geslRows['geslacht'];
}
//----------------------------------
//----------------------------------
$autobezit = array();
$autobezitSQL = "SELECT * FROM user_auto";
$autobezitResult = mysql_query($autobezitSQL);
while($autobezitRows = mysql_fetch_array($autobezitResult))
{
$autobezit[$autobezitRows['id']] = $autobezitRows['autobezit'];
}
//----------------------------------
//----------------------------------
$opleidingen = array();
$opleidingenSQL = "SELECT * FROM user_opleidingen";
$opleidingenResult = mysql_query($opleidingenSQL);
while($opleidingenRows = mysql_fetch_array($opleidingenResult))
{
$opleidingen[$opleidingenRows['id']] = $opleidingenRows['opleiding'];
}
//----------------------------------
$rn = 1;
if($_POST['tag'] <> 0) {
$locatieSQL = "SELECT
app_tags.tag,
app_locaties.id AS id,
app_locaties.locatie AS locatie,
app_locaties.thumb AS thumb
FROM
app_locaties
Inner Join app_locaties_tags ON app_locaties.id = app_locaties_tags.locatie_id
Inner Join app_tags ON app_locaties_tags.tag = app_tags.id
WHERE
app_locaties_tags.tag = '".$_POST['tag']."' AND actief = 1";
}
/*
else{
$locatieSQL = "SELECT
app_locaties.id as id,
app_locaties.locatie AS locatie,
app_locaties.thumb AS thumb
FROM app_locaties";
}
*/
$locatieResult = mysql_query($locatieSQL);
while($row = mysql_fetch_array($locatieResult))
{
$cijferArray = array();
for($i=0; $i <=10; $i++)
{
array_push($cijferArray, 0);
}
$locaties[$row['id']] = array('locatie' => $row['locatie'],
'thumb' => $row['thumb'],
'cijferlijst' => $cijferArray);
}
$joinSQL = " INNER JOIN users ON app_stemmentotaal.user_id = users.id ";
$filterSQL = "";
if($_POST['ervaring'] && $_POST['ervaring'] != "")
{
$joinSQL .= " INNER JOIN user_ervaring ON users.user_ervaring = user_ervaring.id ";
$filterSQL .= " AND users.user_ervaring = '".$_POST['ervaring']."' ";
$filterString .= "ervaring is ". $ervaringen[$_POST['ervaring']] .", <br> ";
}
if($_POST['minGebJaar'] && $_POST['minGebJaar'] != "")
{
$filterSQL .= " AND users.user_geb_datum > '".$_POST['minGebJaar']."' ";
$filterString .= "geboortejaar van " . $_POST['minGebJaar'] .", ";
}
if($_POST['maxGebJaar'] && $_POST['maxGebJaar'] != "")
{
$filterSQL .= " AND users.user_geb_datum < '".$_POST['maxGebJaar']."' ";
$filterString .= "geboortejaar tot is " . $_POST['maxGebJaar'] .", <br>";
}
if($_POST['postcode'] && $_POST['postcode'] != "")
{
$joinSQL .= " INNER JOIN user_postcode ON users.user_postcodegebied = user_postcode.id ";
$filterSQL .= " AND users.user_postcodegebied = '".$_POST['postcode']."' ";
$filterString .= "postcodegebied is " . $postcodeGebieden[$_POST['postcode']] .", <br>";
}
if($_POST['samenstelling'] && $_POST['samenstelling'] != "")
{
$joinSQL .= " INNER JOIN user_samenstellingen ON users.user_samenstelling = user_samenstellingen.id ";
$filterSQL .= " AND users.user_samenstelling = '".$_POST['samenstelling']."' ";
$filterString .= "samenstelling is " . $samenstellingen[$_POST['samenstelling']] .", <br>";
}
if($_POST['autobezit'] && $_POST['autobezit'] != "")
{
$joinSQL .= " INNER JOIN user_auto ON users.user_auto = user_auto.id ";
$filterSQL .= " AND users.user_auto = '".$_POST['autobezit']."' ";
$filterString .= "autobezit is " . $autobezit[$_POST['autobezit']] .", <br>";
}
if($_POST['geslacht'] && $_POST['geslacht'] != "")
{
$joinSQL .= " INNER JOIN user_geslacht ON users.user_geslacht = user_geslacht.id ";
$filterSQL .= " AND users.user_geslacht = '".$_POST['geslacht']."' ";
$filterString .= "geslacht is " . $gesl[$_POST['geslacht']] .", <br>";
}
if($_POST['opleiding'] && $_POST['opleiding'] != "")
{
$joinSQL .= " INNER JOIN user_opleidingen ON users.user_opleiding = user_opleidingen.id ";
$filterSQL .= " AND users.user_opleiding = '".$_POST['opleiding']."' ";
$filterString .= "opleiding is " . $opleidingen[$_POST['opleiding']] .", <br>";
}
$filterString = substr($filterString, 0, strlen($filterString)-2);
//-----------------------------------
$totalSQL = "SELECT * FROM app_stemmentotaal ". $joinSQL . " WHERE 1 ". $filterSQL ;
//----------------------------------
$filterResult = mysql_query($totalSQL) or die(mysql_error());
$filterResultArray = array();
while ($row2 = mysql_fetch_assoc($filterResult))
{
foreach ($row2 as $col => $value)
{
if(substr($col, 0, 1) == "_")
{
$locatieId = substr($col,1);
$locaties[$locatieId]['cijferlijst'][$value]++;
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Haarlem Smaaktest</title>
<link href="_css/uitslag.css" rel="stylesheet" type="text/css" />
</head>
<body bgcolor="#FFFFFF">
<div id='wrapper'>
<br />
<table width="400" align="center" cellpadding="5" cellspacing="2" bordercolor="#FFFFFF">
<tr>
<td colspan="15" style='padding-top:15px;padding-botttom:0px;'><input type="hidden" name="id" value="1" />
Gefilterd op basis van: <?=$filterString?></td>
</tr>
<tr>
<td > </td>
<td colspan="14" bgcolor="#D6605C">Aantal stemmen per foto</td>
</tr>
<tr>
<td align="center"> </td>
<td align="center">Foto</td>
<td align="center" style='background-color:#9C0606'>0</td>
<td align="center" bgcolor="#0000FF">1</td>
<td align="center" style='background-color:#E3412C'>2</td>
<td align="center">3</td>
<td align="center" style='background-color:#E3412C'>4</td>
<td align="center">5</td>
<td align="center" style='background-color:#E3412C'>6</td>
<td align="center">7</td>
<td align="center" style='background-color:#E3412C'>8</td>
<td align="center">9</td>
<td align="center" style='background-color:#E3412C'>10</td>
<td align="center">Totaal</td>
<td align="center">Gemiddeld</td>
</tr>
<?
$rowIndex = 0;
foreach($locaties as $locatie)
{
$totaal = 0;
$totaalStemmen = 0;
$gemiddeld = 0;
for($i=0; $i<=10;$i++)
{
$totaalStemmen += $locatie['cijferlijst'][$i];
$totaal += $i * $locatie['cijferlijst'][$i];
}
if($totaalStemmen == 0){
$gemiddeld = 0;
}else{
$gemiddeld = $totaal / $totaalStemmen;
}
if($rowIndex % 2)
{
$rowStyle = "class='alternate'";
}
$rowIndex++;
?>
<tr <?=$rowStyle?>>
<td class="overzicht_table"><div align="left"><?=$locatie['locatie']?></div></td>
<td class="overzicht_table"><img src="../uploads/<?=$locatie['thumb']?>" width="100" border="0" /></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][0]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][1]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][2]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][3]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][4]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][5]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][6]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][7]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][8]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][9]?></td>
<td class="overzicht_table"><?=$locatie['cijferlijst'][10]?></td>
<td class="overzicht_table"><?=$totaalStemmen?></td>
<td class="overzicht_table"><?=round($gemiddeld, 1)?></td>
</tr>
<?
}
?>
</table>
</div>
<?
/*
$sql = "SELECT
app_tags.tag,
app_locaties.id AS id,
app_locaties.locatie AS locatie
FROM
app_locaties
Inner Join app_locaties_tags ON app_locaties.id = app_locaties_tags.locatie_id
Inner Join app_tags ON app_locaties_tags.tag = app_tags.id
WHERE app_locaties_tags.tag = '".$_POST['tag']."' AND actief = 1";
} else {
$sql = "SELECT
app_locaties.id AS id,
app_locaties.locatie AS locatie
FROM
app_locaties
Inner Join app_locaties_tags ON app_locaties.id = app_locaties_tags.locatie_id
Inner Join app_tags ON app_locaties_tags.tag = app_tags.id
WHERE actief = 1";
}
$r = mysql_query($sql);
$aantal = mysql_num_rows($r);
echo "aantal is: ". $aantal;
//echo $sql."<br /><br />";
if($aantal == 0 ) { echo "Geen resultaten gevonden";} else{
while ($row = mysql_fetch_assoc($r)) {
$loc = "_".$row['id'];
echo "id is: ". $row['id']. "- ". $row['tag'];
$sql2 = "SELECT AVG($loc) AS gemiddeld, app_stemmentotaal.user_id,
users.user_geb_datum,
users.id,
user_ervaring.ervaring,
user_postcode.postcodegebied,
user_samenstellingen.samenstelling,
user_auto.autobezit,
user_geslacht.geslacht,
users.user_opleiding,
user_opleidingen.opleiding
FROM app_stemmentotaal
INNER JOIN users ON app_stemmentotaal.user_id = users.id
INNER JOIN user_ervaring ON users.user_ervaring = user_ervaring.id
INNER JOIN user_postcode ON users.user_postcodegebied = user_postcode.id
INNER JOIN user_samenstellingen ON users.user_samenstelling = user_samenstellingen.id
INNER JOIN user_auto ON users.user_auto = user_auto.id
INNER JOIN user_geslacht ON users.user_geslacht = user_geslacht.id
INNER JOIN user_opleidingen ON users.user_opleiding = user_opleidingen.id
WHERE users.user_ervaring = '".$_POST['ervaring']."'
AND users.user_geb_datum > '".$_POST['minGebJaar']."'
AND users.user_geb_datum < '".$_POST['maxGebJaar']."'
AND users.user_postcodegebied = '".$_POST['postcode']."'
AND users.user_samenstelling = '".$_POST['samenstelling']."'
AND users.user_auto = '".$_POST['autobezit']."'
AND users.user_geslacht = '".$_POST['geslacht']."'
AND users.user_opleiding = '".$_POST['opleiding']."'
" or die ("NO RESULTS");
$r2 = mysql_query($sql2);
//echo $sql2. "<br /><br />";
while ($row2 = mysql_fetch_assoc($r2)) {
array_push($locaties,array('locatie_id'=> $row['id'],
'locatie_naam'=> $row['locatie'],
'gemiddelde' => $row2['gemiddeld'],
'tag' => $row['tag']
));
}
}
$locaties = subval_sort($locaties,'gemiddelde');
print '<pre>';
print_r($locaties);
print '</pre>';
echo "<table width=\"500\">";
echo "<tr><td>Locatie</td><td>Cijfer</td></tr>";
//for($i=0;$i<3;$i++)
foreach($locaties as $value)
{
if($value['gemiddelde'] =="") { echo "<tr><td>".$value['locatie_naam']."</td><td>Geen cijfer gevonden</td></tr>"; } else {
echo "<tr><td>".$value['locatie_naam']."</td><td>". str_replace(".",",",round($value['gemiddelde'],1))."</td></tr>"; }
}
echo "</table>";
}
*
*
*/
} else {
?>
<br />
<?php echo "Deze test is <strong>" .count_test(). "</strong> gedaan"; ?><br />
Huidige Top 3:
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="form1">
<table width="100%" border="0">
<tr>
<td>Geslacht:</td>
<td> <?php $db->radio_query("SELECT id, geslacht FROM user_geslacht",'geslacht'); ?></td>
</tr>
<tr>
<td>Ervaring:</td>
<td> <?php $db->pulldown_query("SELECT id, ervaring FROM user_ervaring",'ervaring'); ?></td>
</tr>
<tr>
<td>Samenstelling:</td>
<td> <?php $db->pulldown_query("SELECT id, samenstelling FROM user_samenstellingen",'samenstelling'); ?></td>
</tr>
<tr>
<td>Postcode:</td>
<td> <?php $db->pulldown_query("SELECT id, postcodegebied FROM user_postcode",'postcode'); ?></td>
</tr>
<tr>
<td>Auto:</td>
<td> <?php $db->checkbox_query("SELECT id,autobezit FROM user_auto",'autobezit'); ?></td>
</tr>
<tr>
<td>Opleiding</td>
<td> <?php $db->pulldown_query("SELECT id, opleiding FROM user_opleidingen",'opleiding'); ?></td>
</tr>
<tr>
<td>tags</td>
<td> <?php $db->pulldown_query("SELECT id, tag FROM app_tags",'tag'); ?></td>
</tr>
<tr>
<td>Geboortejaar</td>
<td> van <select name="minGebJaar">
<?php
for ($minyear = 1900; $minyear < date("Y"); $minyear++) {
?>
<option value="<?php echo $minyear; ?>"><?php echo $minyear; ?></option>
<?php } ?>
</select>
tot <select name="maxGebJaar">
<?php
for ($maxyear = date("Y"); $maxyear > 1900; $maxyear--) {
?>
<option value="<?php echo $maxyear; ?>"><?php echo $maxyear; ?></option>
<?php } ?>
</select></td>
</tr>
<tr>
<td> </td>
<td> <input name="submit" type="submit" value="haal gegevens op" /></td>
</tr>
</table>
</form>
<?php } ?>
<?php makevotelist();?>
</body>
</html>
|
Java
|
UTF-8
| 116
| 1.945313
| 2
|
[] |
no_license
|
package com.gorecode.vk.utilities;
public interface TimeFormatter {
public String format(long timeMillis);
}
|
Markdown
|
UTF-8
| 1,945
| 3.96875
| 4
|
[] |
no_license
|
# 1788. Maximize the Beauty of the Garden
## Level
Hard
## Description
There is a garden of `n` flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array `flowers` of size `n` and each `flowers[i]` represents the beauty of the `i-th` flower.
A garden is **valid** if it meets these conditions:
* The garden has at least two flowers.
* The first and the last flower of the garden have the same beauty value.
As the appointed gardener, you have the ability to **remove** any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden **valid**. The beauty of the garden is the sum of the beauty of all the remaining flowers.
Return the maximum possible beauty of some **valid** garden after you have removed any (possibly none) flowers.
**Example 1:**
**Input:** flowers = [1,2,3,1,2]
**Output:** 8
**Explanation:** You can produce the valid garden [2,3,1,2] to have a total beauty of 2 + 3 + 1 + 2 = 8.
**Example 2:**
**Input:** flowers = [100,1,1,-3,1]
**Output:** 3
**Explanation:** You can produce the valid garden [1,1,1] to have a total beauty of 1 + 1 + 1 = 3.
**Example 3:**
**Input:** flowers = [-1,-2,0,-1]
**Output:** -2
**Explanation:** You can produce the valid garden [-1,-1] to have a total beauty of -1 + -1 = -2.
**Constraints:**
* `2 <= flowers.length <= 10^5`
* `-10^4 <= flowers[i] <= 10^4`
* It is possible to create a valid garden by removing some (possibly none) flowers.
## Solution
First, calculate the prefix sums of `flowers`, but for each element in `flowers`, only remain 0 and positive values, and make the negative values become 0.
Next, use a hash map to store each `flowers[i]`'s first occurrence in `flowers`. Loop over `flowers`. For each `flowers[i]`, obtain its first occurrence and calculate the subarray sum of the prefix sums array. Maintain the maximum beauty and return.
|
Python
|
UTF-8
| 5,158
| 3.046875
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 13:33:20 2020
@author: mason
"""
import numpy as np
import pandas as pd
s = pd.Series([1,3,5,np.nan,6,8])
s
df = pd.DataFrame({'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index = list(range(4)), dtype = 'float32'),
'D': np.array([3]*4, dtype = 'int32'),
'E': pd.Categorical(["test", "train", "test", "train"]),
'F': 'foo'})
df
dates = pd.date_range('20130101', periods=6)
dates
df2 = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df2
df.dtypes
df.head()
df.tail(3)
df.index
df.columns
df.describe()
df.T
df
df.sort_index(axis = 1, ascending=False)
df
df2.sort_index(axis=0, ascending=False)
df2
df2.sort_values(by='B')
df2
df2['A']
df2[0:3]
df2['20130102':'20130104']
df2.loc[dates[0]]
df2.loc[:, ['A', 'B']]
df2.loc['20130102':'20130104', ['A', 'B']]
df2.loc['20130102', ['A', 'B']]
df2.loc[dates[0], 'A']
df2.at[dates[0], 'A']
df2.iloc[3]
df2.iloc[3:5, 0:3]
df2.iloc[[1, 2, 4], [0, 2]]
df2.iloc[:, 1:3]
df2.iloc[1, 1]
df2.iat[1, 1]
##### Boolean indexing #####
df2[df2['A'] > 0]
df2[df2 > 0]
df = df2.copy()
df['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
df
df[df['E'].isin(['two', 'four'])]
##### Setting #####
s1 =pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range('20130102', periods=6))
s1
df2['F'] = s1
df2
df2.at[dates[0], 'A'] = 0
df2
df2.iat[0, 1] = 0
df2
df2.loc[:, 'D'] = np.array([5] * len(df2))
df2
df = df2.copy()
df[df > 0] = -df
df
# Missing Data
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1
df1.loc[dates[0]:dates[1], 'E'] = 1
df1
df1.dropna(how='any')
df1
df1.fillna(value=5)
df1
pd.isna(df1)
# Operations
df.mean()
df.mean(1)
df
s = pd.Series([1, 3, 5, np.nan, 6, 8], index=dates).shift(2)
s
df.sub(s, axis='index')
df
df.apply(np.cumsum)
df.apply(lambda x: x.max() - x.min())
s = pd.Series(np.random.randint(0, 7, size=10))
s
s.value_counts()
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower()
# Merge
df = pd.DataFrame(np.random.randn(10, 4))
df
pieces = [df[:3], df[3:7], df[7:]]
pd.concat(pieces)
left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
pd.merge(left, right, on='key')
left = pd.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]})
pd.merge(left, right, on='key')
# Grouping
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})
df
df.groupby('A').sum()
df.groupby(['A', 'B']).sum()
# Reshaping
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B'])
df
df2 = df[:4]
df2
stacked = df2.stack()
stacked
stacked.unstack()
stacked.unstack(1)
stacked.unstack(0)
df = pd.DataFrame({'A': ['one', 'one', 'two', 'three'] * 3,
'B': ['A', 'B', 'C'] * 4,
'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D': np.random.randn(12),
'E': np.random.randn(12)})
df
pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'] )
# Time series
rng = pd.date_range('1/1/2012', periods=100, freq='S')
rng
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts
ts.resample('5Min').sum()
rng = pd.date_range('3/6/2012 00:00', periods=5, freq='D')
rng
ts = pd.Series(np.random.randn(len(rng)), rng)
ts
ts_utc = ts.tz_localize('UTC')
ts_utc
ts_utc.tz_convert('US/Eastern')
ts_utc
rng = pd.date_range('1/1/2012', periods=5, freq='M')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
ps = ts.to_period()
ps
ps.to_timestamp()
# Categoricals
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
'raw_grade': ['a', 'b', 'b', 'a', 'a', 'e']})
df
df['grade'] = df['raw_grade'].astype('category')
df['grade']
df['grade'].cat.categories = ['very good', 'good', 'very bad']
df['grade']
df['grade'] = df['grade'].cat.set_categories(['very bad', 'bad', 'medium', 'good', 'very good'])
df['grade']
df.sort_values(by='grade')
df.groupby('grade').size()
# Plotting
import matplotlib.pyplot as plt
plt.close('all')
ts = pd.Series(np.random.randn(1000),
index=pd.date_range('1/1/2012', periods=1000))
ts = ts.cumsum()
ts.plot()
df = pd.DataFrame(np.random.randn(1000, 4),
index=ts.index,
columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
plt.figure()
df.plot()
plt.legend(loc='best')
|
Markdown
|
UTF-8
| 1,041
| 2.71875
| 3
|
[] |
no_license
|
# Final-project
## Documentation for bachelor degree's final project
### Multi-Dimensional Scaling Method for Tracking Teenager Group Activity on Crowded Place in Real-Time Based on Data Sensor of Mobile Device
_**Preliminary**_ <br>
we as humans do many activities every day. In the industrial revolution 4.0 and Society 5.0, human behaviour or activities data became very important data, because from these data we can analyze many things to make a decision in the future. So, based on that reason i want to make some system that can collect the data about human activity. <br>
In my system, i used mobile device (smartphone) as an object in my research. why i used smartphone? because at this time, there are many kinds of sensors found on smartphones, but i will not use it all. <br>
There are 3 sensors that i use, i.e.
* Accelerometer sensor
* Accelerometer linear sensor
* Orientation sensor <br>
For more details you can see android developer sensor overview (https://developer.android.com/guide/topics/sensors/sensors_overview)
|
Ruby
|
UTF-8
| 1,438
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
module Crufty
def self.find_methods(dir, sensitivity)
Dir.chdir(RAILS_ROOT)
sensitivity = (sensitivity || 1).to_i
Dir["#{dir.sub(/\/\Z/, '')}/**/*.rb"].each do |file|
methods = []
File.open(file, 'r') do |f|
f.each_line do |l|
methods.push l[/def ([a-z_\?\.!]+)/, 1]
end
end
methods.compact.map {|m| CruftyMethod.new(m)}.each do |m|
if m.crufty?(sensitivity)
puts "\n===> #{m} in #{file}"
puts m.references if sensitivity > 1
end
end
end
end
class CruftyMethod
attr_accessor :name, :references
def initialize(prefixed_name)
prefixed_name.sub!(/\A\./, '')
if prefixed_name.index('.')
@prefix, @name = prefixed_name.split('.', 2)
else
@name = prefixed_name
end
end
def to_s
@prefix ? "#{@prefix}.#{name}" : name
end
def cruft_check
@references = `grep -r #{name} app lib#{scm_based_refinement}`.split("\n")
end
def scm_based_refinement
if self.class.scm == :svn
' | grep -v \\.svn'
else
''
end
end
def crufty?(sensitivity)
cruft_check unless references
references.length <= sensitivity
end
def self.scm
@scm ||= if File.exists?('.svn')
:svn
else
"something we don't need to worry about"
end
end
end
end
|
Swift
|
UTF-8
| 2,860
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// ListConnectionInteractor.swift
// Titan
//
// Created by Nghia Tran on 11/17/16.
// Copyright © 2016 fe. All rights reserved.
//
import Cocoa
import PromiseKit
protocol ListConnectionInteractorInput: ListConnectionsControllerOutput {
}
protocol ListConnectionInteractorOutput {
func presentError(_ error: NSError)
}
//
// MARK: - ListConnectionInteractor
class ListConnectionInteractor {
//
// MARK: - Variable
var output: ListConnectionInteractorOutput!
//
// MARK: - Worker
fileprivate var fetchConnectionWorker: FetchAllGroupConnectionsWorker!
fileprivate var selecteConnectionWorker: SelectConnectionWorker!
fileprivate var createNewGroupConnectionWorker: CreateNewDefaultGroupConnectionWorker!
fileprivate var createNewDatabaseWorker: CreateNewDatabaseWorker!
}
//
// MARK: - ListConnectionInteractorInput
extension ListConnectionInteractor: ListConnectionInteractorInput {
func addNewConnection() {
// Worker
let worker = CreateNewDefaultGroupConnectionWorker()
// Execute
worker.execute().then { group -> Void in
// Nothing
}
.catch { error in
self.output.presentError(error as NSError)
}
// Save
self.createNewGroupConnectionWorker = worker
}
func fetchAllGroupConnections() {
let worker = FetchAllGroupConnectionsWorker()
// Execute
worker.execute().then { groups -> Void in
// Check if there is no connection
// Create new one
// Focus too
if groups.count == 0 {
let worker = CreateNewDefaultGroupConnectionWorker()
worker.execute().then(execute: { group -> Promise<DatabaseObj> in
let worker = CreateNewDatabaseWorker(groupConnectionObj: group)
return worker.execute()
}).catch(execute: {[unowned self] error in
self.output.presentError(error as NSError)
})
}
else if groups.count > 0 || groups.first!.databases.count == 0 {
let worker = CreateNewDatabaseWorker(groupConnectionObj: groups.first!)
worker.execute().then(execute: { (_) -> Void in
}).catch(execute: { (_) in
})
}
}
.catch { error in
self.output.presentError(error as NSError)
}
// Save
self.fetchConnectionWorker = worker
}
func selectConnection(_ connection: DatabaseObj) {
self.selecteConnectionWorker = SelectConnectionWorker(selectedDb: connection)
self.selecteConnectionWorker.execute()
}
}
|
Python
|
UTF-8
| 1,582
| 2.859375
| 3
|
[] |
no_license
|
# Initialization
import time
start_time = time.time()
import pandas as pd
import numpy as np
import nltk
import string
import sklearn
np.set_printoptions(threshold=np.nan)
emails_df = pd.read_csv("./data/spam.csv", encoding= "ISO-8859-1")
emails_df = emails_df.drop(["Unnamed: 2", "Unnamed: 3", "Unnamed: 4"], axis=1)
emails_df.columns = ['type', 'body']
# Separating the dataset between the message bodies and the email types.
X = emails_df.iloc[:, 1].values
y = emails_df.iloc[:, 0].values
# separating the data into training and testing data, with an 80-20 split of training to testing, respectively
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Feature scaling
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(X_train)
X_test = vectorizer.transform(X_test)
# Training the KNN algorithm
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(X_train, y_train)
# predicting our test data
y_pred = classifier.predict(X_test)
# creating a confusion matrix and printing out the report of the classifications
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
# printing the accuracy of predictions
from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred))
print("Execution takes %s seconds" % (time.time() - start_time))
|
Markdown
|
UTF-8
| 5,303
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
# 재사용 메커니즘(Reuse Mechanism)
테이블 뷰에서 셀의 수가 많아도 부드러운 스크롤 UI를 구현할 수있음
동작원리
1. 테이블 뷰가 화면에 나타낼 셀 객체를 자신의 데이터 소스에게 요청
2. 데이터 소스는 재사용큐에서 사용 가능한 셀이 있는지 확인
3. 사용 가능한 셀이 있다면 그중 하나를 꺼내 전달, 없으면 새로운 셀 생성
4. tableView(_:cellForRowAt:) 메소드가 셀의 콘텐츠 구성 후 반환(return cell) 하면 테이블 뷰는 셀을 받아 화면에 표시함
5. 테이블 뷰를 스크롤함에 따라 화면을 벗어난 셀은 테이블 뷰에서 제거(완전삭제 아님) => 재사용 큐에 추가됨
6. 사용자의 스크롤에 따라 1~5 과정 반복
#### 네트워크 통신으로 썸네일을 받아올때
- 문제점: 네트워크로 이미지를 불러오고 -> 셀 콘텐츠를 구성 후 표현하기 => 시간이 오래걸림
- 다음의 프로그래밍 원칙으로 보완
- 반복적으로 호출되는 메소드의 내부에는 네트워크 통신 등 처리 시간이 긴 로직을 포함하지 않아야 함
- 네트워크 통신을 통해 읽어온 데이터는 재사용할 수 있도록 캐싱 처리하여 될 수 있으면 네트워크 통신 횟수를 줄이는 것이 좋음(메모이제이션 기법)
- 네트워크 통신이나 시간이 오래걸리는 코드를 사용할때는 비동기로 처리
```swift
/*
네트워크에서 내려받은 이미지를 MovieVO객체에 담아 self.list 배열에 저장
저장된 이미지는 필요시점에 꺼내 쓰기만 하면 됨
이 방식의 문제점: 초기 로딩시 화면이 지연됨 => 비동기로 해결
*/
//MovieVO.swift
import Foundation
import UIKit //UIImage를 위함
class MovieVO{
var thumbnail: String? //썸네일 주소
var title: String?
var description: String?
var rating: Double?
//영화 썸네일 이미즈를 담을 UIImage 객체 추가
var thumbnailImage: UIImage?
}
//ListViewController.swift
//영화 차트 API호출
func callMovieAPI(){
do{
for row in movie{
//웹 상의 이미지를 읽어와 UIImage 객체로 생성
let url: URL! = URL(string: mvo.thumbnail!)
let imageData = try! Data(contentsOf: url)
mvo.thumbnailImage = UIImage(data:imageData)
self.list.append(mvo)
}
}catch{ NSLog("Parse Error") }
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
cell.thumbnail.image = row.thumbnailImage
return cell
}
```
#### 이미지 비동기 처리하기
- 동기 방식: 차례대로 업무를 처리하며, 이전 업무가 처리되지 않으면 다음으로 넘어가지 않음
- 비동기 방식: 시간이 걸리는 업무는 진행해 둔 채로 기다리는 동안 다른 업무 처리
- 스위프트에서 제공하는 비동기 구현방식
- 델리게이트 패턴 이용
- 네트워크 통신 자체에만 국한된 비동기 처리로 NSURLConectionDelegate객체 이용
- 델리게이트 객체에 이미지 내려받기에 대한 처리를 위임 -> 내려받기가 완료되면 델리게이트 객체가 특정 메소드를 호출하게 하여 메소드 처리
- 범용 비동기 함수 이용
- DispatchQueue.main.async()제공
- 내부적으로 프로세스나 스레드에 직접 접근하지 않고도 비동기 방식으로 처리할 수 있도록 지원
- Block, GCD(Global Centeral Dispatch, 애플에서 개발한 병렬처리, 스레드 풀에 기반한 비동기 처리기술)를 이용
```swift
//ListViewController.swift
func getThumbnailImage(_ index: Int) -> UIImage{
//인자값으로 받은 인덱스를 기반으로 해당하는 배열 데이터를 읽어옴
let mvo = self.list[index]
//메모이제이션: 저장된 이미지가 있으면 그것을 반환하고, 없을 경우 내려받아 저장한 후 반환
if let savedImage = mvo.thumbnailImage{
return saveImage
} else {
let url: URL! = URL(stirng: mvo.thumbnail!)
let imageData = try! Data(contentsOf: url)
mvo.thumbnailImage = UIImage(data:imageData) //UIImage를 MovieVO 객체에 우선 저장
return mvo.thumbnailImage! //저장된 이미지 반환
}
}
//비동기 처리방식 이용
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let row = self.list[indexPath.row]
NSLog("호출된 행 번호: \(indexPath.row), 제목:\(row.title!)")
let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell") as! MovieCell
cell.title?.text = row.title
cell.desc?.text = row.description
cell.rating?.text = "\(row.rating!)"
//비동기 방식으로 섬네일 이미지를 읽어옴
/*클로저는 내부 함수에서 사용되는 외부 환경을 계속 유지해 주는 특성을 가지고 있기 때문에 cell객체가 제거되지 않고 계속 유지될 수 있어 비동기함수에서 이용됨(execute)*/
DispatchQueue.main.async(execute: {
cell.thumbnail.image = self.getThumbnailImage(indexPath.row)
})
return cell
}
```
|
Java
|
UTF-8
| 288
| 1.835938
| 2
|
[] |
no_license
|
package jstarcraft.gui.ui.list;
import javax.swing.JComponent;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicListUI;
public class StarListUI extends BasicListUI {
public static ComponentUI createUI(JComponent c) {
return new StarListUI();
}
}
|
Java
|
UTF-8
| 452
| 3.234375
| 3
|
[] |
no_license
|
package com.uday.java8.joda;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
public class PeriodUsage_43 {
public static void main(String args[]){
LocalDate birthDate=LocalDate.of(1994, Month.JUNE,24);
LocalDate todayDate=LocalDate.now();
Period period= Period.between(birthDate, todayDate);
System.out.println(period.getDays()+" "+period.getMonths()+" "+period.getYears());
}
}
|
Java
|
UTF-8
| 6,982
| 2.6875
| 3
|
[] |
no_license
|
import java.awt.*;
import java.awt.event.*;
public class calculator extends Frame implements ActionListener {
TextField tf;
String s1,s2,s3,s4,s5,c;
int n;
calculator()
{
Font font1 = new Font("SansSerif", Font.BOLD, 20);
tf=new TextField(20);
tf.setBounds(10,70,300,50);
tf.setFont(font1);
Button one=new Button("1");
one.setBounds(10,150,50,50);
Button two=new Button("2");
two.setBounds(60,150,50,50);
Button three=new Button("3");
three.setBounds(110,150,50,50);
Button four=new Button("4");
four.setBounds(10,200,50,50);
Button five=new Button("5");
five.setBounds(60,200,50,50);
Button six=new Button("6");
six.setBounds(110,200,50,50);
Button seven=new Button("7");
seven.setBounds(10,250,50,50);
Button eight=new Button("8");
eight.setBounds(60,250,50,50);
Button nine=new Button("9");
nine.setBounds(110,250,50,50);
Button zero=new Button("0");
zero.setBounds(60,300,50,50);
Button btn_equal=new Button("=");
btn_equal.setBounds(110,300,50,50);
Button clear=new Button("clear");
clear.setBounds(10,300,50,50);
Button btn_add=new Button("add");
btn_add.setBounds(180,150,80,30);
Button btn_sub=new Button("sub");
btn_sub.setBounds(180,180,80,30);
Button btn_mul=new Button("Multiply");
btn_mul.setBounds(180,210,80,30);
Button btn_div=new Button("divide");
btn_div.setBounds(180,240,80,30);
Button btn_mod=new Button("mod");
btn_mod.setBounds(180,270,80,30);
clear.addActionListener(this);
btn_add.addActionListener(this);
btn_sub.addActionListener(this);
btn_mul.addActionListener(this);
btn_div.addActionListener(this);
btn_mod.addActionListener(this);
btn_equal.addActionListener(this);
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
zero.addActionListener(this);
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
// add(label1);
// add(label2);
//add(number1);
add(btn_add);
add(btn_sub);
add(btn_mul);
add(btn_div);
//add(number2);
add(btn_mod);
add(clear);
add(tf);
add(btn_equal);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
String no1,no2,ans;
int no3,no4;
// no1=number1.getText();
// no2=number2.getText();
// no3=Integer.parseInt(no1);
// no4=Integer.parseInt(no2);
if(e.getActionCommand()=="add")
{
s1 = tf.getText();
tf.setText("");
c="add";
}
if(e.getActionCommand()=="sub")
{
s1 = tf.getText();
tf.setText("");
c="sub";
}
if(e.getActionCommand()=="Multiply")
{
s1 = tf.getText();
tf.setText("");
c="mul";
}
if(e.getActionCommand()=="divide")
{
s1 = tf.getText();
tf.setText("");
c="div";
}
else if(e.getActionCommand()=="mod")
{
s1 = tf.getText();
tf.setText("");
c="mod";
}
if(e.getActionCommand()=="clear")
{
tf.setText("");
}
if(e.getActionCommand()=="1")
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getActionCommand()=="2")
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getActionCommand()=="3")
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
} if(e.getActionCommand()=="4")
{
s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
} if(e.getActionCommand()=="5")
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
} if(e.getActionCommand()=="6")
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getActionCommand()=="7")
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
} if(e.getActionCommand()=="8")
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getActionCommand()=="9")
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
} if(e.getActionCommand()=="0")
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getActionCommand()=="=")
{
s2 = tf.getText();
if(c.equals("add"))
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else if(c.equals("sub"))
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else if(c.equals("mul"))
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else if(c.equals("div"))
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("Zero error");
}
catch(Exception i){}
}
if(c.equals("mod"))
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
}
public static void main(String args[])
{
new calculator();
}
}
|
JavaScript
|
UTF-8
| 1,175
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
"use strict";
var Rx = require("rxjs/Rx");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function get(url) {
return Rx.Observable.create(function(observer) {
// Make a traditional Ajax request
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
// If the status is 200, meaning there have been no problems,
// Yield the result to listeners and complete the sequence
observer.next(req.response);
observer.complete();
} else {
// Otherwise, signal to listeners that there has been an error
observer.error(new Error(req.statusText));
}
};
req.onerror = function() {
observer.error(new Error("Unknown Error"));
};
req.send();
});
}
Rx.Observable.interval(1000)
.mergeMap(x => { return get('/app/contents.json'); })
.subscribe(function next(x) { console.log('Result: ' + x); }, function error(err) { console.log('Error: ' + err); }, function complete() { console.log('Completed'); })
|
C#
|
UTF-8
| 2,716
| 2.703125
| 3
|
[] |
no_license
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Printing;
namespace Petzold.PrintWithMargins
{
public class PrintWithMargins : Window
{
PrintQueue prnqueue;
PrintTicket prntkt;
Thickness marginPage = new Thickness(96);
[STAThread]
public static void Main()
{
Application app = new Application();
app.Run(new PrintWithMargins());
}
public PrintWithMargins()
{
Title = "Print with Margins";
FontSize = 24;
StackPanel stack = new StackPanel();
Content = stack;
Button btn = new Button();
btn.Content = "Page Set_up...";
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.Margin = new Thickness(24);
btn.Click += SetupOnClick;
stack.Children.Add(btn);
btn = new Button();
btn.Content = "_Print...";
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.Margin = new Thickness(24);
btn.Click += PrintOnClick;
stack.Children.Add(btn);
}
void SetupOnClick(object sender, RoutedEventArgs args)
{
PageMarginsDialog dlg = new PageMarginsDialog();
dlg.Owner = this;
dlg.PageMargins = marginPage;
if (dlg.ShowDialog().GetValueOrDefault())
{
marginPage = dlg.PageMargins;
}
}
void PrintOnClick(object sender, RoutedEventArgs args)
{
PrintDialog dlg = new PrintDialog();
if (prnqueue != null)
dlg.PrintQueue = prnqueue;
if (prntkt != null)
dlg.PrintTicket = prntkt;
if (dlg.ShowDialog().GetValueOrDefault())
{
prnqueue = dlg.PrintQueue;
prntkt = dlg.PrintTicket;
DrawingVisual vis = new DrawingVisual();
DrawingContext dc = vis.RenderOpen();
Pen pn = new Pen(Brushes.Black, 1);
Rect rectPage = new Rect(marginPage.Left, marginPage.Top,
dlg.PrintableAreaWidth - (marginPage.Left + marginPage.Right),
dlg.PrintableAreaHeight - (marginPage.Top + marginPage.Bottom));
dc.DrawRectangle(null, pn, rectPage);
FormattedText formtxt = new FormattedText(
String.Format("Hello, Printer! {0} x {1}", dlg.PrintableAreaWidth/96, dlg.PrintableAreaHeight/96),
CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(
new FontFamily("Times New Roman"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal),
48, Brushes.Black);
Size sizeText = new Size(formtxt.Width, formtxt.Height);
Point ptText = new Point(rectPage.Left + (rectPage.Width - formtxt.Width) / 2,
rectPage.Top + (rectPage.Height - formtxt.Height) / 2);
dc.DrawText(formtxt, ptText);
dc.DrawRectangle(null,pn, new Rect(ptText, sizeText));
dc.Close();
dlg.PrintVisual(vis, Title);
}
}
}
}
|
Rust
|
UTF-8
| 5,378
| 2.625
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::collections::HashMap;
use sage::Idea;
use book::word::Word;
use model::yaml::seq;
use model::yaml::map;
use std::borrow::Cow;
pub struct Volume {
pub complete: bool,
pub gist: Vec<(Option<String>, usize, Word)>,
buff: Option<HashMap<usize, Idea>>
}
impl Volume {
pub fn new () -> Volume {
Volume {
complete: false,
gist: Vec::with_capacity (0),
buff: Some (HashMap::with_capacity (256))
}
}
pub fn complete (&mut self) {
if self.complete { return }
let mut buff = self.buff.take ().unwrap ();
self.gist.reserve_exact (buff.len ());
let mut border: usize = 0;
for ix in buff.keys () {
border = *ix;
break;
}
/* 1 is always Dawn, so starting from 2 */
for ix in 2..border {
if buff.contains_key (&ix) {
border = ix;
break;
}
}
let mut ix = border;
for _ in 0 .. buff.len () {
loop {
if let Some (idea) = buff.remove (&ix) {
self.process (idea);
ix += 1;
break;
} else {
ix += 1;
continue;
}
}
}
self.complete = true;
}
fn process (&mut self, idea: Idea) {
match idea {
Idea::Error (id, value) => self.gist.push ((None, id.level, Word::Err (Cow::from (value)))),
Idea::ReadError (id, _, string) => self.gist.push ((None, id.level, Word::Err (Cow::from (string)))),
Idea::ReadWarning (id, _, string) => self.gist.push ((None, id.level, Word::Wrn (Cow::from (string)))),
Idea::NodeLiteral (id, alias, value) => self.gist.push ((alias, id.level, Word::Str (value))),
Idea::NodeScalar (id, alias, value) => self.gist.push ((alias, id.level, Word::extract_scalar (value))),
Idea::NodeSequence (id, alias, tag) => self.gist.push ((alias, id.level, Word::Seq (Cow::from (tag)))),
Idea::NodeMetaSeq (id, alias, None) => self.gist.push ((alias, id.level, Word::Seq (Cow::from (seq::TAG)))),
Idea::NodeMetaSeq (id, alias, Some (tag)) => self.gist.push ((alias, id.level, Word::Seq (Cow::from (tag)))),
Idea::NodeDictionary (id, alias, _, firstborn_id) => {
self.gist.push ((alias, id.level, Word::Map (Cow::from (map::TAG))));
if firstborn_id.is_some () {
// TODO: check whether it's ALWAYS the previous node?
let ln = self.gist.len ();
let mut firstborn = self.gist.swap_remove (ln - 2);
firstborn.1 += 1; // level up
self.gist.push (firstborn);
}
}
Idea::NodeMetaMap (id, alias, tag, firstborn_id) => {
if let Some (tag) = tag {
self.gist.push ((alias, id.level, Word::Map (Cow::from (tag))));
} else {
self.gist.push ((alias, id.level, Word::Map (Cow::from (map::TAG))));
}
if firstborn_id.is_some () {
// TODO: check whether it's ALWAYS the previous node?
let ln = self.gist.len ();
let mut firstborn = self.gist.swap_remove (ln - 2);
firstborn.1 += 1; // level up
self.gist.push (firstborn);
}
}
Idea::Alias (id, value) => {
let mut narr: Option<Word> = None;
for (ix, &(ref alias, _, _)) in self.gist.iter ().enumerate ().rev () {
if let Some (ref alias) = *alias {
if *alias == value {
narr = Some (Word::Alias (ix));
break;
}
}
}
if narr.is_some () {
self.gist.push ((None, id.level, narr.take ().unwrap ()));
} else {
self.gist.push ((None, id.level, Word::UnboundAlias (value)));
}
}
Idea::Done | Idea::Dawn | Idea::Dusk => unreachable! ()
};
}
pub fn stamp (&mut self, idea: Idea) {
if self.complete { return }
let ix = match idea {
Idea::Alias (ref id, _) => id.index,
Idea::Error (ref id, _) => id.index,
Idea::NodeMetaMap (ref id, _, _, _) => id.index,
Idea::NodeMetaSeq (ref id, _, _) => id.index,
Idea::NodeDictionary (ref id, _, _, _) => id.index,
Idea::NodeSequence (ref id, _, _) => id.index,
Idea::NodeScalar (ref id, _, _) => id.index,
Idea::NodeLiteral (ref id, _, _) => id.index,
Idea::ReadError (ref id, _, _) => id.index,
Idea::ReadWarning (ref id, _, _) => id.index,
_ => 0
};
if ix > 0 { self.buff.as_mut ().unwrap ().insert (ix, idea); }
}
pub fn unalias (&self, idx: usize) -> &Word {
let &(_, _, ref word) = &self.gist[idx];
match *word {
Word::Alias (idx) => self.unalias (idx),
_ => word
}
}
}
|
PHP
|
UTF-8
| 784
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace WebservicesNl\Connector;
use WebservicesNl\Connector\ProtocolAdapter\AdapterInterface;
/**
* Class BaseConnector.
*
* Platform connector parent.
*/
abstract class AbstractConnector implements ConnectorInterface
{
const PLATFORM_NAME = 'abstract';
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* WsConnector constructor.
*
* @param AdapterInterface $adapter
*/
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
/**
* {@inheritdoc}
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* {@inheritdoc}
*/
public function getPlatform()
{
return static::PLATFORM_NAME;
}
}
|
C++
|
UTF-8
| 1,067
| 3
| 3
|
[] |
no_license
|
#pragma once
#include <iostream>
#include <list>
#include <stack>
#include <random>
#include <chrono>
#include <queue>
#include <conio.h>
using namespace std;
struct MyComparator;
class GraphNode
{
friend MyComparator;
public:
bool visited;
private:
int **boardState;
int h;
GraphNode *contiguousNodes[4];
public:
GraphNode();
GraphNode(int **board);
GraphNode(GraphNode *original);
~GraphNode();
void Shuffle(int steps);
void ShuffleManually();
void Display();
bool IsSolution();
void FindNeighbours(list<GraphNode*> &list);
bool CompareTo(int** other);
void PushNeighbours(stack<GraphNode*>& membersList);
void PushNeighbours(queue<GraphNode*>& membersStack);
void PushNeighbours(priority_queue<GraphNode*, vector<GraphNode*>, MyComparator> &membersQueue);
int CountHeuristic() const;
private:
void CloneBoard(int **original, int **cloned);
void AddNeighbour(int **boardState, list<GraphNode*>& list);
};
struct MyComparator
{
bool operator() (const GraphNode* arg1, const GraphNode* arg2) const
{
return arg1->h > arg2->h;
}
};
|
JavaScript
|
UTF-8
| 3,012
| 2.90625
| 3
|
[] |
no_license
|
import GamestateNode from './GamestateNode';
import { fiveInRow } from './ranking';
const max_children = 40; // s0: 4 10: 18 35
const highValue = fiveInRow * 100;
/**
*
* @param {GamestateNode} gamestateNode
* @param {integer} ply round number
* @param {integer} maxPly number bigger then ply
* @param {1 or 2} team acting team for whole search
* @param {integer} ply0 ply for start of the search
* @param {bool} shouldMax
* @param {number} alpha
* @param {number} beta
*/
export function minMax(gamestateNode, ply, maxPly, team, ply0, shouldMax, alpha, beta) {
const plyTeam = (ply % 2) + 1; // 1 or 2. Acting team for this turn
const prevTeam = plyTeam === 1 ? 2 : 1;
gamestateNode.applyMoveToGameboard(prevTeam);
// stop searching deeper if this node is a win
if (gamestateNode.checkWin(prevTeam)) {
// will reward shortest path to win by subtracting ply
const reward = prevTeam === team ? fiveInRow - ply : -fiveInRow;
gamestateNode.value = reward;
return reward;
}
if (ply === maxPly) {
return gamestateNode.staticEvaluation(prevTeam);
}
// optimization: decrease number of children depending on depth. note: (ply0 - ply) is negative
let nChildren = Math.max(max_children + (ply0 - ply) * 2, 2);
const doEverySurroundingCell = ply0 > 0 && ply === ply0;
const children = gamestateNode.generateChildren(nChildren, doEverySurroundingCell);
const len = children.length;
let value;
if (shouldMax) {
for (let i = 0; i < len; i++) {
value = minMax(children[i], ply + 1, maxPly, team, ply0, !shouldMax, alpha, beta);
// children[i].v = children[i].move.cellIdx; // debugging
alpha = Math.max(value, alpha);
if (beta <= alpha) {
break;
}
}
} else {
for (let i = 0; i < len; i++) {
value = minMax(children[i], ply + 1, maxPly, team, ply0, !shouldMax, alpha, beta);
// children[i].v = children[i].move.cellIdx; // debugging
beta = Math.min(value, beta);
if (beta <= alpha) {
break;
}
}
}
gamestateNode.releaseBoard(); // to save some memory
gamestateNode.sortChildren(!shouldMax); // warning (why not plyTeam?)
gamestateNode.value = gamestateNode.getValueFromFirstChild();
return gamestateNode.value;
}
export default class MinMaxSearch {
constructor(gameBoard, ply, maxSeachDepth) {
this.gameBoard = gameBoard;
this.ply = ply;
this.maxPly = ply + maxSeachDepth;
// 1 or 2. Acting team for this turn. Relevant since we can play on both teams
this.team = (ply % 2) + 1;
}
search() {
const { gameBoard, ply, maxPly, team } = this;
const ply0 = ply;
// move: null, since the move is already integreated into the current gameboard
const node0 = new GamestateNode(gameBoard, null, ply0);
// debugger;
const value = minMax(node0, ply, maxPly, team, ply0, true, -highValue, highValue);
// console.log(node0);
const move = node0.getBestMove();
move.value = value;
return move;
}
}
|
Python
|
UTF-8
| 315
| 4.5
| 4
|
[] |
no_license
|
#利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
score = int(input('输入成绩:\n'))
if score > 90:
grade = 'A'
elif score >= 60:
grade = 'B'
else:
grade = 'C'
print('%d is %s grade'%(score,grade))
|
Ruby
|
UTF-8
| 903
| 2.828125
| 3
|
[] |
no_license
|
require 'json'
require 'uri'
require 'open-uri'
class Search
def self.party(query = "", tags = [])
return if query.empty? && tags.empty?
path = "/search?q=#{query.escaped}"
path << "&tags=#{tags.join(",").escaped}" unless tags.empty?
(query_api path)['results'].flatten
end
def self.cats
(query_api "/Category").flatten # Capital C is SUPER-Important!
end
def self.cat(id)
(query_api "/Category?id=#{id}") # Capital C is SUPER-Important!
end
private
def self.base_uri
"http://searchparty-1.apphb.com"
end
def self.query_api(path)
# For when shit goes bad!
# stub = JSON.parse(File.open('stub-search-results.json').read)
# return stub['results'][0]
begin
uri = "#{base_uri}#{path}"
p "Querying API Via: '#{uri}'"
JSON.parse(URI.parse(uri).read)
rescue => ex
p ex.inspect
end
end
end
|
Java
|
UTF-8
| 16,176
| 2.09375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UI;
/**
*
* @author camin
*/
public class Ajout_Exam extends javax.swing.JFrame {
/**
* Creates new form Param
*/
public Ajout_Exam() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel_Base = new javax.swing.JPanel();
jPanel_Info = new javax.swing.JPanel();
jLabel_DateCrea = new javax.swing.JLabel();
dateCreaDMR = new javax.swing.JLabel();
jLabel_HeureCrea = new javax.swing.JLabel();
heureCreaDMR = new javax.swing.JLabel();
jLabel_Nom = new javax.swing.JLabel();
jLabel_Prenom = new javax.swing.JLabel();
jLabel_Sexe = new javax.swing.JLabel();
jButton_Sauvegarder = new javax.swing.JButton();
jLabel_ExamLier = new javax.swing.JLabel();
jComboBox_Lier = new javax.swing.JComboBox<String>();
jLabel_Reference = new javax.swing.JLabel();
jLabel_IDPatient = new javax.swing.JLabel();
idPatient = new javax.swing.JLabel();
jTextField_Reference = new javax.swing.JTextField();
prenomPatient = new javax.swing.JLabel();
nomPatient = new javax.swing.JLabel();
sexePatient = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel_Base.setBackground(new java.awt.Color(127, 144, 160));
jPanel_Base.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ajout Examen", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 18))); // NOI18N
jPanel_Info.setBackground(new java.awt.Color(163, 209, 180));
jLabel_DateCrea.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_DateCrea.setText("Date de création :");
dateCreaDMR.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
dateCreaDMR.setText(date.toString());
jLabel_HeureCrea.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_HeureCrea.setText("Heure de création :");
heureCreaDMR.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
heureCreaDMR.setText("Heure_DMR");
jLabel_Nom.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_Nom.setText("Nom :");
jLabel_Prenom.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_Prenom.setText("Prénom :");
jLabel_Sexe.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_Sexe.setText("Sexe :");
jButton_Sauvegarder.setFont(new java.awt.Font("Dialog", 0, 16)); // NOI18N
jButton_Sauvegarder.setText("Sauvegarder");
jButton_Sauvegarder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_SauvegarderActionPerformed(evt);
}
});
jLabel_ExamLier.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_ExamLier.setText("Examen éxistant à lier :");
jComboBox_Lier.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jComboBox_Lier.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Non", "Oui (Numérique)", "Oui (Papier)" }));
jComboBox_Lier.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_LierActionPerformed(evt);
}
});
jLabel_Reference.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_Reference.setText("Référence examen :");
jLabel_Reference.setVisible(false);
jLabel_IDPatient.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
jLabel_IDPatient.setText("ID Patient :");
idPatient.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
idPatient.setText("ID_Patient :");
jTextField_Reference.setVisible(false);
prenomPatient.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
prenomPatient.setText("prenom_patient");
nomPatient.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
nomPatient.setText("nom_patient");
sexePatient.setFont(new java.awt.Font("Dialog", 1, 16)); // NOI18N
sexePatient.setText("sexe_patient");
javax.swing.GroupLayout jPanel_InfoLayout = new javax.swing.GroupLayout(jPanel_Info);
jPanel_Info.setLayout(jPanel_InfoLayout);
jPanel_InfoLayout.setHorizontalGroup(
jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_InfoLayout.createSequentialGroup()
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_InfoLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Sauvegarder, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel_InfoLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_DateCrea)
.addGroup(jPanel_InfoLayout.createSequentialGroup()
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_HeureCrea)
.addComponent(jLabel_Nom)
.addComponent(jLabel_Prenom)
.addComponent(jLabel_Sexe)
.addComponent(jLabel_IDPatient))
.addGap(23, 23, 23)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(idPatient)
.addComponent(heureCreaDMR)
.addComponent(dateCreaDMR)
.addComponent(prenomPatient)
.addComponent(nomPatient)
.addComponent(sexePatient))))
.addGap(56, 56, 56)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel_ExamLier)
.addComponent(jLabel_Reference))
.addGap(18, 18, 18)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField_Reference)
.addComponent(jComboBox_Lier, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel_InfoLayout.setVerticalGroup(
jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_InfoLayout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_DateCrea)
.addComponent(dateCreaDMR)
.addComponent(jLabel_ExamLier)
.addComponent(jComboBox_Lier, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel_InfoLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_HeureCrea)
.addComponent(heureCreaDMR)
.addComponent(jLabel_Reference)))
.addGroup(jPanel_InfoLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField_Reference)))
.addGap(20, 20, 20)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_Nom)
.addComponent(nomPatient))
.addGap(20, 20, 20)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_Prenom)
.addComponent(prenomPatient))
.addGap(25, 25, 25)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_Sexe)
.addComponent(sexePatient))
.addGap(22, 22, 22)
.addGroup(jPanel_InfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_IDPatient)
.addComponent(idPatient))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addComponent(jButton_Sauvegarder)
.addContainerGap())
);
javax.swing.GroupLayout jPanel_BaseLayout = new javax.swing.GroupLayout(jPanel_Base);
jPanel_Base.setLayout(jPanel_BaseLayout);
jPanel_BaseLayout.setHorizontalGroup(
jPanel_BaseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel_BaseLayout.createSequentialGroup()
.addComponent(jPanel_Info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel_BaseLayout.setVerticalGroup(
jPanel_BaseLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_BaseLayout.createSequentialGroup()
.addGap(0, 7, Short.MAX_VALUE)
.addComponent(jPanel_Info, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel_Base, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel_Base, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_SauvegarderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SauvegarderActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton_SauvegarderActionPerformed
private void jComboBox_LierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_LierActionPerformed
// TODO add your handling code here:
if (jComboBox_Lier.getSelectedItem().equals("Oui (Numérique)") | jComboBox_Lier.getSelectedItem().equals("Oui (Papier)") ) {
jTextField_Reference.setVisible(true);
jLabel_Reference.setVisible(true);
jPanel_Info.repaint();
jPanel_Info.revalidate();
} else if (jComboBox_Lier.getModel().getSelectedItem().equals("Non")) {
jTextField_Reference.setVisible(false);
jLabel_Reference.setVisible(false);
jPanel_Info.repaint();
jPanel_Info.revalidate();
}
}//GEN-LAST:event_jComboBox_LierActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Window".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Ajout_Exam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Ajout_Exam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Ajout_Exam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Ajout_Exam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Ajout_Exam().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel dateCreaDMR;
private javax.swing.JLabel heureCreaDMR;
private javax.swing.JLabel idPatient;
private javax.swing.JButton jButton_Sauvegarder;
private javax.swing.JComboBox<String> jComboBox_Lier;
private javax.swing.JLabel jLabel_DateCrea;
private javax.swing.JLabel jLabel_ExamLier;
private javax.swing.JLabel jLabel_HeureCrea;
private javax.swing.JLabel jLabel_IDPatient;
private javax.swing.JLabel jLabel_Nom;
private javax.swing.JLabel jLabel_Prenom;
private javax.swing.JLabel jLabel_Reference;
private javax.swing.JLabel jLabel_Sexe;
private javax.swing.JPanel jPanel_Base;
private javax.swing.JPanel jPanel_Info;
private javax.swing.JTextField jTextField_Reference;
private javax.swing.JLabel nomPatient;
private javax.swing.JLabel prenomPatient;
private javax.swing.JLabel sexePatient;
// End of variables declaration//GEN-END:variables
}
|
C
|
UTF-8
| 1,907
| 3.4375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
typedef struct score
{
int num;
int de;
int cai;
int all;
}Student;
int cmp(const void *a,const void *b)
{
if((((Student*)b)->all==((Student*)a)->all))
{
if((((Student*)b)->de==((Student*)a)->de))
return ((Student*)a)->num-((Student*)b)->num;
else return ((Student*)b)->de-((Student*)a)->de;
}
else return ((Student*)b)->all-((Student*)a)->all;
}
int main()
{
int L,H,N,i,t1=0,t2=0,t3=0,t4=0;
Student *type1 = (Student *)malloc(100000*sizeof(Student));
Student *type2 = (Student *)malloc(100000*sizeof(Student));
Student *type3 = (Student *)malloc(100000*sizeof(Student));
Student *type4 = (Student *)malloc(100000*sizeof(Student));
Student temp;
scanf("%d%d%d",&N,&L,&H);
for(i=0;i<N;i++)
{
scanf("%d%d%d",&temp.num,&temp.de,&temp.cai);
temp.all=temp.de+temp.cai;
if(temp.de>=L&&temp.cai>=L)
{
if(temp.de>=H&&temp.cai>=H)
{
type1[t1++]=temp;
}
else if(temp.de>=H&&temp.cai<H)
{
type2[t2++]=temp;
}
else if(temp.de<H&&temp.cai<H&&temp.de>=temp.cai)
{
type3[t3++]=temp;
}
else
{
type4[t4++]=temp;
}
}
}
qsort(type1,t1,sizeof(Student),cmp);
qsort(type2,t2,sizeof(Student),cmp);
qsort(type3,t3,sizeof(Student),cmp);
qsort(type4,t4,sizeof(Student),cmp);
printf("%d\n",t1+t2+t3+t4);
for(i=0;i<t1;i++)
printf("%d %d %d\n",type1[i].num,type1[i].de,type1[i].cai);
for(i=0;i<t2;i++)
printf("%d %d %d\n",type2[i].num,type2[i].de,type2[i].cai);
for(i=0;i<t3;i++)
printf("%d %d %d\n",type3[i].num,type3[i].de,type3[i].cai);
for(i=0;i<t4;i++)
printf("%d %d %d\n",type4[i].num,type4[i].de,type4[i].cai);
return 0;
}
|
C++
|
UTF-8
| 1,789
| 3.828125
| 4
|
[] |
no_license
|
#include "iostream"
#include "fstream"
using namespace std;
class item
{
private:
string name;
int price;
int qty;
public:
item() {}
item(string n, int p, int q);
friend ostream &operator<<(ostream &out, item &it);
friend ofstream &operator<<(ofstream &ofs, item &i);
friend ifstream &operator>>(ifstream &ifs, item &i);
};
int main()
{
int n;
string name;
float price;
int qty;
cout<<"enter number of item"<<endl;
cin>>n;
item *list[n];
cout<<"Enter details of items"<<endl;
for (int i = 0; i < n; i++)
{
cout<<"enter "<<i+1<<" item name, price and quanity"<<endl;
cin>>name;
cin>>price;
cin>>qty;
list[i] = new item(name,price,qty);
}
//writing data
ofstream ofs("my.txt");
for (int i = 0; i < n; i++){
ofs<<*list[i];
}
//reading data
item item;
ifstream ifs;
ifs.open("my.txt");
if(ifs.is_open()){
cout<<endl<<"item list:"<<endl;
}else{
cout<<"no list found"<<endl;
exit(0);
}
for (int i = 0; i < n; i++)
{
ifs>>item;
cout<<endl<<"item "<<i+1<<" "<<item<<endl;
}
ifs.close();
}
//class constructor
item::item(string n, int p, int q)
{
name = n;
price = p;
qty = q;
};
//operator overload
ostream &operator<<(ostream &out, item &i)
{
out << i.name << endl;
out << i.price << endl;
out << i.qty << endl;
return out;
}
//writing file
ofstream &operator<<(ofstream &ofs, item &i)
{
ofs << i.name << endl;
ofs << i.price << endl;
ofs << i.qty << endl;
return ofs;
}
//reading file
ifstream &operator>>(ifstream &ifs, item &i)
{
ifs >> i.name;
ifs >> i.price;
ifs >> i.qty;
return ifs;
}
|
Python
|
UTF-8
| 366
| 3.59375
| 4
|
[] |
no_license
|
n, k = map(int, input().split())
result = 0 # 횟수
#N이 K이상이라면 K로 계속 나누기
while n>=k:
#N이 K로 나누어 떨어지지 않는다면 1씩 빼기
while n % k !=0:
n -=1
result += 1
# K로 나누기
n //= k
result +=1
#마지막으로 남은 수에 대해 1씩 빼기
while n>1:
n -=1
result +=1
print(result)
|
Python
|
UTF-8
| 1,037
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
import torch
import torch.nn as nn
from ..functional import (crop_2d,
crop_3d)
class Crop2d(nn.Module):
"""
:params torch.Tensor input: Input(B, C, W, H)
"""
def __init__(self,
crop_left: int=0, crop_right: int=0,
crop_top: int=0, crop_bottom: int=0):
super(Crop2d, self).__init__()
self.crop_left = crop_left
self.crop_right = crop_right
self.crop_top = crop_top
self.crop_bottom = crop_bottom
def forward(self, input):
return crop_2d(input,
self.crop_left,
self.crop_right,
self.crop_top,
self.crop_bottom)
class Crop3d(nn.Module):
"""
:params torch.Tensor input: Input(B, C, D, W, H)
"""
def __init__(self, crop_size):
super(Crop3d, self).__init__()
self.crop_size = crop_size
def forward(self, input):
return crop_3d(input, self.crop_size)
|
TypeScript
|
UTF-8
| 18,208
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
'use strict'
import * as stringhelper from "../helpers/string";
import * as textTokenFactory from "../models/textToken";
import * as propertyTokenFactory from "../models/propertyToken";
import { TextStream, TextStreamDirection } from "./textStream";
import { TextToken } from "../models/textToken";
import { PropertyToken } from "../models/propertyToken";
import { EntityDocumentScanner, TokenType as EntityTokenType } from "./entityDocumentScanner";
export enum Direction {
Forward,
Backward
}
export enum ScannerState {
Unknown,
WithinContent,
WithinComment,
WithinConfiguration,
AfterMethod,
AfterCommand,
WithinQueryString,
AfterQueryStringName,
BeforeQueryStringValue,
AfterQueryString,
WithinInput,
AfterArgumentName,
BeforeArgumentValue,
AfterInput,
AfterStartBody,
AfterBody
}
export enum TokenType {
Comment,
Configuration,
Command,
Method,
Input,
QueryString,
QueryStringValue,
Argument,
ArgumentValue,
Body,
Empty
}
export class ElasticsearchQueryDocumentScanner {
private _source:string;
private _stream:TextStream;
private _state:ScannerState;
private _detailState:ScannerState;
private _entityDocumentScanner:EntityDocumentScanner
constructor(source:string, position:number=0) {
this._source = source;
this._stream = new TextStream(source, position);
if(position > 0) {
this._state = ScannerState.Unknown;
} else {
this._state = ScannerState.WithinContent;
}
this._detailState = ScannerState.Unknown;
}
public get offset():number {
return this._stream.position;
}
public get isNotEndOfStream(): boolean {
return !this._stream.endOfStream;
}
public isOffsetWithinRange(offset:number) {
return !(this.offset >= offset)
}
public get state(): ScannerState {
return this._state;
}
public scan():TextToken {
if(this._state === ScannerState.Unknown) {
this.calibrate();
}
let token = this.getNextToken();
return token;
}
public scanUntil(state:ScannerState, detailState:ScannerState = ScannerState.Unknown):TextToken {
let token = null;
while(this.isNotEndOfStream && this.state != state) {
token = this.scan();
if(detailState != ScannerState.Unknown && detailState == this._detailState) {
break;
}
if(this.state != state) {
token = null;
}
}
return token;
}
public calibrate() {
let withinQuery = false;
let position = this._stream.position;
let value = this._stream.retreatToTheClosest([/\}/, /\)/, /\/\s/, /\s(DAEH|TUP|ETELED|TSOP|TEG)/i]);
if(value === '}') {
// we can still be within a body, so we need to count the start and closing tags.
this._state = ScannerState.WithinContent;
this._stream.advance(this._stream.position - position);
} else if(value === '{ ') {
withinQuery = true;
this._state = ScannerState.AfterStartBody;
} else if(value === '( ') {
withinQuery = true;
this._state = ScannerState.AfterInput;
} else if(value === ')') {
let currentPosition = this._stream.position;
value = this._stream.advanceUntilNonWhitespace(1);
if(!value || (value && value === '{')) {
this._state = ScannerState.AfterInput;
withinQuery = true;
this._stream.retreat(this._stream.position - currentPosition);
} else {
this._state = ScannerState.WithinContent;
this._stream.advance(this._stream.position - currentPosition);
}
} else if(value === '/ ') {
withinQuery = true;
this._state = ScannerState.AfterMethod;
} else if(value && value.length > 0) {
withinQuery = true;
this._state = ScannerState.WithinContent;
} else {
this._state = ScannerState.WithinContent;
this._stream.advance(this._stream.position - position);
}
if(withinQuery) {
if(this._state === ScannerState.WithinContent) {
this._stream.retreat(value.length);
} else {
value = this._stream.retreatToTheClosest([/\s(DAEH|TUP|ETELED|TSOP|TEG)/i]);
if(value && value.length > 0) {
this._state = ScannerState.WithinContent;
this._stream.retreat(value.length);
}
}
}
}
private getNextToken():TextToken {
let token = null;
if(this._stream.char === '(') {
this._state = ScannerState.WithinInput;
} else if(this._stream.char === '?') {
this._state = ScannerState.WithinQueryString
}
switch(this._state) {
case ScannerState.WithinContent:
case ScannerState.Unknown:
this._stream.advanceUntilNonWhitespace();
if(this._stream.char === '/') {
token = this.getCommentToken();
} else if(this._stream.char === '{') {
token = this.getConfigurationToken();
} else {
token = this.getMethodToken();
}
break;
case ScannerState.WithinConfiguration:
token = this.getConfigurationToken();
break;
case ScannerState.AfterMethod:
token = this.getCommandToken();
break;
case ScannerState.WithinQueryString:
token = this.getQueryStringToken();
break;
case ScannerState.WithinInput:
token = this.getArgumentToken();
break;
case ScannerState.AfterQueryString:
case ScannerState.AfterInput:
case ScannerState.AfterCommand:
token = this.getBodyToken();
break;
}
return token;
}
private getPreviousToken(): TextToken {
let token = null;
if(this._state === ScannerState.WithinContent) {
this._stream.advanceUntil([/\}/, /\(/, /\s\//, /(DAEH|TUP|ETELED|TSOP|TEG)\s/i]);
if(this._stream.char === '}') {
this._state = ScannerState.AfterBody;
} else if(this._stream.char === ')') {
this._state = ScannerState.AfterInput;
} else if(this._stream.char === '/') {
this._state = ScannerState.AfterMethod;
} else {
this._state = ScannerState.WithinContent;
}
}
switch(this._state) {
case ScannerState.WithinContent:
case ScannerState.Unknown:
break;
case ScannerState.AfterMethod:
token = this.getCommandToken();
break;
case ScannerState.WithinInput:
token = this.getArgumentToken();
break;
case ScannerState.AfterBody:
token = this.getBodyTokenInBackward();
break;
}
return token;
}
private getCommentToken(): TextToken {
let token:TextToken = null;
let start = 0;
let value = '';
this._stream.advance();
if(this._stream.char === '*') {
this._state = ScannerState.WithinComment;
start = this._stream.position - 1;
value = this._stream.advanceUntilRegEx(/\*\/\s+/, true, 2);
if(value) {
token = textTokenFactory.createTextToken('/' + value, start, TokenType.Comment);
this._state = ScannerState.WithinContent;
}
}
return token;
}
private getConfigurationToken(): TextToken {
let token:TextToken = null;
if(this._state === ScannerState.WithinContent && this._stream.char === '{') {
this._state = ScannerState.WithinConfiguration;
this._entityDocumentScanner = new EntityDocumentScanner(this._source, this._stream.position);
}
token = this._entityDocumentScanner.scan();
if(token != null) {
if(token.type === EntityTokenType.CloseEntity) {
this._state = ScannerState.WithinContent;
let steps = this._entityDocumentScanner.offset - this.offset;
this._stream.advance(steps);
}
} else {
this._state = ScannerState.WithinContent;
}
return token;
}
public getPreviousMethodToken(): TextToken {
let token = null;
if(this._state === ScannerState.AfterMethod) {
this._stream.direction = TextStreamDirection.Backward;
let method = this._stream.advanceUntilRegEx(/DAEH|TUP|ETELED|TSOP|TEG/i);
if(method) {
token = textTokenFactory.createTextToken(method, this._stream.position, TokenType.Method);
this._state = ScannerState.AfterMethod;
}
this._stream.direction = TextStreamDirection.Forward;
}
return token;
}
private getMethodToken(): TextToken {
let token = null;
let method = this._stream.advanceUntilRegEx(/GET|POST|DELETE|PUT|HEAD/i);
if(method) {
token = textTokenFactory.createTextToken(method, this._stream.position, TokenType.Method);
this._stream.advance(method.length);
this._state = ScannerState.AfterMethod;
this._stream.advanceUntilNonWhitespace();
}
return token;
}
private getCommandToken(): TextToken {
let token = null;
let command = this._stream.advanceUntilRegEx(/[^\?|\(|\{|\n|\s]+/);
if(command) {
this._stream.advance(command.length);
let lengthBeforeTrim = command.length;
command = stringhelper.rtrim(command);
token = textTokenFactory.createTextToken(
command,
this._stream.position - lengthBeforeTrim,
TokenType.Command);
this._stream.advanceUntilNonWhitespace();
if(this._stream.char === '?' || this._stream.char === '(' || this._stream.char === '{') {
this._state = ScannerState.AfterCommand;
} else if(this._stream.position > token.offsetEnd) {
this._state = ScannerState.WithinContent;
} else {
this._state = ScannerState.AfterCommand;
}
}
return token;
}
private getQueryStringToken():PropertyToken {
let token = null;
if(this.isNotEndOfStream) {
if(this._stream.char === '?' || this._stream.char === '&') {
this._stream.advance();
let argumentName = this._stream.advanceUntilRegEx(/[\=|\&|\(|\{|\n]/, true);
token = propertyTokenFactory.createPropertyToken(
argumentName,
this._stream.position - argumentName.length,
TokenType.QueryString
);
token.propertyValueToken = this.getQueryStringValueToken();
this._stream.advanceUntilNonWhitespace();
}
if(this._stream.char == '(' || this._stream.char == '{') {
this._state = ScannerState.AfterQueryString
} else {
this._state = ScannerState.WithinQueryString
}
}
return token;
}
private getArgumentToken(): PropertyToken {
let token = null;
this._stream.advance();
let value = this._stream.advanceToTheClosest([/\)/, /\S/]);
if(value !== ')' && !this._stream.endOfStream) {
let argumentName = this._stream.advanceUntilRegEx(/[\:|\=]/, true);
token = propertyTokenFactory.createPropertyToken(
argumentName,
this._stream.position - value.length,
TokenType.Argument
);
token.propertyValueToken = this.getArgumentValueToken();
this._stream.advanceUntilNonWhitespace();
} else {
token = textTokenFactory.createTextToken(null, 0, TokenType.Empty);
}
if(this._stream.char == ')') {
this._stream.advanceUntilNonWhitespace(1);
let openingTag = '{';
if(this._stream.char == openingTag) {
this._state = ScannerState.AfterInput;
} else {
this._state = ScannerState.WithinContent;
}
} else {
this._state = ScannerState.WithinInput;
}
return token;
}
private getQueryStringValueToken(): TextToken {
let token = null;
this._stream.advanceUntilNonWhitespace();
if(this._stream.char === '=') {
let lastPosition = this._stream.position;
this._stream.advanceUntilNonWhitespace(1);
if(this.isNotEndOfStream) {
let char = this._stream.char;
if(char === '"') {
token = this.getArgumentStringValueToken();
if(token) {
token.type = TokenType.QueryStringValue;
}
} else {
let value = this._stream.advanceUntilRegEx(/[\&|\(|\{|\n)]/, true);
if(value) {
value = value.trim();
}
token = textTokenFactory.createTextToken(
value,
this._stream.position - value.length,
TokenType.QueryStringValue);
}
} else {
token = textTokenFactory.createTextToken(
'',
lastPosition + 1,
TokenType.QueryStringValue);
}
}
return token;
}
private getArgumentValueToken(): TextToken {
let token = null;
this._stream.advance();
this._stream.advanceUntilNonWhitespace();
if(this._stream.char === '"') {
token = this.getArgumentStringValueToken();
} else {
token = this.getArgumentNumberValueToken();
}
return token;
}
private getArgumentStringValueToken(): TextToken {
let token = null;
let value = '';
this._stream.advance();
while(!this._stream.endOfStream) {
if(this._stream.char !== '"') {
value += this._stream.char;
} else {
token = textTokenFactory.createTextToken(
value,
this._stream.position - value.length,
TokenType.ArgumentValue);
this._stream.advance();
break;
}
this._stream.advance();
}
return token;
}
private getArgumentNumberValueToken(): TextToken {
let token = null;
let value = '';
while(!this._stream.endOfStream) {
if(this._stream.char !== ' ' && this._stream.char !== ',' && this._stream.char !== ')') {
value += this._stream.char;
} else {
token = textTokenFactory.createTextToken(
value,
this._stream.position - value.length,
TokenType.ArgumentValue);
break;
}
this._stream.advance();
}
return token;
}
private getBodyTokenInBackward(): TextToken {
let token = this.getBodyToken('}', '{');
if(token) {
token.text = token.text.split('').reverse().join('');
this._stream.advanceUntilNonWhitespace();
if(!this._stream.endOfStream) {
if(this._stream.char === ')') {
this._state = ScannerState.AfterInput;
} else {
this._state = ScannerState.AfterCommand;
}
}
}
return token;
}
private getBodyToken(openingChar='{', closingChar='}'): TextToken {
let token = null;
let startTagsTicks = 0;
let body = '';
while(!this._stream.endOfStream) {
let char = this._stream.char;
body += char;
if(char === openingChar) {
if(this._state === ScannerState.AfterCommand) {
this._state = ScannerState.AfterStartBody;
}
startTagsTicks++;
} else if(char === closingChar) {
startTagsTicks--;
if(startTagsTicks === 0) {
this._state = ScannerState.AfterBody;
this._stream.advance();
break;
}
}
this._stream.advance();
}
if(body) {
token = textTokenFactory.createTextToken(
body,
this._stream.position - body.length,
TokenType.Body);
}
if(this._state === ScannerState.AfterBody) {
this._stream.advanceUntilNonWhitespace();
if(this._stream.char === '{') {
this._state = ScannerState.AfterCommand;
} else {
this._state = ScannerState.WithinContent;
}
} else {
if(token) {
token.isValid = false;
}
this._state = ScannerState.WithinContent;
}
return token;
}
}
|
Java
|
UTF-8
| 1,240
| 2.21875
| 2
|
[] |
no_license
|
package com.lagn.mascotas;
public class Razas {
private int id;
private String razaprro;
private int Fotoperro;
private int boton;
private int Likesdados;
public Razas(String razaprro, int fotoperro, int numerolikes) {
this.razaprro = razaprro;
this.Fotoperro = fotoperro;
this.Likesdados=numerolikes;
}
public Razas() {
}
public void setLikesdados(int likesdados) {
Likesdados = likesdados;
}
private int sumalk=0;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSumalk() {
return sumalk;
}
public void setSumalk(int sumalk) {
this.sumalk = sumalk;
}
public int getBoton() {
return boton;
}
public void setBoton(int boton) {
this.boton = boton;
}
public int getLikesdados() {
return Likesdados;
}
public String getRazaprro() {
return razaprro;
}
public void setRazaprro(String razaprro) {
this.razaprro = razaprro;
}
public int getFotoperro() {
return Fotoperro;
}
public void setFotoperro(int fotoperro) {
Fotoperro = fotoperro;
}
}
|
Java
|
UTF-8
| 11,391
| 1.953125
| 2
|
[] |
no_license
|
package com.imnu.mm.controller;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.imnu.mm.pojo.Image;
import com.imnu.mm.pojo.PagePojo;
import com.imnu.mm.pojo.Photo;
import com.imnu.mm.pojo.User;
import com.imnu.mm.service.ImageService;
import com.imnu.mm.service.PagingService;
import com.imnu.mm.service.PhotoService;
import com.imnu.mm.service.UserService;
@Controller
@RequestMapping("/images")
public class ImageController {
@Autowired
private UserService userService;
@Autowired
private ImageService imageService;
@Autowired
private PhotoService photoService;
@Autowired
private PagingService pagingService;
//跳转主页
@RequestMapping(value = "/forms",produces = "text/html;charset=utf-8")
@ResponseBody
public ModelAndView formsPage(int userId,Integer pageNum){
System.out.println("1.0成功");
if(pageNum==0) {
pageNum++;
}
User u = userService.selectUserById(userId);
ModelAndView mv = new ModelAndView();
if(u!=null) {
List<Image> images;
if(u.getType()==1) {
//管理员
images = imageService.selectImage();
}else {
//用户
images = imageService.selectImageByUserid(userId);
}
//分页显示
PagePojo<Image> pagePojo = new PagePojo();
if(images!=null) {
Integer pageNumber = images.size();
Integer pageCount;
if(pageNumber%10==0) {
pageCount = pageNumber/10;
}else {
pageCount = pageNumber/10+1;
}
pagePojo.setPageNumber(pageNumber);
pagePojo.setPageCount(pageCount);
pagePojo.setPageIndex(pageNum);
Integer pageIndex = (pageNum-1)*10;
if(u.getType()==1) {
//管理员
images =pagingService.pageImages(pageIndex);
}else {
//用户
images = pagingService.pageImagesByUid(userId, pageIndex);
}
mv.addObject("user", u);
mv.addObject("images", images);
mv.addObject("pagePojo", pagePojo);
mv.setViewName("message/forms");
return mv;
}else {
mv.addObject("user", u);
mv.addObject("images", images);
mv.setViewName("message/forms");
return mv;
}
}else {
mv.setViewName("redirect:/login.jsp");
return mv;
}
}
//管理员---摄影图片搜索
@RequestMapping(value = "/selectImg",produces = "text/html;charset=utf-8")
@ResponseBody
public ModelAndView selectImg(int userId,int selectType,String imgDate,String searchInfo){
User u = userService.selectUserById(userId);
ModelAndView mv = new ModelAndView();
if(u!=null) {
List<Image> images = null;
if(selectType==2) {
String str1 = imgDate.substring(0,10);
String str2 = imgDate.substring(13,23);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = sdf.parse(str1);
date2 = sdf.parse(str2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
images = imageService.selectImageByImgdate(date1, date2);
}else {
images = imageService.selectImageByLike(searchInfo);
}
mv.addObject("user", u);
mv.addObject("images", images);
mv.setViewName("message/forms");
return mv;
}else {
mv.setViewName("redirect:/login.jsp");
return mv;
}
}
//用户---日期搜索
@RequestMapping(value = "/selectUserImg",produces = "text/html;charset=utf-8")
@ResponseBody
public ModelAndView selectImg(int userId,String imgDate){
User u = userService.selectUserById(userId);
ModelAndView mv = new ModelAndView();
if(u!=null) {
String str1 = imgDate.substring(0,10);
String str2 = imgDate.substring(13,23);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = sdf.parse(str1);
date2 = sdf.parse(str2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//用户
List<Image> images = imageService.selectImageByImgdateAndUserid(date1, date2, userId);
mv.addObject("user", u);
mv.addObject("images", images);
mv.setViewName("message/forms");
return mv;
}else {
mv.setViewName("redirect:/login.jsp");
return mv;
}
}
//添加图片
@RequestMapping(value = "/addImage",produces = "text/html;charset=utf-8")
@ResponseBody
public String addImage(int userId,String imageData){
User u = userService.selectUserById(userId);
Image image = new Image();
if (u!=null&imageData!=null){
Decoder decoder = Base64.getDecoder();
// Base64解码
try {
byte[] b = decoder.decode(imageData);
for (int i = 0; i < b.length; ++i) {
// 调整异常数据
if (b[i] < 0) {
b[i] += 256;
}
}
// 生成jpeg图片
String photoName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ ".jpg";
// 新生成的图片
String imgFilePath = "D://Program Files (x86)/Camera_robot/photos/"+ photoName;
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
image.setImgaddress(imgFilePath);
image.setImgdatetime(new Date());
image.setImgname(photoName);
image.setUserid(u.getId());
image.setUsername(u.getUsername());
boolean re = imageService.addImage(image);
if(re) {
return JSON.toJSONString("1");
}else {
return JSON.toJSONString("0");
}
} catch (Exception e) {
return JSON.toJSONString("0");
}
}else {
return JSON.toJSONString("0");
}
}
//上传图片
@RequestMapping(value="/uploadImage",method=RequestMethod.POST)
@ResponseBody
public String uploadImage(int userId,String picUrl) {
User u = userService.selectUserById(userId);
Image image = new Image();
if (u!=null&picUrl!=null){
URL url = null;
try {
url = new URL(picUrl);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
// 新生成的图片
String photoName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ ".jpg";
String imgFilePath = "D://Program Files (x86)/Camera_robot/photos/"+ photoName;
FileOutputStream fileOutputStream = new FileOutputStream(new File(imgFilePath));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
image.setImgaddress(imgFilePath);
image.setImgdatetime(new Date());
image.setImgname(photoName);
image.setUserid(u.getId());
image.setUsername(u.getUsername());
boolean re = imageService.addImage(image);
if(re) {
return JSON.toJSONString("success");
}else {
return JSON.toJSONString("error");
}
}catch (IOException e) {
e.printStackTrace();
return JSON.toJSONString("error");
}
}else {
return JSON.toJSONString("error");
}
}
//上传作品页面
@RequestMapping(value = "/imgInfoPage",produces = "text/html;charset=utf-8")
public ModelAndView imgInfoPage(int userId,int imgId){
User u = userService.selectUserById(userId);
ModelAndView mv = new ModelAndView();
if(u!=null) {
Image image = imageService.selectImageById(imgId);
mv.setViewName("message/imgInfo");
mv.addObject("user", u);
mv.addObject("image", image);
return mv;
}else {
mv.setViewName("redirect:/login.jsp");
return mv;
}
}
//上传作品
@RequestMapping(value = "/imgInfo",produces = "text/html;charset=utf-8")
public ModelAndView imgInfoPage(Photo photo,int userId){
Integer pageNum = 1;
User u = userService.selectUserById(userId);
boolean re = photoService.addPhoto(photo);
ModelAndView mv = new ModelAndView();
if(u!=null&re){
List<Image> images;
if(u.getType()==1) {
//管理员
images = imageService.selectImage();
}else {
//用户
images = imageService.selectImageByUserid(userId);
}
//分页显示
PagePojo<Image> pagePojo = new PagePojo();
if(images!=null) {
Integer pageNumber = images.size();
Integer pageCount;
if(pageNumber%10==0) {
pageCount = pageNumber/10;
}else {
pageCount = pageNumber/10+1;
}
pagePojo.setPageNumber(pageNumber);
pagePojo.setPageCount(pageCount);
pagePojo.setPageIndex(pageNum);
Integer pageIndex = (pageNum-1)*10;
if(u.getType()==1) {
//管理员
images =pagingService.pageImages(pageIndex);
}else {
//用户
images = pagingService.pageImagesByUid(userId, pageIndex);
}
mv.addObject("user", u);
mv.addObject("images", images);
mv.addObject("pagePojo", pagePojo);
mv.setViewName("message/forms");
return mv;
}else {
mv.addObject("user", u);
mv.addObject("images", images);
mv.setViewName("message/forms");
return mv;
}
}else {
mv.setViewName("redirect:/login.jsp");
return mv;
}
}
//删除图片
@RequestMapping(value = "/deleteImage",produces = "text/html;charset=utf-8")
public ModelAndView deleteImage(int userId,int imageId){
Integer pageNum = 1;
User u = userService.selectUserById(userId);
boolean re = imageService.deleteImage(imageId);
ModelAndView mv = new ModelAndView();
if(u!=null&re) {
List<Image> images;
if(u.getType()==1) {
//管理员
images = imageService.selectImage();
}else {
//用户
images = imageService.selectImageByUserid(userId);
}
//分页显示
PagePojo<Image> pagePojo = new PagePojo();
if(images!=null) {
Integer pageNumber = images.size();
Integer pageCount;
if(pageNumber%10==0) {
pageCount = pageNumber/10;
}else {
pageCount = pageNumber/10+1;
}
pagePojo.setPageNumber(pageNumber);
pagePojo.setPageCount(pageCount);
pagePojo.setPageIndex(pageNum);
Integer pageIndex = (pageNum-1)*10;
if(u.getType()==1) {
//管理员
images =pagingService.pageImages(pageIndex);
}else {
//用户
images = pagingService.pageImagesByUid(userId, pageIndex);
}
mv.addObject("user", u);
mv.addObject("images", images);
mv.addObject("pagePojo", pagePojo);
mv.setViewName("message/forms");
return mv;
}else {
mv.addObject("user", u);
mv.addObject("images", images);
mv.setViewName("message/forms");
return mv;
}
}else {
mv.setViewName("redirect:/login.jsp");
return mv;
}
}
}
|
Python
|
UTF-8
| 12,249
| 2.71875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#!/usr/bin/env python
import logging
from dipy.data import get_sphere
from nose.tools import assert_equal
import numpy as np
from scipy.spatial.distance import (cosine, euclidean, mahalanobis)
from scipy.special import logsumexp, softmax
import torch
from torch.nn.utils.rnn import PackedSequence
from dwi_ml.models.direction_getter_models import (
CosineRegressionDirectionGetter, FisherVonMisesDirectionGetter,
GaussianMixtureDirectionGetter, L2RegressionDirectionGetter,
SingleGaussianDirectionGetter, SphereClassificationDirectionGetter)
from dwi_ml.models.utils.fisher_von_mises import (
fisher_von_mises_log_prob_vector)
"""
Included utils are:
test_cosine_regression_loss()
- identical vectors
- vectors with same angles
- vectors at 90 degrees
- vectors at 180 degrees
- comparison with scipy.spatial.distance.cosine
test_l2regression_loss()
- identical vectors
- comparison with scipy.spatial.distance.euclidean
test_gaussian_loss()
- x = mu
- comparison with (manual + scipy)
test_mixture_loss()
- comparison with (manual + scipy)
"""
# toDo
# test fisher von mises
tol = 1e-5
d = 3
logging.getLogger().setLevel(level='DEBUG')
def _independent_gaussian_log_prob_vector(x, mus, sigmas):
"""
Equivalent to the torch method in model.utils.gaussians. Easier to test.
Parameters
----------
x = the variable
mu = mean of the gaussian (x,y,z directions)
sigmas = standard deviation of the gaussian (x,y,z directions)
"""
# The inverse of a diagonal matrix is just inverting values on the
# diagonal
cov_inv = np.eye(d) * (1 / sigmas ** 2)
# sum(log) = log(prod)
logpdf = -d / 2 * np.log(2 * np.pi) - np.log(np.prod(sigmas)) \
- 0.5 * mahalanobis(x[:3], mus, cov_inv) ** 2
return logpdf
def _get_random_vector(size=3):
scaling = np.random.randint(1, 9)
return np.array(np.random.randn(size), dtype=np.float32) * scaling
def _prepare_tensor(a):
if isinstance(a, tuple):
a = tuple([torch.as_tensor(i[None, :], dtype=torch.float32)
for i in a])
elif isinstance(a, np.ndarray):
a = torch.as_tensor(a[None, :], dtype=torch.float32)
return a
def _prepare_packedsequence(a):
if not isinstance(a, PackedSequence):
a = PackedSequence(data=(torch.as_tensor(a[None, :],
dtype=torch.float32)),
batch_sizes=torch.as_tensor([1]))
return a
def _compute_loss_tensor(outputs, targets, model):
outputs = _prepare_tensor(outputs)
targets = _prepare_tensor(targets)
mean_loss, _ = model.compute_loss(outputs, targets)
# logging.debug("Means loss: {}.".format(mean_loss))
return np.asarray(mean_loss)
def test_cosine_regression_loss():
logging.debug('Testing cosine regression loss')
np.random.seed(1234)
model = CosineRegressionDirectionGetter(3)
logging.debug(" - Identical vectors x: expecting -1")
a = np.array([1, 0, 0])
b = np.array([1, 0, 0])
expected = np.array(-1)
value = _compute_loss_tensor(a, b, model)
assert_equal(value, expected)
logging.debug(" - Identical vectors y: expecting -1")
a = np.array([0, 1, 0])
b = np.array([0, 1, 0])
expected = np.array(-1)
value = _compute_loss_tensor(a, b, model)
assert_equal(value, expected)
logging.debug(" - Identical vectors z: expecting -1")
a = np.array([0, 0, 1])
b = np.array([0, 0, 1])
expected = np.array(-1)
value = _compute_loss_tensor(a, b, model)
assert_equal(value, expected)
logging.debug(" - Vectors with same angle: expecting -1")
scales = np.random.random(20) * 20
for s in scales:
a = np.array([1, 0, 0])
b = a * s
expected = np.array(-1)
value = _compute_loss_tensor(a, b, model)
assert_equal(value, expected)
logging.debug(" - Vectors with at 90 degrees 1: expecting 0")
a = np.array([1, 0, 0])
b = np.array([0, 1, 0])
expected = np.array(0)
value = _compute_loss_tensor(a, b, model)
assert_equal(value, expected)
logging.debug(" - Vectors with at 90 degrees 2: expecting 0")
a = np.array([1, 0, 0])
b = np.array([0, 0, 1])
expected = np.array(0)
value = _compute_loss_tensor(a, b, model)
assert_equal(value, expected)
logging.debug(" - Vectors with at 90 degrees random: expecting 0")
for _ in range(20):
a = _get_random_vector(3)
b = _get_random_vector(3)
c = np.cross(a, b)
expected = np.array(0)
value = _compute_loss_tensor(a, c, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
value = _compute_loss_tensor(b, c, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - Vectors with at 180 degrees random: expecting 1")
for _ in range(20):
a = _get_random_vector(3)
b = np.array(-a * (np.random.random() + 1e-3) *
np.random.randint(1, 10), dtype=np.float32)
expected = np.array(1)
value = _compute_loss_tensor(a, b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - Random vectors: comparing with cosine.")
for _ in range(200):
a = _get_random_vector(3)
b = _get_random_vector(3)
# model outputs -cos(a,b), but cosine computes 1-cos(a,b)
expected = cosine(a, b) - 1
value = _compute_loss_tensor(a, b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
def test_l2regression_loss():
logging.debug('\nTesting l2 regression loss')
np.random.seed(1234)
model = L2RegressionDirectionGetter(1)
logging.debug(" - Identical vectors: expecting 0")
a = _get_random_vector(3)
b = a
expected = np.array(0)
value = _compute_loss_tensor(a, b, model)
assert np.allclose(value, expected, atol=tol),\
"Failed; got: {}; expected: {}".format(value, expected)
# Test for random vector, compared to scipy's euclidean
for _ in range(200):
a = _get_random_vector(3)
b = _get_random_vector(3)
expected = euclidean(a, b)
value = _compute_loss_tensor(a, b, model)
assert np.allclose(value, expected, atol=tol),\
"Failed; got: {}; expected: {}".format(value, expected)
def test_sphere_classification_loss():
logging.debug('\nTesting sphere classification loss')
model = SphereClassificationDirectionGetter(1)
sphere = get_sphere('symmetric724')
logging.debug(" - Neg log likelihood, expecting -ln(softmax).")
logging.debug(" - Exactly the right class.")
# exactly the right class (#1)
# Note. To be realistic:
# With as many classes (724), the value of the output must be very
# high to have a low loss. The outputs (logits) don't have to be
# probabilities, as a softmax will be applied by torch.
logit = np.zeros((1, 724)).astype('float32')
logit[0, 1] = 100
b = sphere.vertices[1]
expected = -np.log(softmax(logit))[0, 1]
value = _compute_loss_tensor(logit, b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - With eps difference in the target: "
"Should get the same class.")
logit = np.zeros((1, 724)).astype('float32')
logit[0, 1] = 1
eps = 1e-3
b = sphere.vertices[1] + eps
expected = -np.log(softmax(logit))[0, 1]
value = _compute_loss_tensor(logit, b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - Exactly the right class test 2.")
logit = np.random.rand(1, 724).astype('float32')
logit[0, 1] = 1
b = sphere.vertices[1]
expected = -np.log(softmax(logit))[0, 1]
value = _compute_loss_tensor(logit, b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - Random")
logit = np.random.rand(1, 724).astype('float32')
b = sphere.vertices[1]
expected = -np.log(softmax(logit))[0, 1]
value = _compute_loss_tensor(logit, b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
def test_gaussian_loss():
logging.debug('\nTesting gaussian loss')
np.random.seed(1234)
model = SingleGaussianDirectionGetter(1)
logging.debug(" - Expecting mahalanobis value")
logging.debug(" - x = mu")
for _ in range(20):
a_means = _get_random_vector(3)
a_sigmas = np.exp(_get_random_vector(3))
b = a_means
# expected: x-mu = 0 ==> mahalanobis = 0
expected = -(-3 / 2 * np.log(2 * np.pi) - np.log(np.prod(a_sigmas)))
value = _compute_loss_tensor((a_means, a_sigmas), b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - random")
for _ in range(200):
a_means = _get_random_vector(3)
a_sigmas = np.exp(_get_random_vector(3))
b = _get_random_vector(3)
# Manual logpdf computation
logpdf = _independent_gaussian_log_prob_vector(b, a_means, a_sigmas)
expected = -logpdf
value = _compute_loss_tensor((a_means, a_sigmas), b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
def test_mixture_loss():
logging.debug('\nTesting mixture loss')
np.random.seed(1234)
model = GaussianMixtureDirectionGetter(1)
logging.debug(" - Expecting neg logsumexp(log_mixture + logpdf)")
logging.debug(" - Random")
for _ in range(200):
# 3 Gaussians * (1 mixture param + 3 means + 3 variances)
# (no correlations)
a_mixture_logits = _get_random_vector(3)
a_means = _get_random_vector(3 * 3).reshape((3, 3))
a_sigmas = np.exp(_get_random_vector(3 * 3)).reshape((3, 3))
b = _get_random_vector(3)
# Manual logpdf computation
mixture_params = softmax(a_mixture_logits)
logpdfs = np.array(
[_independent_gaussian_log_prob_vector(b, a_means[i], a_sigmas[i])
for i in range(3)])
expected = -logsumexp(np.log(mixture_params) + logpdfs)
value = _compute_loss_tensor(
(a_mixture_logits, a_means, a_sigmas), b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
def test_fisher_von_mises():
logging.debug('\nTesting fisher-Von mises loss')
model = FisherVonMisesDirectionGetter(1)
logging.debug(" - Expecting log prob.")
logging.debug(" - x = mu")
a_means = _get_random_vector(3)
a_kappa = np.exp(_get_random_vector(1))
b = a_means
expected = -fisher_von_mises_log_prob_vector(a_means, a_kappa, b)
value = _compute_loss_tensor((a_means, a_kappa), b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
logging.debug(" - Random")
a_means = _get_random_vector(3)
a_kappa = np.exp(_get_random_vector(1))
b = _get_random_vector(3)
expected = -fisher_von_mises_log_prob_vector(a_means, a_kappa, b)
value = _compute_loss_tensor((a_means, a_kappa), b, model)
assert np.allclose(value, expected, atol=tol), \
"Failed; got: {}; expected: {}".format(value, expected)
if __name__ == '__main__':
np.random.seed(1234)
test_cosine_regression_loss()
test_fisher_von_mises()
test_gaussian_loss()
test_l2regression_loss()
test_mixture_loss()
test_sphere_classification_loss()
|
Swift
|
UTF-8
| 1,726
| 3.3125
| 3
|
[] |
no_license
|
//
// content.swift
// simpleCarousel
//
// Created by Hanson on 16/3/19.
// Copyright © 2016年 hanson. All rights reserved.
//
import UIKit
class Content
{
// MARK: - Public API
var title = ""
var description = ""
var numberOfMembers = 0
var numberOfPosts = 0
var featuredImage: UIImage!
init(title: String, description: String, featuredImage: UIImage!)
{
self.title = title
self.description = description
self.featuredImage = featuredImage
numberOfMembers = 1
numberOfPosts = 1
}
// MARK: - Private
// dummy data
static func createContents() -> [Content]
{
return [
Content(title: "Hello there, my name is Linda", description: "We love backpack and adventures! We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea. ", featuredImage: UIImage(named: "lion")!),
Content(title: "whale", description: "We love romantic stories. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea.",
featuredImage: UIImage(named: "whale")!),
Content(title: "I am a girl", description: "Create beautiful apps. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea.",
featuredImage: UIImage(named: "hello")!),
Content(title: "I'm running,indeed.", description: "Cars and aircrafts and boats and sky. We walked to Antartica yesterday, and camped with some cute pinguines, and talked about this wonderful app idea.", featuredImage: UIImage(named: "run")!)
]
}
}
|
Python
|
UTF-8
| 747
| 2.515625
| 3
|
[] |
no_license
|
from collections import Counter
from nltk import tokenize
from datastore.table_names import BertTokenizedCluewebDoc, TokenizedCluewebDoc, CluewebDocTF
def tokenize_doc_and_save(buffered_saver, doc_id, core_text, tokenize_fn):
# tokenize the docs
chunks = bert_tokenize(core_text, tokenize_fn)
buffered_saver.save(BertTokenizedCluewebDoc, doc_id, chunks)
tokens = tokenize.word_tokenize(core_text)
buffered_saver.save(TokenizedCluewebDoc, doc_id, tokens)
tf = Counter(tokens)
buffered_saver.save(CluewebDocTF, doc_id, tf)
def bert_tokenize(core_text, tokenize_fn):
chunks = []
for sent in tokenize.sent_tokenize(core_text):
tokens = tokenize_fn(sent)
chunks.append(tokens)
return chunks
|
Java
|
UTF-8
| 2,703
| 2.703125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
/*
* Copyright (c) 2010, Nathan McCrina
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mccrina.GameOfLife;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class LifePanel extends JPanel
{
private boolean[][] cellData;
public LifePanel()
{
super();
cellData = new boolean[LifeData.BOARD_SIZE][LifeData.BOARD_SIZE];
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLACK);
if (LifeData.EDIT_MODE)
{
drawEditGrid(g);
drawCells(g);
}
else
{
drawCells(g);
}
}
public void drawCells(Graphics g)
{
for (int row = 0; row < LifeData.BOARD_SIZE; row++)
{
for (int col = 0; col < LifeData.BOARD_SIZE; col++)
{
if (cellData[row][col])
{
g.fillRect((col * 10), (row * 10), 10, 10);
}
}
}
}
public void drawEditGrid(Graphics g)
{
// Draw the grid lines
for (int row = 0; row <= LifeData.BOARD_SIZE; row++)
{
g.drawLine(0, row * 10, 650, row * 10);
}
for (int col = 0; col < LifeData.BOARD_SIZE; col++)
{
g.drawLine(col * 10, 0, col * 10, 605);
}
}
public void setCellData(boolean[][] data)
{
cellData = data;
}
}
|
Python
|
UTF-8
| 2,486
| 2.78125
| 3
|
[] |
no_license
|
import sys
import socket
import json
import glob
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
def download(namanya):
print "Request Download", namanya
sock.sendall("DOWNLOAD")
sock.sendall(namanya)
file_data=""
while True:
data = sock.recv(200)
if data=="FINISHED":
break
file_data+=data
fp = open(namanya,'wb+')
fp.write(file_data)
fp.close()
print namanya, "downloaded"
def upload(namanya):
print "Uploading", namanya
sock.sendall("UPLOAD")
sock.sendall(namanya)
count=0
kirim=""
fp = open(namanya,'rb')
message = fp.read()
fp.close()
for x in message:
kirim+=x
count+=1
if count%200==0:
sock.sendall(kirim)
kirim=""
elif count==len(message):
sock.sendall(kirim)
sock.sendall("FINISHED")
break
def menu():
print "-------------MENU-----------------"
print "1. Download : 1 nama_file"
print "2. Upload : 2 nama_file"
print "3. Your list : mylist"
print "4. Exit : exit"
#Tampilan Menu
jawab = raw_input()
if jawab=="Exit":
sock.sendall("EXIT")
sock.close()
sys.exit()
elif jawab =="mylist":
checkLocalFiles()
else:
if jawab[0]=="1":
namafile=""
count=0
for x in jawab:
if count>1:
namafile+=x
count+=1
print namafile
download(namafile)
elif jawab[0]=="2":
namafile=""
count=0
for x in jawab:
if count>1:
namafile+=x
count+=1
print namafile
upload(namafile)
def checkLocalFiles():
file_server = []
file_server.extend(glob.glob('*'))
print "------------mylist----------------"
for x in file_server:
print x
# Terima Data List Directory Server
listdir=""
while True:
data = sock.recv(200)
if data=="FINISHED":
break
listdir+=data
count=1
print "----------DIRECTORY SERVER------------"
for files in json.loads(listdir):
print count, files
count+=1
while True:
menu()
|
C++
|
UTF-8
| 1,431
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
class Solution {
public:
int myAtoi(string s) {
const int N = s.length();
// Step 1: remove leading whitespaces and save startPos of digits
int startPos = 0;
while(startPos < N && s[startPos] == ' '){
startPos += 1;
}
// Step 2: extract sign and update startPos of digits
int sign = 1;
if(startPos < N){
if(s[startPos] == '-'){
sign = -1;
startPos += 1;
}else if(s[startPos] == '+'){
sign = 1;
startPos += 1;
}
}
// Step 3: compute endPos of digits
int endPos = startPos;
while(endPos < N && isdigit(s[endPos])){
endPos += 1;
}
// Step 4: build num from digits s[startPos .. endPos - 1]
// clamp the answer if sign * num is out of the 32-bit signed integer range
int num = 0;
int limit = INT_MAX;
for(int i = startPos; i < endPos; ++i){
if(num <= (limit - (s[i] - '0')) / 10){
num = num * 10 + (s[i] - '0');
}else{
if(sign == -1){
return INT_MIN;
}else{
return INT_MAX;
}
}
}
return sign * num;
}
};
|
Java
|
UTF-8
| 602
| 2.3125
| 2
|
[] |
no_license
|
package aspects;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import aspects.service.ShapeService;
public class AopMain {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ShapeService shapeServiece = ctx.getBean("shapeService", ShapeService.class);
shapeServiece.getCircle();//.setNameReturn("Dumy name");
// System.out.println(shapeServiece.getCircle().getName());
// System.out.println(shapeServiece.getTriangle().getName());
}
}
|
C++
|
UTF-8
| 341
| 3.125
| 3
|
[] |
no_license
|
#pragma once
#include <string>
#include <iostream>
class Enemy
{
protected:
int _hp;
std::string _type;
public:
Enemy(int hp = 0, std::string const & type = "common");
Enemy(Enemy const &);
Enemy & operator=(Enemy const &);
virtual ~Enemy();
std::string const & getType() const;
int getHP() const;
virtual void takeDamage(int);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.