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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 2,732 | 1.921875 | 2 | [] | no_license | package com.kinth.mmspeed;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
@ContentView(R.layout.activity_flow_favorable_detail)
public class FlowFavorableDetailActivity extends BaseActivity {
@ViewInject(R.id.wv_detail)
private WebView webView;
@ViewInject(R.id.nav_tittle)
private TextView tvTittle;
@ViewInject(R.id.nav_right)
private ImageButton btnNavRight;
private String url;
public static final String INTENT_URL = "INTENT_URL";
public static final String INTENT_TITTLE = "INTENT_TITTLE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewUtils.inject(this);
url = getIntent().getStringExtra(INTENT_URL);
String tittleStr = getIntent().getStringExtra(INTENT_TITTLE);
tvTittle.setText(tittleStr+"");
btnNavRight.setVisibility(View.INVISIBLE);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边
view.loadUrl(url);
return true;
}
});
webView.addJavascriptInterface(new Object() {
@JavascriptInterface
public void sendSMS(String test) {
Message msg = mHandler.obtainMessage(0,test);
mHandler.sendMessage(msg);
}
}, "bridge");
webView.loadUrl(url);
}
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg.what == 0){
Uri uri = Uri.parse("smsto:10086");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", (String)msg.obj);
startActivity(it);
}
return false;
}
});
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();// 返回前一个页面
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
FlowFavorableDetailActivity.this.finish();
overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
|
Markdown | UTF-8 | 554 | 2.78125 | 3 | [] | no_license | # Scrap-a-Rent!
## Purpose
This app is used to scrap data from multiple data sources to find a rent; that data will be sent through email to some targed people
and to a mobile app to be shown as notifications.
## Technologies
1. Node.js
2. Pupeteer
3. Node-cron
## Features
1. Scrap data from Facebook Groups, OLX, storia.ro, imobiliare.ro
2. Email gathered data a couple of people
3. Send to mobile app the data
4. Save the data (optional)
5. Run a cron job every few x hours a day
## Next Phase Features
1. Admin panel
2. UI with scrapped data
|
Python | UTF-8 | 1,753 | 2.953125 | 3 | [
"MIT"
] | permissive | from PIL import Image
import numpy as np
from scipy.ndimage import filters
import matplotlib.pyplot as plt
import pickle
from carla import image_converter
def to_bgra_array(image):
"""Convert a CARLA raw image to a BGRA numpy array."""
array = np.frombuffer(image, dtype=np.dtype("uint8"))
array = np.reshape(array, (600, 800, 4))
return array
def to_rgb_array(image):
"""Convert a CARLA raw image to a RGB numpy array."""
array = to_bgra_array(image)
# Convert BGRA to RGB.
array = array[:, :, :3]
array = array[:, :, ::-1]
return array
def depth_to_array(image):
"""
Convert an image containing CARLA encoded depth-map to a 2D array containing
the depth value of each pixel normalized between [0.0, 1.0].
"""
array = to_bgra_array(image)
array = array.astype(np.float32)
# Apply (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1).
normalized_depth = np.dot(array[:, :, :3], [65536.0, 256.0, 1.0])
normalized_depth /= 16777215.0 # (256.0 * 256.0 * 256.0 - 1.0)
return normalized_depth
def depth_to_logarithmic_grayscale(image):
"""
Convert an image containing CARLA encoded depth-map to a logarithmic
grayscale image array.
"max_depth" is used to omit the points that are far enough.
"""
normalized_depth = depth_to_array(image)
# Convert to logarithmic depth.
logdepth = np.ones(normalized_depth.shape) + \
(np.log(normalized_depth) / 5.70378)
logdepth = np.clip(logdepth, 0.0, 1.0)
logdepth *= 255.0
# Expand to three colors.
return np.repeat(logdepth[:, :, np.newaxis], 3, axis=2)
with open('data.pkl','rb') as f:
rgb = pickle.load(f)
depth = pickle.load(f)
lidar = pickle.load(f)
lidar
|
C++ | UTF-8 | 782 | 2.9375 | 3 | [] | no_license | template<typename T>
struct CSum2D {
vector<vector<T> > d;
CSum2D(int h, int w):d(h+1, vector<T>(w+1,0)){}
void add(int y, int x, T v = 1) {
x++; y++;
assert(y < (int)d.size() && x < (int)d[0].size());
d[y][x] += v;
}
void build() {
for (int y = 0; y < (int)d.size(); ++y) {
for (int x = 1; x < (int)d[0].size(); ++x) {
d[y][x] += d[y][x-1];
}
}
for (int y = 1; y < (int)d.size(); ++y) {
for (int x = 0; x < (int)d[0].size(); ++x) {
d[y][x] += d[y-1][x];
}
}
}
T query(int x1, int y1, int x2, int y2) { //左上(x1,y1),右下(x2,y2) 0indexed
x1++; y1++; x2++; y2++;
assert(x2 < (int)d[0].size() && y2 < (int)d.size());
return d[y2][x2] - d[y1-1][x2] - d[y2][x1-1] + d[y1-1][x1-1];
}
}; |
JavaScript | UTF-8 | 2,086 | 2.75 | 3 | [] | no_license | "use strict"
describe('TasksService', function() {
beforeEach(module('goalbusterApp'));
var TasksService, httpBackend, TasksFactory, task1, task2;
var apiURL = "https://goalbuster-api.herokuapp.com";
var taskData = [{name: "read notes", frequency: "monthly", id: 1, completed: false}, {name: "buy bike", frequency: "daily", id:2, completed: true}];
var formObj = {name: "new task", frequency: "daily"};
var goalId = 1;
beforeEach(inject(function(_TasksService_, _TasksFactory_, $httpBackend){
TasksService = _TasksService_;
TasksFactory = _TasksFactory_;
httpBackend = $httpBackend;
}));
it ('featch a list of tasks for a goal', function() {
httpBackend.expectGET(apiURL + '/goals/' + goalId + "/tasks.json" ).respond(taskData)
task1 = new TasksFactory()
task2 = new TasksFactory()
task1.name = "read notes";
task2.name = "buy bike";
task1.frequency = "monthly"
task2.frequency = "daily"
task1.id = 1;
task2.id = 2;
task1.completed = false;
task2.completed = true;
TasksService.getAllFromApi(goalId).then(function(tasks){
expect(tasks).toContain(task1, task2);
});
httpBackend.flush();
});
it ('sends a post request', function() {
httpBackend.expectPOST(apiURL + '/goals/' + goalId +"/tasks").respond(201, 'success');
TasksService.postTaskToApi(formObj, goalId).then(function(response){
expect(response.status).toEqual(201);
});
httpBackend.flush();
});
it ('sends a put request', function() {
httpBackend.expectPUT(apiURL + "/tasks/" + task1.id).respond(204, 'task updated successfully');
TasksService.editTaskOnApi(task1).then(function(response){
expect(response.status).toEqual(204);
});
httpBackend.flush();
});
it ('deletes a task', function() {
httpBackend.expectDELETE(apiURL + "/tasks/" + task1.id).respond(204, 'task deleted successfully');
TasksService.deleteTaskOnApi(task1).then(function(response){
expect(response.status).toEqual(204);
});
httpBackend.flush();
});
});
|
C++ | UTF-8 | 4,434 | 2.5625 | 3 | [
"BSD-3-Clause-Open-MPI",
"MIT",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | // shasta.
#include "MarkerFinder.hpp"
#include "LongBaseSequence.hpp"
#include "performanceLog.hpp"
#include "ReadId.hpp"
#include "timestamp.hpp"
using namespace shasta;
// Standard library.
#include <chrono>
#include <limits>
MarkerFinder::MarkerFinder(
size_t k,
const MemoryMapped::Vector<KmerInfo>& kmerTable,
const Reads& reads,
MemoryMapped::VectorOfVectors<CompressedMarker, uint64_t>& markers,
size_t threadCountArgument) :
MultithreadedObject(*this),
k(k),
kmerTable(kmerTable),
reads(reads),
markers(markers),
threadCount(threadCountArgument)
{
// Initial message.
performanceLog << timestamp << "Finding markers in " << reads.readCount() << " reads." << endl;
const auto tBegin = std::chrono::steady_clock::now();
// Adjust the numbers of threads, if necessary.
if(threadCount == 0) {
threadCount = std::thread::hardware_concurrency();
}
const size_t batchSize = 100;
markers.beginPass1(2 * reads.readCount());
setupLoadBalancing(reads.readCount(), batchSize);
pass = 1;
runThreads(&MarkerFinder::threadFunction, threadCount);
markers.beginPass2();
markers.endPass2(false);
setupLoadBalancing(reads.readCount(), batchSize);
pass = 2;
runThreads(&MarkerFinder::threadFunction, threadCount);
markers.unreserve();
// Final message.
const auto tEnd = std::chrono::steady_clock::now();
const double tTotal = 1.e-9 * double((std::chrono::duration_cast<std::chrono::nanoseconds>(tEnd - tBegin)).count());
performanceLog << timestamp << "Finding markers completed in " << tTotal << " s." << endl;
}
void MarkerFinder::threadFunction(size_t threadId)
{
// Loop over batches assigned to this thread.
uint64_t begin, end;
while(getNextBatch(begin, end)) {
// Loop over reads of this batch.
for(ReadId readId=ReadId(begin); readId!=ReadId(end); readId++) {
const LongBaseSequenceView read = reads.getRead(readId);
size_t markerCount = 0; // For this read.
CompressedMarker* markerPointerStrand0 = 0;
CompressedMarker* markerPointerStrand1 = 0;
if(pass == 2) {
markerPointerStrand0 = markers.begin(OrientedReadId(readId, 0).getValue());
markerPointerStrand1 = markers.end(OrientedReadId(readId, 1).getValue()) - 1ULL;
}
if(read.baseCount >= k) { // Avoid pathological case.
// Loop over k-mers of this read.
Kmer kmer;
for(size_t position=0; position<k; position++) {
kmer.set(position, read[position]);
}
for(uint32_t position=0; /*The check is done later */; position++) {
const KmerId kmerId = KmerId(kmer.id(k));
if(kmerTable[kmerId].isMarker) {
// This k-mer is a marker.
if(pass == 1) {
++markerCount;
} else {
// Strand 0.
markerPointerStrand0->kmerId = kmerId;
markerPointerStrand0->position = position;
++markerPointerStrand0;
// Strand 1.
markerPointerStrand1->kmerId = kmerTable[kmerId].reverseComplementedKmerId;
markerPointerStrand1->position = uint32_t(read.baseCount - k - position);
--markerPointerStrand1;
}
}
if(position+k == read.baseCount) {
break;
}
// Update the k-mer.
kmer.shiftLeft();
kmer.set(k-1, read[position+k]);
}
}
if(pass == 1) {
markers.incrementCount(OrientedReadId(readId, 0).getValue(), markerCount);
markers.incrementCount(OrientedReadId(readId, 1).getValue(), markerCount);
} else {
SHASTA_ASSERT(markerPointerStrand0 ==
markers.end(OrientedReadId(readId, 0).getValue()));
SHASTA_ASSERT(markerPointerStrand1 ==
markers.begin(OrientedReadId(readId, 1).getValue()) - 1ULL);
}
}
}
}
|
Java | SHIFT_JIS | 1,895 | 2.453125 | 2 | [] | no_license | package jp.co.recruit.mtl.sample.async;
import java.util.ArrayList;
import java.util.List;
import jp.co.recruit.mtl.sample.dto.Tweet;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.content.Context;
import android.os.AsyncTask;
public class TwitterTimelineRequestTask extends
AsyncTask<String, Void, List<Tweet>> {
private Twitter twitter = null;
private AsyncTaskCallback callback;
public TwitterTimelineRequestTask(Context context) {
this.callback = (AsyncTaskCallback)context;
}
//obNOEhŎs鏈
@Override
protected List<Tweet> doInBackground(String... params) {
String userName = params[0];
Paging paging = new Paging();
if(twitter == null){
twitter = new TwitterFactory().getInstance();
}
List<Tweet> list = new ArrayList<Tweet>();
try {
//OAuth͖{̓eƗ̂ŁAPPublicȂ̂擾܂B
ResponseList<twitter4j.Status> timeline = twitter.getUserTimeline(userName, paging);
for(twitter4j.Status status : timeline){
Tweet tweet = new Tweet();
tweet.setId(status.getId());
tweet.setScreenName(status.getUser().getScreenName());
tweet.setImageUrl(status.getUser().getProfileImageURL().toString());
tweet.setText(status.getText());
tweet.setDate(status.getCreatedAt().toLocaleString());
list.add(tweet);
}
} catch (TwitterException e) {
e.printStackTrace();
if(e.isCausedByNetworkIssue()){
//lbg[NڑG[
//G[Ăˁ[
}else{
//ȊO ُ
}
}
return list;
}
//CXbh(GUIXbh)ő鏈
protected void onPostExecute(List<Tweet> result) {
callback.onFinishTask(result);
}
}
|
JavaScript | UTF-8 | 4,682 | 2.84375 | 3 | [] | no_license | d3.json("data/samples.json").then((importedData) => {
console.log("Firs read", importedData);
let names = importedData.names;
let samples = importedData.samples;
let prueba = samples[0].sample_values
let prueba1 = samples[0].otu_ids
let prueba2 = samples[0].otu_labels
let metadata = importedData.metadata
console.log("HOLA", metadata[0])
let table = d3.select("#sample-metadata")
table.append("p")
.attr("id","change")
.text(`\nid : ${metadata[0].id}\n
\nethnicity : ${metadata[0].ethnicity}\n
\ngender : ${metadata[0].gender}\n
\nage : ${metadata[0].age}\n
\nlocation : ${metadata[0].location}\n
\nbbtype : ${metadata[0].bbtype}\n\n ${String.fromCharCode(160)}\n
\nwfreq : ${metadata[0].wfreq}\n`)
//Append each value of "names" to dropdown menu
let dropdown = d3.select("#selDataset")
names.forEach(d => {
dropdown.append("option")
.attr("value", `${d}`)
.text(d)
});
prueba.sort(function (a, b) {
return parseFloat(b.sample_values) - parseFloat(a.sample_values);
})
prueba = prueba.slice(0, 10);
prueba = prueba.reverse();
let trace = {
x: prueba,
y: [`"OTU ${prueba1[9]}"`, `"OTU ${prueba1[8]}"`, `"OTU ${prueba1[7]}"`, `"OTU ${prueba1[6]}"`, `"OTU ${prueba1[5]}"`, `"OTU ${prueba1[4]}"`, `"OTU ${prueba1[3]}"`, `"OTU ${prueba1[2]}"`, `"OTU ${prueba1[1]}"`, `"OTU ${prueba1[0]}"`],
text: prueba2,
type: "bar",
orientation: "h"
}
let data = [trace]
Plotly.newPlot("bar", data)
let trace1 ={
x: prueba1,
y: prueba,
mode:'markers',
marker: {
color:['rgb(31, 119, 180)', 'rgb(255, 127, 14)',
'rgb(44, 160, 44)', 'rgb(214, 39, 40)',
'rgb(148, 103, 189)', 'rgb(140, 86, 75)',
'rgb(227, 119, 194)', 'rgb(127, 127, 127)',
'rgb(188, 189, 34)', 'rgb(23, 190, 207)'],
size:prueba
}
}
let dat=[trace1]
let lay ={
xaxis:{
title:{
text:'OTU ID'
}
}
}
Plotly.newPlot("bubble",dat,lay)
//Listener on change to obtain name choosen
dropdown.on("change", function () {
let namechoosen = d3.select("#selDataset").property("value");
metadata.forEach(d => {
if (d.id == namechoosen) {
let change = d3.select("#change")
table.text(`id:${d.id}\n
ethnicity : ${d.ethnicity}\n
gender : ${d.gender}\n
age : ${d.age}\n
location : ${d.location}\n
bbtype : ${d.bbtype}\n
wfreq : ${d.wfreq}`)
}
})
samples.forEach(d => {
let prueba = d.sample_values
let prueba1 = d.otu_ids
let prueba2 = d.otu_labels
prueba.sort(function (a, b) {
return parseFloat(b.sample_values) - parseFloat(a.sample_values);
})
prue = prueba.slice(0, 10);
prue = prue.reverse();
if (d.id == namechoosen) {
let trace = {
x: prue,
y: [`"OTU ${prueba1[9]}"`, `"OTU ${prueba1[8]}"`, `"OTU ${prueba1[7]}"`, `"OTU ${prueba1[6]}"`, `"OTU ${prueba1[5]}"`, `"OTU ${prueba1[4]}"`, `"OTU ${prueba1[3]}"`, `"OTU ${prueba1[2]}"`, `"OTU ${prueba1[1]}"`, `"OTU ${prueba1[0]}"`],
text: prueba2,
type: "bar",
orientation: "h"
}
let da = [trace]
let layout = {
title: "Otus"
}
Plotly.newPlot("bar", da, layout)
let trace1 ={
x: prueba1,
y: prueba,
mode:'markers',
marker: {
color:['rgb(31, 119, 180)', 'rgb(255, 127, 14)',
'rgb(44, 160, 44)', 'rgb(214, 39, 40)',
'rgb(148, 103, 189)', 'rgb(140, 86, 75)',
'rgb(227, 119, 194)', 'rgb(127, 127, 127)',
'rgb(188, 189, 34)', 'rgb(23, 190, 207)'],
size:prueba
}
}
let dat=[trace1]
let lay ={
xaxis:{
title:{
text:'OTU ID'
}
}
}
Plotly.newPlot("bubble",dat,lay)
}
})
})
}) |
C# | UTF-8 | 516 | 3.078125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace OpenLab_04._09
{
class Class1
{
public List<string> RemoveDups(List<string> a)
{
for (int o = 0; o < a.Count; o++)
{
for (int i = 0; i < a.Count; i++)
{
if (a[o] == a[i] & o != i)
{
a.Remove(a[o]);
}
}
}
return a;
}
}
} |
C++ | UTF-8 | 1,449 | 4.34375 | 4 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
//Here we initialize our function declarations
void showData(priority_queue <int> pq);
void showData(priority_queue <int, vector<int>, greater<int>> gq);
int main()
{
//priority_queue is the syntax we use to create a Priority Queue.
//Think of it similar to a Vector list. We can specifify if we want it
//to print it in descending(min to max) or asscending(max to min) order
//by giving the priority queue variable different parameters.
priority_queue <int> descendingPQ;
priority_queue <int, vector<int>, greater<int>> ascendingPQ;
//This is just pushing numbers into the queue list
//Change this variable to descendingPQ if you want to pop them in descending order.
ascendingPQ.push(4);
ascendingPQ.push(10);
ascendingPQ.push(3);
ascendingPQ.push(32);
ascendingPQ.push(2);
//This is the function we are using to show the data inside the list
showData(ascendingPQ);
return 0;
}
void showData(priority_queue <int> pq)
{
//While the priority queue is not empty, we are going to continuously pop items out of the queue and print them.
while (!pq.empty())
{
cout << " " << pq.top();
pq.pop();
}
cout << '\n';
}
void showData(priority_queue <int, vector<int>, greater<int>> pq)
{
//Same logic as in the previous function except this time we will pop them in ascending order.
while (!pq.empty())
{
cout << " " << pq.top();
pq.pop();
}
cout << '\n';
} |
C# | UTF-8 | 962 | 2.515625 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using UnitTestCoder.Core.Formatting;
using UnitTestCoder.Population.Maker;
namespace UnitTestCoder.Population.Coder
{
public class ObjectPopulationCoder : IObjectPopulationCoder
{
private readonly IObjectPopulationMaker objectPopulationMaker;
private readonly IIndenter indenter;
public ObjectPopulationCoder(
IObjectPopulationMaker objectPopulationMaker,
IIndenter indenter)
{
this.objectPopulationMaker = objectPopulationMaker;
this.indenter = indenter;
}
public string Code(object arg, string lvalue)
{
var lines = new[] { "{" }
.Concat(objectPopulationMaker.Populate(arg, lvalue))
.Concat(new[] { "}", "" });
return String.Join("\r\n", lines.Select(x => indenter.Indent(x, 0)));
}
}
}
|
Java | UTF-8 | 1,172 | 2.6875 | 3 | [
"MIT"
] | permissive | package tafit3.cplibrary;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.util.stream.Collectors.*;
import static tafit3.cplibrary.CartesianPowerDiagonally.*;
import static tafit3.cplibrary.TestUtils.*;
public class CartesianPowerDiagonallyIteratorTest extends AbstractCartesianPowerDiagonallyTest {
protected List<List<Integer>> solve(int setSize, int tupleLength) {
List<List<Integer>> res = new ArrayList<>();
cartesianPowerDiagonallyByIterator(setSize, tupleLength, tuple -> res.add(convertToList(tuple)));
return res;
}
@Test
public void testLimit3() {
Iterator<int[]> it = new CartesianPowerDiagonally.CartesianPowerDiagonallyIterator(100,2);
out(asStream(it).filter(pair -> pair[0] < pair[1]).limit(4).map(TestUtils::convertToList).collect(toList()));
}
public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
Iterable<T> iterable = () -> sourceIterator;
return StreamSupport.stream(iterable.spliterator(), false);
}
}
|
C | UTF-8 | 283 | 2.65625 | 3 | [
"MIT",
"BSD-2-Clause"
] | permissive | /* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
#include "util.h"
int main(void) {
gid_t gid = getgid();
int err = setgid(gid);
atomic_printf("setgid returned: %d\n", err);
test_assert(0 == err);
atomic_puts("EXIT-SUCCESS");
return 0;
}
|
C++ | UTF-8 | 3,758 | 2.875 | 3 | [
"MIT"
] | permissive | // 1057. Campus Bikes
// https://leetcode.com/problems/campus-bikes/
// Runtime: 160 ms, faster than 81.19% of C++ online submissions for Campus Bikes.
// Memory Usage: 44.3 MB, less than 31.19% of C++ online submissions for Campus Bikes.
class Solution {
public:
vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
const int M = workers.size();
const int N = bikes.size();
// {worker_idx, bike_idx}
vector<vector<pair<int, int>>> counters(2000);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
int d = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
counters[d].push_back({i, j});
}
}
vector<int> ans(M, -1);
vector<bool> assigned(N, false);
for (int k = 0, c = 0; k < 2000 && c < M; ++k) {
for (const auto& it : counters[k]) {
int i = it.first;
int j = it.second;
if (ans[i] >= 0 || assigned[j]) continue;
ans[i] = j;
assigned[j] = true;
if (++c >= M) break;
}
}
return ans;
}
};
// Runtime: 1172 ms, faster than 23.20% of C++ online submissions for Campus Bikes.
// Memory Usage: 98.2 MB, less than 7.22% of C++ online submissions for Campus Bikes.
class Solution {
public:
vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
const int M = workers.size();
const int N = bikes.size();
// val: bike_idx * M + worker_idx
vector<set<int>> counters(2000);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
int d = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1]);
counters[d].insert(j * M + i);
}
}
vector<int> ans(M, -1);
vector<bool> assigned(N, false);
for (int k = 0, c = 0; k < 2000 && c < M; ++k) {
for (auto it : counters[k]) {
int i = it % M;
int j = it / M;
if (ans[i] >= 0 || assigned[j]) continue;
ans[i] = j;
assigned[j] = true;
if (++c >= M) break;
}
}
return ans;
}
};
// TLE
class Solution {
public:
vector<int> assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
auto cmp = [&](pair<int, int>& l, pair<int, int>& r) {
const auto& wl = workers[l.first];
const auto& bl = bikes[l.second];
int dl = abs(wl[0] - bl[0]) + abs(wl[1] - bl[1]);
const auto& wr = workers[r.first];
const auto& br = bikes[r.second];
int dr = abs(wr[0] - br[0]) + abs(wr[1] - br[1]);
if (dl == dr) {
if (l.first == r.first) return l.second > r.second;
return l.first > r.first;
}
return dl > dr;
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> q(cmp);
for (int i = 0; i < workers.size(); ++i)
for (int j = 0; j < bikes.size(); ++j)
q.push({i, j});
vector<int> ans(workers.size(), -1);
vector<bool> assigned(bikes.size(), false);
int N = workers.size();
while (N > 0) {
int i = q.top().first;
int j = q.top().second;
q.pop();
if (ans[i] >= 0 || assigned[j]) continue;
ans[i] = j;
assigned[j] = true;
--N;
}
return ans;
}
}; |
C | UTF-8 | 1,538 | 2.71875 | 3 | [] | no_license | #include "HAL_USART.h"
void USART_Initialize(char usart_ch){
if(usart_ch == 2)
{
// Enable USART2 clock
RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
// Enable GPIOA clock (PA2 is used as TX pin, PA3 as RX)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// Set pins PA2 and PA3 to alternate function mode
GPIOA->MODER |= GPIO_MODER_MODER2_1 | GPIO_MODER_MODER3_1;
GPIOA->MODER &= ~(GPIO_MODER_MODER2_0 | GPIO_MODER_MODER3_0);
// Set pins PA2 and PA3 to output push-pull mode - Pins must not be floating for USART communication
GPIOA->OTYPER &= ~(GPIO_OTYPER_OT2 | GPIO_OTYPER_OT3);
// Activate alternate function mode USART2 for pin PA2
GPIOA->AFR[0] |= GPIO_AFRL_AFRL2_0 | GPIO_AFRL_AFRL2_1 | GPIO_AFRL_AFRL2_2;
GPIOA->AFR[0] &= ~GPIO_AFRL_AFRL2_3;
// Activate alternate function mode USART2 for pin PA3
GPIOA->AFR[0] |= GPIO_AFRL_AFRL3_0 | GPIO_AFRL_AFRL3_1 | GPIO_AFRL_AFRL3_2;
GPIOA->AFR[0] &= ~GPIO_AFRL_AFRL3_3;
// Configure USART2
// baudrate = clock / (baudrate * 16)
// The peripheral clock is runing at 16 Mhz -> baudrate = 16000000 / (9600 * 16) = 104,1666667
// hex(104) = 0x68
// 0,1666667 * 16 = 2,666667
// hex(2,666667) = 2
USART2->BRR = 0x682;
USART2->CR1 |= USART_CR1_TE;
//USART2->CR1 |= USART_CR1_RE;
USART2->CR1 |= USART_CR1_UE;
}
}
void USART_Print(char *msg, ...)
{
char buff[80];
va_list args;
va_start(args, msg);
vsprintf(buff, msg, args);
for(uint32_t i = 0; i < strlen(buff); i++)
{
USART2->DR = buff[i];
while( !(USART2->SR & USART_SR_TXE) );
}
}
|
Java | UTF-8 | 1,681 | 2.875 | 3 | [] | no_license | package com.w205.sessions;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.Callable;
import com.w205.utils.FileAccessFactory;
import com.w205.utils.Reader;
import com.w205.utils.Writer;
public class SingleFileOrderer implements Callable<String>
{
private String source;
private String file;
private String dest;
public SingleFileOrderer(String source, String file, String dest) throws Exception
{
this.source = "";
this.file = "";
this.dest = "";
this.file = file;
this.source = source;
this.dest = dest;
}
public String call()
{
try
{
ArrayList<LineUser> lines = new ArrayList<LineUser>();
Reader reader = FileAccessFactory.createReader((new StringBuilder(String.valueOf(source))).append(File.separator).append(file).toString());
for(String line = ""; line != null;)
{
line = reader.next();
if(line != null)
lines.add(new LineUser(line));
}
reader.close();
Collections.sort(lines);
Writer writer = FileAccessFactory.createWriter();
writer.open(dest + File.separator + file);
LineUser l;
for(Iterator<LineUser> iterator = lines.iterator(); iterator.hasNext(); writer.write(l.getLine()))
l = (LineUser)iterator.next();
writer.close();
return file;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
|
Markdown | UTF-8 | 1,395 | 2.828125 | 3 | [
"MIT"
] | permissive | # Table Tennis Tournament Generator
A web app that randomly generates a tournament structure based on a user-submitted list of names.
## How to install
* You'll need [Yarn](https://yarnpkg.com/lang/en/docs/install) or [npm](https://www.npmjs.com/get-npm) installed, so follow the installation docs for whichever you choose.
* Clone this repo.
* `cd` into your new folder.
* Run `yarn` or `npm install`.
* To spin up your local version, run `yarn start` or `npm start`.
* That's it!
## Built with
* [Yarn](https://yarnpkg.com) - package manager
* [React](https://reactjs.org/) - JavaScript library
* [Redux](https://redux.js.org/) - State container for JavaScript apps
* [Sass](https://sass-lang.com/) - CSS extension language
* [Gulp](https://gulpjs.com/) - JavaScript task runner
## Acknowledgements
* [Create React App](https://github.com/facebook/create-react-app) - For a very quick build of a React app
* [Fisher-Yates Shuffle](https://github.com/Daplie/knuth-shuffle) - The [Fisher-Yates Shuffle algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) for effective array randomisation, package-managed
* [Font Awesome](https://github.com/FortAwesome/Font-Awesome) - SVG icons for buttons
* [Normalize.scss](https://github.com/guerrero/normalize.scss) - SCSS version of [Normalize.css](https://necolas.github.io/normalize.css/), for importing and compiling with Sass. |
Python | UTF-8 | 188 | 3.109375 | 3 | [] | no_license | a = int(input())
if a == 1:
print("ACL")
elif a == 2:
print("ACLACL")
elif a == 3:
print("ACLACLACL")
elif a == 4:
print("ACLACLACLACL")
else:
print("ACLACLACLACLACL") |
Java | UTF-8 | 3,399 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2013 OpenBEL Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openbel.framework.compiler.kam;
import java.io.IOException;
import java.sql.SQLException;
import org.openbel.framework.common.cfg.SystemConfiguration;
import org.openbel.framework.core.df.DBConnection;
import org.openbel.framework.internal.KamDbObject;
/**
* KAMSchemaSetupService defines a service to setup a KAM schema instance
* to store a single KAM.
*
* @author Anthony Bargnesi {@code <abargnesi@selventa.com>}
*/
public interface KAMStoreSchemaService {
/**
* Set up the KAM catalog schema (DDL) in the kam catalog schema defined
* by {@link SystemConfiguration}.
*
* @throws SQLException Thrown if a SQL error occurred setting up schema
* @throws IOException Thrown if an I/O error occurred reading SQL files
* needed to set up schema
*/
public void setupKAMCatalogSchema()
throws SQLException, IOException;
/**
* Set up a KAMstore schema for the specific {@link DBConnection}. This
* includes the DDL to establish the schema.
*
* @param dbc {@link DBConnection}, the database connection to use
* @param schemaName {@link String}, the kam schema name, which cannot be
* null or empty
* @throws SQLException Thrown if a SQL error occurred setting up schema
* @throws IOException Thrown if an I/O error occurred reading SQL files
* needed to set up schema
*/
public void setupKAMStoreSchema(DBConnection dbc, String schemaName)
throws SQLException, IOException;
/**
* Delete a KAMstore schema for the specific {@link DBConnection}.
*
* @param dbc {@link DBConnection}, the database connection to use
* @param schemaName {@link String}, the kam schema name
* @throws SQLException Thrown if a SQL error occurred deleting the schema
* @throws IOException Thrown if an I/O error occurred reading SQL files
* needed to delete schema
*/
public boolean deleteKAMStoreSchema(DBConnection dbc, String schemaName)
throws SQLException, IOException;
/**
* Saves the {@link KamDbObject} to the kam catalog.
*
* @param kamDb {@link KamDbObject}, the kam database object
* @return {@link String} the KAM schema name
* @throws SQLException Thrown if a SQL error occurred saving the
* <tt>kamDb</tt> to the KAM catalog.
*/
public String saveToKAMCatalog(KamDbObject kamDb)
throws SQLException;
/**
* Deletes the kam info object with a given name from the kam catalog.
*
* @param kamName, the name of a kam database object
* @throws SQLException Thrown if a SQL error occurred deleting the
* kam database object from the KAM catalog.
*/
public void deleteFromKAMCatalog(String kamName)
throws SQLException;
}
|
Markdown | UTF-8 | 5,370 | 2.703125 | 3 | [] | no_license | # **API Spec - Fabric Grey**
# Feature
* JWT Auth
* MYSQL
# Build
- git clone reposotory
- composer update
- copy .env.example to .env
- php artisan jwt:secret
- php -S localhost:8000 -s public
## Authenticaion
All Api use this authentication
* Request:
- Header :
* Bearer-Token: "your token"
## Login
* Request:
- Method: POST
- Endpoint: /api/v1/login
- Header:
* Content-Type: application/json
* Accept: application/json
- Body:
```
{
"name": "string",
"password": "string"
}
```
- Response:
```
{
"massage": "success",
"result": {
"token":""
},
"code": 200
}
```
## Register
* Request:
- Method: POST
- Endpoint: /api/v1/register
- Header:
* Content-Type: application/json
* Accept: application/json
- Body:
```
{
"name": "string",
"email: : "string"
"password": "string"
}
```
- Response:
```
{
"user": {
"name": "string",
"email": "string",
"updated_at": "timestamp",
"created_at": "timestamp",
"id": "integer"
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N"
}
```
## CREATE Fabric
* Request:
- Method: POST
- Endpoint: /api/v1/fabric/store
- Header:
* Content-Type: application/json
* Accept: application/json
* Bearer Token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N"
- Body:
```
{
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
}
```
- Response:
```
{
"massage": "POST Data",
"data": {
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
"updated_at": "timestamp",
"created_at": "timestamp",
"id": "id"
},
"code": 200
}
```
## GET Fabric
* Request:
- Method: GET
- Endpoint: /api/v1/fabric/
- Header:
* Content-Type: application/json
* Accept: application/json
* Bearer Token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N"
- Response:
```
{
"massage": "GET Success",
"data": [
{
"id": "integer",
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
"updated_at": "timestamp",
"created_at": "timestamp",
},
{
"id": integer,
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
"updated_at": "timestamp",
"created_at": "timestamp",
},
],
"code": 200
}
```
## GET BY ID Fabric
* Request:
- Method: GET
- Endpoint: /api/v1/fabric/show/{param-ID}
- Header:
* Content-Type: application/json
* Accept: application/json
* Bearer Token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N"
- Response:
```
{
"massage": "GET ID Success",
"result": {
"id": integer,
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
"updated_at": "timestamp",
"created_at": "timestamp",
"machine": {
"id": "integer",
"name": "string",
"short_name": "string",
"type_machine": "string",
"created_at": "timestamp",
"updated_at": "timestamp"
}
},
"code": 200
}
```
## PUT Fabric
* Request:
- Method: PUT
- Endpoint: /api/v1/fabric/update/{param-ID}
- Header:
* Content-Type: application/json
* Accept: application/json
* Bearer Token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N"
- Body:
```
{
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
}
```
- Response:
```
{
"massage": "PUT Data",
"data": {
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
"updated_at": "timestamp",
"created_at": "timestamp",
"id": "id"
},
"code": 200
}
```
## DELETE Fabric
* Request:
- Method: DELETE
- Endpoint: /api/v1/fabric/delete/{param-ID}
- Header:
* Content-Type: application/json
* Accept: application/json
* Bearer Token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N"
- Response:
```
{
"massage": "Delete Data",
"data": {
"fabric_type": "string",
"machine_id: : "integer"
"brand": "string"
"po_number": "integer"
"updated_at": "timestamp",
"created_at": "timestamp",
"id": "id"
},
"code": 200
}
```
|
Java | UTF-8 | 1,059 | 1.90625 | 2 | [] | no_license | package com.obpoo.gfsfabricsoftware.PUG.UI;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.obpoo.gfsfabricsoftware.PUG.MVP.NearestLocation.NLView;
import com.obpoo.gfsfabricsoftware.PUG.Model.NLData;
import com.obpoo.gfsfabricsoftware.R;
public class MapViewPUG extends Fragment implements NLView {
public static MapViewPUG newInstance() {
MapViewPUG fragment = new MapViewPUG();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map_pug, container, false);
return view;
}
@Override
public void onGetNLResponse(NLData response) {
}
@Override
public void showDialog() {
}
@Override
public void hideDialog() {
}
@Override
public void showError(String message) {
}
}
|
PHP | UTF-8 | 3,565 | 2.640625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Question;
class QuestionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$questions = Question::all();
return response()->json($questions);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Assign input ke variable baru
$api_token = $request->api_token;
$title = $request->title;
$text = $request->text;
// Ambil data user berdasarkan dengan api token yang masuk
$user = User::where('api_token', $api_token)->first();
// Buat question
$question = new Question;
$question->title = $title;
$question->text = $text;
$question->user_id = $user->id;
$question->save();
// Return response
return response()->json([
'message' => 'Pertanyaan berhasil dibuat',
'data' => $question
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
// Assign parameter ke variabel baru
$question_id = $request->question_id;
// Ambil question sesuai parameter
$question = Question::find($question_id);
// Return response
return response()->json([
'id' => $question->id,
'title' => $question->title,
'text' => $question->text,
'user' => [
'id' => $question->user->id,
'email' => $question->user->email,
'username' => $question->user->username,
],
'answers' => $question->answers,
'created_at' => $question->created_at,
'updated_at' => $question->updated_at,
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
// Assign parameter ke variabel baru
$question_id = $request->question_id;
$title = $request->title;
$text = $request->text;
// Ambil data question sesuai dengan parameter
$question = Question::find($question_id);
// Assign nilai baru ke database
$question->title = $request->title;
$question->text = $request->text;
$question->save();
// Return response
return response()->json([
'message' => 'Data berhasil diupdate',
'data' => $question
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
// Assign parameter ke variabel baru
$question_id = $request->question_id;
// Ambil data question sesuai dengan parameter
$question = Question::find($question_id);
// Delete data
$question->delete();
// Return response
return response()->json([
'message' => 'Data berhasil dihapus',
'data' => $question
]);
}
}
|
Java | UTF-8 | 5,339 | 2.203125 | 2 | [] | no_license | package com.example.ebc003.tripolarcon.model;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by EBC003 on 1/11/2018.
*/
public class EditTradingServicesDetailsAsyncTask extends AsyncTask<String,Void,Boolean>{
private String TAG=EditTradingServicesDetailsAsyncTask.class.getSimpleName ();
ProgressBar progressBar;
private Context context;
public EditTradingServicesDetailsAsyncTask (Context context, ProgressBar progressBar){
this.context=context;
this.progressBar=progressBar;
}
@Override
protected void onPreExecute () {
progressBar.setVisibility (View.VISIBLE);
super.onPreExecute ();
}
@Override
protected Boolean doInBackground (String... strings) {
String mStrProductUnitData=strings[0];
String mStrServiceSourceTypeData=strings[1];
String mStrTradingServicesStatus=strings[2];
String mStrTradingServicesAction=strings[3];
String mStrTradingServicesFollowUp=strings[4];
String StrOrderDescriptionData=strings[5];
String StrProductAreaData=strings[6];
String StrTradingServiceRemark=strings[7];
String CurrentDate=strings[8];
String CurrentTime=strings[9];
String mStrCompanyId=strings[10];
String mStrAssignPersonId=strings[11];
String userID=strings[12];
String mStrCompanyName=strings[13];
String assignToName=strings[14];
String userName=strings[15];
List<NameValuePair> listData=new ArrayList<> ();
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_UNIT,mStrProductUnitData));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_SOURCE_TYPE,mStrServiceSourceTypeData));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_ENQUIRY_STATUS,mStrTradingServicesStatus));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_ENQUIRY_ACTION,mStrTradingServicesAction));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_FOLLOWUP,mStrTradingServicesFollowUp));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_ORDER_DESCRIPTION,StrOrderDescriptionData));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_AREA,StrProductAreaData));
listData.add (new BasicNameValuePair (Constants.TRADING_SERVICE_REMARK,StrTradingServiceRemark));
listData.add (new BasicNameValuePair (Constants.SHOW_PLAN_DATE,CurrentDate));
listData.add (new BasicNameValuePair (Constants.SHOW_PLAN_TIME,CurrentTime));
listData.add (new BasicNameValuePair (Constants.USER_ID,mStrCompanyId));
listData.add (new BasicNameValuePair (Constants.ASSIGN_TO,mStrAssignPersonId));
listData.add (new BasicNameValuePair (Constants.EMP_ID,userID));
listData.add (new BasicNameValuePair (Constants.COMPANY_NAME,mStrCompanyName));
listData.add (new BasicNameValuePair (Constants.ASSIGN_TO_NAME,assignToName));
listData.add (new BasicNameValuePair (Constants.USER_ID_NAME,userName));
Log.i (TAG,"mStrProductUnitData:-"+mStrProductUnitData);
Log.i (TAG,"mStrServiceSourceTypeData:-"+mStrServiceSourceTypeData);
Log.i (TAG,"mStrTradingServicesStatus:-"+mStrTradingServicesStatus);
Log.i (TAG,"mStrTradingServicesAction:-"+mStrTradingServicesAction);
Log.i (TAG,"mStrTradingServicesFollowUp:-"+mStrTradingServicesFollowUp);
Log.i (TAG,"StrOrderDescriptionData:-"+StrOrderDescriptionData);
Log.i (TAG,"StrProductAreaData:-"+StrProductAreaData);
Log.i (TAG,"StrTradingServiceRemark:-"+StrTradingServiceRemark);
Log.i (TAG,"CurrentDate:-"+CurrentDate);
Log.i (TAG,"CurrentTime:-"+CurrentTime);
Log.i (TAG,"mStrCompanyId:-"+mStrCompanyId);
Log.i (TAG,"mStrAssignPersonId:-"+mStrAssignPersonId);
Log.i (TAG,"userID:-"+userID);
Log.i (TAG,"mStrCompanyName:-"+mStrCompanyName);
Log.i (TAG,"assignToName:-"+assignToName);
Log.i (TAG,"userName:-"+userName);
JSONParser parser=new JSONParser ();
JSONObject response=parser.makeHttpRequest (Constants.URL_EDIT_TRADING_SERVICES_DETAILS,Constants.METHOD_POST,listData);
if (!response.isNull (Constants.REQUEST_STATUS)){
try {
String success=response.getString (Constants.REQUEST_STATUS);
Log.i (EditTradingServicesDetailsAsyncTask.class.getSimpleName ()," "+success);
}
catch (JSONException e) {
e.printStackTrace ();
}
}
else {
return false;
}
return true;
}
@Override
protected void onPostExecute (Boolean aBoolean) {
if (aBoolean){
progressBar.setVisibility (View.GONE);
}
else {
Toast.makeText (context,"Something Wrong",Toast.LENGTH_LONG).show ();
}
super.onPostExecute (aBoolean);
}
}
|
Markdown | UTF-8 | 19,988 | 2.9375 | 3 | [] | no_license | <p data-nodeid="2380" class=""><strong data-nodeid="2473">微服务设计最核心的难题是微服务的拆分</strong>,不合理的微服务拆分不仅不能提高研发效率,反倒还使得研发效率更低,因此要讲究“小而专”的设计。“小而专”的设计意味着微服务的设计不是简单拆分,而是对设计提出了更高的要求,要“<strong data-nodeid="2474">低耦合、高内聚</strong>”。那么,如何做到“低耦合、高内聚”,实现微服务的“小而专”呢?那就需要“领域驱动设计”作为方法论,来指导我们的开发。</p>
<p data-nodeid="2381">用“领域驱动设计”是业界普遍认可的解决方案,也就是解决微服务如何拆分,以及实现微服务的高内聚与单一职责的问题。但是,领域驱动设计应当怎样进行呢?怎样从需求分析到软件设计,用正确的方式一步一步设计微服务呢?现在我们用一个在线订餐系统实战演练一下微服务的设计过程。</p>
<h3 data-nodeid="2382">在线订餐系统项目实战</h3>
<p data-nodeid="2383">相信我们都使用过在线订餐系统,比如美团、大众点评、百度外卖等,具体的业务流程如下图所示:</p>
<p data-nodeid="2384"><img src="https://s0.lgstatic.com/i/image/M00/73/8C/CgqCHl_GC1CAIiNuAAXvExRcOfE315.png" alt="Drawing 0.png" data-nodeid="2480"></p>
<div data-nodeid="2385"><p style="text-align:center">在线订餐系统的业务流程图</p></div>
<ul data-nodeid="2386">
<li data-nodeid="2387">
<p data-nodeid="2388">当我们进入在线订餐系统时,首先看到的是各个饭店,进入每个饭店都能看到他们的菜单;</p>
</li>
<li data-nodeid="2389">
<p data-nodeid="2390">下单时,订单中就会包含我们订的是哪家饭店、菜品、数量及我们自己的配送地址;</p>
</li>
<li data-nodeid="2391">
<p data-nodeid="2392">下单后,相应的饭店就会收到该下单系统;</p>
</li>
<li data-nodeid="2393">
<p data-nodeid="2394">接着,饭店接单,然后开始准备餐食;</p>
</li>
<li data-nodeid="2395">
<p data-nodeid="2396">当饭店的餐食就绪以后,通知骑士进行派送;</p>
</li>
<li data-nodeid="2397">
<p data-nodeid="2398">最后,骑士完成了餐食的派送,订单送达,我们就愉悦地收到了订购的美味佳肴。</p>
</li>
</ul>
<p data-nodeid="2399">现在,我们要以此为背景,按照微服务架构来设计开发一个在线订餐系统。那么,我们应当如何从分析理解需求开始,一步一步通过前面讲解的领域驱动设计,最后落实到拆分微服务,把这个系统拆分出来呢?</p>
<h3 data-nodeid="2400">统一语言建模</h3>
<p data-nodeid="2401"><strong data-nodeid="2493">软件开发的最大风险是需求分析</strong>,因为在这个过程中谁都说不清楚能让对方了解的需求。</p>
<p data-nodeid="2402"><img src="https://s0.lgstatic.com/i/image/M00/78/38/Ciqc1F_J28KAVMGVAAEuq941Nzw844.png" alt="image (3).png" data-nodeid="2496"></p>
<h4 data-nodeid="2403">研发不懂客户、客户也不懂研发</h4>
<p data-nodeid="2404">在这个过程中,对于客户来说:</p>
<ul data-nodeid="2405">
<li data-nodeid="2406">
<p data-nodeid="2407">客户十分清楚他的业务领域知识,以及他亟待解决的业务痛点;</p>
</li>
<li data-nodeid="2408">
<p data-nodeid="2409">然而,<strong data-nodeid="2505">客户不清楚技术能如何解决他的业务痛点</strong>。</p>
</li>
</ul>
<p data-nodeid="2410">因此,用户在提需求时,是在用他有限的认知,想象技术如何解决他的业务痛点。所以这样提出的业务需求往往不太靠谱,要么技术难于实现,要么并非最优的方案。</p>
<p data-nodeid="2411">与此同时,在需求分析过程中,对于研发人员来说:</p>
<ul data-nodeid="2412">
<li data-nodeid="2413">
<p data-nodeid="2414">非常清楚技术以及能解决哪些业务问题,同时也清楚它是如何解决的;</p>
</li>
<li data-nodeid="2415">
<p data-nodeid="2416">然而,欠缺的是对客户所在的业务领域知识的掌握,使得无法准确理解客户的业务痛点。</p>
</li>
</ul>
<p data-nodeid="2417">这就局限了我们的设计,进而所做的系统不能完美地解决用户痛点。</p>
<p data-nodeid="2418">因此,在需求分析的过程中,不论是客户还是我们,都不能掌握准确理解需求所需的所有知识,这就导致,不论是谁都不能准确地理解与描述软件需求。在需求分析中常常会出现,客户以为他描述清楚需求了,我们也以为我们听清楚了。但当软件开发出来以后,客户才发现这并不是他需要的软件,而我们也发现我们并没有真正理解需求。尽管如此,客户依然没有想清楚他想要什么,而我们还是不知道该怎样做,这就是软件开发之殇。</p>
<p data-nodeid="2419"><img src="https://s0.lgstatic.com/i/image/M00/78/44/CgqCHl_J28-AUVmoAAElMQ-u9fo352.png" alt="DDD 07--金句.png" data-nodeid="2514"></p>
<h4 data-nodeid="2420">如何破局需求分析的困境?</h4>
<p data-nodeid="2421">如何能够破解这个困局呢?关键的思想就在于“<strong data-nodeid="2525">统一语言建模</strong>”。也就是说,以上问题的根源在于<strong data-nodeid="2526">语言沟通的障碍</strong>,使得我不能理解你,而你也不能理解我。因此,解决的思路就是:</p>
<ul data-nodeid="2422">
<li data-nodeid="2423">
<p data-nodeid="2424">我主动学习你的语言,了解你的业务领域知识,并用你的语言与你沟通;</p>
</li>
<li data-nodeid="2425">
<p data-nodeid="2426">同时,我也主动地让你了解我的语言,了解我的业务领域知识,并用我的语言与你沟通。</p>
</li>
</ul>
<p data-nodeid="2427">回到需求分析领域,我们清楚的是技术,但不了解业务,因此,应当主动地去了解业务。那么,<strong data-nodeid="2538">如何了解业务呢</strong>?找书慢慢地去学习业务吗?也不是,因为我们不是要努力成为业务领域专家,而仅仅是<strong data-nodeid="2539">要掌握与要开发软件相关的业务领域知识</strong>。在业务领域漫无目的地学习,学习效率低而收效甚微。</p>
<p data-nodeid="2428">所以,我们应当从客户那里去学习,比如询问客户,仔细聆听客户对业务的描述,在与客户的探讨中快速地学习业务。然而,在这个过程中,一个非常重要的关键就是,<strong data-nodeid="2545">注意捕获客户在描述业务过程中的那些专用术语,努力学会用这些专用术语与客户探讨业务</strong>。</p>
<p data-nodeid="2429">久而久之,用客户的语言与客户沟通,你们的沟通就会越来越顺畅,客户也会觉得你越来越专业,愿意与你沟通,并可以与你探讨越来越深的业务领域知识。当你对业务的理解越来越深刻,你就能越来越准确地理解客户的业务及痛点,并运用自己的技术专业知识,用更加合理的技术去解决用户的痛点。这样,你们的软件就会越来越专业,让用户能越来越喜欢购买和使用你们的软件,并形成长期合作关系。</p>
<h4 data-nodeid="2430">我的项目应用举例</h4>
<p data-nodeid="2431">以我做过的一个远程智慧诊疗数据模型为例,这是一个面向中医的数据模型。在与客户探讨需求的过程中,我们很快发现,用户在描述中医的诊疗过程中,许多术语与西医有很大的不同。</p>
<p data-nodeid="2432">比如,他们在描述患者症状的时候,通常不用“症状”这个词,而是用“表象”。表象包括症状、体征、检测指标,是医生通过不同方式捕获患者病症的所有外部表现;同时,他们在诊断的时候也不用“疾病”这个词,而是“证候”。中医认为,证候才是患者疾病在身体中的内部根源,抓住证候,将证候的问题解决了,疾病自然就药到病除了。我们把握了这些术语后,用这些术语与业务专家进行沟通,沟通就变得异常顺利。客户会觉得我们非常专业,很懂他们,并且变得异常积极地与我们探讨需求,并很快建立了一种长期合作的关系。</p>
<p data-nodeid="2433">同时,在这个过程中,我们一边在与客户探讨业务领域知识,一边又可以让客户参与到我们分析设计的工作中来,用客户能够理解的语言让客户清楚我们是如何设计软件的。这样,当客户有参与感以后,就会对我们的软件有更强烈的认可度,更有利于软件的推广。此外,客户参与了并理解我们是怎么做软件的,就会逐步形成一种默契。使得客户在日后提需求、探讨需求的时候,提出的需求更靠谱,避免技术无法实现的需求,使得需求质量大幅度得到提高。</p>
<h3 data-nodeid="2434">事件风暴会议</h3>
<h4 data-nodeid="2435">什么是事件风暴</h4>
<p data-nodeid="2436">在领域驱动设计之初的需求分析阶段,<strong data-nodeid="2562">对需求分析的基本思路就是统一语言建模,它是我们的指导思想</strong>。但落实到具体操作层面,可以采用的实践方法是<strong data-nodeid="2563">事件风暴(Event Storming)</strong>。它是一种基于工作坊的 DDD 实践方法,可以帮助我们快速发现业务领域中正在发生的事件,指导领域建模及程序开发。它是由意大利人 Alberto Brandolini 发明的一种领域驱动设计实践方法,被广泛应用于业务流程建模和需求工程。</p>
<p data-nodeid="2437">这个方法的基本思想,就是将软件开发人员和领域专家聚集在一起,一同讨论、相互学习,即统一语言建模。但它的工作方式类似于头脑风暴,让建模过程变得更加有趣,让学习业务变得更加容易。因此,事件风暴中的“风暴”,就是运用头脑风暴会议进行领域分析建模。</p>
<p data-nodeid="2438">那么,这里的“事件”是什么意思呢?<strong data-nodeid="2574">事件即事实</strong>(Event as Fact),<strong data-nodeid="2575">即在业务领域中那些已经发生的事件就是事实</strong>(fact)。过去已经发生的事件已经成为了事实就不会再更改,因此信息管理系统就可以将这些事实以信息的形式存储到数据库中,即信息就是一组事实。</p>
<p data-nodeid="2439">说到底,一个信息管理系统的作用,就是存储这些事实,对这些事实进行管理与跟踪,进而起到提高工作效率的作用。因此,分析一个信息管理系统的业务需求,就是准确地抓住业务进行过程中那些需要存储的关键事实,并围绕着这些事实进行分析设计、领域建模,这就是“事件风暴”的精髓。</p>
<h4 data-nodeid="2440">召开事件风暴会议</h4>
<p data-nodeid="2441">因此,<strong data-nodeid="2587">实践“事件风暴”方法,就是让开发人员与领域专家坐在一起,开事件风暴会议</strong>。<strong data-nodeid="2588">会议的目的就是与领域专家一起进行领域建模</strong>,而会议前的准备就是在会场准备一个大大的白板与各色的便笺纸,如下图所示:</p>
<p data-nodeid="2442"><img src="https://s0.lgstatic.com/i/image/M00/73/81/Ciqc1F_GC3OAV1fMAAMURptGIOs120.png" alt="Drawing 2.png" data-nodeid="2591"></p>
<div data-nodeid="2443"><p style="text-align:center">事件风暴会议图</p></div>
<p data-nodeid="2444">当开始事件风暴会议以后,通常分为这样几个步骤。</p>
<p data-nodeid="2445">首先,在产品经理的引导下,与业务专家开始梳理当前的业务中有哪些领域事件,即已经发生并需要保存下来的那些事实。这时,是按照业务流程依次去梳理领域事件的。例如,在本案例中,整个在线订餐过程分为:已下单、已接单、已就绪、已派送和已送达,这几个领域事件。注意,领域事件是已发生的事实,因此,在命名的时候应当<strong data-nodeid="2598">采用过去时态</strong>。</p>
<p data-nodeid="2446">这里有一个十分有趣的问题值得探讨。在用户下单之前,用户首先是选餐。那么,“用户选餐”是不是领域事件呢?注意,领域事件是那些已经发生并且需要保存的重要事实。这里,“用户选餐”仅仅是一个查询操作,并不需要数据库保存,因此不能算领域事件。那么,难道这些查询功能不在需求分析的过程中吗?</p>
<p data-nodeid="2447">注意,DDD 有自己的适用范围,它往往应用于系统增删改的业务场景中,而查询场景的分析往往不用 DDD,而是通过其他方式进行分析。分析清楚了领域事件以后,就用橘黄色便笺纸,将所有的领域事件罗列在白板上,确保领域中所有事件都已经被覆盖。</p>
<p data-nodeid="2448">紧接着,针对每一个领域事件,项目组成员开始不断地围绕着它进行业务分析,增加各种命令与事件,进而思考与之相关的资源、外部系统与时间。例如,在本案例中,首先分析“已下单”事件,分析它触发的命令、与之相关的人与事儿,以及发生的时间。命令使用蓝色便笺,人和事儿使用黄色便笺,如下图所示:</p>
<p data-nodeid="2449"><img src="https://s0.lgstatic.com/i/image/M00/73/81/Ciqc1F_GC36AZB4BAADY1e6dHOY773.png" alt="Drawing 3.png" data-nodeid="2604"></p>
<div data-nodeid="2450"><p style="text-align:center">“已下单”的领域事件分析图</p></div>
<p data-nodeid="2451">“已下单”事件触发的命令是“下单”,执行者是“用户”(画一个小人作为标识),执行时间是“下单时间”。与它相关的人和事儿有“饭店”与“订单”。在此基础上进一步分析,用户关联到用户地址,饭店关联到菜单,订单关联到菜品明细。</p>
<p data-nodeid="2452">然后,就是识别模型中可能涉及的聚合及其聚合根。第 05 讲谈到,所谓的“聚合”就是整体与部分的关系,譬如,饭店与菜单是否是聚合关系,关键看它俩的数据是如何组织的。如果菜单在设计时是独立于饭店之外的,如“宫保鸡丁”是独立于饭店的菜单,每个饭店都是在引用这条记录,那么菜单与饭店就不是聚合关系,即使删除了这个饭店,这个菜单依然存在。</p>
<p data-nodeid="2453">但如果菜单在设计时,每个饭店都有自己独立的菜单,譬如同样是“宫保鸡丁”,饭店 A 与饭店 B 使用的都是各自不同的记录。这时,菜单在设计上就是饭店的一个部分,删除饭店就直接删除了它的所有菜单,那么菜单与饭店就是聚合关系。在这里,那个代表“整体”的就是聚合根,所有客户程序都必须要通过聚合根去访问整体中的各个部分。</p>
<p data-nodeid="2454">通过以上分析,我们认为用户与地址、饭店与菜单、订单与菜品明细,都是聚合关系。如果是聚合关系,就在该关系上贴一张紫色便笺。</p>
<p data-nodeid="2455">按照以上步骤,一个一个地去分析每个领域事件:</p>
<p data-nodeid="2456"><img src="https://s0.lgstatic.com/i/image/M00/73/8D/CgqCHl_GC6CAe3wiAAEmEkjuc5E956.png" alt="Drawing 4.png" data-nodeid="2612"><br>
<img src="https://s0.lgstatic.com/i/image/M00/73/8D/CgqCHl_GC6WAJbNbAAFIuWmPKd8182.png" alt="Drawing 5.png" data-nodeid="2616"></p>
<div data-nodeid="2457"><p style="text-align:center">在线订餐系统的领域事件分析图</p></div>
<p data-nodeid="2458">当所有的领域事件都分析完成以后,最后再站在全局对整个系统进行模块的划分,划分为多个限界上下文,并在各个限界上下文之间,定义它们的接口,规划上下文地图。</p>
<h3 data-nodeid="2459">总结</h3>
<p data-nodeid="2460">按照 DDD 的思想进行微服务设计,首先是从需求分析开始的。但 DDD 彻底改变了我们需求分析的方式,采用统一语言建模,让我们更加主动地理解业务,用客户的语言与客户探讨需求。<strong data-nodeid="2624">统一语言建模是指导思想,事件风暴会议是实践方法</strong>。运用事件风暴会议与客户探讨需求、建立模型,我们能更加深入地理解需求,而客户也更有参与感。此外,事件风暴会议可以作为敏捷开发中迭代计划会议前的准备会议的一个部分。</p>
<p data-nodeid="2461">然而,通过事件风暴会议形成的领域模型,又该如何落地到微服务的设计呢?还会遇到哪些设计与技术难题呢?下一讲将进一步讲解领域模型的微服务设计实现。</p>
<p data-nodeid="2462" class="te-preview-highlight"><a href="https://shenceyun.lagou.com/t/Mka" data-nodeid="2630"><img src="https://s0.lgstatic.com/i/image/M00/6F/ED/CgqCHl-3asqAMY9AAAhXSgFweBY030.png" alt="Drawing 24.png" data-nodeid="2629"></a></p>
<p data-nodeid="2463" class="">《Java 工程师高薪训练营》</p>
<p data-nodeid="2464" class="">拉勾背书内推+硬核实战技术干货,帮助每位 Java 工程师达到阿里 P7 技术能力。<a href="https://shenceyun.lagou.com/t/Mka" data-nodeid="2635">点击链接</a>,快来领取!</p>
---
### 精选评论
##### **3251:
> 希望这个例子一直能够延续到后面,通过分析,然后转化到整个项目进入开发,太有用了,但还需要深入理解,辛苦啦~
##### **钊:
> 这里的统一语言是指什么? 只看到开发与业务的讨论。
###### 讲师回复:
> 让你与客户用同一个业务领域的术语来讨论问题,即让开发学会用业务领域的术语与客户讨论
##### *欢:
> 范老师抽空麻烦回答下:1.请教下角色和菜单对应关系多对多,所以角色和菜单是各自独立的聚合跟是不?2.在角色选择菜单的时候那么领出来一个角色菜单聚合根引用角色值对象和菜单值对象进行处理是吗?3. 如果很多的多对多的关系岂不是要领出来很类似多对多的聚合根呢?
###### 讲师回复:
> 注意:角色和菜单不是聚合关系,仅仅是关联关系。当删除角色时会删除菜单吗?或者当删除菜单时会删除角色吗?聚合是整体与部分的关系,每个聚合都只能有一个聚合根。如果不是这样,说明我们对聚合的理解出现问题。
##### **高:
> 注意,DDD 有自己的适用范围,它往往应用于系统增删改的业务场景中,而查询场景的分析往往不用 DDD,而是通过其他方式进行分析。 按照这句话理解,那么前面讲的那么多组装数据就没用了?按照之前讲的,我得理解是模型驱动设计,再后来一些列的解耦,查询不算是一种模型驱动组装数据吗??这里为什么说不适用,麻烦解答一下谢谢。
###### 讲师回复:
> 往后面看你就明白了,在DDD+微服务的架构中放弃了join操作,首先做SQL查询但不join,然后根据领域模型,通过DDD的工厂做补填。你也可以仔细研究我的demo代码。
##### **赞:
> 老师,有个疑问,我看例子中已就绪领域事件为关联了用户,已就绪事件跟用户有什么关系?
###### 讲师回复:
> 就绪了接着就要派送,那么派送给谁呀,是不是还是要携带用户信息。
##### **生:
> 终于更新了,等得我好苦呀
###### 编辑回复:
> 哈哈哈哈,辛苦了
|
C | UTF-8 | 6,835 | 2.5625 | 3 | [] | no_license | /************************************************************************************
* *
* SKV data type Release 1.0 *
* Copyright (c) 2018 by Yonsz Information Technology Co. *
* Written by Mr. NieShuai *
* *
* Function: *
* Some basic math function implement by mathematical approximation *
* *
*************************************************************************************/
#ifndef MATH_APPROX_FIX_H
#define MATH_APPROX_FIX_H
#include <math.h>
#include "../basic/skv_config.h"
#include "../basic/skv_types.h"
#include "skv_math_core_fix.h"
#define FIXED_POINT
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef FIXED_POINT
#define spx_sqrt sqrt
#define spx_acos acos
#define spx_exp exp
#define spx_cos_norm(x) (cos((.5f*M_PI)*(x)))
#define spx_atan atan
/** Generate a pseudo-random number */
static inline spx_word16_t speex_rand(spx_word16_t std, spx_int32_t* seed)
{
const unsigned int jflone = 0x3f800000;
const unsigned int jflmsk = 0x007fffff;
union { int i; float f; } ran;
*seed = 1664525 * *seed + 1013904223;
ran.i = jflone | (jflmsk & *seed);
ran.f -= 1.5;
return 3.4642* std* ran.f;
}
#endif
static inline spx_int32_t spx_ilog2(spx_uint32_t x)
{
int r = 0;
if (x >= (spx_int32_t)65536)
{
x >>= 16;
r += 16;
}
if (x >= 256)
{
x >>= 8;
r += 8;
}
if (x >= 16)
{
x >>= 4;
r += 4;
}
if (x >= 4)
{
x >>= 2;
r += 2;
}
if (x >= 2)
{
r += 1;
}
return r;
}
static inline spx_int32_t spx_ilog4(spx_uint32_t x)
{
int r = 0;
if (x >= (spx_int32_t)65536)
{
x >>= 16;
r += 8;
}
if (x >= 256)
{
x >>= 8;
r += 4;
}
if (x >= 16)
{
x >>= 4;
r += 2;
}
if (x >= 4)
{
r += 1;
}
return r;
}
#ifdef FIXED_POINT
/** Generate a pseudo-random number */
static inline spx_int32_t speex_rand(spx_int32_t std, spx_int32_t* seed)
{
spx_int32_t res;
*seed = 1664525 * *seed + 1013904223;
res = MULT16_16(EXTRACT16(SHR32(*seed, 16)), std);
return EXTRACT16(PSHR32(SUB32(res, SHR32(res, 3)), 14));
}
/* sqrt(x) ~= 0.22178 + 1.29227*x - 0.77070*x^2 + 0.25723*x^3 (for .25 < x < 1) */
/*#define C0 3634
#define C1 21173
#define C2 -12627
#define C3 4215*/
/* sqrt(x) ~= 0.22178 + 1.29227*x - 0.77070*x^2 + 0.25659*x^3 (for .25 < x < 1) */
#define C0 3634
#define C1 21173
#define C2 -12627
#define C3 4204
static inline spx_int32_t spx_sqrt(spx_int32_t x)
{
int k;
spx_int32_t rt;
k = spx_ilog4(x) - 6;
x = VSHR32(x, (k << 1));
rt = ADD16(C0, MULT16_16_Q14(x, ADD16(C1, MULT16_16_Q14(x, ADD16(C2, MULT16_16_Q14(x, (C3)))))));
rt = VSHR32(rt, 7 - k);
return rt;
}
/* log(x) ~= -2.18151 + 4.20592*x - 2.88938*x^2 + 0.86535*x^3 (for .5 < x < 1) */
#define A1 16469
#define A2 2242
#define A3 1486
static inline spx_int32_t spx_acos(spx_int32_t x)//spx_word16_t
{
int s = 0;
spx_int32_t ret;
spx_int32_t sq;
if (x < 0)
{
s = 1;
x = NEG16(x);
}
x = SUB16(16384, x);
x = x >> 1;
sq = MULT16_16_Q13(x, ADD16(A1, MULT16_16_Q13(x, ADD16(A2, MULT16_16_Q13(x, (A3))))));
ret = spx_sqrt(SHL32(EXTEND32(sq), 13));
/*ret = spx_sqrt(67108864*(-1.6129e-04 + 2.0104e+00*f + 2.7373e-01*f*f + 1.8136e-01*f*f*f));*/
if (s)
ret = SUB16(25736, ret);
return ret;
}
#define K1 8192
#define K2 -4096
#define K3 340
#define K4 -10
static inline spx_int32_t spx_cos(spx_int32_t x)//spx_int32_t
{
spx_int32_t x2;
if (x < 12868)
{
x2 = MULT16_16_P13(x, x);
return ADD32(K1, MULT16_16_P13(x2, ADD32(K2, MULT16_16_P13(x2, ADD32(K3, MULT16_16_P13(K4, x2))))));
}
else {
x = SUB16(25736, x);
x2 = MULT16_16_P13(x, x);
return SUB32(-K1, MULT16_16_P13(x2, ADD32(K2, MULT16_16_P13(x2, ADD32(K3, MULT16_16_P13(K4, x2))))));
}
}
#define L1 32767
#define L2 -7651
#define L3 8277
#define L4 -626
static inline spx_int32_t _spx_cos_pi_2(spx_int32_t x)//spx_word16_t
{
spx_int32_t x2;
x2 = MULT16_16_P15(x, x);
return ADD16(1, MIN16(32766, ADD32(SUB16(L1, x2), MULT16_16_P15(x2, ADD32(L2, MULT16_16_P15(x2, ADD32(L3, MULT16_16_P15(L4, x2))))))));
}
static inline spx_int32_t spx_cos_norm(spx_int32_t x)//spx_word16_t
{
x = x & 0x0001ffff;
if (x > SHL32(EXTEND32(1), 16))
x = SUB32(SHL32(EXTEND32(1), 17), x);
if (x & 0x00007fff)
{
if (x < SHL32(EXTEND32(1), 15))
{
return _spx_cos_pi_2(EXTRACT16(x));
}
else {
return NEG32(_spx_cos_pi_2(EXTRACT16(65536 - x)));
}
}
else {
if (x & 0x0000ffff)
return 0;
else if (x & 0x0001ffff)
return -32767;
else
return 32767;
}
}
/*
K0 = 1
K1 = log(2)
K2 = 3-4*log(2)
K3 = 3*log(2) - 2
*/
#define D0 16384
#define D1 11356
#define D2 3726
#define D3 1301
/* Input in Q11 format, output in Q16 */
static inline spx_int32_t spx_exp2(spx_int32_t x)
{
int integer;
spx_int32_t frac;
integer = SHR16(x, 11);
if (integer > 14)
return 0x7fffffff;
else if (integer < -15)
return 0;
frac = SHL16(x - SHL16(integer, 11), 3);
frac = ADD16(D0, MULT16_16_Q14(frac, ADD16(D1, MULT16_16_Q14(frac, ADD16(D2, MULT16_16_Q14(D3, frac))))));
return VSHR32(EXTEND32(frac), -integer - 2);
}
/* Input in Q11 format, output in Q16 */
static inline spx_int32_t spx_exp(spx_int32_t x)
{
if (x > 21290)
return 0x7fffffff;
else if (x < -21290)
return 0;
else
return spx_exp2(MULT16_16_P14(23637, x));
}
#define M1 32767
#define M2 -21
#define M3 -11943
#define M4 4936
static inline spx_int32_t spx_atan01(spx_int32_t x)
{
return MULT16_16_P15(x, ADD32(M1, MULT16_16_P15(x, ADD32(M2, MULT16_16_P15(x, ADD32(M3, MULT16_16_P15(M4, x)))))));
}
#undef M1
#undef M2
#undef M3
#undef M4
/* Input in Q15, output in Q14 */
static inline spx_int32_t spx_atan(spx_int32_t x)
{
if (x <= 32767)
{
return SHR16(spx_atan01(x), 1);
}
else {
int e = spx_ilog2(x);
if (e >= 29)
return 25736;
x = DIV32_16(SHL32(EXTEND32(32767), 29 - e), EXTRACT16(SHR32(x, e - 14)));
return SUB16(25736, SHR16(spx_atan01(x), 1));
}
}
#else
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
#define C1 0.9999932946f
#define C2 -0.4999124376f
#define C3 0.0414877472f
#define C4 -0.0012712095f
#ifndef SPX_PI_2
#define SPX_PI_2 1.5707963268
#endif
static inline spx_word16_t spx_cos(spx_word16_t x)
{
if (x < SPX_PI_2)
{
x *= x;
return C1 + x * (C2 + x * (C3 + C4 * x));
}
else {
x = M_PI - x;
x *= x;
return NEG16(C1 + x * (C2 + x * (C3 + C4 * x)));
}
}
#endif
#ifdef __cplusplus
}
#endif
#endif
|
TypeScript | UTF-8 | 2,347 | 2.546875 | 3 | [] | no_license | import { Command } from 'discord-akairo';
import { MESSAGES } from '../../utils/constants';
import { HMessage } from '../../utils/classes/HMessage';
import { User, TextChannel } from 'discord.js';
export default class TrashCleanup extends Command {
public constructor() {
super('trash', {
aliases: [ 'trash', 'ban-sync' ],
description: {
content: MESSAGES.COMMANDS.TRASH.DESCRIPTION
},
category: 'staff',
channel: 'guild',
clientPermissions: [ 'EMBED_LINKS' ],
userPermissions: [ 'ADMINISTRATOR' ]
});
}
public async exec(message: HMessage) {
const allBans: { user: User, reason?: string }[] = [];
const sendResult: (content: string) => void = (content: string) => {
const ch = this.client.channels.cache.get('627501333439578112');
if (ch && ch instanceof TextChannel) {
ch.send(content);
}
};
for (const [ , guild ] of this.client.guilds.cache) {
const bans = await guild.fetchBans();
bans.forEach(ban => {
allBans.push({ user: ban.user, reason: ban.reason });
});
}
console.log(allBans);
const bannedMembers: { [key: string]: boolean } = {};
let totalBanned = 0;
this.client.guilds.cache.forEach(guild => {
allBans.forEach(async ban => {
const members = guild.members.cache;
const mem = members.get(ban.user.id);
if (mem && guild.me.permissions.has('BAN_MEMBERS')) {
sendResult(`**[BAN-SYNC]**: Successfully banned user ${ban.user.username}#${ban.user.discriminator} ${ban.reason ? `(initial reason: ${ban.reason})` : ''} from guild ${guild.name} (owner: ${guild.owner.user.username})`);
mem.ban({
reason: ban.reason
});
bannedMembers[ban.user.id] = true;
totalBanned++;
}
});
});
if (!totalBanned) {
return message.util?.send(`**[BAN-SYNC]**: All guilds have matching ban lists!`);
}
return message.util?.send(`**[BAN-SYNC]**: Synced a total of ${totalBanned} bans.`);
}
}
|
Python | UTF-8 | 1,960 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | ## File Name: androidDBParser.py
##
## Author(s): Daniel "Albinohat" Mercado
##
## Purpose: This script open and parse through the databases used to store
## data for Android applications and store them as objects.
##
## TODO -
##
## Standard imports (Static)
import logging, platform, re, sqlite3, sys
## Third-party imports (Static)
## Global Variable Declarations - CONSTANTS - DO NOT CHANGE @ RUNTIME
## Declare a dictionary to store the possible mimetypes statically.
_mimetype_dict = {\
1: "email_v2", 2: "im", 3: "nickname", 4: "organization",\
5: "phone_v2", 6: "sip_address", 7: "name", 8: "postal-address_v2",\
9: "identity", 10: "photo", 11: "group_membership", 12: "note",\
13: "contact_misc"\
}
## Validate that the a filename was given.
if (len(sys.argv) != 2):
print "\n USAGE: " + sys.argv[0] + " <filename>"
sys.exit(5)
## Create a connection to the database in the file as well as the cursor object.
db_conn = sqlite3.connect(sys.argv[1])
c = db_conn.cursor()
## Get the names of all the tables in the database.
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
for each in c.fetchall():
print str(each[0])
## Get the names of the columns in the contacts database.
c.execute('select * from contacts')
for each in c.description:
print each[0]
sys.exit()
## Show all of the rows of the mimetypes table.
## This table could be used to dynamically configure the mimetypes.
print "\n==MIMETYPES=="
for row in c.execute('SELECT * FROM mimetypes'):
print row
## Show all of the rows of the contacts table.
## This table is the simplest way to get raw_id and correlate the information stored in other tables.
print "\n==CONTACTS=="
for row in c.execute('SELECT * FROM contacts'):
print row
## Show all of the rows of the data table.
## This table contains the actual entries for different types of contact details.
print "\n==DATA=="
for row in c.execute('SELECT * FROM data'):
print row
|
Java | UHC | 1,065 | 3.578125 | 4 | [] | no_license | package interfaceex;
public interface Calc {
// ܰ迡 ȴ.
double PI = 3.14;
int ERROR = -9999999;
int add(int num1,int num2);
int substract(int num1,int num2);
int times(int num1,int num2);
int divide(int num1,int num2);
//ȯ 뷫 ҵ Ʒ ۼ
// public void stringConcat(String s1,String s2);
//Ʈ
default void description() {
System.out.println(" ⸦ մϴ.");
// myMethod();
}
//static method
//̽ Ÿ ٰ ֵ
static int total(int[] arr) {
int total=0;
for(int i:arr) {
total +=i;
}
return total;
}
//ڹ 9 ϴ Ʒ (private)
// private void myMethod() {
// System.out.println("private method");
// }
//
// private static void mystaticMethod() {
// System.out.println("private static mehtod");
// }
}
|
TypeScript | UTF-8 | 2,933 | 2.53125 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | import { Compilation, Compiler, WebpackError, WebpackPluginInstance } from 'webpack';
function maybeFetchPlugin(compiler: Compiler, name: string): WebpackPluginInstance | undefined {
return compiler.options?.plugins
?.map(({ constructor }) => constructor)
.find(constructor => constructor && constructor.name === name);
}
export type HTMLPluginData = {
assetTags: any;
outputName: string;
plugin: any;
};
export type HTMLLinkNode = {
rel?: string;
name?: string;
content?: string;
media?: string;
href?: string;
sizes?: string;
node: any;
};
export default class ModifyHtmlWebpackPlugin {
constructor(private modifyOptions: { inject?: boolean | Function } = {}) {}
async modifyAsync(
compiler: Compiler,
compilation: Compilation,
data: HTMLPluginData
): Promise<HTMLPluginData> {
return data;
}
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(this.constructor.name, (compilation: Compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: this.constructor.name,
// https://github.com/webpack/webpack/blob/master/lib/Compilation.js#L3280
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
async () => {
// Hook into the html-webpack-plugin processing and add the html
const HtmlWebpackPlugin = maybeFetchPlugin(compiler, 'HtmlWebpackPlugin') as any;
if (HtmlWebpackPlugin) {
if (typeof HtmlWebpackPlugin.getHooks === 'undefined') {
compilation.errors.push(
new WebpackError(
'ModifyHtmlWebpackPlugin - This ModifyHtmlWebpackPlugin version is not compatible with your current HtmlWebpackPlugin version.\n'
)
);
return;
}
HtmlWebpackPlugin.getHooks(compilation).alterAssetTags.tapAsync(
this.constructor.name,
async (
data: HTMLPluginData,
htmlCallback: (error: Error | null, data: HTMLPluginData) => void
) => {
// Skip if a custom injectFunction returns false or if
// the htmlWebpackPlugin optuons includes a `favicons: false` flag
const isInjectionAllowed =
typeof this.modifyOptions.inject === 'function'
? this.modifyOptions.inject(data.plugin)
: data.plugin.options.pwaManifest !== false;
if (isInjectionAllowed === false) {
return htmlCallback(null, data);
}
try {
data = await this.modifyAsync(compiler, compilation, data);
} catch (error: any) {
compilation.errors.push(error);
}
htmlCallback(null, data);
}
);
}
}
);
});
}
}
|
Java | UTF-8 | 7,056 | 2.296875 | 2 | [] | no_license | /*******************************************************************************
* 2018, All rights reserved.
*******************************************************************************/
package com.jp.insurance.entities;
import java.util.Date;
// Start of user code (user defined imports)
// End of user code
/**
* Description of Payment.
*
* @author Administrator
*/
public class Payment {
/**
* Description of the property paymentId.
*/
private Long paymentId = Long.valueOf(0L);
/**
* Description of the property policyId.
*/
private Long policyId = Long.valueOf(0L);
/**
* Description of the property nameOnCard.
*/
private String nameOnCard = "";
/**
* Description of the property cardNo.
*/
private String cardNo = "";
/**
* Description of the property cardExpirtDate.
*/
private String cardExpirtDate = "";
/**
* Description of the property policyAmount.
*/
private Float policyAmount = Float.valueOf(0F);
/**
* Description of the property paymentDate.
*/
private Date paymentDate = new Date();
// Start of user code (user defined attributes for Payment)
// End of user code
/**
* The constructor.
*/
public Payment() {
// Start of user code constructor for Payment)
super();
// End of user code
}
/**
* Description of the method getPaymentId.
* @return
*/
public Long getPaymentId() {
// Start of user code for method getPaymentId
Long getPaymentId = Long.valueOf(0L);
return getPaymentId;
// End of user code
}
/**
* Description of the method setPaymentId.
* @param paymentId
*/
public void setPaymentId(Long paymentId) {
// Start of user code for method setPaymentId
// End of user code
}
/**
* Description of the method getPolicyId.
* @return
*/
public Long getPolicyId() {
// Start of user code for method getPolicyId
Long getPolicyId = Long.valueOf(0L);
return getPolicyId;
// End of user code
}
/**
* Description of the method setPolicyId.
* @param policyId
*/
public void setPolicyId(Long policyId) {
// Start of user code for method setPolicyId
// End of user code
}
/**
* Description of the method getNameOnCard.
* @return
*/
public String getNameOnCard() {
// Start of user code for method getNameOnCard
String getNameOnCard = "";
return getNameOnCard;
// End of user code
}
/**
* Description of the method setNameOnCard.
* @param nameOnCard
*/
public void setNameOnCard(String nameOnCard) {
// Start of user code for method setNameOnCard
// End of user code
}
/**
* Description of the method getCardNo.
* @return
*/
public String getCardNo() {
// Start of user code for method getCardNo
String getCardNo = "";
return getCardNo;
// End of user code
}
/**
* Description of the method setCardNo.
* @param cardNo
*/
public void setCardNo(String cardNo) {
// Start of user code for method setCardNo
// End of user code
}
/**
* Description of the method getCardExpirtDate.
* @return
*/
public String getCardExpirtDate() {
// Start of user code for method getCardExpirtDate
String getCardExpirtDate = "";
return getCardExpirtDate;
// End of user code
}
/**
* Description of the method setCardExpirtDate.
* @param cardExpirtDate
*/
public void setCardExpirtDate(String cardExpirtDate) {
// Start of user code for method setCardExpirtDate
// End of user code
}
/**
* Description of the method getPolicyAmount.
* @return
*/
public Float getPolicyAmount() {
// Start of user code for method getPolicyAmount
Float getPolicyAmount = Float.valueOf(0F);
return getPolicyAmount;
// End of user code
}
/**
* Description of the method setPolicyAmount.
* @param policyAmount
*/
public void setPolicyAmount(Float policyAmount) {
// Start of user code for method setPolicyAmount
// End of user code
}
/**
* Description of the method getPaymentDate.
* @return
*/
public Date getPaymentDate() {
// Start of user code for method getPaymentDate
Date getPaymentDate = new Date();
return getPaymentDate;
// End of user code
}
/**
* Description of the method setPaymentDate.
* @param paymentDate
*/
public void setPaymentDate(Date paymentDate) {
// Start of user code for method setPaymentDate
// End of user code
}
/**
* Description of the method toString.
* @return
*/
public String toString() {
// Start of user code for method toString
String toString = "";
return toString;
// End of user code
}
// Start of user code (user defined methods for Payment)
// End of user code
/**
* Returns paymentId.
* @return paymentId
*/
public Long getPaymentId() {
return this.paymentId;
}
/**
* Sets a value to attribute paymentId.
* @param newPaymentId
*/
public void setPaymentId(Long newPaymentId) {
if (this.paymentId != null) {
this.paymentId.set(null);
}
this.paymentId.set(this);
}
/**
* Returns policyId.
* @return policyId
*/
public Long getPolicyId() {
return this.policyId;
}
/**
* Sets a value to attribute policyId.
* @param newPolicyId
*/
public void setPolicyId(Long newPolicyId) {
if (this.policyId != null) {
this.policyId.set(null);
}
this.policyId.set(this);
}
/**
* Returns nameOnCard.
* @return nameOnCard
*/
public String getNameOnCard() {
return this.nameOnCard;
}
/**
* Sets a value to attribute nameOnCard.
* @param newNameOnCard
*/
public void setNameOnCard(String newNameOnCard) {
if (this.nameOnCard != null) {
this.nameOnCard.set(null);
}
this.nameOnCard.set(this);
}
/**
* Returns cardNo.
* @return cardNo
*/
public String getCardNo() {
return this.cardNo;
}
/**
* Sets a value to attribute cardNo.
* @param newCardNo
*/
public void setCardNo(String newCardNo) {
if (this.cardNo != null) {
this.cardNo.set(null);
}
this.cardNo.set(this);
}
/**
* Returns cardExpirtDate.
* @return cardExpirtDate
*/
public String getCardExpirtDate() {
return this.cardExpirtDate;
}
/**
* Sets a value to attribute cardExpirtDate.
* @param newCardExpirtDate
*/
public void setCardExpirtDate(String newCardExpirtDate) {
if (this.cardExpirtDate != null) {
this.cardExpirtDate.set(null);
}
this.cardExpirtDate.set(this);
}
/**
* Returns policyAmount.
* @return policyAmount
*/
public Float getPolicyAmount() {
return this.policyAmount;
}
/**
* Sets a value to attribute policyAmount.
* @param newPolicyAmount
*/
public void setPolicyAmount(Float newPolicyAmount) {
if (this.policyAmount != null) {
this.policyAmount.set(null);
}
this.policyAmount.set(this);
}
/**
* Returns paymentDate.
* @return paymentDate
*/
public Date getPaymentDate() {
return this.paymentDate;
}
/**
* Sets a value to attribute paymentDate.
* @param newPaymentDate
*/
public void setPaymentDate(Date newPaymentDate) {
if (this.paymentDate != null) {
this.paymentDate.set(null);
}
this.paymentDate.set(this);
}
}
|
Markdown | UTF-8 | 14,386 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | import { Alert, Tabs, TabItem } from '@aws-amplify/ui-react';
One of the goals of Amplify is to be a good citizen of the environment it exists in. As such Amplify works hard to not interfere with other tools that are being used.
There are many CSS In JS libraries out there that give a number of benefits. Amplify does not use a CSS In JS library to implement its theming system but operates well with the major CSS In JS libraries out there. Below are a few of the libraries with descriptions of how they work with Amplify's theming system.
<Alert variation="warning" role="none">
If your CSS library depends on injecting style tags into the DOM, make sure they are being injected <b>after</b> Amplify UI's style tag. In other words, ensure the style tag for Amplify UI is listed above your custom styles in the `<head>` tag. If Amplify UI's styles are injected after custom styles, then your custom styles may be unset.
</Alert>
<Tabs>
<TabItem title="Styled Components">
[Styled Components](https://github.com/styled-components/styled-components) allows you to create visual primitives with actual CSS code directly tied to components.
## Usage
```jsx
import * as React from 'react';
import styled from 'styled-components';
import { View } from '@aws-amplify/ui-react';
const StyledView = styled(View)`
background-color: black;
font-size: 32px;
`;
//use it like any other amplify-ui component
<StyledView color="red" className="my-styled-view">
This is my Styled View
</StyledView>;
```
## Interactions
There are various ways to customize an Amplify component and Styled Components will interact with these customizations in the following ways:
### Amplify Styling Props
These are styling props that can be used directly on an Amplify component which will affect a single style property. Examples of styling props are `color` or `fontWeight`. These Amplify styling props will take precedence over Styled Component styling.
```jsx
import * as React from 'react';
import styled from 'styled-components';
import { View } from '@aws-amplify/ui-react';
const StyledView = styled(View)`
color: blue;
`;
<StyledView color="red">Using Styling props</StyledView>;
```
In the example above, the color of the view will be set to `red` because of the Amplify styling prop.
### Amplify variation props
These props change the look and/or behavior of certain Amplify components. Examples include `size` and `variation`.
```jsx
import * as React from 'react';
import styled from "styled-components";
import { Button } from '@aws-amplify/ui-react';
const StyledButton = styled(Button)`
color: blue
`;
<StyledButton variation="primary">Primary Button</StyledButton>
```
In the example above, the color of the button will be set to `blue`. Although the `primary` variation has a color value of white the Styled Components color value of blue will take precedence over the amplify-ui variation styling.
### Amplify Custom ClassNames
These are custom classnames added onto Amplify components and can be used with CSS styling rules to modify the look of an Amplify component.
```jsx
import * as React from 'react';
import styled from 'styled-components';
import { View } from '@aws-amplify/ui-react';
const styledView = styled(View)`
color: blue;
`;
<styledView className="my-styled-view">My Styled View</styledView>;
```
```CSS
/* External Style Sheet */
.my-styled-view {
color: red;
}
```
In the example above, the color of the view will be `blue` because the styled component will take precedence over the classname CSS.
### CSS Root Variable Overrides
Amplify theming provides many CSS variables to customize the look and feel of the entire application. These CSS variables can be used with the `:root` CSS psuedo-class to override all instances of component styling.
```jsx
import * as React from 'react';
import styled from 'styled-components';
import { Button } from '@aws-amplify/ui-react';
const StyledButton = styled(Button)`
color: blue;
`;
<StyledButton>Button</StyledButton>;
```
```CSS
/* External Style Sheet */
:root {
--amplify-components-button-color: red;
}
```
In the example above, the button color will be set to `blue` because the Styled Component will take precedence over the Amplify CSS variable.
</TabItem>
<TabItem title="JSS">
[JSS](https://github.com/cssinjs/jss/tree/master/packages/react-jss) is a library for generating Style Sheets with Javascript.
## Usage
```jsx
import * as React from 'react';
import { createUseStyles } from 'react-jss';
import { View } from '@aws-amplify/ui-react';
const useStyles = createUseStyles({
styledText: {
color: 'blue',
},
});
const classes = useStyles();
//use the JSS create classes in the Amplify ui className
<Text className={classes.styledText}>This is my JSS Text </Text>;
```
## Interactions
There are various ways to customize an Amplify component and JSS will interact with these customizations in the following ways:
### Amplify Styling Props
These are styling props that can be used directly on an Amplify component which will affect a single style property. Examples of styling props are `color` or `fontWeight`. These Amplify styling props will take precedence over JSS styling.
```jsx
import * as React from 'react';
import { createUseStyles } from 'react-jss';
import { View } from '@aws-amplify/ui-react';
const useStyles = createUseStyles({
styledText: {
color: 'blue',
},
});
const classes = useStyles();
<Text className={classes.styledText} color="red">
This is my JSS Text
</Text>;
```
In the example above, the color of the view will be set to `red` because of the Amplify styling prop.
### Amplify variation props
These props change the look and/or behavior of certain Amplify components. Examples include `size` and `variation`.
```jsx
import * as React from 'react';
import { createUseStyles } from 'react-jss';
import { Button } from '@aws-amplify/ui-react';
const useStyles = createUseStyles({
styledButton: {
color: 'blue',
},
});
const classes = useStyles();
<Button className={classes.styledButton} variation="primary">
Primary Button
</Button>;
```
In the example above, the color of the button will be set to `blue`. Although the `primary` variation has a color value of white the JSS color value of blue will take precedence over the amplify-ui variation styling.
### Amplify Custom ClassNames
These are custom classnames added onto Amplify components and can be used with CSS styling rules to modify the look of an Amplify component.
```jsx
import * as React from 'react';
import { createUseStyles } from 'react-jss';
import { View } from '@aws-amplify/ui-react';
const useStyles = createUseStyles({
styledText: {
color: 'blue',
},
});
const classes = useStyles();
const classNames = `${classes.styledText} my-styled-text`;
<Text className={classNames}>This is my JSS Text </Text>;
```
```CSS
/* External Style Sheet */
.my-styled-text {
color: red;
}
```
In the example above, the color of the text will be `blue` because the JSS styling will take precedence over the classname CSS.
### CSS Root Variable Overrides
Amplify theming provides many CSS variables to customize the look and feel of the entire application. These CSS variables can be used at a root level to override all instances of component styling.
```jsx
import * as React from 'react';
import { createUseStyles } from 'react-jss';
import { Button } from '@aws-amplify/ui-react';
const useStyles = createUseStyles({
styledButton: {
color: 'blue',
},
});
const classes = useStyles();
<Button className={classes.styledButton}>Button</Button>;
```
```CSS
/* External Style Sheet */
:root {
--amplify-components-button-color: red;
}
```
In the example above, the button color will be set to `blue` because the JSS styling will take precedence over the Amplify CSS variable.
</TabItem>
<TabItem title="Emotion">
[Emotion](https://github.com/emotion-js/emotion) is a library designed for writing css styles with JavaScript.
## Usage
```jsx
/** @jsxImportSource @emotion/react */
import { jsx, css } from '@emotion/react';
import { Text } from '@aws-amplify/ui-react';
const styles = {
color: 'blue',
};
//use the Emotion css function and css prop
<Text css={css(styles)}>This is my Emotion Text </Text>;
```
## Interactions
There are various ways to customize an Amplify component and Emotion will interact with these customizations in the following ways:
### Amplify Styling Props
These are styling props that can be used directly on an Amplify component which will affect a single style property. Examples of styling props are `color` or `fontWeight`. These Amplify styling props will take precedence over Emotion styling.
```jsx
/** @jsxImportSource @emotion/react */
import { jsx, css } from '@emotion/react';
import { Text } from '@aws-amplify/ui-react';
const styles = {
color: 'blue',
};
<Text css={css(styles)} color="red">
This is my Emotion Text
</Text>;
```
In the example above, the color of the view will be set to `red` because of the Amplify styling prop.
### Amplify variation props
These props change the look and/or behavior of certain Amplify components. Examples include `size` and `variation`.
```jsx
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
import { Button } from '@aws-amplify/ui-react';
const styles = {
color: 'blue',
};
<Button css={css(styles)} variation="primary">
Primary Button
</Button>;
```
In the example above, the color of the button will be set to `blue`. Although the `primary` variation has a color value of white the Emotion color value of blue will take precedence over the amplify-ui variation styling.
### Amplify Custom ClassNames
These are custom classnames added onto Amplify components and can be used with CSS styling rules to modify the look of an Amplify component.
```jsx
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
import { Text } from '@aws-amplify/ui-react';
const styles = {
color: 'blue',
};
<Text css={css(styles)} className="my-styled-text">
This is my Emotion Text
</Text>;
```
```CSS
/* External Style Sheet */
.my-styled-text {
color: red;
}
```
In the example above, the color of the text will be `blue` because the Emotion styling will take precedence over the classname CSS.
### CSS Root Variable Overrides
Amplify theming provides many CSS variables to customize the look and feel of the entire application. These CSS variables can be used at a root level to override all instances of component styling.
```jsx
/** @jsxImportSource @emotion/react */
import { jsx, css } from '@emotion/react';
import { Button } from '@aws-amplify/ui-react';
const styles = {
color: 'blue',
};
<Button css={css(styles)}>Button</Button>;
```
```CSS
/* External Style Sheet */
:root {
--amplify-components-button-color: red;
}
```
In the example above, the button color will be set to `blue` because the Emotion styling will take precedence over the Amplify CSS variable.
</TabItem>
<TabItem title="Aphrodite">
[Aphrodite](https://github.com/Khan/aphrodite) is a Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation.
## Usage
```jsx
import { StyleSheet, css } from 'aphrodite';
import { Text } from '@aws-amplify/ui-react';
const styles = StyleSheet.create({
blue: {
color: 'blue',
},
});
//use the Aphrodite css function and the className prop
<Text className={css(styles.blue)}>This is an aphrodite Text component</Text>;
```
## Interactions
There are various ways to customize an Amplify component and Aphrodite will interact with these customizations in the following ways:
### Amplify Styling Props
These are styling props that can be used directly on an Amplify component which will affect a single style property. Examples of styling props are `color` or `fontWeight`. Aphrodite will take precedence over these Amplify styling props.
```jsx
import { StyleSheet, css } from 'aphrodite';
import { Text } from '@aws-amplify/ui-react';
const styles = StyleSheet.create({
blue: {
color: 'blue',
},
});
<Text className={css(styles.blue)} color="red">
This is an aphrodite Text component
</Text>;
```
In the example above, the color of the view will be set to `blue` because of the Aphrodite styling will take precedence.
### Amplify variation props
These props change the look and/or behavior of certain Amplify components. Examples include `size` and `variation`.
```jsx
import { StyleSheet, css } from 'aphrodite';
import { Button } from '@aws-amplify/ui-react';
const styles = StyleSheet.create({
blue: {
color: 'blue',
},
});
<Button className={css(styles.blue)} variation="primary">
Primary Button
</Button>;
```
In the example above, the color of the button will be set to `blue`, because the Aphrodite styling will take precedence over the Amplify variation styling.
### Amplify Custom ClassNames
These are custom classnames added onto Amplify components and can be used with CSS styling rules to modify the look of an Amplify component.
```jsx
import { StyleSheet, css } from 'aphrodite';
import { Text } from '@aws-amplify/ui-react';
const styles = StyleSheet.create({
blue: {
color: 'blue',
},
});
const classNames = `${css(styles.blue)} my-styled-text`;
<Text className={classNaes}>This is an aphrodite Text component</Text>;
```
```CSS
/* External Style Sheet */
.my-styled-text {
color: red;
}
```
In the example above, the color of the text will be `blue` because the Aphrodite styling will take precedence over the classname CSS.
### CSS Root Variable Overrides
Amplify theming provides many CSS variables to customize the look and feel of the entire application. These CSS variables can be used at a root level to override all instances of component styling.
```jsx
/** @jsxImportSource @emotion/react */
import { StyleSheet, css } from 'aphrodite';
import { Button } from '@aws-amplify/ui-react';
const styles = StyleSheet.create({
blue: {
color: 'blue',
},
});
<Button className={css(styles.blue)}>Button</Button>;
```
```CSS
/* External Style Sheet */
:root {
--amplify-components-button-color: red;
}
```
In the example above, the button color will be set to `blue` because the Aphrodite styling will take precedence over the Amplify CSS variable.
</TabItem>
</Tabs>
|
Ruby | UTF-8 | 549 | 2.875 | 3 | [] | no_license | require 'open-uri'
require 'json'
my_course_sections = "CMSC131-0101,ENGL393-0101,ARTT100-0101"
data = open("http://api.umd.io/v0/courses/sections/#{my_course_sections}").read
sections = JSON.parse(data)
sections.each do |section|
course_id = section['course']
section['meetings'].each do |meet|
days = meet['days']
times = meet['start_time']
building = meet['building']
room = meet['room']
type = meet['classtype']
puts "#{course_id} #{type} on #{days} at #{times} in #{building} #{room}."
end
end
|
JavaScript | UTF-8 | 1,119 | 2.703125 | 3 | [] | no_license | const menu = document.getElementsByClassName("fa-bars")[0];
const mainMenu = document.getElementsByClassName("main-menu")[0];
const dropBtn = document.getElementsByClassName("drop-btn")[0];
const dropDown = document.getElementsByClassName("drop-down")[0];
const subDropBtn = document.getElementsByClassName("sub-drop-btn")[0];
const subDropDown = document.getElementsByClassName("sub-drop-down")[0];
const onClick = () => {
event.preventDefault();
// if (event.target === menu) {
// mainMenu.classList.toggle("display");
// } else if (event.target === dropBtn) {
// dropDown.classList.toggle("display");
// } else if (event.target === subDropBtn) {
// subDropDown.classList.toggle("display");
// } else {
// return;
// }
event.target === menu
? mainMenu.classList.toggle("display")
: event.target === dropBtn
? dropDown.classList.toggle("display")
: event.target === subDropBtn
? subDropDown.classList.toggle("display")
: null;
};
menu.addEventListener("click", onClick);
dropBtn.addEventListener("click", onClick);
subDropBtn.addEventListener("click", onClick);
|
C++ | UTF-8 | 1,681 | 2.953125 | 3 | [] | no_license | #include "relayControl.h"
#include <wiringPi.h>
#define RELAY_GPIO27_PIN 2
// Constructor
RelayControl::RelayControl () {
if (wiringPiSetup() == -1) {
cout << "RelayControl> wiringPi initialization failed" << endl;
// Indicate I/O subsystem problem
ioSubSystemHealth = IO_HEALTH_INIT_FAILED;
return;
}
ioSubSystemHealth = IO_HEALTH_OK; // Set I/O health
pinMode (RELAY_GPIO27_PIN, OUTPUT); // Set realy pin to out
relayState = RELAY_OFF;
digitalWrite (RELAY_GPIO27_PIN, relayState);
cout << "RelayControl> initialized relay to " << getRelayStateDesc() << endl;
};
std::string RelayControl::getRelayStateDesc() {
if (relayState == RELAY_ON) {
return ("ON");
}
else {
return ("OFF");
}
}
RelayControl::~RelayControl() {
cout << "RelayControl> Executing destructor\n";
};
int RelayControl::setRelayOn() {
cout << "RelayControl> Current relay state:\t\t\t" << getRelayStateDesc() << endl;
relayState = RELAY_ON;
digitalWrite (RELAY_GPIO27_PIN, relayState);
cout << "RelayControl> New relay state:\t\t\t" << getRelayStateDesc() << endl;
return relayState;
}
int RelayControl::setRelayOff() {
cout << "RelayControl> Current relay state:\t\t\t" << getRelayStateDesc() << endl;
relayState = RELAY_OFF;
digitalWrite (RELAY_GPIO27_PIN, relayState);
cout << "RelayControl> New relay state:\t\t\t" << getRelayStateDesc() << endl;
return relayState;
}
int RelayControl::getRelayState() {
cout << "RelayControl> Current relay state:\t\t\t" << getRelayStateDesc() << endl;
return relayState;
}
|
C# | UTF-8 | 2,750 | 3 | 3 | [
"MIT"
] | permissive | // PennyLogger: Log event aggregation and filtering library
// See LICENSE in the project root for license information.
namespace PennyLogger.Internals.Estimator
{
/// <summary>
/// Generic interface for a probabilistic frequency estimator that maximizes space-efficiency at the expense of
/// accuracy. PennyLogger has a pluggable model, as probabilistic data structures are an area of active research
/// and there is no one optimal algorithm.
/// </summary>
public interface IFrequencyEstimator
{
/// <summary>
/// Controls the maximum amount of memory used by the frequency estimator, in bytes. Note that this limit is an
/// estimate and not strictly enforced. Also, note that reducing this setting after adding values may not free
/// up memory that has already been allocated.
/// </summary>
public long MaxBytes { get; set; }
/// <summary>
/// Maximum count which may be stored for a value
/// </summary>
public long MaxCount { get; }
/// <summary>
/// Total memory (in bytes) consumed by the frequency estimator, including extra memory allocated but currently
/// not holding a value.
/// </summary>
public long TotalBytes { get; }
/// <summary>
/// Total memory (in bytes) consumed by the frequency estimator. Dividing this value by <see cref="TotalBytes"/>
/// can estimate the load factor of the frequency estimator.
/// </summary>
public long BytesUsed { get; }
/// <summary>
/// Estimates the count of a value
/// </summary>
/// <param name="hash">Value, specified as a 128-bit hash</param>
/// <returns>Estimated count</returns>
public long Estimate(Hash hash);
/// <summary>
/// Increments the count of a value and returns the post-incremented estimate
/// </summary>
/// <param name="hash">Value, specified as a 128-bit hash</param>
/// <param name="estimate">Returns the estimated count, post-increment</param>
/// <returns>See <see cref="IncrementResult"/></returns>
public IncrementResult TryIncrementAndEstimate(Hash hash, out long estimate);
/// <summary>
/// Zeroes the count of all values
/// </summary>
/// <remarks>
/// Calling <see cref="Clear"/> is preferrable to instantiating a new frequency estimator because it clears all
/// values, without necessarily clearing out all state. Some frequency estimators may optimize themselves based
/// on the input from past runs, so may perform better over time.
/// </remarks>
public void Clear();
}
}
|
Python | UTF-8 | 1,091 | 3.40625 | 3 | [] | no_license | class Staff:
def __init__(self,name,salary,yob):
self.name=name
self.salary=salary
self.yob=yob
def showname(self):
print("name od the staff is:",self.name)
def showsalary(self):
print("salary of the staff is:",self.salary)
def showyob(self):
print("year of birth is:",self.yob)
def showid(self):
print("id:",self._id)
stf1=Staff("abhishek",50000,1996,"apabhishek")
stf2=Staff("abhinav",70000,1991,"abhim")
stf1.showname()
class Doctors(Staff):
def __init__(self,name,salary,yob,id,speciality):
super().__init__(name,salary,id,yob)
self.speciality=speciality
def showspec(self):
print("speciality is;",self.speciality)
stf3=Doctors("ananya",60000,1997,"ananyag","phisician")
stf3.showspec()
stf3.showid()
class Nurse(Staff):
def __init__(self,name,salary,yob,section):
super().__init__(name,salary,yob,id)
self.section=section
def showsection(self):
print("section of nurse is:",self.section)
stf4=Nurse("anamika",30000,1997,"OPD")
stf4.showsection()
|
SQL | UTF-8 | 636 | 3.71875 | 4 | [
"MIT"
] | permissive | SELECT event, repo.id, COUNT(*) as count FROM (
SELECT JSON_EXTRACT(payload, '$.action') as event, repo.id, repo.name, created_at as ts
FROM
[githubarchive:month.201801],
[githubarchive:month.201802],
[githubarchive:month.201803],
[githubarchive:month.201804],
[githubarchive:month.201805],
[githubarchive:month.201806],
[githubarchive:month.201807],
[githubarchive:month.201808],
[githubarchive:month.201809],
[githubarchive:month.201810]
WHERE type = 'IssuesEvent' AND (repo.id = 23050110 OR repo.id = 9476938)
)
WHERE event = '"closed"' OR event = '"opened"'
GROUP BY event, repo.id
ORDER BY repo.id, event
|
C++ | UTF-8 | 476 | 3.21875 | 3 | [] | no_license | /*
Simple math problem
n*(n+1)/2 = s
n^2+n=2*s
n^2+n+(-2*s)=0
Using quadratic equation ax^2+bx+c=0
del = sqrt(b*b-4*a*c) = sqrt(1-4*1*(-2s)) = sqrt(1+8s)
we know x = (-b(+-) del)/2a
Here i use only + value because del is always positive
so n = (-1+sqrt(1+8s))/2
*/
#include<bits/stdc++.h>
using namespace std;
main()
{
long long int t,n;
double x;
cin>>t;
while(t--)
{
cin>>n;
x=(sqrt(1+8*n)-1)/2;
cout<<(int)x<<endl;
}
}
|
Java | UTF-8 | 5,427 | 2.078125 | 2 | [] | no_license | package com.example.plantshop.helper;
import android.app.Application;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import android.webkit.WebView;
import com.tealium.internal.data.Dispatch;
import com.tealium.internal.listeners.WebViewLoadedListener;
import com.tealium.internal.tagbridge.RemoteCommand;
import com.tealium.library.BuildConfig;
import com.tealium.library.DispatchValidator;
import com.tealium.library.Tealium;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* This class abstracts interaction with the Tealium library and simplifies comprehension
*/
public final class TealiumHelper {
static {
Log.i("TagBridge", " --- START --- ");
}
private final static String KEY_TEALIUM_INIT_COUNT = "tealium_init_count";
private final static String KEY_TEALIUM_INITIALIZED = "tealium_initialized";
private final static String TAG = "TealiumHelper";
// Identifier for the main Tealium instance
public static final String TEALIUM_MAIN = "main";
// Not instantiatable.
private TealiumHelper() {
}
public static void initialize(Application application) {
Log.i(TAG, "initialize(" + application.getClass().getSimpleName() + ")");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && BuildConfig.DEBUG) {
WebView.setWebContentsDebuggingEnabled(true);
}
final Tealium.Config config = Tealium.Config.create(application, "tealiummobile", "demo", "dev");
// (OPTIONAL) Get the WebView with UTag loaded
config.getEventListeners().add(createWebViewLoadedListener());
// (OPTIONAL) Control how the library treats views/links
config.getDispatchValidators().add(createDispatchValidator());
final Tealium instance = Tealium.createInstance(TEALIUM_MAIN, config);
// (OPTIONAL) Enhanced integrations
instance.addRemoteCommand(createLoggerRemoteCommand());
// (OPTIONAL) Use tealium.getDataSources().getPersistentDataSources() to set/modify lifetime values
SharedPreferences sp = instance.getDataSources().getPersistentDataSources();
sp.edit().putInt(KEY_TEALIUM_INIT_COUNT, sp.getInt(KEY_TEALIUM_INIT_COUNT, 0) + 1).commit();
// (OPTIONAL) Use tealium.getDataSources().getVolatileDataSources() to set/modify runtime only values
instance.getDataSources().getVolatileDataSources()
.put(KEY_TEALIUM_INITIALIZED, System.currentTimeMillis());
// (OPTIONAL) tracking initialization
final Map<String, Object> data = new HashMap<>(2);
data.put("logged_in", false);
data.put("visitor_status", new String[]{"new_user", "unregistered"});
TealiumHelper.trackEvent("initialization", data);
}
public static void trackView(String viewName, Map<String, ?> data) {
final Tealium instance = Tealium.getInstance(TEALIUM_MAIN);
// Instance can be remotely destroyed through publish settings
if (instance != null) {
instance.trackView(viewName, data);
}
}
public static void trackEvent(String eventName, Map<String, ?> data) {
final Tealium instance = Tealium.getInstance(TEALIUM_MAIN);
// Instance can be remotely destroyed through publish settings
if (instance != null) {
instance.trackEvent(eventName, data);
}
}
private static WebViewLoadedListener createWebViewLoadedListener() {
return new WebViewLoadedListener() {
@Override
public void onWebViewLoad(WebView webView, boolean success) {
Log.d(TAG, "WebView " + webView +
(success ? " loaded successfully" : "failed to load"));
}
@Override
public String toString() {
return "LoggingWebViewLoadListener";
}
};
}
private static DispatchValidator createDispatchValidator() {
return new DispatchValidator() {
@Override
protected boolean shouldDrop(Dispatch dispatch) {
// Drop any desired dispatches here by returning true. (Never queued nor sent)
return super.shouldDrop(dispatch);
}
@Override
protected boolean shouldQueue(Dispatch dispatch, boolean shouldQueue) {
Log.d(TAG, String.format(
Locale.ROOT,
"%s dispatch: %s",
(shouldQueue ? "Queueing" : "Sending"),
dispatch));
return super.shouldQueue(dispatch, shouldQueue);
}
@Override
public String toString() {
return "CustomDispatchValidator";
}
};
}
private static RemoteCommand createLoggerRemoteCommand() {
return new RemoteCommand("logger", "Logs dispatches") {
@Override
protected void onInvoke(Response response) throws Exception {
final String message = response.getRequestPayload()
.optString("message", "no_message");
Log.i(TAG, "RemoteCommand Message: " + message);
}
@Override
public String toString() {
return "LoggerRemoteCommand";
}
};
}
}
|
JavaScript | UTF-8 | 672 | 2.53125 | 3 | [] | no_license | import React, { Component } from 'react'
import classNames from 'classnames';
export default class Text extends Component {
constructor(props) {
super(props);
this.state = {
truncate: true
}
this.toggleBody = this.toggleBody.bind(this);
}
toggleBody(e) {
e.preventDefault();
e.stopPropagation();
this.setState({ truncate: !this.state.truncate });
}
render() {
const className = classNames(this.props.className,
this.state.truncate ? 'clickable text-truncate' : 'clickable')
return (
<p className={className} onClick={this.toggleBody}>
{this.props.children}
</p>
)
}
}
|
Python | UTF-8 | 716 | 3.9375 | 4 | [] | no_license | #prints a line
print "I will now count my chickens:"
#counts hens then adds and divides
print "Hens", 25 + 30 /6
#counts roosters with MaTH~~~
print "Roosters", 100 - 25 * 3 % 4
#prints more
print "Now I will count the eggs:"
#does a lotta math
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
#set up
print "Is it true that 3 + 2 < 5 - 7?"
#does some more math
print 3 + 2 < 5 - 7
#answers the questions that its printing
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
#prints some more
print "Oh, thats's why it's False."
print "How about some more."
#checks question with logic using MaTH
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
|
PHP | UTF-8 | 830 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Http\Repositories;
use App\Http\Traits\ApiResponse;
use App\Http\Models\CarbonFootprint;
use App\Http\Interfaces\CarbonFootprintInterface;
use DB;
class CarbonFootprintRepository implements CarbonFootprintInterface
{
// Use ResponseAPI Trait in this repository
use ApiResponse;
public function storeCarbonFootprint($data)
{
try {
$model = new CarbonFootprint;
$model->activity = $data['activity'];
$model->activity_type = $data['activity_type'];
$model->country = $data['country'];
$model->mode = $data['mode'];
$model->carbon_footprint = $data['carbon_footprint'];
$model->save();
} catch(\Exception $e) {
return $this->error($e->getMessage(), $e->getCode());
}
}
} |
Markdown | UTF-8 | 11,555 | 2.9375 | 3 | [] | no_license | # Article 5
TEXTE
5.1. CENTRE D'ANNONCE DE ...
COMMENTAIRES
Chaque centre de prévision fera l'objet d'un sous-chapitre spécial.
TEXTE
5.1.1. Mission et organisation.
Le centre d'annonce des crues de ...
est placé sous l'autorité de ...
COMMENTAIRES
Indiquer l'ingénieur responsable du centre d'annonce par sa fonction, par exemple : "Subdivisionnaire de ...".
TEXTE
Il est chargé de recueillir les informations provenant des stations d'observation ou centres d'annonce suivants :
Stations hydrométriques de ...
Station pluviométrique de ...
Centre d'annonce de ...
COMMENTAIRES
Un centre d'annonce peut recevoir des informations de différentes stations d'observation ou d'autres centres d'annonce, situés par exemple en amont.
TEXTE
Autres sources d'information (autres que celles relevant du service) s'il y en a.
A partir des informations ainsi recueillies il élabore des avis de crue concernant les stations d'annonces suivantes : ...
...
...
COMMENTAIRES
Les stations d'annonce sont généralement aussi des stations d'observation. Elles figureront donc dans les deux listes.
TEXTE
5.1.2. Mise en état de vigilance du centre.
L'état de vigilance du centre est caractérisé par ....
COMMENTAIRES
Préciser s'il s'agit, par exemple d'une permanence continue de tel agent à tel endroit, d'une astreinte à domicile, etc..
TEXTE
La mise en état de vigilance intervient lorsque ....
COMMENTAIRES
Il est possible de prévoir plusieurs niveaux de vigilance.
Préciser par exemple : lorsqu'un avis émis par telle station fait état d'une cote supérieure à telle valeur, ou lorsque la hauteur de pluie recueillie dans tel délai à tel endroit dépasse telle valeur, ou plus généralement lorsque les prévisions météorologiques émises par tel centre de renseignements météo laissent prévoir d'abondantes précipitations.
TEXTE
Lorsque le centre d'annonce est en état de vigilance, il doit ...
COMMENTAIRES
Préciser par exemple :
- mettre en état de vigilance telle station ou tel autre
centre ou tel service ;
- interroger telle station d'observation ou tel centre météo
ou recueillir tels renseignements à telle fréquence ;
- établir les avis et les transmettre comme indiqué ci-après.
TEXTE
Il est rappelé que des permanences doivent être organisées dans les services d'annonce pour que les chefs de service responsables ou les ingénieurs délégués soient à même de prendre à tout moment les décisions nécessaires.
L'état de vigilance cesse lorsque ...
COMMENTAIRES
Préciser de même les conditions précises de cessation.
TEXTE
5.1.3. Mise en état de vigilance des stations d'observations.
Toutes les fois que les circonstances l'exigeront, le chef du centre d'annonce pourra mettre en état de vigilance une ou plusieurs stations d'observation par l'envoi d'un avis spécial aux observateurs de ces stations.
COMMENTAIRES
Cet article est à prévoir dans le cas où certaines stations devraient être mises en état de vigilance à partir du centre. En fait les stations les plus importantes doivent se mettre d'elles-mêmes en état de vigilance.
TEXTE
Cet avis sera conforme au modèle suivant :
COMMENTAIRES
On pourra, le cas échéant renvoyer à un formulaire type.
TEXTE
Il sera transmis par ...
Au cas où ce mode de transmission serait défaillant, l'avis serait transmis par ...
L'état de vigilance de la station d'observation cessera lorsque ...
COMMENTAIRES
Préciser par exemple : lorsque le centre d'annonce l'aura signifié à l'observateur dans les mêmes conditions.
TEXTE
5.1.4. Mise en état de vigilance de services d'annonce ou de centres d'annonce en aval.
Le chef du centre d'annonce devra provoquer la mise en état de vigilance de ...
COMMENTAIRES
Indiquer les services et centres concernés.
TEXTE
Lorsque ...
COMMENTAIRES
Indiquer dans quel cas doit intervenir cette mise en état d'alerte.
TEXTE
L'avis correspondant sera conforme au modèle suivant :
COMMENTAIRES
Renvoyer, le cas échéant, à un formulaire type.
TEXTE
Il sera transmis par ...
COMMENTAIRES
Indiquer le mode de transmission.
TEXTE
Au cas où ce mode de transmission serait défaillant, l'avis serait transmis par ...
5.1.5. Mise en état de vigilance des organes responsables de la transmission des avis de crue (voir règlement départemental).
COMMENTAIRES
Cet article vise, par exemple, les PTT, la protection civile, la gendarmerie.
TEXTE
Toutes les fois que les circonstances laisseront prévoir la nécessité de recourir au service de ...
COMMENTAIRES
Préciser : par exemple, le directeur départemental des télécommunications, conformément au règlement départemental.
TEXTE
Pour assurer les transmissions des avis de crues en dehors des heures normales de travail, le chef du centre d'annonce de ... demandera la mise en place des moyens en personnel et en matériel nécessaires à ...
COMMENTAIRES
Il est possible de prévoir plusieurs niveaux de vigilance.
TEXTE
Cette demande sera formulée ou confirmée par écrit conformément au modèle suivant :
COMMENTAIRES
On pourra, le cas échéant, renvoyer à un formulaire type.
TEXTE
et transmise par ... à ... qui devra en accuser réception également par écrit.
La cessation de l'état de vigilance sera signifiée dans les mêmes conditions.
TEXTE
5.1.6. Elaboration des avis.
Le centre d'annonce doit centraliser les observations faites aux stations figurant au paragraphe 5.1.1.. S'il ne reçoit pas l'une d'elles dans les délais prévus, il lui appartient de mettre en oeuvre les moyens d'observation et de transmission de remplacement prévus dans ce cas et indiqués au chapitre suivant.
COMMENTAIRES
La rédaction de cet article sera adaptée suivant que les avis sont à caractère d'observation ou de prévision.
TEXTE
Lorsque les renseignements reçus des stations d'observation feront prévoir (ou constater) l'arrivée d'une crue telle que le niveau prévu ou observé à ...
dépassera la cote (ou le débit) :
COMMENTAIRES
On peut aussi se référer à des quantités de pluie recueillies en telle station dans tel intervalle de temps.
TEXTE
Le chef du centre établira des avis de crue ;
Le chef du centre d'annonce établira alors des prévisions sur l'évaluation de la crue pour les stations de ...
COMMENTAIRES
On pourra renvoyer, le cas échéant, à la liste donnée en 5.1.1..
TEXTE
Il conservera copie des calculs et évaluations ayant fondé ces prévisions. Le résultat de ces prévisions (ou observations) fera l'objet d'un avis rédigé suivant le modèle suivant : ... et transmis comme indiqué au paragraphe 5.1.7. suivant.
COMMENTAIRES
On pourra renvoyer à un ou plusieurs formulaires types et préciser dans quel cas chacun d'eux doit être utilisé.
TEXTE
De tels avis seront établis ...
tant que la cote (ou le débit) de l'eau à la station de ...
restera supérieure à ...
COMMENTAIRES
On pourra, le cas échéant, prévoir différentes fréquences suivant les niveaux atteints par la crue.
TEXTE
La hauteur et l'heure du maximum de chaque crue feront l'objet d'un avis spécial.
COMMENTAIRES
A prévoir éventuellement.
TEXTE
Les avis cesseront lorsque ...
5.1.7. Transmission des avis émis par le centre d'annonce.
Le tableau suivant indique pour chaque modèle d'avis de crue les destinataires de l'avis et les modes de transmission, normaux et de secours.
COMMENTAIRES
En principe le service d'annonce des crues n'est tenu de transmettre ses avis qu'à l'autorité préfectorale à qui il appartient de faire prévenir les populations.
TEXTE
<table>
<tr>
<td> :================:=======================:=======================:</td>
</tr>
<tr>
<td> : AVIS relatif : : :</td>
</tr>
<tr>
<td> : à la station : MODELE de l'avis. : O ou P :</td>
</tr>
<tr>
<td> : de ... : : :</td>
</tr>
<tr>
<td> :----------------:-----------------------:-----------------------:</td>
</tr>
<tr>
<td> : : : :</td>
</tr>
<tr>
<td> : : : :</td>
</tr>
<tr>
<td> : : : :</td>
</tr>
<tr>
<td> : : : :</td>
</tr>
<tr>
<td> : : : :</td>
</tr>
<tr>
<td> :================:=======================:=======================:</td>
</tr>
<tr>
<td> :===========================:====================================:</td>
</tr>
<tr>
<td> : : MODE DE TRANSMISSION :</td>
</tr>
<tr>
<td> : :------------:------------:----------:</td>
</tr>
<tr>
<td> : DESTINATAIRES. : : Hors : :</td>
</tr>
<tr>
<td> : : Heures : heures : De :</td>
</tr>
<tr>
<td> : : ouvrables : ouvrables : secours :</td>
</tr>
<tr>
<td> :---------------------------:------------:------------:----------:</td>
</tr>
<tr>
<td> : : : : :</td>
</tr>
<tr>
<td> : : : : :</td>
</tr>
<tr>
<td> : : : : :</td>
</tr>
<tr>
<td> : : : : :</td>
</tr>
<tr>
<td> : : : : :</td>
</tr>
<tr>
<td> :===========================:====================================:</td>
</tr>
</table>
COMMENTAIRES
Dans certains cas particuliers le centre d'annonce peut être amené à transmettre directement ses avis à certains maires ou services (cf. circulaire n° 75-61 du 21 avril 1975) et aux services d'annonce situés en aval.
Ces transmissions sont définies par les règlements départementaux auxquels on pourra se référer explicitement.
On mentionnera les transmissions à un centre d'annonce aval ou service aval d'annonce de crues.TEXTE
Chacun des avis émis sera transcrit sur un registre chronologique comportant la date, l'heure, le contenu et le destinataire et le mode de transmission.
COMMENTAIRES
On décrira ici les procédures de confirmation écrite des avis transmis verbalement, d'accusé de réception ...
TEXTE
5.1.8. Fonctionnement en dehors des périodes de crue.
Les services chargés de la maintenance, lorsqu'ils n'ont pas l'annonce de crue dans leur attribution, ou le chef du centre d'annonce de ...
sont chargés de veiller au bon état de fonctionnement et à l'exploitation correcte des stations d'observation suivantes : ...
COMMENTAIRES
S'il s'agit de toutes les stations dont il utilise les observations, on pourra simplement renvoyer à la liste donnée en 5.1.1..
TEXTE
Le chef du centre d'annonce de ...
contrôle en particulier les feuilles périodiques d'observation rédigées par les observateurs.
5.1.9. Compte rendu du centre d'annonce au chef de service d'annonce.
Le chef du centre d'annonce rendra compte au chef du service d'annonce des crues dans les conditions suivantes :
COMMENTAIRES
Mention d'approbation.
TEXTE
5.1.10. Comptes rendus à l'administration supérieure.
5.2. Centre d'annonce de ...
COMMENTAIRES
On reprendra pour chaque centre d'annonce l'ensemble des paragraphes donnés en 5.1..
|
Java | UTF-8 | 2,870 | 1.898438 | 2 | [] | no_license | package com.xuyang.mapper;
import com.xuyang.model.GlobalAssortment;
import com.xuyang.model.GlobalAssortmentExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface GlobalAssortmentMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
long countByExample(GlobalAssortmentExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int deleteByExample(GlobalAssortmentExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer globalId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int insert(GlobalAssortment record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int insertSelective(GlobalAssortment record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
List<GlobalAssortment> selectByExample(GlobalAssortmentExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
GlobalAssortment selectByPrimaryKey(Integer globalId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int updateByExampleSelective(@Param("record") GlobalAssortment record, @Param("example") GlobalAssortmentExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int updateByExample(@Param("record") GlobalAssortment record, @Param("example") GlobalAssortmentExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(GlobalAssortment record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table global_assortment
*
* @mbg.generated
*/
int updateByPrimaryKey(GlobalAssortment record);
} |
Java | UTF-8 | 2,611 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xbean.recipe;
import org.apache.xbean.propertyeditor.PropertyEditors;
import org.apache.xbean.propertyeditor.PropertyEditorException;
import org.apache.xbean.ClassLoading;
/**
* @version $Rev: 6689 $ $Date: 2006-01-02T06:48:49.815187Z $
*/
public class ValueRecipe implements Recipe {
private final String type;
private final String value;
public ValueRecipe(Class type, String value) {
if (type == null) throw new NullPointerException("type is null");
if (!PropertyEditors.canConvert(type)) {
throw new IllegalArgumentException("No converter available for " + ClassLoading.getClassName(type));
}
this.type = type.getName();
this.value = value;
}
public ValueRecipe(String type, String value) {
if (type == null) throw new NullPointerException("type is null");
this.type = type;
this.value = value;
}
public ValueRecipe(Object value) {
if (value == null) throw new NullPointerException("value is null");
this.type = value.getClass().getName();
this.value = PropertyEditors.toString(value);
}
public ValueRecipe(ValueRecipe valueRecipe) {
if (valueRecipe == null) throw new NullPointerException("valueRecipe is null");
this.type = valueRecipe.type;
this.value = valueRecipe.value;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
public Object create(ClassLoader classLoader) {
if (value == null) {
return null;
}
try {
return PropertyEditors.getValue(type, value, classLoader);
} catch (PropertyEditorException e) {
throw new ConstructionException(e);
}
}
}
|
Markdown | UTF-8 | 1,277 | 2.671875 | 3 | [] | no_license | # i3
Super-Enter open terminal
Super-d exec dmenu_run
Super-Super-Shift-q kill
Super-<number> switch to workspace <number>
Super-Shift-<number> move window to workspace <number>
#### Split
Super-o split horizontal
Super-e split vertical
#### Change focus
Super-h focus left
Super-j focus down
Super-k focus up
Super-l focus right
Super-a focus parent
#### Move focused window
Super-Shift-h move left
Super-Shift-j move down
Super-Shift-k move up
Super-Shift-l move right
#### Resize window
Super-r enter resize mode
h shrink 1px width
j grow 1px height
k shrink 1px height
l grow 1px width
#### Change layout container
Super-f toggle fullscreen mode
Super-s enable layout stacking
Super-w enable layout tabbed
Super-t toggle layout split
#### Toggle tiling / floating
Super-Shift-space togglefloatting togle
Super-space toggle focus between tiling / floating windows
#### Exit
Super-Shift-q kills (close) current window
Super-Shift-r restarts i3 in place
Super-Shift-e exits i3
Super-Shift-z lock session
|
C# | UTF-8 | 338 | 3.3125 | 3 | [] | no_license | using System;
using System.Text;
class PrintIsoscelesTriangle
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
char c = '\u00A9';
Console.WriteLine(" {0}", c);
Console.WriteLine(" {0} {1} {2}", c, c, c);
Console.WriteLine("{0} {1} {2} {3} {4}", c, c, c, c, c);
}
} |
C++ | UTF-8 | 677 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
double alpha = 0.5, beta, input;
Mat src1, src2, dst;
if (argc != 3) {
cout << "Input two same sized images" << endl;
return -1;
}
cout << "Enter alpha[0-1]" << endl;
cin >> input;
if (input >= 0.0 && input <= 1.0) {
alpha = input;
}
else {
cout << "Invalid alpha value. Using default value of 0.5" << endl;
}
beta = 1.0 - alpha;
src1 = imread(argv[1]);
src2 = imread(argv[2]);
namedWindow("Linear Blender", 1);
addWeighted(src1, alpha, src2, beta, 0.0, dst);
imshow("Linear Blender", dst);
waitKey(0);
return 0;
}
|
JavaScript | UTF-8 | 449 | 3.046875 | 3 | [
"MIT"
] | permissive | const ObjectStringify = require('../src/stringify');
const obj1 = {};
console.log(ObjectStringify(obj1));
const obj2 = function () {};
console.log(ObjectStringify(obj2));
const obj3 = [];
console.log(ObjectStringify(obj3));
const obj4 = '';
console.log(ObjectStringify(obj4));
const obj5 = 1;
console.log(ObjectStringify(obj5));
obj1['a'] = obj2;
obj1['b'] = obj3;
obj1['c'] = obj4;
obj1['d'] = obj5;
console.log(ObjectStringify(obj1));
|
Markdown | UTF-8 | 486 | 2.578125 | 3 | [] | no_license | # React Recipe Application
A simple React appliaction that uses Edamam API to fetch recipes from the web. Upon searching for a certain keyword, relevant recipes are displayed with basic informations.
## Tools Used
- Visual Studio Code
- React 17.0.2
## Resources
- [YouTube - Dev Ed](https://www.youtube.com/channel/UClb90NQQcskPUGDIXsQEz5Q)
- [Fresh Background Gradients](https://webgradients.com/)
- [CodePen](https://codepen.io/)
## Screenshots
 |
JavaScript | UTF-8 | 1,148 | 2.640625 | 3 | [] | no_license | const request = require('request');
const config = require('../config.js');
const db = require('../database/index.js');
let getReposByUsername = (username, cb) => {
// TODO - Use the request module to request repos for a specific
// user from the github API
// The options object has been provided to help you out,
// but you'll have to fill in the URL
console.log(`token ${config.TOKEN}`);
console.log('https://api.github.com/users/' + username + '/repos');
let options = {
url: 'https://api.github.com/users/' + username + '/repos',
headers: {
'User-Agent': 'request',
'Authorization': `token ${config.TOKEN}`
}
};
function callback(error, response, body) {
if (error) return console.log(error);
if (JSON.parse(body).message != 'Not Found') {
let cbCount = 0;
let callback = function() {
cbCount++
if (cbCount === JSON.parse(body).length) {
cb();
}
};
JSON.parse(body).forEach((elt)=>{db.save(elt, callback)});
} else {
cb();
}
}
request(options, callback);
}
module.exports.getReposByUsername = getReposByUsername; |
Java | UTF-8 | 2,868 | 2.1875 | 2 | [] | no_license | package com.pfisterfarm.popularmovies.models;
import android.app.Activity;
import android.content.Context;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.pfisterfarm.popularmovies.R;
import com.pfisterfarm.popularmovies.utils.helpers;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class TrailerAdapter extends RecyclerView.Adapter<TrailerAdapter.trailerViewHolder> {
private int mNumberTrailers;
private ArrayList<Trailer> mTrailers;
final private ListItemClickListener mOnClickListener;
public interface ListItemClickListener {
void onListItemClick(int clickItemIndex);
}
public TrailerAdapter(int numberOfTrailers, ListItemClickListener listener) {
mNumberTrailers = numberOfTrailers;
mOnClickListener = listener;
}
@Override
public trailerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.trailer_element, parent, false);
TrailerAdapter.trailerViewHolder viewHolder = new TrailerAdapter.trailerViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(trailerViewHolder holder, int position) {
holder.bind(position, holder.trailerThumb.getContext());
}
@Override
public int getItemCount() {
return mNumberTrailers;
}
public void setTrailers(ArrayList<Trailer> incomingTrailers) {
mTrailers = incomingTrailers;
notifyDataSetChanged();
}
class trailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView trailerThumb;
TextView trailerName;
public trailerViewHolder(View itemView) {
super(itemView);
trailerThumb = (ImageView) itemView.findViewById(R.id.trailer_thumbnail);
trailerName = (TextView) itemView.findViewById(R.id.trailer_name);
itemView.setOnClickListener(this);
}
void bind(int listIndex, Context context) {
trailerName.setText(mTrailers.get(listIndex).getVideoName());
Picasso.with(context).
load(helpers.makeTrailerURL(mTrailers.get(listIndex).getVideoKey())).
fit().
into(trailerThumb);
}
@Override
public void onClick(View view) {
int clickedPosition = getAdapterPosition();
mOnClickListener.onListItemClick(clickedPosition);
}
}
} |
Python | UTF-8 | 1,561 | 3.28125 | 3 | [] | no_license | #!/usr/bin/python3
"""this model contain square class that inheret from rectangle class"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""class Square inheret from Rectangle"""
def __init__(self, size, x=0, y=0, id=None):
super().__init__(self, size, size, x, y, id)
def __str__(self):
return("[Square] (self.id) self.x/self.y - self.size")
@property
def size(self):
"""size getter"""
retrurn self.size
@size.setter
def size(self, value):
"""setter for size"""
super().width(self, value)
def update(self, *args, **kwargs):
""" It allows don´t have a fixed number of arguments """
if args:
if len(args) == 4:
self.id = args[0]
self.size = args[1]
self.x = args[2]
self.y = args[3]
if len(args) == 3:
self.id = args[0]
self.size = args[1]
self.x = args[2]
if len(args) == 2:
self.id = args[0]
self.size = args[1]
if len(args) == 1:
self.id = args[0]
else:
for key, value in kwargs.items():
if hasattr(self, key) is True:
setattr(self, key, value)
def to_dictionary(self):
"""dictionary rep"""
dictionary = {'id': self.id, 'x': self.x, 'size': self.size, 'y': self.
y}
return(dictionary)
|
Markdown | UTF-8 | 1,211 | 2.71875 | 3 | [] | no_license | # What is PySpark?
PySpark is the collaboration Apache Spark and python.It is python API for spark.
# PySpark for Mac
Install spark using this link https://spark.apache.org/downloads.html
Choose your package type and download the associated tar file on your system.
Extract the tar file on system and move it to home directory for ease access.
This will create a directory with the full name.For simplicity you can just write spark.
# Mininum Requirements for spark
1)Check if java is installed or not using java -version.
2)Check for python(By default Mac OS already have python installed)
After Installation go to Terminal and move to your spark directory created using cd spark(directory name).
Now go to bin directory it contains binary files for running spark comman-line processors.

To use python type- ./pyspark

References:-
1) https://www.linkedin.com/learning/spark-for-machine-learning-a by Dan Sullivan
|
Markdown | UTF-8 | 3,494 | 3.015625 | 3 | [] | no_license | # 后端语言初识
## 1. PHP
世界最好的语言 PHP,php 上手比较快,所以前端想了解服务端语言的话,php 可以作为服务端入门语言。
**特点:**
- 开放源码,免费
- 开发快捷,入门快
- 跨平台,配置简单
- 开源框架丰富
- 面向对象
**欠缺点:**
- 多线程不好
- 编码规范不统一
- 语法不严谨
PHP 属于脚本语言,不需要进行编译成包去运行,在特点的环境下就可以跑起来,一般的生产环境配置都是`Apache` + `MySql` + `PHP` + `Linux`。
**适用范围:**
- 中小型网站
- CMS
- 单用作后端接口
- 与前端代码混用
## 2. Java
最早主要用于嵌入式开发,后续发展成用于其他开发。
**特点:**
- 面向对象编程
- 强类型语言,动态语言
- 跨平台,高移植性
- 稳定,安全性高
- 各种类库非常丰富
因为 Java 是强类型语言,所以在 Java 中规定一种变量类型时,传参必须是相对应的类型,否则就会报错。这种强类型语言增强了语言的稳定性。
Java 属于动态语言,没有用到的包,在内存中不会使用,只有用到的包内存中才会使用。
Java 的安全性很高,本身的漏洞很少,几乎没有。
Java 的框架也很多,包括很多方面,生态圈特别庞大,有很多类库。
综上所述,Java 成为了很多大型公司受欢迎的语言。
**适用范围:**
- 大型网站的前端(jsp)和后端
- 嵌入式
- 桌面程序
- 追求安全和稳定的商业系统
**名词解释:**
- JVM
Java 虚拟机
- JRE
Java 运行时环境,包含了 Java 虚拟机,Java 基础类库。
- JDK
Java 开发工具包。JDK 包含了 JRE,同时还包含了编译 Java 源码的编译器 Javac,还包含了很多 Java 程序调试和分析的工具:jconsole,jvisualvm 等工具软件,还包含了 Java 程序编写所需的文档和 demo 例子程序
- spring boot
Java 微服务框架
## 3. C
C# 前几年用的人很多,主要写桌面应用。虽然现在用的人越来越少了,但是前几年还是占据了很大市场的。
**特点:**
- 微软的亲儿子
- 强类型语言,安全稳定
- 面向对象
- 开发高效
**欠缺点:**
- 依赖 .NET Framework
**适用范围:**
- 网站系统(ASP)
- 后台服务
- 桌面程序(主要用途)
## 4. Python
主要用于大数据,人工智能方面,可以嵌入到其他语言中,而且书写起来语法很简洁,本身具有可扩展性,和`JavaScript`风格类似,后续应该多关注学习一下。
**特点:**
- 免费开源
- 完全面向对象
- 语法简洁清晰
- 语言本身就是可扩展的
- 扩展类库非常丰富
- 可以嵌入其他语言中
- 运行速度快
**欠缺点:**
- 跨平台特性稍差
**应用范围:**
- web 开发
- 服务器端后台
- 图形、数学、文本处理功能强大
- 桌面程序(很少)
- 黑客比较喜欢的语言
## 5. Go
运行速度非常快,接近于 C 语言,而且还在浏览器端有赶超`JavaScript`的趋势,目前主要用于`Google`扩展程序,前端人员应该多多关注。说不定后续就是拿 Go 语言开发浏览器的应用了。
**特点:**
- Google 的亲儿子
- 编译型语言,静态类型语言
- 编译和运行速度快,接近 C 语言
- 在浏览器端有可能会挑战 JavaScript 的地位
- 支持多核 CPU 运行
- 完全支持垃圾回收
- 很适合大型程序
|
Shell | UTF-8 | 305 | 2.84375 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | #!/bin/bash -ex
pushd $(dirname $0) > /dev/null 2>&1;
#
# -c INI configuration file
# -t Document root
# -S Start a built-in PHP server on host:port
# router.php to configure 'rewrites'
#
php \
-c php.ini \
-t src/htdocs \
-S localhost:9040 \
$(pwd)/router.php
popd > /dev/null 2>&1;
exit 0;
|
C++ | UTF-8 | 1,515 | 2.859375 | 3 | [] | no_license | // ll_map
// Longitude & Latitude Map
// NOTES:
// 1 degree = 69 miles
// Burlington
// Lat: 44.476266
// Lon: -73.205509
#ifndef LL_MAP_H
#define LL_MAP_H
#include <iostream>
#include <math.h>
#include <sstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
namespace gfox
{
struct my_string {
char *ptr;
size_t len;
};
class ll_map;
void init_my_string(my_string*);
size_t write_func(void*, size_t, size_t, my_string*);
void pull_data(double*, double*, size_t num_points);
class ll_map {
private:
// The geographic center of the map
double m_latitude;
double m_longitude;
// The distance between two adjacent map points
double m_spacing_degrees;
double m_spacing_meters;
// The upper left of the map
double m_upper_left_lat;
double m_upper_left_lon;
// How far the map spans from the center
double m_width_degrees;
double m_width_meters;
// The density of the map
size_t m_density;
// The height map
float** m_map;
public:
ll_map();
~ll_map();
void build_map(double, double, double, size_t);
void clean_map();
void from_int_to_xy(size_t, size_t*, size_t*);
void from_ll_to_xy(double, double, size_t*, size_t*);
void from_xy_to_int(size_t, size_t, size_t*);
void from_xy_to_ll(size_t, size_t, double*, double*);
double get_density() { return m_density; }
float get_height(size_t, size_t);
double get_spacing_meters() { return m_spacing_meters; }
double get_width_meters() { return m_width_meters; }
};
}
#endif
|
TypeScript | UTF-8 | 394 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | import { Derivable } from './derivable';
/**
* Unpacks a derivable or does nothing if `v` is not a derivable.
*
* @param v a value or derivable
*/
export function unpack<T>(v: T | Derivable<T>): T;
export function unpack<T>(v: T | Derivable<T> | undefined): T | undefined;
export function unpack<T>(v?: T | Derivable<T>): T | undefined {
return v instanceof Derivable ? v.get() : v;
}
|
JavaScript | UTF-8 | 633 | 2.9375 | 3 | [
"MIT"
] | permissive | // profile lookup
var contacts = [
{
"firstName" : "pooya",
"lastName" : "panahi",
"id" : "212112"
},
{
"firstName" : "parham",
"lastName" : "panahijat",
"id" : "212156"
},
{
"firstName" : "pashmak",
"lastName" : "panahim",
"id" : "217812"
},
{
"firstName" : "pashmam",
"lastName" : "panahesh",
"id" : "212092"
}
];
function lookUpProfile(name, prob) {
for (var counter = 0 ; counter < contacts.length ; counter++ ){
if (contacts[counter].firstName === name) {
return contacts[counter][prob]
}
}
return "no such a contact"
}
var data = lookUpProfile("pooya", "id")
document.write(data) |
C# | UTF-8 | 4,498 | 2.53125 | 3 | [] | no_license | using UnityEngine;
using System;
namespace Reference
{
[RequireComponent(typeof(CharacterController))]
public class ProtoCharControl : MonoBehaviour
{
public BaseMotionVars Motion = new BaseMotionVars();
public GravityVars Gravity = new GravityVars();
protected float _xVel = 0f;
protected float _yVel = 0f;
protected float _zVel = 0f;
protected float _zeroThreshold = 0.1f;
protected Rigidbody _rb;
protected Collider _collider;
protected CharacterController _charController;
public virtual bool IsGrounded
{
get
{
// return var
var isGrounded = false;
isGrounded = _charController.isGrounded;
return isGrounded;
}
}
[Serializable]
public class BaseMotionVars
{
public float Speed = 1f;
public float Acceleration = 0.2f;
public float DragX = 0.05f;
public float DragY = 0.00f;
public float DragZ = 0.05f;
}
[Serializable]
public class GravityVars
{
public bool UsesGravity = false;
public float GravityMax = 4f;
public float GravityAcceleration = 0.1f;
public LayerMask Ground;
}
protected virtual void Awake()
{
_charController = GetComponent<CharacterController>();
}
protected virtual void FixedUpdate()
{
if (Gravity.UsesGravity) ApplyGravity();
ApplyMovement();
}
/// <summary>
/// Immediatley set velocities to this force
/// </summary>
/// <remarks>
/// Ignores MaxSpeed
/// </remarks>
/// <param name="force"></param>
public void UpdateVelocity(Vector3 force)
{
_xVel = force.x;
_yVel = force.y;
_zVel = force.z;
}
public void ResetVelocity()
{
_xVel = 0;
_yVel = 0;
_zVel = 0;
}
/// <summary>
/// Move the charater
/// </summary>
protected void ApplyMovement()
{
_charController.Move(new Vector3(_xVel, _yVel, _zVel));
}
/// <summary>
/// Check if the player is grounded, and apply gravity if they aren't
/// </summary>
protected void ApplyGravity()
{
// if not on ground
if (!IsGrounded)
{
// add negative velocity
if (_yVel >= -Gravity.GravityMax) _yVel -= Gravity.GravityAcceleration;
}
else
{
if (_yVel < 0) _yVel = 0;
}
}
/// <summary>
/// Apply drag to the character's Y axis.
/// </summary>
protected void ApplyDrag()
{
// apply X drag
if (Motion.DragX != 0)
{
if (_xVel != 0)
{
if ((_xVel < _zeroThreshold && _xVel > 0) ||
(_xVel > -_zeroThreshold && _xVel < 0))
{
_xVel = 0;
}
else
{
_xVel -= Motion.DragX * Math.Sign(_xVel);
}
}
}
// apply Y drag
if (Motion.DragY != 0)
{
if (_yVel != 0)
{
if ((_yVel < _zeroThreshold && _yVel > 0) ||
(_yVel > -_zeroThreshold && _yVel < 0))
{
_yVel = 0;
}
else
{
_yVel -= Motion.DragY * Math.Sign(_yVel);
}
}
}
// apply Z drag
if (Motion.DragZ != 0)
{
if (_zVel != 0)
{
if ((_zVel < _zeroThreshold && _zVel > 0) ||
(_zVel > -_zeroThreshold && _zVel < 0))
{
_zVel = 0;
}
else
{
_zVel -= Motion.DragZ * Math.Sign(_zVel);
}
}
}
}
}
} |
Java | UTF-8 | 3,041 | 2.109375 | 2 | [] | no_license | package com.team3.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.team3.model.APIResponse;
import com.team3.model.Account;
import com.team3.model.Position;
import com.team3.model.Pager;
import com.team3.model.Position;
import com.team3.repository.PositionRepository;
import com.team3.resources.UserInformation;
import com.team3.repository.PositionRepository;
@Service
public class PositionService {
@Autowired
private PositionRepository positionRepository;
@PersistenceContext
private EntityManager em;
public ArrayList<Position> getAllPosition() {
List<Position> list = new ArrayList<Position>();
list = positionRepository.findAll();
return (ArrayList<Position>) list;
}
public Optional<Position> getById(int id) {
return positionRepository.findById(id);
}
public void addPosition(Position position) {
positionRepository.save(position);
}
public void editPosition(Position position) {
positionRepository.save(position);
}
public void deletePosition(int id) {
positionRepository.deleteById(id);
}
public APIResponse findByCondition(Position position) {
ArrayList<Position> list = new ArrayList<Position>();
String query = "from Position where id >0 ";
if (!(position.getDescription() == null)) {
query += " and description like :description";
}
if (!(position.getPositionName() == null)) {
query += " and positionName like :positionName ";
}
Query q = em.createQuery(query);
if (!(position.getDescription() == null)) {
q.setParameter("description", "%" + position.getDescription() + "%");
}
if (!(position.getPositionName() == null)) {
q.setParameter("positionName", "%" + position.getPositionName() + "%");
}
APIResponse response = new APIResponse();
Pager pager = new Pager();
List<Object[]> totalRow = q.getResultList();
pager.setTotalRow(totalRow.size());
q.setFirstResult(position.getPager().getPage() * position.getPager().getPageSize());
q.setMaxResults(position.getPager().getPageSize());
list = (ArrayList<Position>) q.getResultList();
pager.setPageSize(position.getPager().getPageSize());
pager.setPage(position.getPager().getPage());
response.setPager(pager);
response.setData(list);
return response;
}
public Position getPositionById(Integer id) {
Position position = new Position();
String hql = "FROM Position WHERE id = :id ";
Query q = em.createQuery(hql);
q.setParameter("id", id);
position = (Position) q.getResultList().stream().findFirst().orElse(null);
return position;
}
public List<String> getListPositionName() {
List<String> list = new ArrayList<String>();
String hql = " select positionName from Position";
Query q = em.createQuery(hql);
list = q.getResultList();
return list;
}
}
|
Python | UTF-8 | 2,574 | 3.015625 | 3 | [
"MIT"
] | permissive | """
Tests for botogram/utils.py
Copyright (c) 2015 Pietro Albini <pietro@pietroalbini.io>
Released under the MIT license
"""
import botogram.utils
import botogram.decorators
STRANGE_DOCSTRING = """ a
b
"""
def test_strip_urls():
# Standard HTTP url
assert botogram.utils.strip_urls("http://www.example.com") == ""
# Standard HTTPS url
assert botogram.utils.strip_urls("https://www.example.com") == ""
# HTTP url with dashes in the domain (issue #32)
assert botogram.utils.strip_urls("http://www.ubuntu-it.org") == ""
# HTTP url with a path
assert botogram.utils.strip_urls("http://example.com/~john/d/a.txt") == ""
# Standard email address
assert botogram.utils.strip_urls("john.doe@example.com") == ""
# Email address with a comment (+something)
assert botogram.utils.strip_urls("john.doe+botogram@example.com") == ""
# Email address with subdomains
assert botogram.utils.strip_urls("john.doe@something.example.com") == ""
# Email address with dashes in the domain name (issue #32)
assert botogram.utils.strip_urls("pietroalbini@ubuntu-it.org") == ""
def test_format_docstr():
# This docstring needs lots of cleanup...
res = botogram.utils.format_docstr(STRANGE_DOCSTRING)
assert res == "a\n\nb"
# This instead should be left as it is
ok = "a\nb"
assert botogram.utils.format_docstr(ok) == ok
def test_docstring_of(bot):
# This function will be used in the testing process
def func():
"""docstring"""
# Before everything, test with the default docstring
assert botogram.utils.docstring_of(func) == "docstring"
# Next try with an empty docstring
func.__doc__ = ""
assert botogram.utils.docstring_of(func) == "No description available."
# And else try to use a custom function
# This will also test if botogram.utils.format_docstr is called
@botogram.decorators.help_message_for(func)
def help_func():
return STRANGE_DOCSTRING
assert botogram.utils.docstring_of(func) == "a\n\nb"
def test_usernames_in():
assert botogram.utils.usernames_in("Hi, what's up?") == []
assert botogram.utils.usernames_in("Hi @johndoe!") == ["johndoe"]
multiple = botogram.utils.usernames_in("Hi @johndoe, I'm @pietroalbini")
assert multiple == ["johndoe", "pietroalbini"]
command = botogram.utils.usernames_in("/say@saybot I'm @johndoe")
assert command == ["johndoe"]
email = botogram.utils.usernames_in("My address is john.doe@example.com")
assert email == []
username_url = botogram.utils.usernames_in("http://pwd:john@example.com")
assert username_url == []
|
C++ | UTF-8 | 2,727 | 2.71875 | 3 | [
"MS-PL",
"BSL-1.0",
"MIT"
] | permissive | #pragma once
#include <condition_variable>
#include <functional>
#include <mutex>
namespace sptf
{
class AbortManager
{
private:
using Task = std::function<void()>;
struct AbortableTask
{
std::unique_ptr<Task> task;
abort_callback* pAbort;
};
public:
class AbortableScope
{
friend class AbortManager;
public:
AbortableScope( AbortableScope&& other );
~AbortableScope();
private:
AbortableScope( size_t taskId, AbortManager& parent );
private:
AbortManager& parent_;
bool isValid_ = true;
size_t taskId_;
};
public:
AbortManager();
AbortManager( const AbortManager& other ) = delete;
AbortManager( AbortManager&& other ) = delete;
~AbortManager() = default;
void Finalize();
template <typename T>
AbortableScope GetAbortableScope( T&& task, abort_callback& abort )
{
return AbortableScope( AddTask( std::forward<T>( task ), abort ), *this );
}
private:
void StartThread();
void StopThread();
void EventLoop();
template <typename T>
size_t AddTask( T&& task, abort_callback& abort )
{
static_assert( std::is_invocable_v<T> );
static_assert( std::is_move_constructible_v<T> || std::is_copy_constructible_v<T> );
const auto taskId = [&] {
std::unique_lock lock( mutex_ );
const auto taskId = [&] {
auto id = idCounter_;
while ( idToTask_.count( id ) )
{
id = ++idCounter_;
}
return id;
}();
if constexpr ( !std::is_copy_constructible_v<T> && std::is_move_constructible_v<T> )
{
auto taskLambda = [taskWrapper = std::make_shared<T>( std::forward<T>( task ) )] {
std::invoke( *taskWrapper );
};
idToTask_.try_emplace( taskId, AbortableTask{ std::make_unique<Task>( taskLambda ), &abort } );
}
else
{
idToTask_.try_emplace( taskId, AbortableTask{ std::make_unique<Task>( std::forward<T>( task ) ), &abort } );
}
return abortToIds_[&abort].emplace_back( taskId );
}();
eventCv_.notify_all();
return taskId;
}
void RemoveTask( uint32_t taskId );
private:
std::unique_ptr<std::thread> pThread_;
std::mutex mutex_;
std::condition_variable eventCv_;
bool isTimeToDie_ = false;
size_t idCounter_ = 0;
std::unordered_map<size_t, AbortableTask> idToTask_;
std::unordered_map<abort_callback*, std::vector<size_t>> abortToIds_;
};
} // namespace sptf
|
Java | UTF-8 | 2,109 | 2.296875 | 2 | [] | no_license | package com.AlphaDevs.cloud.web.JSFBeans;
import com.AlphaDevs.cloud.web.Entities.Logger;
import com.AlphaDevs.cloud.web.Entities.Units;
import com.AlphaDevs.cloud.web.Enums.TransactionTypes;
import com.AlphaDevs.cloud.web.Helpers.EntityHelper;
import com.AlphaDevs.cloud.web.SessionBean.LoggerController;
import com.AlphaDevs.cloud.web.SessionBean.UnitsController;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* @author Mihindu Gajaba Karunarathne Alpha Development Team (Pvt) Ltd
*
*/
@ManagedBean
@ViewScoped
public class UnitsHandler {
@EJB
private LoggerController loggerController;
@EJB
private UnitsController unitsController;
private String RDStatus;
private Units current;
public UnitsHandler() {
if (current == null) {
current = new Units();
}
}
public UnitsController getUnitsController() {
return unitsController;
}
public void setUnitsController(UnitsController unitsController) {
this.unitsController = unitsController;
}
public Units getCurrent() {
return current;
}
public void setCurrent(Units current) {
this.current = current;
}
public List<Units> getList() {
return unitsController.findAll();
}
public String persistUOM() {
Logger Log = EntityHelper.createLogger("Create UOM", current.getUnitCode(), TransactionTypes.UOM);
loggerController.create(Log);
current.setLogger(Log);
unitsController.create(current);
if (getRDStatus() != null) {
System.out.println(getRDStatus());
return getRDStatus();
} else {
return "Home";
}
}
/**
* @return the RDStatus
*/
public String getRDStatus() {
return RDStatus;
}
/**
* @param RDStatus the RDStatus to set
*/
public void setRDStatus(String RDStatus) {
System.out.println(RDStatus);
this.RDStatus = RDStatus;
System.out.println(this.RDStatus);
}
}
|
Java | UTF-8 | 608 | 3.53125 | 4 | [] | no_license | package binarytree;
import tree.Node;
public class DeleteTree {
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
// Node node =
delete(root);
}
public static Node delete(Node root) {
if (root != null) {
delete(root.left);
delete(root.right);
System.err.println("Deleting node is " + root.data);
root = null;
return root;
}
return null;
}
}
|
Markdown | UTF-8 | 1,059 | 2.859375 | 3 | [
"MIT"
] | permissive | # Rank Scoring via Collaborative Filtering
Efficient implementation of User-User and Item-Item Collaborative Filtering in Python using parallelization for faster pre-processing.
## Collaborative Filtering
Collaborative Filtering is a scoring algorithm based on prior knowledge used in recommendation systems.
**User-User** collaborative filtering ranks and scores possible recommendations by assessing whether or not users similar to the subject have a history of liking the item in question.
**Item-Item** collaborative filtering ranks and scores possible recommendations by assessing whether or not the subject have a history of liking things similar to the items in question.
CF can be used to make recommendations for basically any kind of data (e-commerce, videos, music, etc.).
The notebook contained in this repo is a part of a study on recommender systems using the [MovieLens 20M dataset](https://www.kaggle.com/grouplens/movielens-20m-dataset) from Kaggle as a proof of concept and implements/evaluates both kinds of collaborative filtering.
|
Go | UTF-8 | 3,158 | 2.609375 | 3 | [] | no_license | package main
import (
"ceph-tools/ceph_client"
"ceph-tools/host"
"fmt"
"github.com/liucxer/ceph-tools/pkg/cluster_client"
"sort"
"time"
)
type CephStatus struct {
Time time.Time `json:"time"`
HealthMinimalResp ceph_client.HealthMinimalResp `json:"health_minimal_resp"`
}
var mapCephStatus = map[int64]CephStatus{}
func DoCollect(clientHost *host.Host) error {
client := ceph_client.CephClientSt{
Host: "10.0.20.29",
Port: "8443",
UserName: "admin",
Password: "xv07b7uhkm1",
}
HealthMinimalReq := &ceph_client.HealthMinimalReq{}
HealthMinimalResp := &ceph_client.HealthMinimalResp{}
err := client.HealthMinimal(HealthMinimalReq, HealthMinimalResp)
if err != nil {
return err
}
var cephStatus CephStatus
cephStatus.Time = time.Now()
cephStatus.HealthMinimalResp = *HealthMinimalResp
mapCephStatus[cephStatus.Time.Unix()] = cephStatus
return nil
}
type CephStatusList []CephStatus
func (list CephStatusList) Len() int {
return len(list)
}
func (list CephStatusList) Less(i, j int) bool {
return (list)[i].Time.Unix() < (list)[j].Time.Unix()
}
func (list CephStatusList) Swap(i, j int) {
item := (list)[i]
(list)[i] = (list)[j]
(list)[j] = item
}
func (list CephStatusList) ToCsv() string {
var res = ""
header := "time," +
"recovering_bytes_per_sec" +
"read_bytes_sec,write_bytes_sec,read_op_per_sec,write_op_per_sec"
res = res + header + "\n"
for _, item := range list {
itemStr := fmt.Sprintf("%s, %d,%d,%d,%d,%d",
item.Time.Format("2006-01-02 15:04:05"),
item.HealthMinimalResp.ClientPerf.RecoveringBytesPerSec,
item.HealthMinimalResp.ClientPerf.ReadBytesSec,
item.HealthMinimalResp.ClientPerf.WriteBytesSec,
item.HealthMinimalResp.ClientPerf.ReadOpPerSec,
item.HealthMinimalResp.ClientPerf.WriteOpPerSec,
)
res = res + itemStr + "\n"
}
return res
}
func main() {
//logrus.SetLevel(logrus.DebugLevel)
totalTime := 1 * 60 // 10分钟
clientHost := host.NewHost("10.0.20.29")
// 收集10分钟数据
go func() {
for i := 0; i < totalTime*2; i++ {
go DoCollect(clientHost)
time.Sleep(500 * time.Millisecond)
}
}()
// 数据写入
// 1.先确保rbd进程全部关闭
// 2.开启协程 执行rbd写入
// 3.10分钟之后 关闭rbd进程
go func() {
clientHost.ExecCmd("killall rbd")
go func() {
clientHost.ExecCmd("rbd -p data_pool bench foo1 --io-type write --io-size 4K --io-threads 64 --io-total 500G --io-pattern seq")
}()
time.Sleep(time.Duration(totalTime) * time.Second)
clientHost.ExecCmd("killall rbd")
}()
// recovery
// 第5分钟开启recovery
// 第10分钟关闭recovery
go func() {
time.Sleep(time.Duration(totalTime) * time.Second / 2)
clientHost.ExecCmd("ceph osd pool set rb_pool size 3")
time.Sleep(time.Duration(totalTime) * time.Second / 2)
clientHost.ExecCmd("ceph osd pool set rb_pool size 2")
}()
time.Sleep(time.Duration(totalTime) * time.Second)
var cephStatusList CephStatusList
for _, cephStatus := range mapCephStatus {
cephStatusList = append(cephStatusList, cephStatus)
}
sort.Sort(cephStatusList)
csv := cephStatusList.ToCsv()
fmt.Println(csv)
}
|
PHP | UTF-8 | 3,016 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
/**
* KePHP, Keep PHP easy!
*
* @license https://opensource.org/licenses/MIT
* @copyright Copyright 2015 - 2020 KePHP Authors All Rights Reserved
* @link http://kephp.com ( https://git.oschina.net/kephp/kephp-core )
* @author 曾建凯 <janpoem@163.com>
*/
namespace Ke\Cli\Cmd;
use Ke\App;
use Ke\Cli\ReflectionCommand;
class Server extends ReflectionCommand
{
const CURRENT_DIR = 1;
const PARENT_DIR = 2;
protected static $commandName = 'server';
protected static $commandDescription = 'start php embed web-server';
/**
* @var string
* @type string
* @field listen
* @shortcut l
*/
protected $listen = '';
/**
* @var string
* @type string
* @field documentRoot
* @shortcut d
*/
protected $documentRoot = '';
/**
* @var string
* @type string
* @field router
* @shortcut r
*/
protected $router = '';
protected $cwd = '';
protected $inKephpApp = 0;
protected function onPrepare($argv = null)
{
if (empty($this->listen))
$this->listen = 'localhost:8080';
$this->cwd = getcwd();
if (is_file("{$this->cwd}/ke.php"))
$this->inKephpApp = 1;
elseif (is_file("{$this->cwd}/../ke.php"))
$this->inKephpApp = 2;
if (empty($this->router)) {
if ($this->inKephpApp) {
$this->router = 'index.php';
}
}
if (empty($this->documentRoot)) {
if ($this->inKephpApp === self::CURRENT_DIR) {
$this->documentRoot = $this->cwd . '/public';
} elseif ($this->inKephpApp === self::PARENT_DIR) {
$this->documentRoot = $this->cwd . '/../public';
} else {
$this->documentRoot = $this->console->getCwd();
$dir = real_dir($this->documentRoot . '/public');
if (!empty($dir) && is_dir($dir))
$this->documentRoot = $dir;
}
} else {
$dir = real_dir($this->documentRoot);
if (empty($dir) || !is_dir($dir))
$this->exit("Directory {$this->ansi($this->documentRoot, 'yellow')} {$this->ansi('not exists', 'red')}!");
$this->documentRoot = $dir;
}
if (!empty($this->router)) {
if (!is_file("{$this->documentRoot}/{$this->router}")) {
$this->exit("The specified router file `{$this->ansi($this->router, 'red')}` does not exist!");
}
}
}
protected function onExecute($argv = null)
{
$versions = [
$this->ansi('PHP ' . phpversion(), 'blue'),
$this->ansi('kephp ' . KE_VER, 'cyan'),
];
$this->println(implode(', ', $versions));
$dirTail = $this->inKephpApp ? '(kephp-app)' : '';
$this->println("entry dir {$this->ansi($this->documentRoot, 'green')}{$dirTail}");
chdir($this->documentRoot);
if (empty($this->router)) {
$this->println("Try to start php embed server in {$this->ansi("http://{$this->listen}", 'blue|underline')} without router");
$this->println(system("php -S {$this->listen}"));
} else {
$this->println("Try to start php embed server in {$this->ansi("http://{$this->listen}", 'blue|underline')} with router {$this->ansi($this->router, 'yellow')}");
$this->println(system("php -S {$this->listen} {$this->router}"));
}
}
} |
Swift | UTF-8 | 2,363 | 2.75 | 3 | [] | no_license | //
// PrivateCustomItem.swift
// SimpleNeteaseMusic
//
// Created by shenjie on 2021/1/13.
// Copyright © 2021 shenjie. All rights reserved.
//
import Foundation
import UIKit
let JJINTERVAL: CGFloat = 20
class PrivateCustomItem: UICollectionViewCell {
// stackView
private var stack: UIStackView!
// 私人定制数据
private var privateDataList: [SongModel]!
// 私人定制列表
private var privateRowViews: [RowStyleView]!
// 默认排行榜单个 item 的高度为 40
public var height: CGFloat = 40.0
override init(frame: CGRect) {
super.init(frame: frame)
// self.backgroundColor = .white
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Lifeycle
extension PrivateCustomItem {
/* 布局尺寸必须在 layoutSubViews 中, 否则获取的 size 不正确 **/
override func layoutSubviews() {
superview?.layoutSubviews()
// 进行约束
stack.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.top.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalToSuperview()
}
}
}
// MARK: - Configuration
extension PrivateCustomItem {
private func createRowStyleView() {
// 宽度
let width: CGFloat = self.frame.size.width - JJINTERVAL * 2
privateRowViews = [RowStyleView]()
privateRowViews.removeAll()
for listItem in privateDataList {
let rowView = RowStyleView(frame: CGRect(x: 0, y: 0, width: Double(width), height: Double(20)), style: .SubTitleStyle)
rowView.setUpRowViewWithSubTitleStyle(image: listItem.image, songName: listItem.songName, singer: listItem.singer, foreword: " privateRowViews = [RowStyleView]()", style: .SubTitleStyle, extra: "")
privateRowViews.append(rowView)
}
stack = UIStackView(arrangedSubviews: privateRowViews)
stack.spacing = 10
stack.axis = .vertical
stack.distribution = .fillEqually
self.contentView.addSubview(stack)
}
// 更新数据,并重绘界面
public func updateUI(data: [SongModel]) {
privateDataList = data
createRowStyleView()
}
}
|
PHP | UTF-8 | 1,088 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BotUser extends Model
{
use HasFactory;
protected $fillable = [
'user_id', 'user_name', 'first_name', 'last_name',
'active', 'current_action', 'company_telegram_id', 'company_name',
];
protected $casts = [
'active' => 'boolean',
];
public function getCreatedAtAttribute($value): string
{
return Carbon::parse($value)->translatedFormat('d M Y, H:i');
}
public static function getAllUsers()
{
return self::all(['id', 'user_id', 'user_name', 'first_name', 'last_name', 'active', 'created_at', 'updated_at']);
}
public static function getActiveUsers()
{
return self::where('active', true)->get(['id', 'user_id', 'user_name', 'first_name', 'last_name', 'active', 'created_at', 'updated_at']);
}
public function toggleActive()
{
$this->timestamps = false;
$this->update(['active' => !$this->active]);
}
}
|
Markdown | UTF-8 | 2,220 | 3.0625 | 3 | [] | no_license | # Week 5 Journal: Brielle Purnell
This week my API was added to the main working code. I worked on the Cashier's App view and controller.
The two commits that show this work are below:
**Added API**
https://github.com/nguyensjsu/sp21-172-debuggers/commit/34101fe625dad4e799818c374d5c1b36114c16a5
**Updated Cashier's App view**
https://github.com/nguyensjsu/sp21-172-debuggers/commit/b959d650335bcbe413178042bc4074fd30e453ef
## Fixed Console Output
The first thing I did this week was fix the console output for creating an order.

Before, it did not include the id, total, or status of the order. I did this by rearranging a few lines of code.
## Created the Receipt
I created the Receipt portion of the Cashier's App.

I added all of the order's details as model attributes and grabbed them using th:text attributes to display them on the UI. I also added a double lined border around the receipt for a more professional look.
## Updating the Drink Part and Heading of the UI
The next task I moved on to was the drink selection part of the user interface.

Before, these images were squares and closer together, and the text was not bolded. I transformed the images into circles for an aesthetic closer to the Starbucks company. I bolded the hyperlinked text. I also added padding to the bottoms of the text in order to make it easier to read and determine which text belongs to which image. Furthermore, I reduced the original size of the Starbucks logo from 225x225 pixels to 45x45 pixels and moved it up to the upper left. Before the large logo was in the middle of the UI under the Cashier's App header. Now with the logo placed to the left of the header, that part of the UI conveys a more standard nav-bar feeling. I also fixed the small typo from "Cashiers" to "Cashier's".
## Challenges
I tried updating the look of the form that is created from selecting the drink, milk, and size. I ran into trouble after I tried to make them labels instead of inputs because placing the order submitted a form created from the inputs.
|
Python | UTF-8 | 514 | 3.640625 | 4 | [] | no_license | ############################################################
#
# assert statements
#
############################################################
def CalculateQuartile(percent):
assert type(percent).__name__ == 'int'
assert percent >= 0 and percent <= 100
quartile = 1
if percent > 25:
quartile = 2
if percent > 50:
quartile = 3
if percent > 75:
quartile = 4
return quartile
print CalculateQuartile(34)
print CalculateQuartile(104)
|
C# | UTF-8 | 1,153 | 2.515625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media.Imaging;
namespace GravitatioanlSimulation.Writer
{
class GifWriter:IWriter
{
private GifBitmapEncoder _gifBitmapEncoder;
private string _outputFile;
public void Initialization(string OutputFile, int Width, int Height)
{
_gifBitmapEncoder = new GifBitmapEncoder();
_outputFile = OutputFile;
}
public void Write(Bitmap bitmap)
{
var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
_gifBitmapEncoder.Frames.Add(BitmapFrame.Create(src));
}
public void SaveResult()
{
using (FileStream fs = new FileStream(_outputFile, FileMode.Create))
{
_gifBitmapEncoder.Save(fs);
}
}
}
}
|
Java | UTF-8 | 576 | 2.375 | 2 | [] | no_license | package com.branthragan.vending_machine.state;
import com.branthragan.vending_machine.inventory.InventoryItem;
import com.branthragan.vending_machine.machine.VendingMachine;
public interface VendingState {
String MAKE_A_SELECTION = "Please make a selection";
String SOLD_OUT = "Sold Out";
String INVALID_ACTION = "Invalid Action";
String insertFunds(VendingMachine machine);
String ejectFunds(VendingMachine machine);
void selectItem(VendingMachine machine, InventoryItem item);
String dispense(VendingMachine machine, InventoryItem item);
}
|
C++ | UTF-8 | 1,641 | 3.015625 | 3 | [] | no_license | //baekjoon 1767
//N-Rook II
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
long long d[101][101][101];
long long mod = 100001;
/*4가지 경우가 있다.
//d[n][m][k]일때 그 수는 크리 n x m의 상자에 rook을 k개 넣을 수 있는
//경우의 수이다. 룩은 안 넣거나, 1개 넣거나, 2개를 넣을 수 있다. 안 넣는 다면
//d[n-1][m][k-1]이다. 1개를 같은 columnㅇ에 공격하는 룩이 없는 곳에 넣을 때는 새로운
줄을 끼워 넣는 다고 생각하고 row column을 줄인다. go(y - 1, x - 2, rook - 2).
1개를 위의 것과 공격하는 column에 넣을 때는 위의 룩의 row에 아무 룩이 없어야 하기 때문에
go(y - 2, x - 1, rook - 2)이다. 경우의 수는 (y - 1) * x이 된다.
2개를 넣을 때는 서로 이미 공격하기 떄문에 위에서 공격당할 수가 없다. 때문에 2 column을
넣는다고 생각하면 된다. go(y - 1, x - 2, rook - 2)이 된다. xC2는 x * (x - 1)/2이기
때문에 이걸 곱해주면 된다.
*/
long long go(int y, int x, int rook)
{
if (rook == 0)
{
return 1;
}
if (y <= 0 || x <= 0 || rook < 0)
return 0;
long long &ans = d[y][x][rook];
if (ans != -1)
return ans;
ans = go(y - 1, x, rook) + go(y - 1, x - 1, rook - 1) * x + go(y - 1, x - 2, rook - 2) * x * (x - 1) / 2 + go(y - 2, x - 1, rook - 2) * (y - 1) * x;
ans %= 1000001;
return ans;
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m >> k;
memset(d, -1, sizeof(d));
cout << go(n, m, k) << "\n";
return 0;
}
|
Java | UTF-8 | 1,647 | 2.734375 | 3 | [] | no_license | package com.study.utils;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by zbl on 2017/6/23.
*
*/
public class CommonUtil {
/**
* 从request中获得参数Map,并返回可读的Map.
*
* @param request the request
* @return the parameter map
*/
public static Map<String, Object> getParameterMap(HttpServletRequest request) {
// 参数Map
Map<String, String[]> properties = request.getParameterMap();
//返回值Map
Map<String, Object> returnMap = new HashMap<String, Object>();
Set<String> keySet = properties.keySet();
for (String key : keySet) {
String[] values = properties.get(key);
StringBuilder value = new StringBuilder();
if (values != null && (values.length == 1 && StringUtils.isNotBlank(values[0]))) {
for (String value1 : values) {
if (value1 != null && !"".equals(value1)) {
value.append(value1).append(",");
}
}
if (!"".equals(value.toString())) {
value = new StringBuilder(value.substring(0, value.length() - 1));
}
if (key.equals("keywords")) {//关键字特殊查询字符转义
value = new StringBuilder(value.toString().replace("_", "\\_").replace("%", "\\%"));
}
returnMap.put(key, value.toString());
}
}
return returnMap;
}
}
|
Java | UTF-8 | 2,610 | 2.40625 | 2 | [] | no_license | package no.acntech.rules.application.rules;
import no.acntech.rules.application.rules.basis.Person;
import org.jeasy.rules.api.*;
import org.junit.Before;
import org.junit.Test;
import java.time.LocalDate;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.jeasy.rules.core.RulesEngineBuilder.aNewRulesEngine;
public class IsOldEnoughRuleTest {
private Person testPerson;
@Test
public void testWayTooOldPassTheValidation() {
IsOldEnoughRule rule = new IsOldEnoughRule();
Facts facts = new Facts();
facts.put("person", testPerson);
Rules rules = new Rules();
rules.register(rule);
RulesEngine rulesEngine = aNewRulesEngine()
.withSkipOnFirstFailedRule(true)
.withSkipOnFirstAppliedRule(true)
.withSilentMode(true)
.build();
rulesEngine.fire(rules, facts);
assertThat(rule.isSuccess(), is(true));
assertThat(rule.getPriority(), is(1));
}
@Test
public void testEighteenYearsOldPassTheValidation() {
IsOldEnoughRule rule = new IsOldEnoughRule();
Facts facts = new Facts();
testPerson.setBirthdate(LocalDate.now().minusYears(18));
facts.put("person", testPerson);
Rules rules = new Rules();
rules.register(rule);
RulesEngine rulesEngine = aNewRulesEngine()
.withSkipOnFirstFailedRule(true)
.withSkipOnFirstAppliedRule(true)
.withSilentMode(true)
.build();
rulesEngine.fire(rules, facts);
assertThat(rule.isSuccess(), is(true));
assertThat(rule.getPriority(), is(1));
}
@Test
public void testSeventeenYearsAnd364DaysOldFailTheValidation() {
IsOldEnoughRule rule = new IsOldEnoughRule();
Facts facts = new Facts();
testPerson.setBirthdate(LocalDate.now().minusYears(17).plusDays(364));
facts.put("person", testPerson);
Rules rules = new Rules();
rules.register(rule);
RulesEngine rulesEngine = aNewRulesEngine()
.withSkipOnFirstFailedRule(true)
.withSkipOnFirstAppliedRule(true)
.withSilentMode(true)
.build();
rulesEngine.fire(rules, facts);
assertThat(rule.isSuccess(), is(false));
assertThat(rule.getPriority(), is(1));
}
@Before
public void setup() {
testPerson = new Person();
testPerson.setBirthdate(LocalDate.of(1977, 6, 30));
}
} |
Java | UTF-8 | 758 | 1.921875 | 2 | [] | no_license | package com.example.bmaz.coscproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
/**
* A simple {@link Fragment} subclass.
*/
public class LocalAttractionsTab extends ParentFragmentLayout {
public LocalAttractionsTab() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presentors = getResources().getStringArray(R.array.LocalAttractions);
presentorsInfo = new String[][]{
{getResources().getString(R.string.attractOne)},
{getResources().getString(R.string.attractTwo)},
{getResources().getString(R.string.attractThree)},
};
}
}
|
Python | UTF-8 | 2,608 | 3.125 | 3 | [] | no_license | #Import dependencies
import pandas as pd
import csv, sqlite3
from sqlite3 import Error
#Function to connect to database
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
#Function to create table and insert csv data
def create_table(conn, create_table_sql, csvfile):
""" create a table from the create_table_sql statement then import csv
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
df = pd.read_csv(csvfile)
df.to_sql('bechdel', conn, if_exists='append', index=False)
#close connection
# conn.close()
except Error as e:
print(e)
#Query the table
def select_all(conn):
"""
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM bechdel")
rows = cur.fetchall()
for row in rows:
print(row)
#close connection
conn.close()
#Connect to db, create table, import csv data
def main():
database = r'../App/bechdel.db'
create_bechdel_table = """CREATE TABLE IF NOT EXISTS bechdel (
imdbid integer NOT NULL,
bechdel_rating integer NOT NULL,
title text NOT NULL,
year integer NOT NULL,
binary integer NOT NULL,
budget_2013 integer NOT NULL,
domgross_2013 integer NOT NULL,
intgross_2013 integer NOT NULL,
genres text NOT NULL,
A text NOT NULL,
B text NOT NULL,
C text NOT NULL,
averageRating real NOT NULL,
numVotes integer NOT NULL);"""
csv = "../bechdel_final.csv"
# create a database connection
conn = create_connection(database)
# create tables
if conn is not None:
# create projects table and insert csv
create_table(conn, create_bechdel_table, csv)
select_all(conn)
else:
print("Error! cannot create the database connection.")
if __name__ == '__main__':
main() |
PHP | UTF-8 | 3,710 | 2.671875 | 3 | [] | no_license | <?php
class SinaOauth {
private $_host = "http://api.t.sina.com.cn/";
private $_sha1Method;
private $_consumer;
private $_token;
public function accessTokenURL() {
return 'http://api.t.sina.com.cn/oauth/access_token';
}
public function authenticateURL() {
return 'http://api.t.sina.com.cn/oauth/authenticate';
}
public function authorizeURL() {
return 'http://api.t.sina.com.cn/oauth/authorize';
}
public function requestTokenURL() {
return 'http://api.t.sina.com.cn/oauth/request_token';
}
public function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
$this->_sha1Method = new OAuthSignatureMethod_HMAC_SHA1 ();
$this->_consumer = new OAuthConsumer ( $consumer_key, $consumer_secret );
if (! empty ( $oauth_token ) && ! empty ( $oauth_token_secret )) {
$this->_token = new OAuthConsumer ( $oauth_token, $oauth_token_secret );
} else {
$this->_token = NULL;
}
}
public function getRequestToken($oauth_callback = NULL) {
$parameters = array ();
if (! empty ( $oauth_callback )) {
$parameters ['oauth_callback'] = $oauth_callback;
}
$request = $this->oAuthRequest ( $this->requestTokenURL (), 'GET', $parameters );
$token = OAuthUtil::parse_parameters ( $request );
$this->_token = new OAuthConsumer ( $token ['oauth_token'], $token ['oauth_token_secret'] );
return $token;
}
public function getAuthorizeURL($token, $back) {
if (is_array ( $token )) {
$token = $token ['oauth_token'];
}
return $this->authorizeURL () . "?oauth_token={$token}&oauth_callback=" . urlencode ( $back );
}
public function getAccessToken($oauth_verifier = FALSE, $oauth_token = false) {
$parameters = array ();
if (! empty ( $oauth_verifier )) {
$parameters ['oauth_verifier'] = $oauth_verifier;
}
$request = $this->oAuthRequest ( $this->accessTokenURL (), 'GET', $parameters );
$token = OAuthUtil::parse_parameters ( $request );
$this->_token = new OAuthConsumer ( $token ['oauth_token'], $token ['oauth_token_secret'] );
return $token;
}
public function oAuthRequest($url, $method, $parameters) {
if (strrpos ( $url, 'http://' ) !== 0 && strrpos ( $url, 'http://' ) !== 0) {
$url = "{$this->_host}{$url}.{$this->format}";
}
$request = OAuthRequest::from_consumer_and_token ( $this->_consumer, $this->_token, $method, $url, $parameters );
$request->sign_request ( $this->_sha1Method, $this->_consumer, $this->_token );
switch ($method) {
case 'GET' :
return $this->httpRequest ( $request->to_url () );
default :
return $this->httpRequest ( $request->get_normalized_http_url (), $request->to_postdata () );
}
}
private function httpRequest($url, $params = null, $decode = 0) {
$curlHandle = curl_init ( $url );
if (! empty ( $params )) {
curl_setopt ( $curlHandle, CURLOPT_POST, true );
if (is_array ( $params )) {
$params = http_build_query ( $params );
}
echo $params;
curl_setopt ( $curlHandle, CURLOPT_POSTFIELDS, $params );
}
curl_setopt ( $curlHandle, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $curlHandle, CURLOPT_TIMEOUT, 15 );
curl_setopt ( $curlHandle, CURLOPT_ENCODING, 'UTF-8' );
$response = curl_exec ( $curlHandle );
curl_close ( $curlHandle );
$response = trim ( $response );
switch ($decode) {
case 0 :
return $response;
break;
case 1 :
return json_decode ( $response );
break;
case 2 :
return json_decode ( $response, true );
break;
default :
return $response;
break;
}
}
}
?> |
Java | UTF-8 | 589 | 2.859375 | 3 | [] | no_license | package com.example.administrator.myapp;
public class Events {
private String date;
private String time;
private String thing;
public Events(String date, String time,String thing){
this.date = date;
this.time = time;
this.thing = thing;
}
public String getDate(){return date;}
public void setDate(String date){this.date = date;}
public String getTime(){return time;}
public void setTime(String time){this.time = time;}
public String getThing(){return thing;}
public void setThing(String thing){this.thing = thing;}
}
|
Java | UTF-8 | 14,715 | 2.21875 | 2 | [] | no_license | package strategyimpl.fundrank;
import CalculateTool.CalculateTool;
import blimpl.CalculateDataHandler;
import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import dataservice.BaseInfoDataService;
import dataserviceimpl.DataServiceController;
import entities.ConstParameterEntity;
import entities.FundInfosEntity;
import exception.ObjectNotFoundException;
import matlabtool.TypeConverter;
import util.SectorType;
import util.TimeType;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Created by Daniel on 2016/11/15.
*/
public class FundRank {
String[] sectorTypes = new String[]{SectorType.STOCK_TYPE, SectorType.BOND_TYPE, SectorType
.MONEY_MARKET_TYPE};
Map<String, List<String>> fundPool;
double[][] totalWeight = {{0.7, 0.3, 0, 0}, {0.6, 0.1, 0.3, 0}, {0.5, 0.1, 0.4, 0}},
profitWeight = {{0.3, 0.4, 0.3}, {0.8, 0, 0.2}, {1.0, 0, 0}},
riskWeight = {{0.4, 0.4, 0.2}, {0.5, 0.5, 0}, {0.8, 0.2, 0}},
stableWeight = {{0, 0}, {0.7, 0.3}, {0.9, 0.1}};
String baseCode = "I000300";
TimeType calTimeType = TimeType.THREE_YEAR;
private static final int UNIT = 5;
/**
* 获得总的基金池
* 筛选掉成立时间短和规模小的(成立时间两年以内,资产规模小于2亿(1亿?)的筛选掉)
*
* @return 以sectorType作为键,即按基金分类返回基金代码
*/
public Map<String, List<String>> getTotalFundPool() {
Map<String, List<String>> re = new HashMap<>();
BaseInfoDataService baseInfoDataService = DataServiceController.getBaseInfoDataService();
try {
List<String> qdii = baseInfoDataService.getSectorCodes(SectorType.QDII_TYPE);
for (String str : sectorTypes) {
List<String> tem = baseInfoDataService.getSectorCodes(str);
tem.removeAll(qdii);
re.put(str,
tem.stream().filter(new Predicate<String>() {
@Override
public boolean test(String s) {
try {
FundInfosEntity fundInfosEntity = baseInfoDataService.getFundInfo(s);
LocalDate localDate = LocalDate.now();
localDate = localDate.minusYears(3);
String date = localDate.toString();
if (fundInfosEntity.getScale() == null || fundInfosEntity
.getScale() <= 2 || fundInfosEntity.getEstablishDate()
== null || fundInfosEntity.getEstablishDate()
.compareTo(date) > 0 || fundInfosEntity.getSimpleName()
.contains("B") || fundInfosEntity.getSimpleName()
.contains("C")) {
return false;
}
return true;
} catch (ObjectNotFoundException e) {
e.printStackTrace();
}
return false;
}
}).collect(Collectors.toList()));
}
} catch (ObjectNotFoundException e) {
e.printStackTrace();
}
fundPool = re;
return re;
}
public List<FundIndexInfo> getFundRank(List<String> codes, String sectorType) {
Map<String, Double> re = new HashMap<>();
Map<String, List<Double>> fundRiseInfos = new HashMap<>();
Map<String, List<Double>> baseRiseInfos = new HashMap<>();
int index = getIndexBySectorType(sectorType);
if (index == -1)
return null;
CalculateTool calculateTool = null;
ConstParameterEntity constParameterEntity = DataServiceController.getBaseInfoDataService()
.getConstParameter();
try {
calculateTool = new CalculateTool();
} catch (MWException e) {
e.printStackTrace();
}
/**
* 获取数据
*/
System.out.println("开始获取数据");
for (String code : codes) {
CalculateDataHandler cal = new CalculateDataHandler(code);
cal.setTimeType(calTimeType);
cal.setBaseCode(baseCode);
try {
Map<String, List<Double>> info = cal.getDatasByRise();
fundRiseInfos.put(code, info.get(code));
baseRiseInfos.put(code, info.get(baseCode));
} catch (ObjectNotFoundException e) {
e.printStackTrace();
}
}
System.out.println("数据获取结束");
/**
* ----------------------计算盈利能力-----------------------
*/
double pw = totalWeight[index][0];
List<FundIndexInfo> totalProfit = new ArrayList<>(), sharpe = new ArrayList<>(), jensen = new ArrayList<>();
for (String code : codes) {
double p = fundRiseInfos.get(code).stream().reduce((x, y) -> (1 + x) * (1 + y) - 1).get();
if (code.equals("070005"))
System.out.println(p);
totalProfit.add(new FundIndexInfo(code, p));
}
addScore(re, totalProfit, profitWeight[index][0], pw, 1);
System.out.println("profit over----start sharpe");
if (profitWeight[index][1] != 0) {
try {
for (String code : codes) {
MWNumericArray fof_info_mwn = TypeConverter.convertList(fundRiseInfos.get(code));
double s = TypeConverter.getSingleDoubleResult(calculateTool.calSharpe(1,
fof_info_mwn, constParameterEntity.getNoRiskProfit() / 100, 1.0));
sharpe.add(new FundIndexInfo(code, s));
}
addScore(re, sharpe, profitWeight[index][1], pw, 1);
} catch (MWException e) {
e.printStackTrace();
}
}
System.out.println("sharpe over----start jensen");
if (profitWeight[index][2] != 0) {
try {
for (String code : codes) {
MWNumericArray fof_info_mwn = TypeConverter.convertList(fundRiseInfos.get(code));
MWNumericArray base_info_mwn = TypeConverter.convertList(baseRiseInfos.get(code));
double j = TypeConverter.getSingleDoubleResult(calculateTool.calJensen
(1, fof_info_mwn, base_info_mwn, constParameterEntity
.getNoRiskProfit() / 100, 1.0));
jensen.add(new FundIndexInfo(code, j));
}
addScore(re, jensen, profitWeight[index][2], pw, 1);
} catch (MWException e) {
e.printStackTrace();
}
}
/**
* ----------------------------盈利能力计算结束-------------------------------
*/
/**
* ----------------------------计算抗风险能力--------------------------------
*/
double rw = totalWeight[index][1];
List<FundIndexInfo> vRatio = new ArrayList<>(), averageV = new ArrayList<>(), maxRecu = new
ArrayList<>();
for (String code : codes) {
int vSize = fundRiseInfos.get(code).size();
double fr = 0;
double total = 0;
for (double d : fundRiseInfos.get(code)) {
if (d < 0) {
fr++;
total += d;
}
}
vRatio.add(new FundIndexInfo(code, fr / vSize));
averageV.add(new FundIndexInfo(code, total / vSize));
}
addScore(re, vRatio, riskWeight[index][0], rw, -1);
addScore(re, averageV, riskWeight[index][1], rw, -1);
if (riskWeight[index][2] != 0) {
for (String code : codes) {
maxRecu.add(new FundIndexInfo(code, maxRe(fundRiseInfos.get(code))));
}
addScore(re, maxRecu, riskWeight[index][2], rw, -1);
}
/**
* --------------------------------抗风险能力计算结束----------------------------
*/
/**
* --------------------------------计算业绩稳定性-------------------------------
*/
double sw = totalWeight[index][2];
List<FundIndexInfo> hurstHolder = new ArrayList<>(), profitWinRate = new ArrayList<>();
if (stableWeight[index][0] != 0) {
for (String code : codes) {
double h = hurstHolder(UNIT, fundRiseInfos.get(code));
hurstHolder.add(new FundIndexInfo(code, h));
}
addScore(re, hurstHolder, stableWeight[index][0], sw, 1);
}
if (stableWeight[index][1] != 0) {
Map<String, List<Double>> monthInfo = new HashMap<>();
int monthNum = 3 * 12;
for (String code : codes) {
List<Double> info = fundRiseInfos.get(code);
int unit = info.size() / monthNum;
List<Double> m = new ArrayList<>();
for (int i = 0; i < monthNum; i++) {
m.add(info.subList(i * unit, (i + 1) * unit).stream().mapToDouble(e -> e).sum
());
}
monthInfo.put(code, m);
}
double[] aveRise = new double[monthNum];
for (int i = 0; i < monthNum; i++) {
aveRise[i] = 0;
}
for (String code : codes) {
for (int i = 0; i < monthNum; i++) {
aveRise[i] += monthInfo.get(code).get(i) / monthNum;
}
}
for (String code : codes) {
int count = 0;
for (int i = 0; i < monthNum; i++) {
if (monthInfo.get(code).get(i) > aveRise[i])
count++;
}
profitWinRate.add(new FundIndexInfo(code, count));
}
addScore(re, profitWinRate, stableWeight[index][1], sw, 1);
}
List<FundIndexInfo> fundIndexInfos = new ArrayList<>();
for (String str : re.keySet()) {
fundIndexInfos.add(new FundIndexInfo(str, re.get(str)));
}
fundIndexInfos.sort(new FundComparator());
return fundIndexInfos;
}
private void addScore(Map<String, Double> scoreMap, List<FundIndexInfo> fundIndexInfos, double
w1, double w2, int order) {
fundIndexInfos.sort(new FundComparator(order));
int size = fundIndexInfos.size();
for (int i = 0; i < size; i++) {
FundIndexInfo fundIndexInfo = fundIndexInfos.get(i);
double v = scoreMap.get(fundIndexInfo.fundCode) == null ? 0 : scoreMap.get(fundIndexInfo
.fundCode);
scoreMap.put(fundIndexInfo.fundCode, v + (size - i) / ((double) size) * w1 * w2);
}
}
private double maxRe(List<Double> rises) {
double maxRe = 0, temRe = 1;
for (double d : rises) {
if (d > 0) {
temRe = 1 - temRe;
maxRe = Math.max(maxRe, temRe);
temRe = 1;
} else {
temRe *= (1 + d);
}
}
return maxRe;
}
private double hurstHolder(int unit, List<Double> infos) {
int size = infos.size();
// List<List<Double>> totalUnitInfos = new ArrayList<>();
// int sizeNum = size / unit;
// for (int i = 0; i < sizeNum; i++) {
// totalUnitInfos.add(infos.subList(unit * i, unit * (i + 1)));
// }
double ave = infos.stream().mapToDouble(e -> e).sum() / size;
double[] zt = new double[size];
for (int i = 0; i < size; i++) {
zt[i] = infos.get(i) - ave;
}
double max = 0, min = Double.MAX_VALUE, tem = 0;
for (double d : zt) {
tem += d;
max = Math.max(tem, max);
min = Math.min(tem, min);
}
double standar = 0;
for (int i = 0; i < size; i++) {
standar += zt[i] * zt[i];
}
standar = standar / (size - 1);
standar = Math.sqrt(standar);
double h = 1 / Math.log(size);
h *= Math.sqrt((max - min) / standar);
return h;
}
private int getIndexBySectorType(String sectorType) {
switch (sectorType) {
case SectorType.STOCK_TYPE:
return 0;
case SectorType.BOND_TYPE:
return 1;
case SectorType.MONEY_MARKET_TYPE:
return 2;
}
return -1;
}
void outPut(String filePath, String sectorType) {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
List<FundIndexInfo> fundIndexInfos = getFundRank(fundPool.get(sectorType), sectorType);
String format = "%-4d%-10s%-5.2f\n";
for (int i = 0; i < fundIndexInfos.size(); i++) {
bufferedWriter.write(String.format(format, i + 1, fundIndexInfos.get(i).fundCode,
fundIndexInfos.get(i).value * 100));
}
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
void outPut() {
getTotalFundPool();
outPut("D:/股票型.txt", SectorType.STOCK_TYPE);
outPut("D:/债券型.txt", SectorType.BOND_TYPE);
outPut("D:/货币市场型.txt", SectorType.MONEY_MARKET_TYPE);
}
public static void main(String[] args) throws Exception {
FundRank fundRank = new FundRank();
System.out.println(fundRank.getTotalFundPool().get(SectorType.STOCK_TYPE).size());
fundRank.getTotalFundPool().get(SectorType.STOCK_TYPE).forEach(System.out::println);
// CalculateDataHandler calculateDataHandler = new CalculateDataHandler("164509");
// double h=fundRank.hurstHolder(1,calculateDataHandler.getDatasByRise().get("164509"));
// System.out.println(h);
// fundRank.outPut();
}
}
|
Python | UTF-8 | 2,608 | 2.8125 | 3 | [] | no_license | from os.path import dirname
import util
import inspect
import reader
from util import Struct
import sys
#simple requirement for Bhumibol Dam
#unit here M-m^3 = million m^3
#water lvl is betwen 13462(capacity) and 4000 M-m^3(historical low)
#out flow capacity is 60M-m^3/day but in rainy season maximum is 30M-m^3/day so that central part won't be flooded
#min_flow =0.05M-m^3/day (made this up for power i guess)
#but in napee season( 6 7 8 9 10 11) one must flow water out at least 20 M-m^3/day (made this up too)
#and in naprang season(12 1 2) one must flow water out at least 10 M-m^3/day (made this up)
class BhumibolDam:
def __init__(self):
self.capacity = 13462. #m^3 everything here is m^3/day
self.min_capacity = 3500.
self.max_flow_day = 60. #no spill way
self.max_flow_rainy = 35. # maximum flow for rainy season because of rain fall in central area already
#self.max_flow_week = 30*7 #or it will flood
self.min_flow = 0.1 #for power
self.min_flow_napee = 20.
self.min_flow_naprang = 10.
self.rainy_month = set([6,7,8,9,10])
self.napee_month = set([6,7,8,9,10,11])
self.naprang_month = set([12,1,2])
#simple bound hint about the requirement
def max_flow_for_date(self,day,month):
if month in self.rainy_month: return self.max_flow_rainy
return self.max_flow_day
#simple bound hint about the requirement
def min_flow_for_date(self,day,month):
if month in self.napee_month: return self.min_flow_napee
if month in self.naprang_month: return self.min_flow_naprang
return self.min_flow
#check all requirement
#cl include water_in and water_out
def run_check(self,cl,dec):
self.check_capacity(cl,dec)
self.check_flow(cl,dec)
#currentlevel after applying the decision and today incoming water
def check_capacity(self,cl, dec):
assert cl < self.capacity,'exceed dam capacity'
assert cl > self.min_capacity,'reach min water level'
def check_flow(self,cl, dec):
date = dec.lastdate()
flow = dec.latest()
week_flow = dec.weeksum()
assert flow >= self.min_flow,'less than min flow'
if date.month in self.napee_month: assert flow >= self.min_flow_napee,'not enough water for napee'
if date.month in self.naprang_month: assert flow >= self.min_flow_naprang,'not enough water for naprang'
#check max flow
assert flow <= self.max_flow_day,'spill way open'
#assert(week_flow < self.max_flow_week,'too much flow in a week')
|
Java | UTF-8 | 994 | 2.15625 | 2 | [] | no_license | package com.exercise.gmsys.imp;
import com.exercise.gmsys.mapper.DepartmentMapper;
import com.exercise.gmsys.model.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DepartmentServiceImp {
@Autowired
DepartmentMapper departmentMapper;
public List<Department> findAll() {
return departmentMapper.findAll();
}
public Department findById(Integer did){
return departmentMapper.selectByPrimaryKey(did);
}
public void update(Department department){
departmentMapper.updateByPrimaryKey(department);
}
public void insert(Department department){
departmentMapper.insert(department);
}
public void delete(Integer did) {
departmentMapper.deleteByPrimaryKey(did);
}
public List<Department> findByKeyword(String keyword) {
return departmentMapper.findByKeyword(keyword);
}
}
|
Java | UTF-8 | 1,968 | 3.015625 | 3 | [] | no_license | package suite04;
import org.junit.Test;
import srdk.theDrake.*;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class ActionsTest {
private Set<Move> makeSet(Move ...moves) {
Set<Move> result = new HashSet<Move>();
for(Move m : moves) {
result.add(m);
}
return result;
}
@Test
public void test() {
Board board = new Board(4);
StandardDrakeSetup setup = new StandardDrakeSetup();
BoardTroops blueTroops = new BoardTroops(PlayingSide.BLUE);
blueTroops = blueTroops
.placeTroop(setup.DRAKE, board.pos("a1"))
.placeTroop(setup.CLUBMAN, board.pos("a2"))
.placeTroop(setup.SPEARMAN, board.pos("b2"));
Army blueArmy = new Army(blueTroops, Collections.emptyList(), Collections.emptyList());
BoardTroops orangeTroops = new BoardTroops(PlayingSide.ORANGE);
orangeTroops = orangeTroops
.placeTroop(setup.DRAKE, board.pos("c4"))
.placeTroop(setup.MONK, board.pos("c3"))
.placeTroop(setup.CLUBMAN, board.pos("b3"));
Army orangeArmy = new Army(orangeTroops, Collections.emptyList(), Collections.emptyList());
GameState state = new GameState(board, blueArmy, orangeArmy);
assertEquals(
makeSet(
new StepOnly(board.pos("a1"), board.pos("b1")),
new StepOnly(board.pos("a1"), board.pos("c1")),
new StepOnly(board.pos("a1"), board.pos("d1"))
),
new HashSet<Move>(
state.tileAt(board.pos("a1")).movesFrom(board.pos("a1"), state)
)
);
assertEquals(
makeSet(
new StepOnly(board.pos("a2"), board.pos("a3"))
),
new HashSet<Move>(
state.tileAt(board.pos("a2")).movesFrom(board.pos("a2"), state)
)
);
assertEquals(
makeSet(
new StepAndCapture(board.pos("b2"), board.pos("b3")),
new CaptureOnly(board.pos("b2"), board.pos("c4"))
),
new HashSet<Move>(
state.tileAt(board.pos("b2")).movesFrom(board.pos("b2"), state)
)
);
}
}
|
Python | UTF-8 | 154 | 3 | 3 | [] | no_license | n = int(input())
a = map(int, input().split())
a = sorted(a)
a.reverse()
ans = 0
for i, v in enumerate(a):
if i % 2 == 0:
ans += v
print(ans)
|
JavaScript | UTF-8 | 2,268 | 4.09375 | 4 | [
"MIT"
] | permissive | // This is a solo challenge
// Your mission description:
// Move Theozy in an 'S' formation
// Execute an attack
// Move back to Theozy's original position
// Pseudocode
// Move object right
// Move object up
// Move object left
// Move object up
// Move object right
// Execute the attack method
// Move object left
// Move object down
// Move object right
// Move object down
// Move object left
// Initial Code
var = theozy {
moveRight: right(X,Y)
"Move 5 spaces to the right";
moveUp: up(X,Y)
"Move 5 spaces up";
moveLeft: left(X,Y)
"Move 5 spaces to the left";
moveDown: down(X,Y)
"Move 5 spaces down";
attack: fight(X,Y)
"Attack";
// I don't know how to write the code for the functions to actually perform a move
// or attack action so I've put a string in the function as a placeholder for it.
this.moveRight();
this.moveUp();
this.moveLeft();
this.moveUp();
this.moveRight();
this.attack();
this.moveLeft();
this.moveDown();
this.moveRight();
this.moveDown();
this.moveLeft();
}
// Refactored Code
// The 5 methods are defined withing the Object theozy. Below that the methods are
// called within the object theozy using the 'this' statemtent to perform the desired
// actions to complete the mission objectives.
// Reflection
// 1.What worked for me was referencing the code combat mission and understanding the format they used.
// I know we were given a lot of creative freedom for this exercise but I struggled a little bit with
// the lack of direction.
// 2.The questions I had were mainly about the syntax on how to define a method for an object. I found
// information on the w3schools site that told me a method is defined as a function property of an object.
// 3.I was not sure how to actually write code to make the object move. I used a string as a placeholder
// where that code would have gone.
// 4.Learned at a high level how games and programming are used together.
// 5.I am very confident in defining local variables in JavaScript, very confident in creating, adding, and deleting
// properties from javascript objects.
// 6.I enjoyed makng up actions that this game would perform and defining the methods inside the object.
// 7.I found it tedious to figure out what excactly the challenge wanted to see from us. |
C# | UTF-8 | 509 | 2.515625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaterCreator : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] GameObject water;
void Start()
{
for(int i = 0; i <= 50; i++)
{
for (int j = 0; j <= 50; j++)
{
Instantiate(water, transform.position + new Vector3(i*10f, 0f, j*10f), Quaternion.identity, this.transform.parent);
}
}
}
}
|
Java | UTF-8 | 5,708 | 1.960938 | 2 | [] | no_license | package com.example.myprivacy;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
//import com.squareup.picasso.Picasso;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class Imageview extends Activity {
ImageView img;
public static String file="",url="",ff="",dwn="";
public static String f[];
ProgressDialog mProgressDialog;
private PowerManager.WakeLock mWakeLock;
SharedPreferences sh;
String postid;
static final int DIALOG_DOWNLOAD_PROGRESS = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageview);
img=(ImageView)findViewById(R.id.imageView1);
url=getIntent().getStringExtra("filename");
ff=getIntent().getStringExtra("file");
Toast.makeText(getApplicationContext(), url,Toast.LENGTH_LONG ).show();
sh=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// postid=getIntent().getStringExtra("postid");
//urll="http://192.168.43.79:5000/static/faces/"+file;
// Toast.makeText(getApplicationContext(), "url"+urll, Toast.LENGTH_LONG).show();
// Picasso.with(getApplicationContext())
// .load(urll)
// //.transform(new Circulartransform())
// .error(R.drawable.ic_launcher)
// .into(img);
//
java.net.URL thumb_u;
try {
//"http://"+sh.getString("ip", "")+":5000/static/faces/"+url+""
thumb_u = new java.net.URL(url);
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
img.setImageDrawable(thumb_d);
}
catch(Exception e){
}
img.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder ald=new AlertDialog.Builder(Imageview.this);
ald.setTitle("Do you want to download??")
.setPositiveButton(" YES ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
startDownload();
}
})
.setNegativeButton(" NO ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog al=ald.create();
al.show();
return true;
}
});
}
private void startDownload() {
Log.d("url------------------------", url);
new DownloadFileAsync().execute(url);
Log.d("compete------------",url);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading File...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
}
return null;
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
PowerManager pm = (PowerManager) getSystemService(Imageview.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,getClass().getName());
mWakeLock.acquire();
Log.d("333333333333333",url);
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
Log.d("urllllllllllllllllllllllllllllll",aurl[0]);
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Length of file: " + lenghtOfFile);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Downloadssss");
if (!imagesFolder.exists())
imagesFolder.mkdirs();
InputStream input = new BufferedInputStream(url.openStream());
Log.d("fileeeeeeeeee",ff);
OutputStream output = new FileOutputStream(imagesFolder + "/" + ff);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.imageview, menu);
return true;
}
}
|
Java | UTF-8 | 7,792 | 1.664063 | 2 | [] | no_license | package com.example.a69477.myapplication;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import static com.example.a69477.myapplication.R.id.nav_Admission;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ViewPager mPcitureviewpager;
private int[] mImage = new int[10];
// private CircleIndicator = mCircleindicator;
private void initView() {
mPcitureviewpager = (ViewPager) findViewById(R.id.picture);
mImage[0] = R.drawable.hku1;
mImage[1] = R.drawable.slide1;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---------------------------------------------------------------------
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);//标题
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//---------------------------------------------------------------------
ImageView img1 =(ImageView) findViewById(R.id.schedule);
Glide.with(this).load("https://www.msc-cs.hku.hk/Media/Default/ContentImages/ProgrammeSchedule.jpg").into(img1);
ImageView img2 =(ImageView) findViewById(R.id.fee);
Glide.with(this).load("https://www.msc-cs.hku.hk/Media/Default/ContentImages/ProgrammeFees.jpg").into(img2);
ImageView img3 =(ImageView) findViewById(R.id.ddl);
Glide.with(this).load("https://www.msc-cs.hku.hk/Media/Default/ContentImages/ApplicationDeadlines.jpg").into(img3);
ImageView img4 =(ImageView) findViewById(R.id.Overview);
Glide.with(this).load(R.drawable.cover).into(img4);
//---------------------------------------------------------------------
CardView my_program_sch = (CardView) findViewById(R.id.psCard);
my_program_sch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent1 = new Intent(MainActivity.this,ProSchedule.class);
startActivity(intent1);
}
});
CardView my_composition_fee = (CardView) findViewById(R.id.cfCard);
my_composition_fee.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(MainActivity.this,CompositionFees.class);
startActivity(intent2);
}
});
CardView my_application_ddl = (CardView) findViewById(R.id.ddlCard);
my_application_ddl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent3 = new Intent(MainActivity.this,application.class);
startActivity(intent3);
}
});
CardView my_pro_overview = (CardView) findViewById(R.id.poCard);
my_pro_overview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent4 = new Intent(MainActivity.this,Curriculum.class);
startActivity(intent4);
}
});
//---------------------------------------------------------------------
NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
}
navView.setCheckedItem(nav_Admission);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_Admission) {
Intent intent = new Intent(MainActivity.this, application.class);
startActivityForResult(intent, 11);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
} else if (id == R.id.nav_Curriculum) {
Intent intent = new Intent(MainActivity.this, Curriculum.class);
startActivityForResult(intent, 11);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
} else if (id == R.id.nav_Graduate) {
Intent intent = new Intent(MainActivity.this, Alumni.class);
startActivityForResult(intent, 11);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
} /*else if (id == R.id.nav_News) {
}*/ else if (id == R.id.nav_About) {
Intent intent = new Intent(MainActivity.this, About.class);
startActivityForResult(intent, 11);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
} else if (id == R.id.nav_Resource) {
Intent intent = new Intent(MainActivity.this, UsefulLinks.class);
startActivityForResult(intent, 11);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
}
mDrawerLayout.closeDrawers();
return true;
}
});
//---------------------------------------------------------------------
initView();
AdvertiseViewpagerAdapter advertiseViewpagerAdapter = new AdvertiseViewpagerAdapter(mImage);
mPcitureviewpager.setAdapter(advertiseViewpagerAdapter);
} //---------------------------------------------------------------------
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar, menu);
return true;
}//右上菜单
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
break;
case R.id.backup:
//Toast.makeText(this, "You clicked Phone Call", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:85239171828"));
startActivity(intent);
break;
case R.id.mail_us:
//Toast.makeText(this, "You clicked Mail us", Toast.LENGTH_SHORT).show();
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("text/plain");
startActivity(emailIntent);
break;
//case R.id.settings:
//Toast.makeText(this, "You clicked Settings", Toast.LENGTH_SHORT).show();
//break;
default:
}
return true;
}//右上菜单触发效果
}
|
C# | UTF-8 | 4,911 | 3.25 | 3 | [] | no_license | namespace OutLookAR
{
public struct ArrayMat
{
double[,] _data;
public double[,] ToArray { get { return _data; } }
public int Rows { get { return _data.GetLength(0); } }
public int Cols { get { return _data.GetLength(1); } }
public double At(int row, int col) { return _data[row, col]; }
public void At(int row, int col, double pt) { _data[row, col] = pt; }
public ArrayMat(int rows, int cols)
{
_data = new double[rows, cols];
}
public ArrayMat(int rows, int cols, double[] data)
{
if (data.Length != rows * cols)
throw new OutLookARException("dataサイズが異なります");
_data = new double[rows, cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
_data[r, c] = data[r * cols + c];
}
}
}
public ArrayMat(double[,] data)
{
_data = data;
}
public static ArrayMat operator *(ArrayMat z, ArrayMat w)
{
if (z.Cols != w.Rows)
{
throw new OutLookARException("Mat type must bu equal to the number of w.rows and z.cols.");
}
ArrayMat v = new ArrayMat(z.Rows, w.Cols);
for (int r = 0; r < v.Rows; r++)
{
for (int c = 0; c < v.Cols; c++)
{
double at = 0;
for (int b = 0; b < w.Rows; b++)
{
at += z.At(r, b) * w.At(b, c);
}
v.At(r, c, at);
}
}
return v;
}
public static ArrayMat operator +(ArrayMat z, ArrayMat w)
{
if (z.Cols != w.Rows)
{
throw new OutLookARException("Mat type must bu equal to the number of w.rows and z.cols.");
}
ArrayMat v = new ArrayMat(z.Rows, w.Cols);
for (int r = 0; r < v.Rows; r++)
{
for (int c = 0; c < v.Cols; c++)
{
v.At(r, c, z.At(r, c) + w.At(r, c));
}
}
return v;
}
public static ArrayMat zeros(int rows, int cols)
{
double[,] data = new double[rows, cols];
return new ArrayMat(data);
}
public static ArrayMat eye(int rows, int cols)
{
double[,] data = new double[rows, cols];
int min = (rows < cols) ? rows : cols;
for (int i = 0; i < min; i++)
data[i, i] = 1;
return new ArrayMat(data);
}
public override string ToString()
{
string text = "{\n";
for (int r = 0; r < Rows; r++)
{
text += "[";
for (int c = 0; c < Cols; c++)
{
text += _data[r, c] + ",";
}
text += "],\n";
}
text += "}";
return string.Format(
"Rows : {0} Cols : {1}\n" +
"Data : {2}",
Rows, Cols, text);
}
public ArrayMat inv()
{
int i, j;
int n = Rows;
if (n != Cols)
throw new OutLookARException("正方行列ではありません.");
double[,] _invData = new double[Rows, Cols];
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
_invData[i, j] = (i == j) ? 1.0 : 0.0;
}
}
double buf;
double[,] a = _data;
for (i = 0; i < n; i++)
{
buf = 1 / a[i, i];
for (j = 0; j < n; j++)
{
a[i, j] *= buf;
_invData[i, j] *= buf;
}
for (j = 0; j < n; j++)
{
if (i != j)
{
buf = a[j, i];
for (int k = 0; k < n; k++)
{
a[j, k] -= a[i, k] * buf;
_invData[j, k] -= _invData[i, k] * buf;
}
}
}
}
return new ArrayMat(_invData);
}
public ArrayMat t()
{
ArrayMat tMat = new ArrayMat(Cols, Rows);
for (int r = 0; r < Rows; r++)
{
for (int c = 0; c < Cols; c++)
{
if(r!=c)
tMat.At(c,r,At(r,c));
}
}
return tMat;
}
}
} |
Rust | UTF-8 | 1,021 | 3.09375 | 3 | [
"MIT"
] | permissive | //use utils;
//mod utils;
pub mod entities {
use utils::*;
use extra::time::Timespec;
#[deriving(Eq, ToStr)]
enum EntityType {
Hero,
Enemy
}
impl EntityType {
fn to_str(&self) -> ~str {
match *self {
Hero => ~"Hero",
Enemy => ~"Enemy",
}
}
}
#[deriving(Eq, ToStr)]
pub struct Entity {
name: ~str,
position: @mut utils::Point,
kind: EntityType
}
impl Entity {
pub fn new_player() -> Entity {
Entity {
name: ~"Entity",
position: @mut utils::Point {x: 0f, y: 0f},
kind: Hero
}
}
}
pub trait Updatable {
fn update(&self, dt: Timespec);
}
pub trait Drawable {
fn draw(&self, dt: Timespec);
}
impl Updatable for Entity {
fn update(&self, dt: Timespec) {
match self.kind {
_ => println(fmt!("Updating \t[%s:%s]", self.name, self.kind.to_str()))
}
}
}
impl Drawable for Entity {
fn draw(&self, dt: Timespec) {
match self.kind {
_ => println(fmt!("Drawing: \t[%s:%s]", self.name, self.kind.to_str()))
}
}
}
} |
Java | UTF-8 | 2,520 | 2.84375 | 3 | [] | no_license | package main.component.chart.data;
import java.util.Collections;
import java.util.List;
import main.component.chart.data.calculator.ICalculator;
public class MetaData<N extends Number> implements IMetaDataSet{
private String name = "";
public List<N> data = Collections.emptyList();
public ICalculator<N> calculator;
private int beforeDataSize = 0;
private double globalMin = Double.POSITIVE_INFINITY;
private double globalMax = Double.NEGATIVE_INFINITY;
public void setCalculator(ICalculator<N> calculator){ this.calculator = calculator; }
public void setData(List<N> data){
this.data = data;
reset();
}
public MetaData(){}
public MetaData(String name, List<N> data, ICalculator<N> calculator){
this();
this.name = name;
setData(data);
setCalculator(calculator);
}
public void reset(){
beforeDataSize = 0;
globalMin = Double.POSITIVE_INFINITY;
globalMax = Double.NEGATIVE_INFINITY;
}
double []valueSet = new double[1];
@Override
public double[] get(int index){
valueSet[0] = calculator.doubleValue(data.get(index));
return valueSet;
}
@Override
public void onUpdateData(){
calculateGlobalMin();
calculateGlobalMax();
beforeDataSize = data.size();
}
@Override
public double getMinBetween(int leftIndex, int rightIndex){
double min = Double.POSITIVE_INFINITY;
for(int i = leftIndex; i <= rightIndex; i++){
double value = calculator.doubleValue(data.get(i));
if(min > value) min = value;
}
return min;
}
@Override
public double getMaxBetween(int leftIndex, int rightIndex){
double max = Double.NEGATIVE_INFINITY;
for(int i = leftIndex; i <= rightIndex; i++){
double value = calculator.doubleValue(data.get(i));
if(max < value) max = value;
}
return max;
}
private void calculateGlobalMin(){
for(int i = beforeDataSize; i < data.size(); i++){
double value = calculator.doubleValue(data.get(i));
if(globalMin > value) globalMin = value;
}
}
private void calculateGlobalMax(){
for(int i = beforeDataSize; i < data.size(); i++){
double value = calculator.doubleValue(data.get(i));
if(globalMax < value) globalMax = value;
}
}
@Override public int size() { return data.size(); }
@Override public double getGlobalMin() { return globalMin; }
@Override public double getGlobalMax() { return globalMax; }
@Override public int getSetSize() { return 1; }
@Override public void setName(int i, String name) { this.name = name; }
@Override public String getName(int index) { return name; }
} |
C++ | UTF-8 | 1,045 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <utility>
using namespace std;
#if defined(o1)
class Solution {
public:
void swap(int& a, int& b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
void nextPermutation(vector<int>& nums) {
int size = nums.size();
pair<int, int> record;
int pre_pos = -1;
for(int i = size - 1; i > 0; i--)
{
for(int j = i - 1; j >=0;j++)
{
if(nums[i] > nums[j])
{
if(j > pre_pos)
{
record = {j, i};
pre_pos = j;
}
break;
}
}
}
if(pre_pos == -1)
sort(nums.begin(), nums.end());
else
{
swap(nums[record.first], nums[record.second]);
sort(nums.begin() + record.first + 1, nums.end());
}
}
};
#elif defined(o2)
#endif |
Java | UTF-8 | 2,447 | 2.625 | 3 | [] | no_license | package cn.huhuiyu.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import cn.huhuiyu.entity.TbGoods;
public class TbGoodsDAO extends BaseDAO {
public static final String INSERT = "insert into TbGoods(gname,ginfo,price,amount) values(?,?,?,?) ";
public int add(TbGoods goods) throws Exception {
PreparedStatement ps = connection.prepareStatement(INSERT);
ps.setString(1, goods.getGname());
ps.setString(2, goods.getGinfo());
ps.setBigDecimal(3, goods.getPrice());
ps.setInt(4, goods.getAmount());
int result = ps.executeUpdate();
ps.close();
return result;
}
public int delete(TbGoods goods) throws Exception {
PreparedStatement ps = connection.prepareStatement
("delete from TbGoods where gid=?");
ps.setInt(1, goods.getGid());
int result = ps.executeUpdate();
ps.close();
return result;
}
public int modify(TbGoods goods) throws Exception {
PreparedStatement ps = connection
.prepareStatement(
"update TbGoods set gname=?,ginfo=?,price=?,amount=? where gid=?");
ps.setString(1, goods.getGname());
ps.setString(2, goods.getGinfo());
ps.setBigDecimal(3, goods.getPrice());
ps.setInt(4, goods.getAmount());
ps.setInt(5, goods.getGid());
int result = ps.executeUpdate();
ps.close();
return result;
}
public TbGoods queryByKey(TbGoods goods) throws Exception {
PreparedStatement ps = connection.prepareStatement(
"select * from TbGoods where gid=?");
TbGoods result = null;
ps.setInt(1, goods.getGid());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
result = new TbGoods();
result.setGid(rs.getInt("gid"));
result.setGname(rs.getString("gname"));
result.setGinfo(rs.getString("ginfo"));
result.setPrice(rs.getBigDecimal("price"));
result.setAmount(rs.getInt("amount"));
}
rs.close();
ps.close();
return result;
}
public List<TbGoods> query() throws Exception {
List<TbGoods> list = new ArrayList<TbGoods>();
PreparedStatement ps = connection.prepareStatement("select * from TbGoods");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
TbGoods goods = new TbGoods();
goods.setGid(rs.getInt("gid"));
goods.setGname(rs.getString("gname"));
goods.setGinfo(rs.getString("ginfo"));
goods.setPrice(rs.getBigDecimal("price"));
goods.setAmount(rs.getInt("amount"));
list.add(goods);
}
rs.close();
ps.close();
return list;
}
}
|
Python | UTF-8 | 611 | 3.390625 | 3 | [] | no_license | from dados.observer import Observer
class Tabela(Observer):
"""
Classe responsavel por observar os dados e imprimi-los em forma de tabela.
"""
def __init__(self, dados):
"""
Inicializa os dados.
"""
super().__init__(dados)
def atualiza(self):
"""
Mostra os dados em forma de tabela
"""
print("Tabela:")
print("Valor A: " + str(self.dados.pega_estado().valorA))
print("Valor B: " + str(self.dados.pega_estado().valorB))
print("Valor C: " + str(self.dados.pega_estado().valorC))
print("\n")
|
C# | UTF-8 | 1,608 | 3.09375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class Publisher
{
public string _pubid;
public string _pub;
public string _state;
public string _country;
public string _city;
public Publisher(string pubid, string pub,string state, string country ,string city)
{//constructor
_pubid = pubid;
if (city ==null)
{
_city = "Unknown";
}
else
{
_city = city;
}
if (pub == null)
{
_pub = "Anonymous";
}
else
{
_pub = pub;
}
if (state == null)
{
_state = "Unknown";
}
else
{
_state = state;
}
if (country==null)
{
_country = "UnKnown";
}
else
{
_country = country;
}
}
public string pubid
{
get { return _pubid;}
}
public string pub
{
get { return _pub; }
set { _pub = value; }
}
public string state
{
get { return _state; }
set { _state = value; }
}
public string country
{
get { return _country; }
set { _country = value; }
}
}
} |
Java | UTF-8 | 1,498 | 2.203125 | 2 | [] | no_license | package mx.ipn.americamartinezandevelinecruz.login;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText correo, contrasenia;
Button login;
TextView ingreso;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
correo= (EditText) findViewById(R.id.email);
contrasenia=(EditText)findViewById(R.id.password);
login=(Button)findViewById(R.id.login);
ingreso= (TextView)findViewById(R.id.mensaje);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String email=correo.getText().toString();
final String password= contrasenia.getText().toString();
if (email.equals("merimtz1@hotmail.com") && password.equals("12345")){
Intent intent = new Intent(MainActivity.this, MenuPrincipalActivity.class);
finish();
startActivity(intent);
}
else{
ingreso.setText("Usuario o contraseña incorrectos");
}
}
});
}
}
|
Java | UTF-8 | 925 | 2.640625 | 3 | [] | no_license | package bank;
import data.ManagerBank;
import data.ManagerUsers;
import utils.Utils;
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* Created by user on 19/01/16.
*/
public class GetBankInformation {
ManagerBank mb;
ManagerUsers mu;
public GetBankInformation() {
this.mb = new ManagerBank();
this.mu = new ManagerUsers();
}
public static void main(String[] args) {
GetBankInformation gbi = new GetBankInformation();
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ( ) ;
df.setMaximumFractionDigits (2); //arrondi à 2 chiffres apres la virgules
df.setMinimumFractionDigits (2);
df.setDecimalSeparatorAlwaysShown (true);
System.out.println("Current bank balance : " + df.format(gbi.mb.getMontantForBankAccount(gbi.mu.getAccountNumberByName(sc.nextLine(), Utils.pathToUser))));
}
}
|
Java | UTF-8 | 2,795 | 4.15625 | 4 | [] | no_license | /*
*Assignment 1, Movie Ratings
*
*For this assignment, write a program that will aggregate a set of movie ratings for a new film, entitled AP CSA: The Movie! Your program will compute an overall movie rating as a weighted average of ratings from a popular movie review website, ratings given by a private focus group, and movie critic ratings.
*
*For input, the program should accept 3 ratings from a movie review website (as ints), 2 ratings from a focus group (as doubles), and 1 average rating from professional movie critics (as a double).
*
*The program should then output the average website rating, the average focus group rating, the average movie critic rating, and the overall movie rating (as doubles).
*
*The overall movie rating should be computed as a weighted average. Count the average website rating as 20% of the overall rating, the average focus group rating as 30% of the overall rating, and the average movie critic rating as 50% of the overall rating.
*
*If you notice that your overall rating is off by a very small amount, this may be due to roundoff error, which we will discuss in an upcoming lesson. Visit the student forum on Piazza for some tips on avoiding roundoff error on this assignment.
*
*Sample Run:
Please enter ratings from the movie review website.
75
99
10
Please enter ratings from the focus group.
84.5
92.3
Please enter the average movie critic rating.
87.42
Average website rating: 61.333333333333336
Average focus group rating: 88.4
Average movie critic rating: 87.42
Overall movie rating: 82.49666666666667
*/
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter ratings from the movie review website.");
int website1 = scan.nextInt();
int website2 = scan.nextInt();
int website3 = scan.nextInt();
System.out.println("Please enter ratings from the focus group.");
double focus1 = scan.nextDouble();
double focus2 = scan.nextDouble();
System.out.println("Please enter the average movie critic rating.");
double critic = scan.nextDouble();
double averageWebsite = (website1 + website2 + website3) / 3.0;
double averageFocus = (focus1 + focus2) / 2.0;
System.out.println("Average website rating: " + averageWebsite);
System.out.println("Average focus group rating: " + averageFocus);
System.out.println("Average movie critic rating: " + critic); //There's only one critic, so no need to take the average
double overall = 0.2 * averageWebsite + 0.3 * averageFocus + 0.5 * critic;
System.out.println("Overall movie rating: " + overall);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.