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
| 978
| 2.34375
| 2
|
[] |
no_license
|
package com.ryklief;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
public class shapesTest {
shapes shape = new shapes();
@Test (timeout = 1000)
@Before
public void setUp() throws Exception {
shape.calcArea(23);
shape.calcArea(3.0);
shape.calcArea(23,4);
}
@Test
public void calcArea() {
}
@Test
public void testCalcArea() {
assertEquals(92,92);
assertNotEquals(959,512);
Assert.fail("incorrect");
}
@Test
public void testCalcArea1() {
assertEquals(529, 529);
assertNotEquals(59,52);
//Assert.fail("incorrect");
}
@Test
public void testCalcArea2() {
assertEquals(28.274333882308138,28.274333882308132,28.274333882308138);
}
@Ignore
@Test
public void testToString() {
}
@Test
public void main() {
}
}
|
PHP
|
UTF-8
| 1,773
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: yuhanghe
* Date: 2019/5/12
* Time: 下午8:39
*/
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH.'models/OrderModel.php';
require APPPATH.'models/ProductionModel.php';
class OrderService
{
public function insertOrder($token, $content, $address){
$model = new OrderModel();
return $model->insertOrder($token, $content, $address);
}
public function orderCount($token){
$model = new OrderModel();
$unPayCount = $model->countByState($token, 1);
$unSendCount = $model->countByState($token, 2);
$receiveCount = $model->countByState($token, 3);
$commentCount = $model->countByState($token, 4);
$serviceCount = $model->countByState($token, 5);
$countInfo = array();
$countInfo['unPayCount'] = $unPayCount;
$countInfo['unSendCount'] = $unSendCount;
$countInfo['receiveCount'] = $receiveCount;
$countInfo['commentCount'] = $commentCount;
$countInfo['serviceCount'] = $serviceCount;
return $countInfo;
}
public function orderList($token, $state){
$model = new OrderModel();
$proModel = new ProductionModel();
$orderList = $model->getOrderList($token, $state);
$list = array();
foreach ($orderList as $entity){
$proIds = explode(',', $entity->content);
$proList = array();
foreach($proIds as $proId){
$production = $proModel->get($proId);
array_push($proList, $production);
}
$entity->proList = $proList;
array_push($list, $entity);
}
return $list;
}
public function __construct()
{
}
}
|
JavaScript
|
UTF-8
| 2,397
| 3.078125
| 3
|
[] |
no_license
|
// HACK: Monkey patch the language so WET widgets work properly.
// WET determines the current language based on the value of
// document.documentElement.lang. It then uses that language to set the text
// in some of its widgets (e.g. the social media Share button and popup)
// since the WET scripts need to run before any VueJS stuff, we need to patch
// the language with a plain JS script called from index.html.
// NB: This needs to work in old browsers, so don't use any modern JS features
// (stick to ES3, if possible)
(function () {
var DEFAULT_LANGUAGE = "en";
var SUPPORTED_LANGUAGES = ["en", "fr"];
var LANG_KEY = "lang";
setCurrentLanguage(SUPPORTED_LANGUAGES, DEFAULT_LANGUAGE, LANG_KEY);
function setCurrentLanguage(supportedLanguages, fallback, langKey) {
var userRequestedLanguage =
getLanguageFromQueryString(langKey) ||
getLanguageFromPath(supportedLanguages) ||
getLanguageFromLocalStorage(langKey);
var currentLanguage = ensureSupportedLanguage(
userRequestedLanguage,
supportedLanguages,
fallback
).toLowerCase();
saveLanguage(currentLanguage, langKey);
}
function getLanguageFromQueryString(langKey) {
var params = {};
window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function (_, key, value) {
params[key] = value;
return params[key];
}
);
return params[langKey];
}
function getLanguageFromPath(supportedLanguages) {
var pathParam = window.location.href.split("/")[3];
if (isSupportedLanguage(pathParam, supportedLanguages)) {
return pathParam;
}
return null;
}
function getLanguageFromLocalStorage(langKey) {
return window.localStorage.getItem(langKey);
}
function ensureSupportedLanguage(language, supportedLanguages, fallback) {
if (isSupportedLanguage(language, supportedLanguages)) {
return language;
}
return fallback;
}
function isSupportedLanguage(language, supportedLanguages) {
return language == null
? false
: supportedLanguages.some(function (supportedLanguage) {
return supportedLanguage.toLowerCase() === language.toLowerCase();
});
}
function saveLanguage(language, langKey) {
document.documentElement.lang = language;
if (window.localStorage) {
window.localStorage.setItem(langKey, language);
}
}
})();
|
C#
|
UTF-8
| 1,209
| 3.453125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Flower_Shop
{
class Program
{
static void Main(string[] args)
{
int countOfMagnolia = int.Parse(Console.ReadLine());
int countOfzyumbul = int.Parse(Console.ReadLine());
int countOfRosees = int.Parse(Console.ReadLine());
int countOfCactus = int.Parse(Console.ReadLine());
double priceOfToy = double.Parse(Console.ReadLine());
double income = (countOfMagnolia * 3.25) + (countOfzyumbul * 4)
+ (countOfRosees * 3.50) + (countOfCactus * 8);
double incomeAfterTaxes = income * 0.95;
if (incomeAfterTaxes >= priceOfToy)
{
double moneyLeft = Math.Floor(incomeAfterTaxes - priceOfToy);
Console.WriteLine($"She is left with {moneyLeft} leva.");
}
else
{
double moneyNotEnough = Math.Ceiling(priceOfToy - incomeAfterTaxes);
Console.WriteLine($"She will have to borrow {moneyNotEnough} leva.");
}
}
}
}
|
Python
|
UTF-8
| 1,304
| 2.640625
| 3
|
[] |
no_license
|
import os
from os import listdir
from os.path import isfile, join
data = "NP.txt"
### print possible datasets ###
if os.path.exists('./dbase'):
cwd = os.getcwd()
datasets = [f for f in listdir('./dbase/raw') if isfile(join('./dbase/raw/', f))]
print('\n'+'#'*50+'\n\n'"Possible datasets are:\n")
for f in datasets:
print('"'+cwd+'/dbase/raw/'+f+'"')
print('\n'+'#'*50+'\n')
### choose parameters, run autoencoder ###
data = input("Please enter the path to the desired dataset. Possibilities are listed above\n")
encoded_data = "/home/pgian1/practice/csc534/project/dbase/encoded/" + data[46:-4] + "_encoded.txt"
encoded = []
with open(data) as dataReader:
for line in dataReader:
encoded_tran = ""
for base in line:
if base == 'A' or base == 'a':
encoded_tran = encoded_tran + '0 '
if base == 'T' or base == 't':
encoded_tran = encoded_tran + '1 '
if base == 'C' or base == 'c':
encoded_tran = encoded_tran + '2 '
if base == 'G' or base == 'g':
encoded_tran = encoded_tran + '3 '
encoded.append(encoded_tran)
with open(encoded_data, 'w') as encodedReader:
for transcript in encoded:
encodedReader.write(transcript+'\n')
|
Markdown
|
UTF-8
| 968
| 2.765625
| 3
|
[] |
no_license
|
Here is another skeletal document.
There really isn't much more to say, other than that this is the basic skeleton of a new document.
I am going to add some text to this markdown editor. We will see what happens.
I need more practice with git diff. I am also still completely in the dark about files that are in the pdf format. I did not understand the info I was provided on that subject.
So now I have created a Github repository. There is no difference between the origin master and the remote master.
Whew!
Now I want to add some more text to the master branch
Now I want to practice branching and merging some more. Not all that sure I can do a lot more today, but mostly I just want to take a look at the basic commands some more.
So this is what I am going to do: add some text, make some slight alterations, and merge them back into master. I will also create a merge conflict on master, then fix it.
Now it's time to create a conflict. Here we go!
|
Java
|
UTF-8
| 3,971
| 3.75
| 4
|
[] |
no_license
|
public class RobotManager {
//Метод автоматического перемещения робота в заданную позицию
public static void moveRobot(Robot robot, int toX, int toY) {
int nowX = robot.getX();
int nowY = robot.getY();
boolean needXplus = (nowX < toX);
boolean needXminus = (nowX > toX);
boolean needYplus = (nowY < toY);
boolean needYminus = (nowY > toY);
//Сначала ведется движение вдоль оси Х
//Поворот в нужную сторону вдоль оси Х
if (needXplus || needXminus) {
turnX(robot, needXplus, needXminus);
}
//Движение вдоль оси Х
while (robot.getX() != toX ) {
robot.stepForward();
}
//Поворот в нужную сторону вдоль оси Y
if (needYplus || needYminus) {
turnY(robot, needYplus, needYminus);
}
//Движение вдоль оси Y
while (robot.getY() != toY ) {
robot.stepForward();
}
}
//Метод поворачивает робота вдоль оси X в нужном направлении
public static void turnX(Robot robot, boolean needXplus, boolean needXminus) {
//Если нужно двигаться вправо
if (needXplus) {
if (robot.getDirection() == Direction.UP) {
robot.turnRight();
}
if (robot.getDirection() == Direction.DOWN) {
robot.turnLeft();
}
if(robot.getDirection() == Direction.LEFT) {
robot.turnRight();
robot.turnRight();
}
}
//Если нужно двигаться влево
if (needXminus) {
if (robot.getDirection() == Direction.UP) {
robot.turnLeft();
}
if (robot.getDirection() == Direction.DOWN) {
robot.turnRight();
}
if (robot.getDirection() == Direction.RIGHT) {
robot.turnLeft();
robot.turnLeft();
}
}
}
//Метод поворачивает робота вдоль оси Y в нужном направлении
public static void turnY(Robot robot, boolean needYplus, boolean needYminus) {
//Если нужно двигаться вверх
if (needYplus) {
if (robot.getDirection() == Direction.LEFT) {
robot.turnRight();
}
if (robot.getDirection() == Direction.RIGHT ) {
robot.turnLeft();
}
if (robot.getDirection() == Direction.DOWN) {
robot.turnRight();
robot.turnRight();
}
}
//Если нужно двигаться вниз
if (needYminus) {
if (robot.getDirection() == Direction.LEFT) {
robot.turnLeft();
}
if (robot.getDirection() == Direction.RIGHT) {
robot.turnRight();
}
if (robot.getDirection() == Direction.UP) {
robot.turnRight();
robot.turnRight();
}
}
}
//Метод печати статуса робота
public static void printStatus(Robot robot) {
System.out.println("Координата х: "+robot.getX()+ ", координата y: " + robot.getY()+ "; взгляд: " + robot.getDirection());
}
public static void main(String[] args) {
//Начальное состояние робота
Direction dir = Direction.DOWN;
int startX = 0;
int startY = 0;
Robot robot = new Robot(startX, startY, dir);
printStatus(robot);
moveRobot(robot,-5,2);
printStatus(robot);
}
}
|
Python
|
UTF-8
| 743
| 3
| 3
|
[] |
no_license
|
#!/usr/bin/python
# coding=utf-8
import numpy as np
import cv2
# 创建一块黑板
img = np.zeros((512, 512, 3), np.uint8)
# Draw Line
img = cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
# Drawing Rectangle
img = cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 1)
# Drawing Circle
img = cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)
# Drawing Ellipse
img = cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, 255, -1)
# Drawing Text
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'wangning', (10, 500), font, 4, (255, 255, 255), 2, cv2.LINE_AA)
# 展示图片 (窗口名称,图片引用)
cv2.imshow('Hello', img)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows() # Create a black image
|
Python
|
UTF-8
| 791
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import json
REGISTER_PACKETS_NAME = b"RGTR"
class RegisterPackets:
def __init__(self, name: str = None, email: str = None, password: str = None, data=None):
self.name, self.email, self.password = name, email, password
self.jdict = dict()
if data is not None:
self.jdict = json.loads(data)
self.name, self.email, self.password = self.jdict["name"], self.jdict["email"], self.jdict["password"]
elif name is not None and email is not None and password is not None:
self.jdict = {
"name": self.name,
"email": self.email,
"password": self.password,
}
def __bytes__(self):
return REGISTER_PACKETS_NAME + bytes(json.dumps(self.jdict), encoding='ascii')
|
C++
|
UTF-8
| 581
| 2.53125
| 3
|
[] |
no_license
|
long fang(long x);
void main()
{
long sum,a,b,i,t,s,p;
sum=0;
scanf("%d",&a);
i=4;
p=10000;
s=a/p; // s=a/p; b=a%p;
while(s==0)
{
i=i-1;
p=fang(i);
s=a/p; // s=b/p; b=b%p;
}
t=i;
while(t>=0)
{
b=a%10;
a=a/10;
sum=sum+fang(t)*b;
t=t-1;
}
printf("%d",sum);
}
long fang(long x)
{
long i,y;
i=1;
y=1;
while(i++<=x) // while(i++<=x)
y=y*10;
return(y);
}
|
Java
|
UTF-8
| 1,108
| 2.25
| 2
|
[] |
no_license
|
package Back;
import Back.FolderManager.CompareIdentTOExcelList;
import Back.FolderManager.GetList;
import Back.FolderManager.Task.Task;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CertificateTask {
public void execute() {
ExecutorService pool = null;
try {
pool = Executors.newFixedThreadPool(10);
GetList list = new GetList();
CompareIdentTOExcelList comList = new CompareIdentTOExcelList();
//CompareIdentTOExcelList comList,String number, Back.Pasport pasport
List<Task> taskList = new ArrayList<>();
list.resultMap.forEach((e,z) -> {
if(!e.equals("")) taskList.add(new Task(comList,e,z));
});
pool.invokeAll(taskList);
pool.shutdown();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (pool != null) {
pool.shutdown();
}
}
}
}
|
Java
|
UTF-8
| 728
| 2.421875
| 2
|
[] |
no_license
|
package yarangi.game.harmonium.enemies;
import yar.quadraturin.objects.IBehavior;
public class ElementalDarknessBehavior implements IBehavior<ElementalDarkness>
{
public boolean behave(double time, ElementalDarkness entity, boolean isVisible)
{
// AABB aabb = entity.getAABB();
// aabb.x += entity.getVelocity().x;
// aabb.y += entity.getVelocity().y;
if(entity.getIntegrity().getHitPoints() <= 0)
{
entity.markDead();
return false;
}
// BezierBubble curve = entity.getCurve();
/* for(int idx = 0; idx < curve.getNodesCount(); idx ++)
{
curve.setCurvature(idx, curve.getAngle(idx)+Angles.PI_div_20/2, 5);
}*/
// System.out.println(entity);
return true;
}
}
|
Ruby
|
UTF-8
| 2,959
| 2.859375
| 3
|
[] |
no_license
|
=begin
This little spider will collect security oriented change log data from all of the most
popular plugins on WordPress.org.
Copyright (C) 2013 Joshua Reynolds
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=end
#!/usr/bin/ruby
require 'net/http'
require 'uri'
@log_file = File.new("log.txt", "w")
def start
puts "Would you like to search for plugins?"
answer = gets.chomp
getTags if answer.upcase == "Y"
end
def grabPlugins(tag)
uri = URI('http://wordpress.org/plugins/tags/' + tag)
resp = Net::HTTP.get_response(uri)
arrPageNums = resp.body.scan(/dots.*\/span><a class="page-numbers" href="\/plugins\/tags\/.*\/page\/(.*?)"/)
puts "Grabbing links..."
for i in 1..arrPageNums[0][0].to_i
uri = URI('http://wordpress.org/plugins/tags/' + tag + '/page/' + i.to_s)
resp = Net::HTTP.get_response(uri)
arrPlugins = resp.body.scan(/<h3><a href="http:\/\/wordpress.org\/plugins\/(.*?)\/">(.*?)<\/a><\/h3>/)
for i in 0..arrPlugins.length-1
spiderPlugin(arrPlugins[i][1], arrPlugins[i][0])
end
end
end
def spiderPlugin(pluginName, uri)
finished = 0;
while finished == 0
begin
uri = URI("http://wordpress.org/plugins/" + uri + "/changelog/")
resp = Net::HTTP.get_response(uri)
arrChangeLogData = resp.body.scan(/<h4>(.*?)<\/h4>.*?<li>(.*?)<\/li>/m)
readChangeLog(arrChangeLogData, pluginName, uri)
finished = 1
rescue
sleep 5
end
end
end
def readChangeLog(arrData, pluginName, uri)
for i in 0..arrData.length-1
version = arrData[i][0]
log = arrData[i][1]
if(checkForSec(log))
@log_file.puts "\nPlugin: #{pluginName}\nURI: #{uri}\nVersion: #{version}\nLog: #{log}"
puts "\nPlugin: #{pluginName}\nURI: #{uri}\nVersion: #{version}\nLog: #{log}"
end
end
end
def getTags
puts "Getting most popular tags..."
uri = URI('http://wordpress.org/plugins/tags/')
resp = Net::HTTP.get_response(uri)
scanned = resp.body.scan(/\/tags\/(.*)'.*title.*style='font-size:(.*)pt;'>/)
scanned = scanned.sort{|a, b| a[1].to_f <=> b[1].to_f}
puts "Starting with the most popular: #{scanned[scanned.length-1][0]}"
for i in 1..scanned.length-1
grabPlugins(scanned[scanned.length-i][0])
end
end
def checkForSec(log)
arr = log.scan(/XSS|Cross[\-\s]Site Scripting|XSRF|CSRF|SQL Injection|Cross[\-\s]Site Request Forgery|Security/i)
if(arr.length > 0)
return true
else
return false
end
end
start
|
C#
|
UTF-8
| 936
| 2.625
| 3
|
[] |
no_license
|
using Microsoft.EntityFrameworkCore;
using registru_auto.Contexts;
using registru_auto.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace registru_auto.Services.Repositories
{
public class CarRepository : Repository<Cars>, ICarRepository
{
private readonly CarsContexts _context;
public CarRepository(CarsContexts context) : base(context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Cars GetBookDetails(Guid carId)
{
return _context.Cars
.Where(b => b.ChassisSeries == carId && (b.Deleted == false || b.Deleted == null))
.Include(b => b.Owner)
.FirstOrDefault();
}
public Cars GetCarDetails(Guid carId)
{
throw new NotImplementedException();
}
}
}
|
Python
|
UTF-8
| 121
| 2.9375
| 3
|
[] |
no_license
|
A, B, C = map(int, input().split())
ABC = sorted([A, B, C], reverse=True)
print(int(str(ABC[0]) + str(ABC[1])) + ABC[2])
|
JavaScript
|
UTF-8
| 3,235
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
/*global $*/
function Ebay(config) {
var callbackName = "";
if ($.type(config) === "string") {
callbackName = config;
config = {};
config.callbackName = callbackName;
}
this.setParameters(config);
}
Ebay.prototype.setParameters = function (config) {
this.baseUrl = config.url || "https://svcs.ebay.com/services/search/FindingService/v1?";
this.security_appname = config.security_appname || "SteveMcA-9f89-4f43-8387-76544c4cb335";
this.payload = config.payload || "REST-PAYLOAD";
this.callback = config.callback || config.callbackName;
this.service_version = "1.0.0&RESPONSE-DATA-FORMAT=JSON";
this.sortOrder = config.sortOrder || "EndTimeSoonest";
this.itemFilters = [];
this.itemFilters.push({
name: "LocatedIn",
value: config.locatedIn || "GB"
});
this.itemFilters.push({
name: "MaxPrice",
value: config.maxPrice || 200
});
this.paginationInput = {
entriesPerPage: config.entriesPerPage || 40
};
this.global_id = config.global_id || "GLOBAL-ID=EBAY-GB";
this.siteid = config.siteid || 3;
this.scriptId = config.scriptId || "ebay-url";
this.buildURL();
};
Ebay.prototype.buildURL = function () {
this.scriptURL = this.baseUrl +
"SECURITY-APPNAME=" + this.security_appname +
//"&OPERATION-NAME=findItemsByKeywords" +
"&OPERATION-NAME=" + this.operation_name +
"&SERVICE-VERSION=" + this.service_version +
"&callback=" + this.callback +
"&" + this.payload +
"&keywords=" + this.keywords +
"&categoryId=" + this.categoryId +
"&sortOrder=" + this.sortOrder;
this.itemFilters.forEach(function (filter, i) {
this.scriptURL += "&itemFilter(" + i + ").name=" + filter.name;
this.scriptURL += "&itemFilter(" + i + ").value=" + filter.value;
}, this);
if (this.paginationInput) {
var prop;
for (prop in this.paginationInput) {
this.scriptURL += "&paginationInput." + prop + "=" + this.paginationInput[prop];
}
}
this.URL += "&" + this.global_id;
this.URL += "&siteid=" + this.siteid;
};
Ebay.prototype.findItemsAdvanced = function (keywords, categoryId) {
this.operation_name = "findItemsAdvanced";
this.keywords = keywords;
if (categoryId) {
this.categoryId = categoryId;
}
this.buildURL();
this.fetchData();
};
Ebay.prototype.fetchData = function () {
$('#' + this.scriptId).remove();
$('body').append('<script id="' + this.scriptId + '" src="' + this.scriptURL + '"></script>');
};
Ebay.prototype.setEndTimeWindow = function (from, to) {
if (($.type(from) !== "date") || ($.type(to) !== "date")) {
throw new Error("from or to must both be date objects");
}
this.itemFilters.push({
name: "EndTimeFrom",
value: from
});
this.itemFilters.push({
name: "EndTimeTo",
value: to
});
};
Ebay.prototype.removeTimeWindow = function () {
this.itemFilters.forEach(function (filter) {
if ((filter.name !== "EndTimeFrom") && (filter.name !== "EndTimeTo")) {
return true;
}
return false;
}, this);
}
|
Python
|
UTF-8
| 1,826
| 3.953125
| 4
|
[] |
no_license
|
### hangman.
### 1st make sure this file and the file of words are saved in the same folder
def oneW(letter,word,sentlist):
empty=True
for ii in range(0,len(word)):
if word[ii]==letter:
sentlist[ii]=word[ii]
empty=False
return sentlist,empty
def hangman(name_of_file):
## read in the file, e.g. "What.txt":
uuu=open(name_of_file,"r")
words=uuu.read()
words=words.lower()
## creating spaces:
## sentence=words.replace(" ","")
sentence=list(words.lower())
import string
alpha=string.ascii_lowercase
## This prints out the sentence in "stars"
for x in range(0,len(words)):
if sentence[x] in alpha:
sentence[x]='*'
sentlist=sentence ## starts list
print("Let's start guessing. Your sentence is:")
phrase=" ".join(sentence)
print(phrase) ## Prints out the unrevealed sentence
wordlist=list(words) ##revealed letter list
## the sentece to guess is: words
## the intial output the user sees: sentence
## Set the number of guesses according to length of words
char=len(list(words))
wordlis=words.split(" ")
totlet=char-len(wordlis)
guesses=totlet
if guesses>15:
guesses=15
while guesses > 0:
print("you got "+str(guesses)+" guesses")
let = input('What is your guess: ')
TF=True
out=oneW(let,words,sentlist)
revealed=out[0]
print(" ".join(revealed))
TF=TF and out[1]
if TF==True:
guesses=guesses-1
print("Nope, try again")
elif TF==False: print("good guess!")
if "*" not in revealed:
print("Great Job, you win!")
break
if guesses==0: print("Sorry you lose!")
hangman('What.txt')
|
JavaScript
|
UTF-8
| 3,804
| 3.140625
| 3
|
[] |
no_license
|
function getToken() {
var username = "3b264586439c0c3af05fa5c857aa9a95";
var password = "e35b17d041dfb51c209012248750ae54";
var token = username + ":" + password;
var hash = btoa(token);
return hash;
}
function loadConstructs(statementName, ticker) {
var hash = getToken();
var req = new XMLHttpRequest();
req.open('GET', 'https://api.intrinio.com/tags/standardized?identifier=' + ticker + '&statement=' + statementName, true);
req.setRequestHeader("Authorization", "Basic " + hash);
req.send();
//Send data to add constructs post in order to load to db
req.onreadystatechange = function processRequest(e) {
if (req.readyState == 4) {
var response = JSON.parse(req.responseText);
console.log(response);
var url = './LoadData/AddConstructs';
var data = response.data;
var constructs = [];
data.forEach(function (ele) {
var construct = {
'name': ele.name,
'tag': ele.tag
};
constructs.push(construct);
})
loadToDb(url, constructs);
}
}
}
function loadStatement(statementName, companyName, ticker, year) {
var hash = getToken();
var req = new XMLHttpRequest();
console.log(year);
req.open('GET', 'https://api.intrinio.com/financials/standardized?identifier='+ ticker +'&statement='+ statementName +'&fiscal_year='+ year +'&fiscal_period=FY', true);
req.setRequestHeader("Authorization", "Basic " + hash);
req.send();
//Send data to add statement post in order to load to db
req.onreadystatechange = function processRequest(e) {
if (req.readyState == 4) {
var response = JSON.parse(req.responseText);
console.log(response);
var url = 'LoadData/AddStatement';
var statement = response.data;
var statementObj = {
'company': {
'symbol': ticker,
'name': companyName
},
'name': statementName,
'statement-details': statement,
'year': year,
'quarter': 0
};
console.log(statementObj);
loadToDb(url, statementObj);
}
}
}
function loadToDb(url, statementObj) {
fetch(url, {
method: 'POST',
body: JSON.stringify(statementObj),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.ok)
.catch(error => console.error('Error:', error))
.then(response => console.log('Success'));
}
/******* INSTRUCTIONS
To add a Company and its financial statements, uncomment the
lines below, and replace 'MU' with the
company's ticker, and 'Micron' with the company's name. Then run
the application and go to /LoadConstructs and wait a few minutes while they load.
You may need to replace the credentials up top if they expire. If they do, register for
a free trial at Intrinio.com and replace them with your new credentials *********/
//loadConstructs('balance_sheet', 'MU');
//loadConstructs('income_statement', 'MU');
//loadStatement('income_statement', 'Micron', 'MU', 2017);
//loadStatement('income_statement', 'Micron','MU', 2016);
//loadStatement('income_statement', 'Micron', 'MU', 2015);
//loadStatement('income_statement', 'Micron', 'MU', 2014);
//loadStatement('balance_sheet', 'Micron' , 'MU', 2017);
//loadStatement('balance_sheet','Micron', 'MU', 2016);
//loadStatement('balance_sheet', 'Micron', 'MU', 2015);
//loadStatement('balance_sheet', 'Micron', 'MU', 2014);
console.log("finished");
|
Markdown
|
UTF-8
| 13,156
| 2.59375
| 3
|
[] |
no_license
|
---
title: ०८३
---
द्रौपदीं प्रति श्रीकृष्णपत्नीनां स्वस्वोद्वाहवृत्तांतवर्णनम् -
अथ त्र्यशीतितमोऽध्यायः 10.83
श्रीशुक उवाच
तथानुगृह्य भगवान्गोपीनां स गुरुर्गतिः
युधिष्ठिरमथापृच्छत्सर्वांश्च सुहृदोऽव्ययम् १
त एवं लोकनाथेन परिपृष्टाः सुसत्कृताः
प्रत्यूचुर्हृष्टमनसस्तत्पादेक्षाहतांहसः २
कुतोऽशिवं त्वच्चरणाम्बुजासवं महन्मनस्तो मुखनिःसृतं क्वचित्
पिबन्ति ये कर्णपुटैरलं प्रभो देहंभृतां देहकृदस्मृतिच्छिदम् ३
हित्वात्म धामविधुतात्मकृतत्र्यवस्थाम्
आनन्दसम्प्लवमखण्डमकुण्ठबोधम्
कालोपसृष्टनिगमावन आत्तयोग
मायाकृतिं परमहंसगतिं नताः स्म ४
श्रीऋषिरुवाच
इत्युत्तमःश्लोकशिखामणिं जनेष्व्
अभिष्टुवत्स्वन्धककौरवस्त्रियः
समेत्य गोविन्दकथा मिथोऽगृणंस्
त्रिलोकगीताः शृणु वर्णयामि ते ५
श्रीद्रौपद्युवाच
हे वैदर्भ्यच्युतो भद्रे हे जाम्बवति कौशले
हे सत्यभामे कालिन्दि शैब्ये रोहिणि लक्ष्मणे ६
हे कृष्णपत्न्य एतन्नो ब्रूत वो भगवान्स्वयम्
उपयेमे यथा लोकमनुकुर्वन्स्वमायया ७
श्रीरुक्मिण्युवाच
चैद्याय मार्पयितुमुद्यतकार्मुकेषु
राजस्वजेयभटशेखरिताङ्घ्रिरेणुः
निन्ये मृगेन्द्र इव भागमजावियूथात्
तच्छ्रीनिकेतचरणोऽस्तु ममार्चनाय ८
श्रीसत्यभामोवाच
यो मे सनाभिवधतप्तहृदा ततेन
लिप्ताभिशापमपमार्ष्टुमुपाजहार
जित्वर्क्षराजमथ रत्नमदात्स तेन
भीतः पितादिशत मां प्रभवेऽपि दत्ताम् ९
श्रीजाम्बवत्युवाच
प्राज्ञाय देहकृदमुं निजनाथदैवं
सीतापतिं त्रिनवहान्यमुनाभ्ययुध्यत्
ज्ञात्वा परीक्षित उपाहरदर्हणं मां
पादौ प्रगृह्य मणिनाहममुष्य दासी १०
श्रीकालिन्द्युवाच
तपश्चरन्तीमाज्ञाय स्वपादस्पर्शनाशया
सख्योपेत्याग्रहीत्पाणिं योऽहं तद्गृहमार्जनी ११
श्रीमित्रविन्दोवाच
यो मां स्वयंवर उपेत्य विजित्य भूपान्
निन्ये श्वयूथगं इवात्मबलिं द्विपारिः
भ्रातॄंश्च मेऽपकुरुतः स्वपुरं श्रियौकस्
तस्यास्तु मेऽनुभवमङ्घ्र्यवनेजनत्वम् १२
श्रीसत्योवाच
सप्तोक्षणोऽतिबलवीर्यसुतीक्ष्णशृङ्गान्
पित्रा कृतान्क्षितिपवीर्यपरीक्षणाय
तान्वीरदुर्मदहनस्तरसा निगृह्य
क्रीडन्बबन्ध ह यथा शिशवोऽजतोकान् १३
य इत्थं वीर्यशुल्कां मां
दासीभिश्चतुरङ्गिणीम्
पथि निर्जित्य राजन्यान्
निन्ये तद्दास्यमस्तु मे १४
श्रीभद्रोवाच
पिता मे मातुलेयाय स्वयमाहूय दत्तवान्
कृष्णे कृष्णाय तच्चित्तामक्षौहिण्या सखीजनैः १५
अस्य मे पादसंस्पर्शो भवेज्जन्मनि जन्मनि
कर्मभिर्भ्राम्यमाणाया येन तच्छ्रेय आत्मनः १६
श्रीलक्ष्मणोवाच
ममापि राज्ञ्यच्युतजन्मकर्म श्रुत्वा मुहुर्नारदगीतमास ह
चित्तं मुकुन्दे किल पद्महस्तया वृतः सुसम्मृश्य विहाय लोकपान् १७
ज्ञात्वा मम मतं साध्वि पिता दुहितृवत्सलः
बृहत्सेन इति ख्यातस्तत्रोपायमचीकरत् १८
यथा स्वयंवरे राज्ञि मत्स्यः पार्थेप्सया कृतः
अयं तु बहिराच्छन्नो दृश्यते स जले परम् १९
श्रुत्वैतत्सर्वतो भूपा आययुर्मत्पितुः पुरम्
सर्वास्त्रशस्त्रतत्त्वज्ञाः सोपाध्यायाः सहस्रशः २०
पित्रा सम्पूजिताः सर्वे यथावीर्यं यथावयः
आददुः सशरं चापं वेद्धुं पर्षदि मद्धियः २१
आदाय व्यसृजन्केचित्सज्यं कर्तुमनीश्वराः
आकोष्ठं ज्यां समुत्कृष्य पेतुरेकेऽमुनाहताः २२
सज्यं कृत्वापरे वीरा मागधाम्बष्ठचेदिपाः
भीमो दुर्योधनः कर्णो नाविदंस्तदवस्थितिम् २३
मत्स्याभासं जले वीक्ष्य ज्ञात्वा च तदवस्थितिम्
पार्थो यत्तोऽसृजद्बाणं नाच्छिनत्पस्पृशे परम् २४
राजन्येषु निवृत्तेषु भग्नमानेषु मानिषु
भगवान्धनुरादाय सज्यं कृत्वाथ लीलया २५
तस्मिन्सन्धाय विशिखं मत्स्यं वीक्ष्य सकृज्जले
छित्त्वेषुणापातयत्तं सूर्ये चाभिजिति स्थिते २६ अभिजित्
दिवि दुन्दुभयो नेदुर्जयशब्दयुता भुवि
देवाश्च कुसुमासारान्मुमुचुर्हर्षविह्वलाः २७
तद्रङ्गमाविशमहं कलनूपुराभ्यां
पद्भ्यां प्रगृह्य कनकोज्वलरत्नमालाम्
नूत्ने निवीय परिधाय च कौशिकाग्र्ये
सव्रीडहासवदना कवरीधृतस्रक् २८
उन्नीय वक्त्रमुरुकुन्तलकुण्डलत्विड्
गण्डस्थलं शिशिरहासकटाक्षमोक्षैः
राज्ञो निरीक्ष्य परितः शनकैर्मुरारेर्
अंसेऽनुरक्तहृदया निदधे स्वमालाम् २९
तावन्मृदङ्गपटहाः शङ्खभेर्यानकादयः
निनेदुर्नटनर्तक्यो ननृतुर्गायका जगुः ३०
एवं वृते भगवति मयेशे नृपयूथपाः
न सेहिरे याज्ञसेनि स्पर्धन्तो हृच्छयातुराः ३१
मां तावद्रथमारोप्य हयरत्नचतुष्टयम्
शार्ङ्गमुद्यम्य सन्नद्धस्तस्थावाजौ चतुर्भुजः ३२
दारुकश्चोदयामास काञ्चनोपस्करं रथम्
मिषतां भूभुजां राज्ञि मृगाणां मृगराडिव ३३
तेऽन्वसज्जन्त राजन्या निषेद्धुं पथि केचन
संयत्ता उद्धृतेष्वासा ग्रामसिंहा यथा हरिम् ३४
ते शार्ङ्गच्युतबाणौघैः कृत्तबाह्वङ्घ्रिकन्धराः
निपेतुः प्रधने केचिदेके सन्त्यज्य दुद्रुवुः ३५
ततः पुरीं यदुपतिरत्यलङ्कृतां
रविच्छदध्वजपटचित्रतोरणाम्
कुशस्थलीं दिवि भुवि चाभिसंस्तुतां
समाविशत्तरणिरिव स्वकेतनम् ३६
पिता मे पूजयामास सुहृत्सम्बन्धिबान्धवान्
महार्हवासोऽलङ्कारैः शय्यासनपरिच्छदैः ३७
दासीभिः सर्वसम्पद्भिर्भटेभरथवाजिभिः
आयुधानि महार्हाणि ददौ पूर्णस्य भक्तितः ३८
आत्मारामस्य तस्येमा वयं वै गृहदासिकाः
सर्वसङ्गनिवृत्त्याद्धा तपसा च बभूविम ३९
महिष्य ऊचुः
भौमं निहत्य सगणं युधि तेन रुद्धा
ज्ञात्वाथ नः क्षितिजये जितराजकन्याः
निर्मुच्य संसृतिविमोक्षमनुस्मरन्तीः
पादाम्बुजं परिणिनाय य आप्तकामः ४०
न वयं साध्वि साम्राज्यं स्वाराज्यं भौज्यमप्युत
वैराज्यं पारमेष्ठ्यं च आनन्त्यं वा हरेः पदम् ४१
कामयामह एतस्य श्रीमत्पादरजः श्रियः
कुचकुङ्कुमगन्धाढ्यं मूर्ध्ना वोढुं गदाभृतः ४२
व्रजस्त्रियो यद्वाञ्छन्ति पुलिन्द्यस्तृणवीरुधः
गावश्चारयतो गोपाः पदस्पर्शं महात्मनः ४३
इति श्रीमद्भागवते महापुराणे पारमहंस्यां संहितायां दशमस्कन्धे उत्तरार्धे त्र्यशीतितमोऽध्यायः
|
C#
|
UTF-8
| 902
| 2.703125
| 3
|
[] |
no_license
|
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
namespace PokeForms.Helpers
{
public class PokeApiData
{
static PokeApiData _default;
public static PokeApiData Default {
get{
if (_default == null)
_default = new PokeApiData ();
return _default;
}
}
HttpClient _webClient;
public PokeApiData ()
{
_webClient = new HttpClient ();
_webClient.Timeout = TimeSpan.FromSeconds (30);
}
public async Task<PokemonData> GetPokemonData (int PokemonID)
{
var uri = new Uri (Constants.EndPoint + "pokemon/" + PokemonID);
var response = await _webClient.GetAsync (uri);
if (response.IsSuccessStatusCode) {
var content = await response.Content.ReadAsStringAsync ();
var Items = JsonConvert.DeserializeObject <PokemonData> (content);
var debug = true;
return Items;
}
return null;
}
}
}
|
Python
|
UTF-8
| 813
| 2.828125
| 3
|
[] |
no_license
|
import os
from PIL import Image, ImageStat
from pathlib import Path
# -- Variables -- #
FOLDER_IMAGES = r"C:\Images"
EXTENSION = "jpg"
# --- Functions -- #
def hash_image(image_path):
img = Image.open(image_path).resize((8, 8), Image.LANCZOS).convert(mode="L")
mean = ImageStat.Stat(img).mean[0]
sum_aux = sum((1 if p > mean else 0) << i for i, p in enumerate(img.getdata()))
# Quedaba abierta?
img.close()
return sum_aux
# -- Program -- #
files = Path(FOLDER_IMAGES).glob('**/*.' + EXTENSION)
final_files = []
files_aux = []
for file in files:
for file_aux in files_aux:
if hash_image(file_aux) == hash_image(file):
continue
files_aux.append(file)
if file not in files_aux:
final_files.append(file)
else:
os.remove(Path(file))
|
Java
|
UTF-8
| 1,454
| 2.390625
| 2
|
[] |
no_license
|
package com.codecool.shop.controller;
import com.codecool.shop.dao.implementation.UserDaoMem;
import com.codecool.shop.model.User;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import java.util.HashMap;
import java.util.Map;
public class LoginController {
private static LoginController instance = null;
private LoginController() {}
public static LoginController getInstance() {
if (instance == null) {
instance = new LoginController();
}
return instance;
}
public ModelAndView renderLogin(Request req, Response res) {
UserDaoMem userDataStore = UserDaoMem.getInstance();
Map<String, Object> params = new HashMap<>();
params.put("users", userDataStore.getAll());
return new ModelAndView(params, "login");
}
public ModelAndView renderLoginPost(Request req, Response res){
UserDaoMem userDataStore = UserDaoMem.getInstance();
User user = userDataStore.find(req.queryParams("username"));
if (req.queryParams("username").equals(user.getName())){
if (req.queryParams("password").equals(user.getPassword())) {
req.session(true);
req.session().attribute("user", req.queryParams("username"));
req.session().attribute("type", user.getRank());
res.redirect("/");
}
}
return renderLogin(req, res);
}
}
|
C++
|
UTF-8
| 591
| 3.4375
| 3
|
[] |
no_license
|
#include "note.h"
/*! Genera una nota desde un string respetando el formato
* asignado para guardar las notas
* RETURNS:
* < 0 on error
* 0 if success
*/
int Note::fromString(string &str)
{
cout << "estamos parseando una nota: "<< str << endl;
this->note = str;
return 0;
}
/*! Convierte una nota en un string listo para ser guardada
* en un archivo.
* RETURNS:
* NULL if error
* strNote otherwise
* NOTE: Genera memoria
*/
string *Note::toString(void)
{
return new string(this->note);
}
bool Note::operator==(Note &other)
{
return (this->note.compare(other.getNote()) == 0);
}
|
C++
|
UTF-8
| 1,019
| 3.375
| 3
|
[] |
no_license
|
//
// Created by ali5 on 11/5/18.
//
#include "AST/ASTNodes/TerminalNodes/NullNode.h"
NullNode::NullNode(int line) :ASTNode(line) {
setType(NULLTY);
this->vector = new std::vector<std::string>;
this->vector->push_back("null");
}
void NullNode::pushType(std::string type) {
this->vector->push_back(type);
}
std::string NullNode::popType(int pos) {
return this->vector->at(pos);
}
void NullNode::assignType(std::string newType, int pos) {
int curTypePos = this->getTypePos(this->vector->at(pos));
int newTypePos = this->getTypePos(newType);
std::string varType = typeTable[curTypePos][newTypePos];
this->vector->at(pos) = varType;
}
int NullNode::getTypePos(std::string type) {
if(type == "bool")
return 0;
else if(type == "char")
return 1;
else if(type == "int")
return 2;
else if(type == "real")
return 3;
else if(type == "null")
return 4;
else {
std::cerr << "Unknown type \n";
exit(1);
}
}
|
C
|
UTF-8
| 386
| 3.796875
| 4
|
[] |
no_license
|
#include<stdio.h>
void main()
{
int a,b,c;
printf("enter three numbers a,b,c respectively");
scanf("%d%d%d",&a,&b,&c);
if(a=b=c)
printf("all numbers are equal");
else if(a=b)
printf("%d",c);
else if(b=c)
printf("%d",a);
else if(c=a)
printf("%d",b);
else
printf("none of the numbers are equal");
}
|
Markdown
|
UTF-8
| 1,859
| 3.171875
| 3
|
[] |
no_license
|
# SBF (Simple Binary Format) v0.2.0
A simple binary format for storing data.
SBF files are designed to be as braindead as possible,
i.e. easy to write, easy to read.
# Why?
It's nice to have a simple binary data format
for straightforward applications that don't have complex
requirements. (e.g. HDF5, netCDF etc.) Plus it's (much)
faster than passing ASCII/UTF8 encoded numerical data around.
# What data formats does it support, how are they defined?
As of now there are byte, character, integer,
long, float, double, complex float and complex
double datatypes.
These are defined as follows:
```
sbf_byte = C uint8_t
sbf_character = C char
sbf_integer = C int32_t
sbf_long = C int64_t
sbf_float = C float
sbf_double = C double
sbf_complex_float = 2 C floats {real, imaginary}
sbf_complex_double = 2 C doubles {real, imaginary}
```
# Does this format support XYZ?
If XYZ is anything other than writing binary data arrays
of dimension up to 8, consisting of the aforementioned
data types, then no.
# Why not XYZ {hierarchical data, compression etc.}?
Basically:
- I want to keep the format as simple as possible, have only simple
responsibilities.
- I believe hierarchy can be done by the file system and directories etc.
- I might support compression later, but doing so requires dependencies,
something I don't wish to add.
# File Structure
An SBF File is structured as follows:
```
+--------------------+
| sbf_FileHeader | file description e.g. number of datasets
+--------------------+
| sbf_DataHeader(s) | 0 or more, one for EACH dataset, containing a
| ... | description of what is stored in `binary_data`
+--------------------+
| binary_blobs | binary data described in data header section(s)
+--------------------+
```
|
Markdown
|
UTF-8
| 3,841
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
---
author: "Fanny COURTIN"
author_url: ""
date: "2017-10-27 14:00:00 +0000 UTC"
location: "Amphi G. Besse"
title: "Soutenance de thèse: Étude de l'incinération du plutonium en REP MOX sur support d'uranium enrichi avec le code de simulation dynamique du cycle CLASS"
author_filiation: "Subatech (groupe Neutrino)"
author_filiation_url: ""
type: "spécialisé"
author2: ""
author_url2: ""
author_filiation2: ""
author_filiation_url2: ""
title2: ""
category: "seminar"
layout: "seminar"
---
Résumé Les codes de simulation du cycle du combustible nucléaire sont utilisés comme outils d’évaluation des stratégies futures. Ces outils permettent, entres autres, de comprendre les mécanismes qui régissent la physique du cycle du combustible nucléaire. Dans le contexte d’incertitude entourant l’évolution future du parc nucléaire français, notamment concernant le déploiement de Réacteurs à Neutrons Rapides au sodium (RNR-Na), la problématique de cette thèse est d’étudier des solutions alternatives de gestion du plutonium et des autres noyaux lourds, basées sur les Réacteurs à Eau Pressurisés (REP). Les stratégies étudiées s’appuient sur deux hypothèses. La première suppose un retard important dans le déploiement des RNR-Na, impliquant une stratégie d’attente visant à stabiliser l’inventaire en plutonium. La deuxième hypothèse suppose un abandon de la stratégie de déploiement des RNR. Dans ce cadre, une stratégie d’incinération du plutonium a été étudiée pour quantifier la capacité de réduction de l’inventaire par les REP. Le code de simulation CLASS, développé par le CNRS/IN2P3 et l’IRSN, est utilisé. Le multi-recyclage du plutonium en REP requiert un combustible dédié. Des développements ont été réalisés pour modéliser le combustible étudié, composé de MOx sur un support d'uranium enrichi. Une méthodologie innovante d’évaluation de scénarios nucléaires basée sur l’analyse globale de sensibilité a été appliquée. Cette méthode a permis d’identifier des scénarios de référence pour la stabilisation et l’incinération du plutonium. Des simulations du cycle détaillées ont été réalisées afin d'analyser la capacité des REP à gérer le plutonium à l’échelle du cycle.
Abstract Fuel cycle simulators are used worldwide to provide scientific assessment to fuel cycle future strategies. Those tools help understanding the fuel cycle physics and determining the most impacting drivers at the cycle scale. In the context of uncertainty related to the future of the French nuclear fleet, especially on Sodium Fast Reactors (SFR) deployment, the present work aims to study alternative solutions for plutonium and heavy isotopes management, based on Pressurized Water Reactor (PWR). Two hypothesis have been formulated to identify strategies. First, a delay has been expected in SFR deployment, inducing a stabilization of plutonium inventory before SFR integration. The second hypothesis is based on the assumption that SFR won’t be deployed in France. For this specific case, a plutonium incineration strategy has been studied to quantify the PWR plutonium inventory reduction capacity. Calculations are done with the fuel cycle simulator CLASS developed by the CNRS/IN2P3 in collaboration with IRSN. Plutonium multi-reprocessing in thermal reactor requires an innovative fuel. Developments have been made to simulate a fuel composed of MOx on enriched uranium support. An innovative methodology for fuel cycle simulation evaluation based on Global Sensitivity Analysis has been used. This methodology leads to reference scenarios identification for plutonium stabilization and incineration. Fuel cycle detailed simulations has been performed to produce important data to analyze PWR plutonium management at the cycle scale.
|
Markdown
|
UTF-8
| 4,293
| 2.546875
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: GitHub Enterprise Server-Releases
intro: '{% data variables.product.company_short %} veröffentlicht regelmäßig neue Versionen von {% data variables.product.product_name %}. Du kannst die unterstützten Versionen überprüfen, das Datum der Veralterung einsehen und die Dokumentation für das von dir bereitgestellte Release durchsuchen.'
allowTitleToDifferFromFilename: true
versions:
ghes: '*'
topics:
- Enterprise
- Upgrades
shortTitle: Releases
ms.openlocfilehash: 85b0848f77b12920ba853bc674327392b6a89389
ms.sourcegitcommit: 47bd0e48c7dba1dde49baff60bc1eddc91ab10c5
ms.translationtype: HT
ms.contentlocale: de-DE
ms.lasthandoff: 09/05/2022
ms.locfileid: '147062906'
---
## Informationen zu Releases von {% data variables.product.product_name %}
{% data reusables.enterprise.constantly-improving %} {% data variables.product.company_short %} unterstützt die vier neuesten Featurereleases. Weitere Informationen findest du unter [Informationen zu Upgrades auf neue Releases](/admin/overview/about-upgrades-to-new-releases).
Informationen zu den Neuigkeiten in den einzelnen Releases findest du in den [Versionshinweisen](/admin/release-notes). Die Administrator- und Benutzerdokumentation für alle Releases kannst du hier auf {% data variables.product.prodname_docs %} einsehen. Stelle beim Lesen der Dokumentation sicher, dass du die deinem Produkt entsprechende Version auswählst. Weitere Informationen findest du unter [Informationen zu Versionen von {% data variables.product.prodname_docs %}](/get-started/learning-about-github/about-versions-of-github-docs).
## Derzeit unterstützte Releases
{% data variables.product.company_short %} unterstützt die folgenden Releases von {% data variables.product.product_name %}. Weitere Informationen zum neuesten Release findest du auf der Website zu [{% data variables.product.prodname_enterprise %}](https://github.com/enterprise).
| Version | Release | Eingestellte Unterstützung | Versionshinweise | Dokumentation |
| :- | :- | :- | :- | :- |
{%- for version in enterpriseServerReleases.supported %} | {{version}} | {{enterpriseServerReleases.dates[version].releaseDate}} | {{enterpriseServerReleases.dates[version].deprecationDate}} | [Versionshinweise zu {{version}}](/enterprise-server@{{version}}/admin/release-notes) | [Dokumentation zu {{version}}](/enterprise-server@{{version}}) | {%- endfor %}
## Veraltete Releases
{% data variables.product.company_short %} stellt Dokumentationen für veraltete Versionen bereit, die Dokumentation wird jedoch nicht gepflegt und aktualisiert.
| Version | Release | Eingestellte Unterstützung | Versionshinweise | Dokumentation |
| :- | :- | :- | :- | :- |
{%- for version in enterpriseServerReleases.deprecatedReleasesWithNewFormat %} | {{version}} | {{enterpriseServerReleases.dates[version].releaseDate}} | {{enterpriseServerReleases.dates[version].deprecationDate}} | [Versionshinweise zu {{version}}](/enterprise-server@{{version}}/admin/release-notes) | [Dokumentation zu {{version}}](/enterprise-server@{{version}}) | {%- endfor %} {%- for version in enterpriseServerReleases.deprecatedReleasesWithLegacyFormat %} | {{version}} | {{enterpriseServerReleases.dates[version].releaseDate}} | {{enterpriseServerReleases.dates[version].deprecationDate}} | [Versionshinweise zu {{version}}](https://enterprise.github.com/releases/series/{{version}}) | [Dokumentation zu {{version}}](/enterprise/{{version}}) | {%- endfor %}
### Veraltete Entwicklerdokumentation
{% data variables.product.company_short %} hat Entwicklerdokumentation für {% data variables.product.product_name %} bis zum Release 2.17 auf einer separaten Website gehostet. {% data variables.product.company_short %} stellt weiterhin Entwicklerdokumentation für Version 2.16 und ältere Versionen bereit, die Dokumentation wird jedoch nicht gepflegt und aktualisiert.
| Version | Release | Eingestellte Unterstützung | Entwicklerdokumentation |
| :- | :- | :- | :- |
{%- for version in enterpriseServerReleases.deprecatedReleasesOnDeveloperSite %} | {{version}} | {{enterpriseServerReleases.dates[version].releaseDate}} | {{enterpriseServerReleases.dates[version].deprecationDate}} | [Entwicklerdokumentation zu {{version}}](https://developer.github.com/enterprise/{{version}}) | {%- endfor %}
|
Python
|
UTF-8
| 1,650
| 2.578125
| 3
|
[] |
no_license
|
from datetime import datetime, timedelta
import pytz
from apps.subject.models import Semester
from tests.conftest import TestCase
class TestCourseLookup(TestCase):
@classmethod
def setUp(cls):
super().setUpClass()
values = [
{"year": 2020, "semester": 1},
{"year": 2019, "semester": 2},
{"year": 2019, "semester": 4},
{"year": 2020, "semester": 2},
{"year": 2020, "semester": 4},
{"year": 2019, "semester": 3},
{"year": 2019, "semester": 1},
{"year": 2020, "semester": 3},
]
now = pytz.timezone("Asia/Seoul").localize(datetime(2018, 10, 29, 12, 1, 8))
Semester.objects.bulk_create(
[
Semester(year=args["year"], semester=args["semester"], beginning=now, end=(now + timedelta(days=1)))
for args in values
]
)
def tearDown(self):
super().tearDown()
Semester.objects.filter(year__gte=2019, year__lte=2020).delete()
def test_schema(self):
pass
def test_type_search(self):
response = self.request_get(None, "/api/semesters")
semesters = response.data
assert len(semesters) == 8
for i in range(len(semesters) - 1):
key_now = semesters[i]["year"] * 4 + semesters[i]["semester"]
key_next = semesters[i + 1]["year"] * 4 + semesters[i + 1]["semester"]
assert key_now < key_next
for semester in semesters:
assert semester["beginning"] == "2018-10-29T03:01:08Z"
assert semester["end"] == "2018-10-30T03:01:08Z"
|
PHP
|
UTF-8
| 1,182
| 2.546875
| 3
|
[] |
no_license
|
<?php
if(isset($_SESSION['chatuser'])){
$q = new apm_Database_Query ();
$q->addTable ( 'forum_chat_chatters' );
$q->addQuery ( '*' );
$q->addWhere('name='.$_SESSION['chatuser']);
$q->exec ();
$row = $q->fetchRow ();
if (!empty($row[0])) {
$q = new apm_Database_Query ();
$q->addTable ( 'forum_chat_chatters' );
$q->addUpdate ( 'seen', date('Y-m-d H:i:s') );
$q->addWhere('name='.$_SESSION['chatuser']);
$q->exec ();
}else{
$q = new apm_Database_Query ();
$q->addTable ( 'forum_chat_chatters' );
$q->addInsert( 'name', $_SESSION['chatuser']);
$q->addInsert( 'seen', date('Y-m-d H:i:s'));
$q->exec ();
}
}
/* Make sure the timezone on Database server and PHP server is same */
$q = new apm_Database_Query ();
$q->addTable ( 'forum_chat_chatters' );
$q->addQuery ( '*' );
$q->addWhere('name='.$_SESSION['chatuser']);
$q->exec ();
$row = $q->fetchRow ();
if (!empty($row[0])) {
$curtime=strtotime(date("Y-m-d H:i:s",strtotime('-25 seconds', time())));
if(strtotime($row['seen']) < $curtime){
$q = new apm_Database_Query ();
$q->setDelete( 'forum_chat_chatters' );
$q->addWhere('name=\''.$row[0]['name'].'\'');
$q->exec ();
}
}
?>
|
Python
|
UTF-8
| 714
| 2.59375
| 3
|
[] |
no_license
|
from google.auth.transport import requests
from google.oauth2 import id_token
CLIENT_ID = "508553430731-3sjtbacd9na89labelop5fii28h4ho1m.apps.googleusercontent.com"
def get_google_user_from_google_token(token):
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
# ID token is valid. Get the user's Google Account ID from the decoded token.
return idinfo
except ValueError as err:
# Invalid token
print(err)
return None
|
C++
|
UTF-8
| 1,180
| 2.640625
| 3
|
[] |
no_license
|
#include "chatserverwidget.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
ChatServerWidget::ChatServerWidget(QWidget *parent) :
QWidget(parent)
{
QLabel *label = new QLabel(tr("port"));
m_linePort = new QLineEdit;
m_buttonListen = new QPushButton(tr("listen"));
m_buttonStop = new QPushButton(tr("stop"));
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(label);
layout->addWidget(m_linePort);
layout->addWidget(m_buttonListen);
layout->addWidget(m_buttonStop);
setLayout(layout);
connect(m_buttonListen, SIGNAL(clicked(bool)), this, SLOT(buttonListenClicked()));
connect(m_buttonStop, SIGNAL(clicked(bool)), this, SLOT(buttonStopClicked()));
}
ChatServerWidget::~ChatServerWidget()
{
}
void ChatServerWidget::buttonListenClicked()
{
QString text = m_linePort->text();
bool ok;
qint16 port = text.toInt(&ok);
if(ok){
m_chatServer.listen(port);
}
else{
QMessageBox messageBox(this);
messageBox.setText("Port number must be an integer.");
messageBox.exec();
}
}
void ChatServerWidget::buttonStopClicked()
{
m_chatServer.stop();
}
|
C#
|
UTF-8
| 405
| 2.59375
| 3
|
[] |
no_license
|
using System;
// server's copy of the client
public class ServerClientHandle
{
public int id;
private NetGameConnection m_connection;
public ServerClientHandle(int idIn)
{
this.id = idIn;
m_connection = null;
}
public void SetGameConnection(NetGameConnection connectionIn)
{
m_connection = connectionIn;
}
public NetGameConnection GetGameConnection()
{
return m_connection;
}
}
|
C
|
UTF-8
| 638
| 2.671875
| 3
|
[] |
no_license
|
#include <SDL2/SDL.h>
void constant(char name[], int value) {
printf("public export\n");
printf("%s : Bits32\n", name);
printf("%s = %d\n\n", name, value);
}
int main(int argc, char *argv[]) {
/*
printf("sizeof(enum Fred) = %lu\n", sizeof(enum Fred));
int keyUp = 1073741906;
printf("keyUp = %d\n", keyUp);
*/
printf("module Constants\n\n");
constant("QUIT", SDL_QUIT);
constant("KEYDOWN", SDL_KEYDOWN);
constant("KEYUP", SDL_KEYUP);
constant("KEY_ESCAPE", SDLK_ESCAPE);
constant("KEY_UP", SDLK_UP);
constant("KEY_RIGHT", SDLK_RIGHT);
constant("KEY_DOWN", SDLK_DOWN);
constant("KEY_LEFT", SDLK_LEFT);
}
|
C#
|
UTF-8
| 1,833
| 2.96875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//After we add all models to Models folder we have to add ".Models" after TrackerLibrary
//if you create a new class from the Models file ".Models" will added automaticlly
//but becasue we create our models before and we added them to the Models folder later we have to add ".Models"
//namespace TrackerLibrary --> original
namespace TrackerLibrary.Models
{
/// <summary>
/// Represents one tournament, with all of the rounds, matchups, prizes and outcomes.
/// </summary>
public class TournamnetModel //make it public
{
public event EventHandler<DateTime> onTournamentComplete;
/// <summary>
/// The unique identifier for the tournament.
/// </summary>
public int Id { get; set; }
/// <summary>
/// The name given to this tournament.
/// </summary>
public string TournamentName { get; set; }
/// <summary>
/// The amount of money each team needs to put up to enter
/// </summary>
public decimal EntryFee { get; set; }
/// <summary>
/// The set of teams that have been entered.
/// </summary>
public List<TeamModel> EnteredTeams { get; set; } = new List<TeamModel>();
/// <summary>
/// The list of prizes for the various places
/// </summary>
public List<PrizeModel> Prizes { get; set; } = new List<PrizeModel>();
/// <summary>
/// The mathups per round.
/// </summary>
public List<List<MatchupModel>> Rounds { get; set; } = new List<List<MatchupModel>>();
public void CompleteTournament()
{
onTournamentComplete?.Invoke(this, DateTime.Now);
}
}
}
|
C#
|
UTF-8
| 541
| 2.625
| 3
|
[] |
no_license
|
using SavasLibrary.Abstract;
using System;
using System.Drawing;
namespace SavasLibrary.Concrete
{
internal class Mermi : Cisim
{
public Mermi(Size hareketAlaniBoyutlari, int namluOrtasiX) : base(hareketAlaniBoyutlari)
{
BaslangicKonumunuAyarla(namluOrtasiX);
HareketMesafesi =(int) (Height * 1.5d);
}
private void BaslangicKonumunuAyarla(int namluOrtasiX)
{
Bottom = HareketAlaniBoyutlari.Height;
Center = namluOrtasiX;
}
}
}
|
Markdown
|
UTF-8
| 1,336
| 2.578125
| 3
|
[
"CC0-1.0"
] |
permissive
|
## Screenshots during Execution of the Code
### Rules and Instructions of the game:

### Player Info:

### Round 1 Quiz :


### Results of Round 1:

### Round 2 Quiz :

### Results of Round 2:

### Round 3 Quiz :

### Final Scoresheet:

|
SQL
|
UTF-8
| 731
| 3.890625
| 4
|
[] |
no_license
|
CREATE TABLE object
(
city VARCHAR(25),
date_created DATETIME DEFAULT NOW(),
description VARCHAR(200),
id INTEGER NOT NULL AUTO_INCREMENT,
price INTEGER,
PRIMARY KEY (id),
);
CREATE TABLE order
(
class_id INTEGER NOT NULL,
child_first_name VARCHAR(30),
child_last_name VARCHAR(30),
id INTEGER NOT NULL AUTO_INCREMENT,
user_id INTEGER NOT NULL,
FOREIGN KEY(user_id) REFERENCES user (id)
FOREIGN KEY(class_id) REFERENCES class (id)
)
CREATE TABLE user
(
first_name VARCHAR(30)
last_name VARCHAR(30)
email VARCHAR(50),
id INTEGER NOT NULL AUTO_INCREMENT,
password VARCHAR(60),
PRIMARY KEY (id),
UNIQUE (email),
);
|
Python
|
UTF-8
| 3,433
| 2.71875
| 3
|
[] |
no_license
|
import numpy as np
import cPickle as pickle
import random
from logProgress import *
'''
Description : The file builds the ARCmtDataset using the ChildrenDict. The output
from this file is in comment_name format. To convert the output to
text_format, use buildARCmtDatasetText.py
Ouput : ARCmtDataset.txt (Dataset in comment_name format)
'''
data_path = "/home/cse/dual/cs5130275/scratch/DERP/Reddit/"
output_file_name = 'NewPrunedDataset/ARCmtDataset'
## Functions
def getPermutationPairs(num):
pairs = []
for i in range(num):
for j in range(i+1, num):
pairs.append((i, j))
random.shuffle(pairs)
return pairs[:6]
## Load Data
print "Loading data..."
child_dict = pickle.load(open(data_path+'ChildrenDict.pkl'))
parent_dict = pickle.load(open(data_path+'Name2ParentId.pkl'))
link_id = pickle.load(open(data_path+'Name2LinkId.pkl'))
for parent in child_dict:
if parent not in link_id:
link_id[parent] = link_id[child_dict[parent][0]]
## Permutations of child pairs to use
selected_pairs = {}
for i in range(2, 11):
selected_pairs[i] = getPermutationPairs(i)
## Creat Link ID Splits
splits = ['_train', '_val', '_test']
all_link_ids = list(set(link_id.values()))
random.shuffle(all_link_ids)
split_link_ids = {}
num_link_ids = len(all_link_ids)
split_link_ids['_train'] = set(all_link_ids[:int(0.91*num_link_ids)])
split_link_ids['_val'] = set(all_link_ids[int(0.91*num_link_ids):int(0.955*num_link_ids)])
split_link_ids['_test'] = set(all_link_ids[int(0.955*num_link_ids):])
for split in splits:
## Random comments list for bad child
random_comments = []
for comment_name in child_dict:
if link_id[comment_name] in split_link_ids[split]:
random_comments.extend(child_dict[comment_name])
random.shuffle(random_comments)
curr_random = 0
## Extract good and bad pairs
useful_comments = []
for comment_name in logProgress(child_dict):
if link_id[comment_name] in split_link_ids[split]:
num_child_comments = len(child_dict[comment_name])
if num_child_comments >= 2 and num_child_comments <= 10:
curr_dict = {}
## Find true child comment pairs
curr_dict['true_child_pairs'] = []
for pair in selected_pairs[num_child_comments]:
gold_child = child_dict[comment_name][pair[0]]
alternate_child = child_dict[comment_name][pair[1]]
curr_dict['true_child_pairs'].append((gold_child, alternate_child))
## Find false comment pairs
curr_dict['false_child_pairs'] = []
for pair in selected_pairs[num_child_comments]:
gold_child = child_dict[comment_name][pair[0]]
bad_child = random_comments[curr_random]
curr_random = (curr_random+1)%len(random_comments)
curr_dict['false_child_pairs'].append((gold_child, bad_child))
## Find entire context
curr_dict['context'] = []
curr = comment_name
while curr in parent_dict:
curr_dict['context'].append(curr)
curr = parent_dict[curr]
curr_dict['context'].append(curr)
useful_comments.append(curr_dict)
## Dump to file
with open(data_path+output_file_name+split+'.txt','w') as f:
for comment in logProgress(useful_comments):
for pair in comment['true_child_pairs']:
f.write(str(comment['context'])+'\t')
f.write(pair[0]+'\t')
f.write(pair[1]+'\t')
f.write('1\n')
for pair in comment['false_child_pairs']:
f.write(str(comment['context'])+'\t')
f.write(pair[0]+'\t')
f.write(pair[1]+'\t')
f.write('0\n')
|
Markdown
|
UTF-8
| 882
| 2.625
| 3
|
[] |
no_license
|
# Article D546-4
Lorsque le prévenu n'était pas présent à l'audience, la décision du juge de l'application des peines prévue par le troisième
alinéa de l'article 741-2 doit intervenir dans un délai de quatre mois à compter de la date à laquelle la condamnation lui a
été notifiée.
**Nota:**
Aux termes du premier alinéa de l’article 7 du décret n° 2020-81 du 3 février 2020, conformément aux dispositions de
l'article 112-2 du code pénal et de la première phrase du XIX de l'article 109 de la loi n° 2019-222 du 23 mars 2019, les
présentes
<font color="black">dispositions entrent en vigueur le 24 mars 2020 pour les condamnations prononcées à compter de cette
date, y compris si elles concernent des infractions commises avant cette date.</font>
**Liens relatifs à cet article**
_Créé par_:
- Décret n°2020-81 du 3 février 2020 - art. 4
|
Swift
|
UTF-8
| 429
| 2.921875
| 3
|
[] |
no_license
|
//
// Reward.swift
// Rewardr
//
// Created by Kenny on 4/19/20.
// Copyright © 2020 Hazy Studios. All rights reserved.
//
import Foundation
//MARK: - Codable -
typealias RewardRep = [UUID:Reward]
//MARK: - Object -
struct Reward: Codable, Equatable {
let id: UUID
let name: String
var points: Int
// MARK: Equatable
static func == (lhs: Reward, rhs: Reward) -> Bool {
lhs.id == rhs.id
}
}
|
Java
|
UTF-8
| 625
| 3
| 3
|
[
"MIT"
] |
permissive
|
package db;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import logging.Logger;
public class FileOperations {
public static void writeFile(String file, String text, boolean append) {
BufferedWriter fileWriter = null;
try {
fileWriter = new BufferedWriter(new FileWriter(file, append));
} catch (IOException e) {
Logger.error("Could not find file: " + file);
Logger.logStackTrace(e);
}
try {
fileWriter.write(text);
fileWriter.close(); // Close calls flush
} catch (IOException e1) {
Logger.logStackTrace(e1);
}
}
}
|
Shell
|
UTF-8
| 1,782
| 4.0625
| 4
|
[] |
no_license
|
#!/bin/bash
#Script to identify java VM. Also modifies classpath on cygwin.
#Also used to instantiate headless version of Mesquite.
#Written by Travis Wheeler (www.traviswheeler.com)
#If you find bugs or modify the script to improve functionality,
# please let us know so we can improve the script for everyone
# Thanks to William Cook (http://www.cs.utexas.edu/users/wcook/) for the bit that
# identifies the path containing this script, and uses it to set the classpath.
# (the exact site of the work that served as inspiration for this code is lost to antiquity)
#To increase memory allocation adjust the following line: e.g. to
#mem="500M"
mem="2G"
#figure out where java lives
if [ $NINJA_JAVA_HOME ]
then
java="$NINJA_JAVA_HOME/bin/java"
elif [ $JAVA_HOME ]
then
java="$JAVA_HOME/bin/java"
else
tmp=`java -version 2>&1`
if echo "$tmp" | grep -q "command not found" # no "java", so try "jre"
then
tmp=`jre -version 2>&1`
if echo "$tmp" | grep -q "command not found"
then
echo "Can't find java. Try setting either the JAVA_HOME environment variable"
exit
else
java="jre"
fi
else
java="java"
fi
fi
# figure out where I live, then run java w/ my containing dir as classpath
dir=`dirname "$0"`
os=`uname`
if test ${os:0:6} = "CYGWIN"
then
if test ${dir:1:8} = "cygdrive"
then
dir="${dir:10:1}:/${dir:12}"
fi
fi
abspath="$(cd "${0%/*}" 2>/dev/null; echo "$PWD"/"${0##*/}")"
path_only=`dirname "$abspath"`
cmd="$java -server -Xmx$mem -jar $path_only/Ninja.jar $*"
echo "running the following java command:" 1>&2
echo "$cmd" 1>&2
$cmd
#When a script ends with an exit that has no parameter, the exit status of the script is the exit status of the last command executed in the script (previous to the exit).
|
Markdown
|
UTF-8
| 2,102
| 2.59375
| 3
|
[] |
no_license
|
# WES upload
CIDC Whole Exome Pipeline is a computational workflow for identifying somatic variants from tumor sample. The pipeline includes
tools for quality control (QC) and characterization of paired (tumor/normal) whole exome sequencing data.
## WES Workflow Overview
1. The CIMAC technician who is performing the experiment will download a copy of the WES metadata spreadsheet template via the CIDC portal.
2. The CIMAC technician will begin populating the metadata spreadsheet.
(**NOTE** If the biospecimens have not be relabled to use CIMAC ids, then the technician should *digitally* re-label the sample by replacing the native identifiers with the CIMAC ID when loading the samples into the machine.)
3. The CIMAC technician will perform the experiment and data analysis.
4. The CIMAC technician or CIMAC bioinformatics support will fill in the columns of the metadata spreadsheet.
5. The CIMAC technician or CIMAC bioinformatics support will transfer the metadata and files to CIDC using the command line tool.
## WES files
Each Whole Exome Sequencing experiment requires fastq files and a config file. **NOTE** CIDC will process the fastq files into derivative results in a seperate process coordinated by the CIDC bioinformatics team.
Example directory for WES data transfer:
```
.
├── fwd.1.1.1.fastq.gz
├── fwd.2.2.2.fastq.gz
├── rev.1.1.1.fastq.gz
├── rev.2.2.2.fastq.gz
├── rgm.1.1.1.txt
├── rgm.2.2.2.txt
├── wes_metadata_082919.xlsx
```
## WES metadata
Click [here](https://cimac-cidc.github.io/cidc-schemas/docs/templates.metadata.wes_template.html) to see the specific metadata collected for the WES assay.
Click [here](https://github.com/CIMAC-CIDC/cidc-schemas/blob/master/template_examples/wes_template.xlsx) to see an example of a metadata xlsx file.
## Uploading Files
**Start the CLI and use your JWT to log in**
```bash
cidc login [token]
```
**Run upload command:**
```bash
cidc assays upload --assay wes --xlsx wes_metadata_082919.xlsx
```
The process will then use the metadata file to upload the required files.
|
Java
|
UTF-8
| 1,497
| 3.296875
| 3
|
[] |
no_license
|
import java.util.LinkedList;
//这是一个Trie树
public class TT {
private class node {
char con;
boolean isE;
int count;
LinkedList<node> son;
public node(char ch){
son = new LinkedList<node>();
isE = false;
con = ch;
count = 0;
}
public node position(char ch) {
if (son != null) {
for (node each : son){
if (each.con == ch) {
return each;
}
}
}
return null;
}
}
private node root;
TT() {
root = new node(' ');
}
public void add(String name) {
if (ex(name)) return;
node now = root;
for (int i = 0; i < name.length(); i++){
char ch = name.charAt(i);
node ason = now.position(ch);
if (ason != null) {
now = ason;
}else {
now.son.add(new node(ch));
now = now.position(ch);
}
now.count ++;
}
now.isE = true;
}
public boolean ex(String name) {
node now = root;
for (int i = 0; i < name.length(); i ++) {
char ch = name.charAt(i);
if (now.position(ch) == null) {
return false;
}else {
now = now.position(ch);
}
}
return now.isE;
}
}
|
C++
|
UTF-8
| 1,394
| 3.03125
| 3
|
[] |
no_license
|
#ifndef MONSTER
#define MONSTER
#include "humanoids.h"
#include <iostream> //include input output stream library
#include <vector> //include the vector library
#include <cmath> //include the c math library
#include <cstdlib> //include the c standard library
#include <string> //include string library
//using commonly used terms
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
//the barbarian class subclass of humanoids
class monster: public humanoids
{
private:
string name; //stores the name of the room
public:
//accepts large amount of ints, which respectively are set equal to the monsters stats
monster(string name, int HP, int ADT, int DDT, int ADN, int DDN, int armor) //barbarian constructor feeds barbarian stat values to the humanoids constructor
:humanoids("monster", armor, HP, ADT, DDT, ADN, DDN, false, HP, false, false, name)
{
}
int the_attack(humanoids *a); //attack function, the pointer to their target as a paramter
int the_defense(); //defense function, rolls and returns defensive dice
void refresh(); //refreshes the barbarian's strength and hamstring status
void resolve_damage(int a); //resolve damage accepts int and alters barbarians strength
void hamstring(); //hamstring sets barbarians hamstring value to true
};
#endif
|
C++
|
UTF-8
| 10,988
| 3.421875
| 3
|
[] |
no_license
|
#pragma once
#include "Vector3D.h"
#include "Vector4D.h"
namespace ae
{
//------------------------------------------------------------------
inline uint getAlpha(uint Color)
{
return Color >> 24;
}
inline uint getRed(uint Color)
{
return (Color >> 16) & 0xFF;
}
inline uint getGreen(uint Color)
{
return (Color >> 8) & 0xFF;
}
inline uint getBlue(uint Color)
{
return Color & 0xFF;
}
inline uint getColor(uint Red, uint Green, uint Blue, uint Alpha)
{
return ((Alpha & 0xFF) << 24) | ((Red & 0xFF) << 16) | ((Green & 0xFF) << 8) | (Blue & 0xFF);
}
class color
{
public:
color() :
Red(255),
Green(255),
Blue(255),
Alpha(255)
{
}
color(uchar Brightness) :
Red(Brightness),
Green(Brightness),
Blue(Brightness),
Alpha(255)
{
}
color(uchar R, uchar G, uchar B, uchar A = 255) :
Red(R),
Green(G),
Blue(B),
Alpha(A)
{
}
color(const color &Other) :
Red(Other.Red),
Green(Other.Green),
Blue(Other.Blue),
Alpha(Other.Alpha)
{
}
color(const color &Other, uchar A) :
Red(Other.Red),
Green(Other.Green),
Blue(Other.Blue),
Alpha(A)
{
}
color(const vector3df &Color, bool Adjust = true) :
Red(255),
Green(255),
Blue(255),
Alpha(255)
{
if ( Adjust )
{
Red = static_cast<uchar>(Color.X * 255);
Green = static_cast<uchar>(Color.Y * 255);
Blue = static_cast<uchar>(Color.Z * 255);
Alpha = 255;
}
else
{
Red = static_cast<uchar>(Color.X);
Green = static_cast<uchar>(Color.Y);
Blue = static_cast<uchar>(Color.Z);
Alpha = 255;
}
}
color(const vector4df &Color, bool Adjust = true) :
Red(255),
Green(255),
Blue(255),
Alpha(255)
{
if ( Adjust )
{
Red = static_cast<uchar>(Color.X * 255);
Green = static_cast<uchar>(Color.Y * 255);
Blue = static_cast<uchar>(Color.Z * 255);
Alpha = static_cast<uchar>(Color.W * 255);
}
else
{
Red = static_cast<uchar>(Color.X);
Green = static_cast<uchar>(Color.Y);
Blue = static_cast<uchar>(Color.Z);
Alpha = static_cast<uchar>(Color.W);
}
}
~color()
{
}
/* === Operators - comparisions === */
inline bool operator == (const color &Other) const
{
return Red == Other.Red && Green == Other.Green && Blue == Other.Blue && Alpha == Other.Alpha;
}
inline bool operator != (const color &Other) const
{
return Red != Other.Red || Green != Other.Green || Blue != Other.Blue || Alpha != Other.Alpha;
}
/* === Operators - addition, subtraction, division, multiplication === */
inline color operator + (const color &Other) const
{
return color(Red + Other.Red, Green + Other.Green, Blue + Other.Blue, Alpha + Other.Alpha);
}
inline color& operator += (const color &Other)
{
Red += Other.Red; Green += Other.Green; Blue += Other.Blue; Alpha += Other.Alpha; return *this;
}
inline color operator - (const color &Other) const
{
return color(Red - Other.Red, Green - Other.Green, Blue - Other.Blue, Alpha - Other.Alpha);
}
inline color& operator -= (const color &Other)
{
Red -= Other.Red; Green -= Other.Green; Blue -= Other.Blue; Alpha -= Other.Alpha; return *this;
}
inline color operator / (const color &Other) const
{
return color(Red / Other.Red, Green / Other.Green, Blue / Other.Blue, Alpha / Other.Alpha);
}
inline color& operator /= (const color &Other)
{
Red /= Other.Red; Green /= Other.Green; Blue /= Other.Blue; Alpha /= Other.Alpha; return *this;
}
inline color operator / (uchar Factor) const
{
return color(Red / Factor, Green / Factor, Blue / Factor, Alpha);
}
inline color& operator /= (uchar Factor)
{
Red /= Factor; Green /= Factor; Blue /= Factor; return *this;
}
inline color operator * (const color &Other) const
{
return color(Red * Other.Red, Green * Other.Green, Blue * Other.Blue, Alpha * Other.Alpha);
}
inline color& operator *= (const color &Other)
{
Red *= Other.Red; Green *= Other.Green; Blue *= Other.Blue; Alpha *= Other.Alpha; return *this;
}
inline color operator * (uchar Factor) const
{
return color(Red*Factor, Green*Factor, Blue*Factor, Alpha);
}
inline color& operator *= (uchar Factor)
{
Red *= Factor; Green *= Factor; Blue *= Factor; return *this;
}
inline color operator * (float Factor) const
{
return color(uchar(float(Red)*Factor), uchar(float(Green)*Factor), uchar(float(Blue)*Factor), Alpha);
}
inline color& operator *= (float Factor)
{
Red = uchar(float(Red)*Factor); Green = uchar(float(Green)*Factor); Blue = uchar(float(Blue)*Factor);
return *this;
}
/* === Additional operators === */
inline const uchar operator [] (uint i) const
{
switch ( i )
{
case 0: return Red;
case 1: return Green;
case 2: return Blue;
case 3: return Alpha;
}
return 0;
}
inline uchar& operator [] (uint i)
{
return *(&Red + i);
}
/* === Extra functions === */
inline color getInverse() const
{
return color(255 - Red, 255 - Green, 255 - Blue, 255 - Alpha);
}
inline color& setInverse()
{
Red = 255 - Red, Green = 255 - Green, Blue = 255 - Blue, Alpha = 255 - Alpha;
return *this;
}
inline color getInverse(
bool isRedInverse, bool isGreenInverse, bool isBlueInverse, bool isAlphaInverse = false) const
{
return color(
isRedInverse ? 255 - Red : Red,
isGreenInverse ? 255 - Green : Green,
isBlueInverse ? 255 - Blue : Blue,
isAlphaInverse ? 255 - Alpha : Alpha
);
}
inline color& setInverse(
bool isRedInverse, bool isGreenInverse, bool isBlueInverse, bool isAlphaInverse = false)
{
if ( isRedInverse ) Red = 255 - Red;
if ( isGreenInverse ) Green = 255 - Green;
if ( isBlueInverse ) Blue = 255 - Blue;
if ( isAlphaInverse ) Alpha = 255 - Alpha;
return *this;
}
/**
Sets the color with the specified float array.
This is the opposite function for "getFloatArray".
\see getFloatArray
*/
inline void setFloatArray(const float* ColorArray)
{
if ( ColorArray )
{
Red = static_cast<uchar>(ColorArray[0] * 255);
Green = static_cast<uchar>(ColorArray[1] * 255);
Blue = static_cast<uchar>(ColorArray[2] * 255);
Alpha = static_cast<uchar>(ColorArray[3] * 255);
}
}
/**
Stores the color data into the given float array.
\param[out] ColorArray Pointer to the float array where the color data is to be stored.
This must have at least 4 elements! The components are then in the range [0.0 .. 1.0].
\code
float ColorArray[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
MyColor.getFloatArray(ColorArray);
\endcode
\see setFloatArray
*/
inline void getFloatArray(float* ColorArray) const
{
if ( ColorArray )
{
ColorArray[0] = static_cast<float>(Red) / 255;
ColorArray[1] = static_cast<float>(Green) / 255;
ColorArray[2] = static_cast<float>(Blue) / 255;
ColorArray[3] = static_cast<float>(Alpha) / 255;
}
}
inline void setIntensity(const color &Other)
{
Red = uchar(static_cast<int>(Red)* static_cast<int>(Other.Red) / 255);
Green = uchar(static_cast<int>(Green)* static_cast<int>(Other.Green) / 255);
Blue = uchar(static_cast<int>(Blue)* static_cast<int>(Other.Blue) / 255);
Alpha = uchar(static_cast<int>(Alpha)* static_cast<int>(Other.Alpha) / 255);
}
inline color getIntensity(const color &Other) const
{
color clr(*this);
clr.setIntensity(Other);
return clr;
}
inline void setIntensity(float Intensity)
{
Red = static_cast<uchar>(Intensity * Red);
Green = static_cast<uchar>(Intensity * Green);
Blue = static_cast<uchar>(Intensity * Blue);
Alpha = static_cast<uchar>(Intensity * Alpha);
}
inline color getIntensity(float Intensity) const
{
color clr(*this);
clr.setIntensity(Intensity);
return clr;
}
inline void set(uchar R, uchar G, uchar B, uchar A)
{
Red = R; Green = G; Blue = B; Alpha = A;
}
inline uint getSingle() const
{
return getColor(Red, Green, Blue, Alpha);
}
inline void setSingle(uint Color)
{
Red = getRed(Color);
Green = getGreen(Color);
Blue = getBlue(Color);
Alpha = getAlpha(Color);
}
inline bool equal(const color &Other, bool isIncludingAlpha = true) const
{
return Red == Other.Red && Green == Other.Green && Blue == Other.Blue && (!isIncludingAlpha || Alpha == Other.Alpha);
}
//! Returns true if the color is gray scaled, i.e. all color components (red, green and blue) are equal.
inline bool gray() const
{
return Red == Green && Green == Blue;
}
//! \todo Rename to "getVector3"
vector3df getVector(bool Adjust = false) const
{
if ( !Adjust )
{
return vector3df(
static_cast<float>(Red), static_cast<float>(Green), static_cast<float>(Blue)
);
}
return getVector(false) / 255.0f;
}
vector4df getVector4(bool Adjust = false) const
{
if ( !Adjust )
{
return vector4df(
static_cast<float>(Red), static_cast<float>(Green), static_cast<float>(Blue), static_cast<float>(Alpha)
);
}
return vector4df(
static_cast<float>(Red) / 255.0f,
static_cast<float>(Green) / 255.0f,
static_cast<float>(Blue) / 255.0f,
static_cast<float>(Alpha) / 255.0f
);
}
template <typename T> inline T getBrightness() const
{
return static_cast<T>((static_cast<int>(Red)+static_cast<int>(Green)+static_cast<int>(Blue)) / 3);
}
/* === Static members === */
static const color empty; //!< color(0, 0, 0, 0). \deprecated
static const color red; //!< color(255, 0, 0, 255). \deprecated
static const color green; //!< color(0, 255, 0, 255). \deprecated
static const color blue; //!< color(0, 0, 255, 255). \deprecated
static const color yellow; //!< color(255, 255, 0, 255). \deprecated
static const color pink; //!< color(255, 0, 255, 255). \deprecated
static const color black; //!< color(0, 0, 0, 255). \deprecated
static const color white; //!< color(255, 255, 255, 255). \deprecated
static const color EMPTY; //!< color(0, 0, 0, 0).
static const color RED; //!< color(255, 0, 0, 255).
static const color GREEN; //!< color(0, 255, 0, 255).
static const color BLUE; //!< color(0, 0, 255, 255).
static const color YELLOW; //!< color(255, 255, 0, 255).
static const color PINK; //!< color(255, 0, 255, 255).
static const color BLACK; //!< color(0, 0, 0, 255).
static const color WHITE; //!< color(255, 255, 255, 255).
uchar Red, Green, Blue, Alpha;
};
//------------------------------------------------------------------
} // namespace ae
|
Markdown
|
UTF-8
| 759
| 2.671875
| 3
|
[] |
no_license
|
(83) Afin de déterminer ce que signifie le fait de communiquer l’information en temps utile avant le moment spécifié dans la présente directive, il convient que l’entreprise d’investissement prenne en considération, en tenant compte de l’urgence de la situation, le besoin qu’a le client de disposer de suffisamment de temps pour la lire et la comprendre avant de prendre une décision d’investissement. Un client aura probablement besoin de davantage de temps pour passer en revue des informations s’il s’agit d’un service ou d’un produit complexe ou qui ne lui est pas familier ou qu’il n’a jamais expérimenté que s’il s’agit d’un produit ou d’un service plus simple ou plus familier ou qu’il a déjà expérimenté.
|
C#
|
UTF-8
| 3,909
| 2.734375
| 3
|
[] |
no_license
|
/**
* Created by KanishkaUdapitiya on 10/22/2016.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cafe_Management_System
{
class Cafe
{
// Default Constructor
public Cafe()
{
newlatte_Coff = 0.0;
newespresson = 0.0;
newIced_Latte = 0.0;
newvalee_Coff = 0.0;
newafri_Coff = 0.0;
newameri_Coff = 0.0;
newcapp_Coff = 0.0;
newiceCapp_Coff = 0.0;
newc_Cake = 0.0;
newv_Cake = 0.0;
newbF_Cake = 0.0;
newcB_Cake = 0.0;
newcL_Cake = 0.0;
newcK_Cake = 0.0;
newR_Cake = 0.0;
newK_Cake = 0.0;
}
// Overload Constructor
public Cafe(double latte_Coff, double espresson, double iced_Latte,double vale_Coff, double afri_Coff, double ameri_Coff, double capp_Coff, double iCapp_Coff, double c_Cakes, double vl_Cakes, double bf_Cakes, double cb_Cakes, double cl_Cakes, double ck_Cakes, double r_Cakes, double k_Cakes)
{
// Coffee
newlatte_Coff = latte_Coff;
newespresson = espresson;
newIced_Latte = iced_Latte;
newvalee_Coff = vale_Coff;
newafri_Coff = afri_Coff;
newameri_Coff = ameri_Coff;
newcapp_Coff =capp_Coff;
newiceCapp_Coff = iCapp_Coff;
// Cake
newc_Cake = c_Cakes;
newv_Cake =vl_Cakes;
newbF_Cake = bf_Cakes;
newcB_Cake = cb_Cakes;
newcL_Cake = cl_Cakes;
newcK_Cake = ck_Cakes;
newR_Cake = r_Cakes;
newK_Cake = k_Cakes;
}
// Accessor Functions
public double getlatte_Coff()
{
return newlatte_Coff;
}
public double getespresson()
{
return newespresson;
}
public double geticed_Latte()
{
return newIced_Latte;
}
public double getvale_Coff()
{
return newvalee_Coff;
}
public double getafri_Coff()
{
return newafri_Coff;
}
public double getameri_Coff()
{
return newameri_Coff;
}
public double getcapp_Coff()
{
return newcapp_Coff;
}
public double getiCapp_Coff()
{
return newiceCapp_Coff;
}
public double getc_Cakes()
{
return newc_Cake;
}
public double getvl_Cakes()
{
return newv_Cake;
}
public double getbf_Cakes()
{
return newbF_Cake;
}
public double getcb_Cakes()
{
return newcB_Cake;
}
public double getcl_Cakes()
{
return newcL_Cake;
}
public double getck_Cakes()
{
return newcK_Cake;
}
public double getr_Cakes()
{
return newR_Cake;
}
public double getk_Cakes()
{
return newK_Cake;
}
// Memeber Variables Declared For Coffe
private double newlatte_Coff;
private double newespresson;
private double newIced_Latte;
private double newvalee_Coff;
private double newafri_Coff;
private double newameri_Coff;
private double newcapp_Coff;
private double newiceCapp_Coff;
// Member Variables Declared For Cake
private double newc_Cake;
private double newv_Cake;
private double newbF_Cake;
private double newcB_Cake;
private double newcL_Cake;
private double newcK_Cake;
private double newR_Cake;
private double newK_Cake;
}
}
|
C#
|
UTF-8
| 588
| 3.09375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Division : Operacion
{
private int num1;
private int num2;
public Division()
{
this.num1 = 0;
this.num2 = 0;
}
public Division(int num1, int num2)
{
this.num1 = num1;
this.num2 = num2;
}
public override decimal dividir()
{
return (decimal)this.num1 / (decimal)this.num2;
}
}
}
|
Markdown
|
UTF-8
| 5,775
| 3.09375
| 3
|
[] |
no_license
|
#### Guide to UIST 2019
###### General goals
* What problems are you solving or what opportunities are you seizing?
*Problems:*
1. Assessment of user experience in 3D while interacting with objects at different levels of depth.
2. It is unclear how to switch seamlessly between multiple interactive contexts in mixed reality that are placed at different depths in respect to the user.
3. Midas touch problem with gaze interaction in 3D. The majority (if not all) solutions to this problem are based on 2D interaction. When we move to 3D, new possibilities to cope with this issue arise.
4. 3D eye gaze estimation is still unreliable when compared to 2D methods.
*Opportunities:*
5. Full or partial gaze-based control over the 3D environment using vergence
6. Novel interaction techniques that leverage depth and focus depth for selection or context-switching
7. Vergence could be a hands-free resource of triggering virtual information in translucent displays without the Midas touch problem, or lack of control and latency typically found in dwell-based selection.
8. There is also an opportunity to come up with technical solutions to come around the lack of reliability in 3D eye gaze estimation.
* What are the previous solutions?
This theme is virtually unexplored. The only work that investigated the use of gaze focus depth as an interaction modality was proposed by Pai et al. at UIST 2016. However, they only assessed the usability of this technique as a scroll-based mechanism between two planes, which were placed between 5 and 25 m in a VR setting.
No new application or use case was actually developed in this case, and no new selection technique was proposed. Besides, gaze ray intersection has been demonstrated to be very unreliable to estimate focus depth. Ideally, accommodation and pupil diameter should also be employed in this case. Moreover, above 5 m of depth, gaze vectors are virtually parallel in any commercial video-based eye tracking system, so it seems that this distance was not scaled properly (e.g., if it was between 0.5 and 2.5 m, it would make much more sense). Finally, this is study is confined to VR and cannot be applied to AR or mixed reality systems, in general.
Another study that conjectured the use of gaze focus depth for interaction was proposed in a short paper at ISMAR 2015. In this work, authors considered vergence as a response to build a new visualization method that allows for some sort of "X-ray vision".
* How (well) can you solve the problem?
This problem could be solved by leveraging the latest findings in 3D eye gaze estimation, showing that multi feature-based techniques can actually improve focus depth estimation [ETRA 2018], and also that geometry-based procedures provide higher stability while navigating through different depth planes [COGAIN 2018]. With a hybrid approach, it is possible to have a reasonable 3D eye gaze estimation that can support a reliable transition between multiple depth planes.
Given that we can solve the major technical issues, the next step is to design how we interact using vergence. Simply put, we rarely perform this kind of movement without stimuli, even though it is possible to consciously converge or diverge the eyes in a single direction. Therefore, it sounds sensible to place visual cues in our augmented virtual layer of the world to guide the eyes, so that convergence can be performed seamlessly. These cues could be virtual spheres hovering in the space near a selectable object that show a converging path in the direction of the user once he sits his eyes upon one of these spheres. Another possibility is to show this converging path in respect to the selectable object, that is, once the user fixates over an object, a translucent path with markings is shown, in which the markings indicate planes of interaction. In the case of translucent physical displays, such as home or car windows, we could overlay virtual information on top of it when the user is actually gazing on them.
Vergence could also be a high-latency movement and an uncomfortable one when performed repetitively, thus it is not recommended to design an interaction process in which vergence is used as a rapid selection mechanism. Thus, we see it as more suitable to discriminate unambiguously different interactive contexts, in a way, similar to a "toggle" button. Using like that, we can transit between multiple depths without the explicit indication through gestures, mechanical switches, or other kind of toggling.
When moving between planes, vergence could also have a secondary role as a selection mechanism that does not rely on dwell-time or is subject to the Midas touch problem -- at least not in the same level as other 2D techniques. By fixating on some button shown on a virtual plane and then diverging the eyes to focus on a physical device linked to this plane, we could trigger this button function without explicit gestures. It is as if almost we were using the Midas touch problem for selection.
* What is the main contribution of this work to the field?
The main contribution would be a hands-free interaction technique that is based on multiple depth interfacing. The key feature would be the use of vergence to his end. Such choice also implicates other secondary contributions, such as:
* technical improvements over 3D eye gaze estimation
* design of vergence-based interfaces (Pai et al. suggested it, but they have never done it)
###### Paper-related
* Is the paper complete?
* Does the paper contain too much information?
* Can this paper be presented well?
* Does this paper present good quality?
|
C#
|
UTF-8
| 5,691
| 3
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using QuanLyDayDep;
// Sử dụng đối tượng MessageBox
namespace QuanLyDayDep
{
//string sql;
class Functions
{
public static SqlConnection con; //Khai báo đối tượng kết nối . biến toàn cục.muốn dùng có thể gọi trưc tiếp
//tạo phương thức connection
public static void Connect()
{
con = new SqlConnection(); //Khởi tạo đối tượng
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=CuaHangGiayDep;Integrated Security=True";
con.Open(); //Mở kết nối
//Kiểm tra kết nối
if (con.State == ConnectionState.Open)
MessageBox.Show("Kết nối thành công");
else MessageBox.Show("Không thể kết nối với dữ liệu");
}
public static void Disconnect()
{
if (con.State == ConnectionState.Open)
{
con.Close(); //Đóng kết nối
con.Dispose(); //Giải phóng tài nguyên
con = null;
}
}
public static DataTable GetDataToTable(string sql)
{
SqlDataAdapter dap = new SqlDataAdapter(sql,con);
DataTable table = new DataTable();
dap.Fill(table);//đổ kq từ câu lệnh sql vào table
return table;
}
public static void RunSqlDel(string sql)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Functions.con;
cmd.CommandText = sql;
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
cmd.Dispose();
cmd = null;
}
public static bool checkKey(string sql)
{
SqlDataAdapter dap = new SqlDataAdapter(sql, con);
DataTable table = new DataTable();
dap.Fill(table);
if (table.Rows.Count > 0)
return true;
else return false;
}
public static string GetFieldValues(string sql)
{
string ma = "";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
ma = reader.GetValue(0).ToString();
reader.Close();
return ma;
}
public static void FillCombo(string sql, ComboBox cbo, string ma,string ten)
//hiển thị theo tên trong cbo từ đó ánh xạ được cả mã.để chèn vào mã của bảng khác
//mục đích đổ dữ liệu vào cbo
{
SqlDataAdapter dap = new SqlDataAdapter(sql, con);
DataTable table = new DataTable();
dap.Fill(table);
cbo.DataSource = table;
cbo.ValueMember = ma; // Truong gia tri
cbo.DisplayMember = ten;
// cbo.ValueMember = ma; //Trường giá trị//gắn với trường mã
// cbo.DisplayMember = ten; //Trường hiển thị
//string sql = "select *from tblPhong";
//SqlDataAdapter adp = new SqlDataAdapter(sql, con);
//DataTable tabletblPhong = new DataTable();
//adp.Fill(tabletblPhong);
//dataGridView_tblPhong.DataSource = tabletblPhong;
}
public static void RunSql(string sql)
{
SqlCommand cmd; // Khai báo đối tượng SqlCommand
cmd = new SqlCommand(); // Khởi tạo đối tượng
cmd.Connection = Functions.con; // Gán kết nối
cmd.CommandText = sql; // Gán câu lệnh SQL
try
{
cmd.ExecuteNonQuery(); // Thực hiện câu lệnh SQL
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
cmd.Dispose();
cmd = null;
}
public static bool CheckKey(string sql)
{
SqlDataAdapter dap= new SqlDataAdapter(sql,con);
DataTable table = new DataTable();
dap.Fill(table);
if (table.Rows.Count > 0)
return true;
else
return false;
}
public static void RunSQL(string sql)
{
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sql;
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
cmd.Dispose();
cmd = null;
}
//public static void RunSqlDel(string sql)
//{
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = Functions.con;
// cmd.CommandText = sql;
// try
// {
// cmd.ExecuteNonQuery();
// }
// catch (System.Exception)
// {
// MessageBox.Show("Dữ liệu đang được dùng, không thể xóa","Thông báo",
// MessageBoxButtons.OK, MessageBoxIcon.Stop);
// }
// cmd.Dispose();
// cmd = null;
//}
}
}
|
Java
|
UTF-8
| 4,747
| 1.976563
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-gutenberg-2020",
"CC0-1.0",
"BSD-3-Clause"
] |
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.ignite.internal.commandline.snapshot;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.commandline.CommandArgIterator;
import org.apache.ignite.internal.commandline.systemview.SystemViewCommand;
import org.apache.ignite.internal.util.GridStringBuilder;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.visor.snapshot.VisorSnapshotStatusTask;
import org.apache.ignite.internal.visor.snapshot.VisorSnapshotStatusTask.SnapshotStatus;
import static org.apache.ignite.internal.commandline.CommandList.SNAPSHOT;
import static org.apache.ignite.internal.commandline.snapshot.SnapshotSubcommands.STATUS;
import static org.apache.ignite.internal.visor.systemview.VisorSystemViewTask.SimpleType.NUMBER;
import static org.apache.ignite.internal.visor.systemview.VisorSystemViewTask.SimpleType.STRING;
/**
* Command to get the status of the current snapshot operation in the cluster.
*/
public class SnapshotStatusCommand extends SnapshotSubcommand {
/** */
protected SnapshotStatusCommand() {
super("status", VisorSnapshotStatusTask.class);
}
/** {@inheritDoc} */
@Override protected void printResult(Object res, IgniteLogger log) {
if (res == null) {
log.info("There is no create or restore snapshot operation in progress.");
return;
}
SnapshotStatus status = (SnapshotStatus)res;
boolean isCreating = status.operation() == VisorSnapshotStatusTask.SnapshotOperation.CREATE;
GridStringBuilder s = new GridStringBuilder();
if (isCreating)
s.a("Create snapshot operation is in progress.").nl();
else
s.a("Restore snapshot operation is in progress.").nl();
s.a("Snapshot name: ").a(status.name()).nl();
s.a("Operation request ID: ").a(status.requestId()).nl();
s.a("Started at: ").a(DateFormat.getDateTimeInstance().format(new Date(status.startTime()))).nl();
s.a("Duration: ").a(X.timeSpan2DHMSM(System.currentTimeMillis() - status.startTime())).nl()
.nl();
s.a("Estimated operation progress:").nl();
log.info(s.toString());
List<String> titles = isCreating ? F.asList("Node ID", "Processed, bytes", "Total, bytes", "Percent") :
F.asList("Node ID", "Processed, partitions", "Total, partitions", "Percent");
List<List<?>> rows = status.progress().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(e -> {
UUID nodeId = e.getKey();
long processed = e.getValue().get1();
long total = e.getValue().get2();
if (total <= 0)
return F.asList(nodeId, "unknown", "unknown", "unknown");
String percent = (int)(processed * 100 / total) + "%";
if (isCreating)
return F.asList(nodeId, U.humanReadableByteCount(processed), U.humanReadableByteCount(total), percent);
else
return F.asList(nodeId, processed, total, percent);
}).collect(Collectors.toList());
SystemViewCommand.printTable(titles, F.asList(STRING, NUMBER, NUMBER, NUMBER),
rows, log);
log.info(U.nl());
}
/** {@inheritDoc} */
@Override public void parseArguments(CommandArgIterator argIter) {
if (argIter.hasNextSubArg())
throw new IllegalArgumentException("Unexpected argument: " + argIter.peekNextArg() + '.');
}
/** {@inheritDoc} */
@Override public void printUsage(IgniteLogger log) {
usage(log, "Get the status of the current snapshot operation:", SNAPSHOT, STATUS.toString());
}
}
|
PHP
|
UTF-8
| 5,676
| 2.796875
| 3
|
[] |
no_license
|
<?php
require_once("config.php");
?>
<?php
$sid = $_POST['sid'];
$res= mysqli_query($con,"select distinct class_id , courses_enrolled from student where sid='$sid'");
while($row= mysqli_fetch_array($res))
{
$res2= mysqli_query($con,"select table_name from information_schema.tables where table_type='base table' and table_name like '$row[0]%$row[1]'" );
while($row2=mysqli_fetch_array($res2))
{
//echo $row2[0];
$table=$row2['table_name'];
$lec="select column_name from information_schema.columns where table_name='$table' and column_name like '2018%L'";
$prac="select column_name from information_schema.columns where table_name='$table' and column_name like '2018%P'";
$tut="select column_name from information_schema.columns where table_name='$table' and column_name like '2018%T'";
$if_L=mysqli_query($con,"select lecture from department where Courses='$row[1]'");
$if_P=mysqli_query($con,"select practical from department where Courses='$row[1]'");
$if_T=mysqli_query($con,"select tut from department where Courses='$row[1]'");
$if_lec=mysqli_fetch_array($if_L);
$if_prac=mysqli_fetch_array($if_P);
$if_tut=mysqli_fetch_array($if_T);
$string=null;
$string1=null;
$string2=null;
$attended_L[0]=0;
$attended_P[0]=0;
$attended_T[0]=0;
$result_L=mysqli_query($con,$lec);
$result_P=mysqli_query($con,$prac);
$result_T=mysqli_query($con,$tut);
while($col=mysqli_fetch_array($result_L))
{
$column=$col['column_name'];
if ($string == null)
$string = $column;
else
$string = $string . " + " . $column;
}
while($col=mysqli_fetch_array($result_P))
{
$column=$col['column_name'];
if ($string1 == null)
$string1 = $column;
else
$string1 = $string1 . " + " . $column;
}
while($col=mysqli_fetch_array($result_T))
{
$column=$col['column_name'];
if ($string2 == null)
$string2 = $column;
else
$string2 = $string2 . " + " . $column;
}
echo "<table border='1'>";
echo "<th colspan='10'>";
echo "$row[1]";
echo "</th>";
echo "<tr>";
echo "<td>";
echo "SID";
echo "</td>";
echo "<td>";
echo "Name";
echo "</td>";
if($if_lec[0])
{
echo "<td>";
echo "LECTURES HELD";
echo "</td>";
}
if($if_prac[0])
{
echo "<td>";
echo "PRACTICALS HELD";
echo "</td>";
}
if($if_tut[0])
{
echo "<td>";
echo "TUTORIALS HELD";
echo "</td>";
}
if($if_lec[0])
{
echo "<td>";
echo "LECTURES ATTENDED";
echo "</td>";
}
if($if_prac[0])
{
echo "<td>";
echo "PRACTICALS ATTENDED";
echo "</td>";
}
if($if_tut[0])
{
echo "<td>";
echo "TUTORIALS ATTENDED";
echo "</td>";
}
echo "<td>";
echo "PERCENTAGE ATTENDANCE";
echo "</td>";
echo "<td>";
echo "ATTENDANCE SHORT";
echo "</td>";
echo "</tr>";
if($string != null)
{$myquery= "select $string from $table where SID='$sid'";
$myres= mysqli_query($con,$myquery);
$attended_L=mysqli_fetch_array($myres);
}
if($string1 != null)
{$myquerya= "select $string1 from $table where SID='$sid'";
$myresa= mysqli_query($con,$myquerya);
$attended_P=mysqli_fetch_array($myresa);
}
if($string2 != null)
{$myqueryb= "select $string2 from $table where SID='$sid'";
$myresb= mysqli_query($con,$myqueryb);
$attended_T=mysqli_fetch_array($myresb);
}
$second_query="SELECT count(*) FROM information_schema.columns WHERE table_name = '$table' and column_name like '%L'";
$myres2=mysqli_query($con,$second_query);
$third_query="SELECT count(*) FROM information_schema.columns WHERE table_name = '$table' and column_name like '%T'";
$myres3=mysqli_query($con,$third_query);
$fourth_query="SELECT count(*) FROM information_schema.columns WHERE table_name = '$table' and column_name like '%P'";
$myres4=mysqli_query($con,$fourth_query);
$fifth_query="select distinct Sname from student where SID='$sid'";
$myres5=mysqli_query ($con,$fifth_query);
$held_L=mysqli_fetch_array($myres2);
$held_T=mysqli_fetch_array($myres3);
$held_P=mysqli_fetch_array($myres4);
$held=$held_L[0] + $held_T[0] + 2* ($held_P[0]);
$attended=$attended_L[0] + $attended_T[0] + 2*$attended_P[0];
$names=mysqli_fetch_array($myres5);
if($held == 0)
$percent=100;
else
$percent = ($attended / $held) * 100;
$short = 0;
if ( $percent < 75 )
$short=1;
echo "<tr>";
echo "<td>";
echo $sid;
echo "</td>";
echo "<td>";
echo $names[0];
echo "</td>";
if($if_lec[0])
{
echo "<td>";
echo $held_L[0];
echo "</td>";
}
if($if_prac[0])
{
echo "<td>";
echo $held_P[0];
echo "</td>";
}
if($if_tut[0])
{
echo "<td>";
echo $held_T[0];
echo "</td>";
}
if($if_lec[0])
{
echo "<td>";
echo $attended_L[0];
echo "</td>";
}
if($if_prac[0])
{
echo "<td>";
echo $attended_P[0];
echo "</td>";
}
if($if_tut[0])
{
echo "<td>";
echo $attended_T[0];
echo "</td>";
}
echo "<td>";
echo $percent;
echo "</td>";
if($short)
{
echo "<td>";
echo "YES";
echo "</td>";
}
else
{
echo "<td>";
echo "NO";
echo "</td>";
}
echo "</tr>";
echo "</table>";
}
}
?>
|
Rust
|
UTF-8
| 10,645
| 2.78125
| 3
|
[] |
no_license
|
#![warn(const_err, clippy::all)]
use parser::section::ByteSection;
use parser::tokenizer::{compress_next_token, utils::is_whitespace, Token};
use parser::validator::{ValidationContext, ValidationError, ValidationState, Validator};
use parser::{JsonPath, JsonPathSegment, JsonType};
use log::*;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::io::{self, stdin, Read, Write};
use derive_more::From;
#[derive(Debug, From)]
enum Error {
Io(io::Error),
Validation(ValidationError),
}
#[derive(Debug, Default)]
struct Output {
url: Option<String>,
title: Option<String>,
}
impl fmt::Display for Output {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(
fmt,
r#"{{"url":{},"title":{}}}"#,
self.url.as_ref().unwrap(),
self.title.as_ref().unwrap()
)
}
}
impl Output {
fn is_invalid(&self) -> bool {
self.url.is_none() || self.title.is_none()
}
}
fn entrypoint(input: &[u8]) -> Result<(), Error> {
let mut validator = Validator::new();
let mut last_state = ValidationState::Incomplete;
let stdout = io::stdout();
let mut stdout = stdout.lock();
let mut path: Vec<JsonPathSegment> = Vec::new();
// TODO(ashkan): make the output ordered.
let mut outputs: HashMap<JsonPath, Output> = Default::default();
let mut ordering: Vec<JsonPath> = Vec::new();
macro_rules! flush_outputs {
() => {
for key in ordering.drain(..) {
let output = &outputs[&key];
if !output.is_invalid() {
writeln!(stdout, "{}", output)?;
}
}
outputs.clear();
};
}
macro_rules! lookup_output {
($key:expr) => {{
use std::collections::hash_map::Entry;
match outputs.entry($key) {
Entry::Occupied(occupied) => occupied.into_mut(),
Entry::Vacant(vacant) => {
ordering.push(vacant.key().clone());
vacant.insert(Default::default())
}
}
}};
}
let mut section = ByteSection::new(input);
while let Ok(token) = compress_next_token(&mut section, is_whitespace) {
if token.is_whitespace() {
continue;
}
// Any calculations should be done past this point, since validation is done above.
last_state = validator.process_token(&token)?;
if last_state == ValidationState::Complete {
flush_outputs!();
}
/*
* SKELETON: All tokens are processed at this point, including punctuation, which means
* that you could process the token in this loop as well. Dealing with non-punctuation
* should be done in the:
* - is_start_of_value hook: for the beginning of values
* - is_start_of_value && is_end_of_value hook for values
* - is_start_of_value hook: for the end of values
*
* Example to print tokens eagerly.
*
* token.print(&mut stdout)?;
*/
// token.print(&mut stdout)?;
let token_value_type: Option<JsonType> = token.value_type();
let current_context = validator.current_context();
let token_is_start = token.is_value_start();
let token_is_close = token.is_close();
let is_object_key = current_context == Some(ValidationContext::ObjectEntryKey);
// let is_start_of_value =
// token_is_start && current_context != Some(ValidationContext::ObjectEntryKey);
let is_start_of_value = token_is_start && !is_object_key;
let is_end_of_value = {
// True if we are in a context where we just finished a value.
let is_context_in_value = match current_context {
// None covers the case where our entire value is not an array or object
None => true,
// This covers the case where we just finished processing a value.
Some(ref context) => context.in_value(),
};
(token_is_close || token_is_start) && is_context_in_value
};
/*
* DO calculations after this point
*/
/* Ordering is important here: Change the path before the post-order visit entrypoint so
* that it is correct for the consideration of the parent container.
* Return the last_segment so that you can access the last array index (to get the array
* length) or the last object key (for whatever you might want that for).
*/
let container_last_segment = if let Token::ArrayClose = token {
// Must be popped before doing the post-visit below
path.pop()
} else if token == Token::ObjectClose {
// Must be popped before doing the post-visit below
path.pop()
} else {
None
};
let display_path = JsonPath::new(path.clone().into());
// PREORDER: Results in printing values, arrays, and objects at the start.
if is_start_of_value {
/*
* SKELETON: You can put code here for preorder processing of arrays/objects/values
* This is mostly useful for arrays/objects
*/
match token_value_type {
Some(JsonType::Object) => {
info!("{} = object.start", display_path);
}
Some(JsonType::Array) => {
info!("{} = array.start", display_path);
}
_ => (),
}
};
// INORDER: This can only be the start & end if it is not a container, but a plain value.
if is_start_of_value && is_end_of_value {
/*
* SKELETON: you can access plain values here.
*/
// At this point, you have access to the path and the value
info!("{} = {:?}", display_path, token);
if let Some(key) = display_path.last().and_then(|p| p.as_key()) {
if key == r#""url""# {
if let Some(url) = token.as_string() {
// TODO(ashkan): check if url is already set?
lookup_output!(display_path.parent()).url = Some(url.to_owned());
}
} else if key == r#""title""# {
if let Some(title) = token.as_string() {
lookup_output!(display_path.parent()).title = Some(title.to_owned());
}
}
}
}
// POSTORDER: Results in printing values, arrays, and objects only at the end.
if is_end_of_value {
// SKELETON: You can put code here for postorder processing of arrays/objects/values
// This is mostly useful for arrays/objects
match token_value_type {
Some(JsonType::Object) => {
let last_key = container_last_segment.and_then(|p| p.as_key());
info!("{} = object.end, lastkey={:?}", display_path, last_key,);
// TODO figure out how to make this work.
// if let Some(output) = outputs.get(&display_path) {
// println!("{:?}", output);
// }
}
Some(JsonType::Array) => {
let array_length = container_last_segment
.and_then(|p| p.as_index())
.expect("expected index at path segment");
info!("{} = array.end, length={}", display_path, array_length,);
}
_ => (),
}
}
/* Update the path.
* Path changes should occur:
* - At the start of an array, push 0
* - After a comma for an array element, increment 1
* - After array end, pop
* - At object start, push null
* - At an object key, change key
* - After an object close, pop
*/
match validator.current_context() {
Some(ValidationContext::ObjectStart) => {
/*
* SKELETON: Entrypoint to start of new object.
*/
// Push path for modification
path.push(parser::EMPTY_KEY);
}
Some(ValidationContext::ObjectEntryKey) => {
if let Token::String(new_key) = token {
if let Some(ref mut segment) = path.last_mut() {
if let Some(key) = segment.as_key_mut() {
/*
* SKELETON: Transition from old key to new key. Path is still pointing to the old
*/
// *key = new_key;
*key = match new_key {
Cow::Borrowed(bytes) => {
Cow::Borrowed(unsafe { std::str::from_utf8_unchecked(bytes) })
}
Cow::Owned(bytes) => {
Cow::Owned(unsafe { String::from_utf8_unchecked(bytes) })
}
}
}
/*
* SKELETON: Entrypoint to new key. Path is updated
*/
}
}
}
// Some(ValidationContext::ObjectEnd) | Some(ValidationContext::ArrayEnd) => { }
Some(ValidationContext::ArrayStart) => {
// Set up index path for new values.
// If the array is empty, then this shouldn't be used.
path.push(0.into());
}
Some(ValidationContext::ArrayValue) => {
// I wish I could use this instead.
// try {
// *path.last_mut()?.as_index()? += 1;
// }
// if let Some(n) = path.last_mut().and_then(|p| p.as_index_mut()) {
if let Some(JsonPathSegment::Index(ref mut n)) = path.last_mut() {
*n += 1;
}
}
_ => (),
}
}
validator.finish()?;
flush_outputs!();
Ok(())
}
fn main() -> Result<(), Error> {
env_logger::init();
let mut stdin = stdin();
let mut buffer = Vec::new();
stdin.read_to_end(&mut buffer)?;
entrypoint(&buffer)?;
Ok(())
}
|
Java
|
UTF-8
| 630
| 2.921875
| 3
|
[] |
no_license
|
package com.kodilla.rps;
import java.util.Objects;
public class Shape {
private final String shape;
public Shape(String shape) {
this.shape = shape;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Shape)) return false;
Shape shape1 = (Shape) o;
return Objects.equals(shape, shape1.shape);
}
@Override
public int hashCode() {
return shape != null ? shape.hashCode() : 0;
}
@Override
public String toString() {
return
"'" + shape + '\''
;
}
}
|
Python
|
UTF-8
| 723
| 3.296875
| 3
|
[] |
no_license
|
from flask import jsonify
def resposta(status, message, http_code=200, dados=None):
"""
devolve um string json com formato especifico para as respostas dos endpoints
:param status: True ou False
:param message: string
:param http_code=200: código da requisição
:param dados=None: dados a serem apresentados no retorno
"""
# 0 se status é false e 1 se é true
sts = 1 if status else 0
resposta = {"state": sts, "value": message}
if dados is not None:
z = resposta.copy() # start with x's keys and values
z.update(dados=dados)
resposta = z
response = jsonify(resposta)
response.status_code = http_code
return response
|
Shell
|
UTF-8
| 492
| 3.296875
| 3
|
[] |
no_license
|
#!/bin/bash
if [[ $1 == "" ]] || [[ $2 == "" ]] || [[ $3 == "" ]]; then
echo "Usage: $0 <player_max> <min_pop> <max_pop>"
exit
fi
player_max=$1
min_pop_i=$2
max_pop_i=$(($3 - 1))
max_pop_j=$3
for n in $(seq 1 $player_max); do
for i in $(seq $min_pop_i $max_pop_i); do
min_pop_j=$((i + 1))
for j in $(seq $min_pop_j $max_pop_j); do
if [[ ! -f "output/$n.75.$i.$j.pdf" ]]; then
echo "Generating $n.75.$i.$j.pdf"
./stack-game.py graph $n 75 $i $j
fi
done
done
done
|
Markdown
|
UTF-8
| 270
| 2.546875
| 3
|
[] |
no_license
|
A program to name organic chemical compounds according to the IUPAC guidelines.
Currently supports simple alkanes, alkenes, alkynes and branched forms of them.
The inputs must be in the form of "CCC(C)C=C" (without quotes) and the branches must be the shortest group.
|
Markdown
|
UTF-8
| 700
| 2.71875
| 3
|
[] |
no_license
|
# Android_Adapter_Intent_Most_Populated_Country
using adapter intent and serialisation to pass object around in Android
ListView Custom ArrayAdapter Homework
Learning objectives
Practise creating a listView using a custom ArrayAdapter in an Android App
Task
Create a new Android app that displays a collection of your choice in a list. Maybe different types of trees, a songs chart, or whatever you feel like.
Create a model that returns an ArrayList of your objects.
Create and activity and arraylist adapter that populates a listview with your collection.
Extensions
Include an image for each list item And/Or
Add an onclick to the list items that displays the informtation on a new activity
|
Java
|
UTF-8
| 573
| 2.421875
| 2
|
[] |
no_license
|
package com.jiuxian.example1_sample;
import java.time.LocalDateTime;
/**
* @author: liuzejun
* *
* @email: 857591294@qq.com
* *
* @date: 2019-05-28 12:57:26
* *
* @description: 场景类
**/
public class Main {
public static void main(String[] args) {
IGamePlayer proxy = new GamePlayerProxy(new GamePlayer("张三"));
System.out.println("开始时间:" + LocalDateTime.now());
proxy.login("zhangsan", "123456");
proxy.killBoss();
proxy.upgrade();
System.out.println("结束时间:" + LocalDateTime.now());
}
}
|
C#
|
UTF-8
| 1,405
| 2.8125
| 3
|
[] |
no_license
|
using System;
namespace DataStores
{
public abstract class OrderLine
{
protected OrderLine(Guid id, GoodsType goodsType, int sKU, string? remark)
{
Id = id;
GoodsType = goodsType;
SKU = sKU;
Remark = remark;
}
public Guid Id { get; private set; }
public GoodsType GoodsType { get; private set; }
public int SKU { get; private set; }
public string? Remark { get; private set; }
public abstract Model.OrderLine ToModel();
}
public static class OrderLineExtensions
{
public static OrderLine ToDataContract(this Model.OrderLine orderLine)
{
return orderLine switch
{
Model.BreadOrderLine breadOrderLine => new BreadOrderLine(
breadOrderLine.Id,
breadOrderLine.SKU,
breadOrderLine.Remark,
breadOrderLine.Input?.ToDataContract()
),
Model.PieOrderLine pieOrderLine => new PieOrderLine(
pieOrderLine.Id,
pieOrderLine.SKU,
pieOrderLine.Remark,
pieOrderLine.Input?.ToDataContract()
),
_ => throw new ArgumentException($"Unsupported goodsType ({orderLine.GoodsType})")
};
}
}
}
|
Java
|
UTF-8
| 1,879
| 2.28125
| 2
|
[] |
no_license
|
/*
* Copyright 2010 Ivan Bogicevic, Markus Knauß, Daniel Kulesz, Holger Röder, Matthias Wetzel
*
* This file is part of Jabi.
*
* Jabi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Jabi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Jabi. If not, see <http://www.gnu.org/licenses/>.
*/
package jabi.ui.actions;
import jabi.model.IEntry;
import jabi.model.Model;
import jabi.ui.MainWindow;
import jabi.util.I18N;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
* Deletes the selected entry from Jabi's model.
*/
@SuppressWarnings("serial")
public class DeleteAction extends AbstractAction {
public DeleteAction() {
ImageIcon icon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/jabi/res/note_delete.png")));
putValue(Action.SMALL_ICON, icon);
putValue(Action.NAME, I18N.instance.getMessage("DeleteAction.Label"));
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(
MainWindow.instance, I18N.instance
.getMessage("DeleteAction.Confirm"), I18N.instance
.getMessage("DeleteAction.Label"),
JOptionPane.YES_NO_OPTION)) {
for (IEntry entry : MainWindow.instance.getSelectedEntries()) {
Model.instance.removeEntry(entry);
}
}
}
}
|
Swift
|
UTF-8
| 1,676
| 3.390625
| 3
|
[] |
no_license
|
//
// main.swift
// 0915
//
// Created by 조윤영 on 2021/09/08.
//
import Foundation
var N = 0
var M = 0
var board: [[Int]] = []
var chickens: [(y: Int, x: Int)] = []
var houses: [(y: Int, x: Int)] = []
var answer: Int = 5000
func input() {
let inputList = readLine()!.split(separator: " ").map{ Int($0)! }
N = inputList[0]
M = inputList[1]
for _ in 0..<N {
board.append(readLine()!.split(separator: " ").map{ Int($0)! })
}
for i in 0..<N {
for j in 0..<N {
if board[i][j] == 2 { chickens.append((y: i, x: j))}
else if board[i][j] == 1 { houses.append((y: i, x: j))}
}
}
}
func solution() {
selectChickenHouse(0, selected_chickens: [])
print(answer)
}
func selectChickenHouse(_ idx: Int, selected_chickens: [(y: Int, x: Int)]) {
if selected_chickens.count == M {
//도시의 치킨 거리 계산
var sum = 0
for house in houses {
var chickenDistance = 100
for chicken in selected_chickens {
let distance = abs(house.y - chicken.y) + abs(house.x - chicken.x)
chickenDistance = min(chickenDistance, distance)
}
sum += chickenDistance
}
answer = min(answer, sum)
return
}
guard idx < chickens.count else { return }
var new_selected_chickens = selected_chickens
for i in idx..<chickens.count {
new_selected_chickens.append((y: chickens[i].y, x: chickens[i].x))
selectChickenHouse(i+1, selected_chickens: new_selected_chickens)
new_selected_chickens.removeLast()
}
}
input()
solution()
|
Python
|
UTF-8
| 1,603
| 3.859375
| 4
|
[] |
no_license
|
"""
============================
Author:柠檬班-木森
Time:2020/2/15 12:15
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
break:强制跳出循环
continue:中止当前本轮循环,直接进行下一轮循环的条件判断
pass:没有具体的语义,用来占行,执行到改行代码直接通过,执行下一行
"""
#
# n = 0
# while n < 100:
# n += 1
# print("这是第{}打印:hello python".format(n))
# 需求:打印完第10遍退出循环
# n = 0
# while n < 100:
# n += 1
# print("这是第{}打印:hello python".format(n))
# # 当n等于10的时候,退出循环
# if n == 10:
# break
# 需求:第10遍到第15遍不打印
n = 0
while n < 100:
n += 1
# 当n在10到15之间时,执行continue中止本轮循环,直接进行下一轮循环的条件判断
if 10 <= n <= 15:
# continue
pass
print("这是第{}打印:hello python".format(n))
# 关于pass
# data = {"user": "python27", "pwd": "lemonban"}
# # 第二步:提示用户输入账号,密码
# user = input("请输入账号:")
# pwd = input("请输入密码:")
# # 第三步:判断账号密码是否输入正确
# if user == data["user"]:
# pass
# else:
# print("输入的账号不对")
score = float(input("请输入您的成绩:"))
if 0 <= score < 40:
pass
elif 40 <= score < 60:
pass
elif 60 <= score < 75:
pass
elif 75 <= score < 85:
pass
elif 85 <= score <= 100:
print("您的成绩等级为:A")
else:
print("您输入的成绩有误!")
|
PHP
|
UTF-8
| 2,582
| 2.703125
| 3
|
[] |
no_license
|
<?php
$path = realpath(__DIR__);
$dbfile = 'last.db';
include $path.'/config.php';
date_default_timezone_set("Europe/Istanbul"); // set PDT
$x = simplexml_load_file($rssurl);
$file = 'last.db';
if(!is_file($file)){
$contents = ''; // Some simple example content.
file_put_contents($file, $contents); // Save our content to the file.
}
class OneSignal{
private $app_id;
private $auth_key;
private $api_logo;
public function __construct($app_id, $auth_key, $api_logo){
$this->app_id = $app_id;
$this->auth_key = $auth_key;
$this->api_logo = $api_logo;
}
public function sendMessage($title, $content, $url, $lang = 'en'){
$content = array(
$lang => $content,
);
$heading = array(
$lang => $title,
);
$fields = array(
'app_id' => $this->app_id,
'included_segments' => array('Active Users'),
'contents' => $content,
'url' => $url,
'headings' => $heading,
'chrome_web_icon' => $this->api_logo,
);
$headers = array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic '.$this->auth_key,
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
}
$i = 1;
foreach ($x->channel->item as $item) {
$reallink = readnow($dbfile);
$title = $item->title;
$guid = $item->link;
$desc = $item->description;
$postDate = $item->pubDate;
if($reallink != base64_encode($guid)) {
PushOSNotification($title, $desc, $guid);
writenow($dbfile, $guid);
}
if($i >= 1 ) { break; }
$i++;
}
function writenow($file,$lnk) {
$my_file = $file;
$lnk64 = base64_encode($lnk);
$myfile = file_put_contents($my_file, $lnk64 , LOCK_EX);
}
function readnow($file) {
$my_file = $file;
$handle = fopen($my_file, 'r');
$data = '';
if(filesize($my_file) > 0)
$data = fread($handle,filesize($my_file));
return $data;
fclose($handle);
}
function PushOSNotification($title, $msg, $guid){
$on = new OneSignal($app_id, $auth_key, $api_logo);
$content = $msg;
$url = $guid;
$res = $on->sendMessage($title, $content, $url , $lang = 'en');
$book = json_decode($res, true);
print_r ($book['recipients']);
}
|
JavaScript
|
UTF-8
| 514
| 2.53125
| 3
|
[] |
no_license
|
// TODO 正则表达式匹配用户id 和密码 返回bool值
// 传进的参数值是否是字符串
// user_id【8位数字】
export function is_userID(user_id) {
return true;
}
// password【6-18位,数字+大小写字母】
export function is_password(password) {
return true;
}
// course_id 正整数
export function is_courseID(course_id) {
return true;
}
// student_id 【8位数字】
export function is_studentID(student_id) {
return true;
}
export function is_gps(gps) {
return true;
}
|
Python
|
UTF-8
| 10,149
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
import pandas as pd
import numpy as np
from datetime import datetime, date, timedelta
import requests
import matplotlib.pyplot as plt
from countries import countries_dict
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
def continents ():
date_url = date.today().strftime('%m-%d-%Y')
inputValid = False
continent_list = ['Africa', 'Asia', 'Europa', 'North America', 'Oceania', 'Other', 'South America']
while inputValid == False:
url = r'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/' + date_url + '.csv'
feedback = requests.get(url)
if feedback.status_code != 200:
date_url = (date.today() - timedelta(days=1)).strftime('%m-%d-%Y')
continue
else:
inputValid = True
#Total Cases
df = pd.read_csv(url)
df['Continent'] = df['Country_Region'].map(countries_dict)
table_country = pd.pivot_table(df, values = ['Confirmed', 'Deaths'], index = 'Country_Region', aggfunc = np.sum, margins = True)
table_continent = pd.pivot_table(df, values = ['Confirmed', 'Deaths'], index = 'Continent', aggfunc = np.sum, margins=True).sort_values(by='Confirmed', ascending=False)
table_continent['Mortality'] = (table_continent['Deaths'] / table_continent['Confirmed']).map(lambda n: '{:.2%}'.format(n))
total_confirmed = df['Confirmed'].sum()
total_deaths = df['Deaths'].sum()
#Daily Cases
daily_cases_url = r'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'
df_daily_cases = pd.read_csv(daily_cases_url)
df_daily_cases.insert(2, column = "Continent", value = df_daily_cases['Country/Region'].map(countries_dict))
df_daily_cases['Cases Increase'] = (df_daily_cases.iloc[:,-1] - df_daily_cases.iloc[:,-2])
continent_daily_cases = pd.pivot_table(df_daily_cases, values = ['Cases Increase'], index = 'Continent', aggfunc = np.sum, margins=True)
#get the first avilable date (1/22/20)
dates_list = list(df_daily_cases)[5:-1]
continent_plot_cases = pd.pivot_table(df_daily_cases, values = [dates_list[0]], index = 'Continent', aggfunc = np.sum)
#loop through the dates
for i in range(1, len(dates_list)):
append_df = pd.pivot_table(df_daily_cases, values = [dates_list[i]], index = 'Continent', aggfunc = np.sum)
continent_plot_cases = pd.concat([continent_plot_cases, append_df], axis=1)
#get the daily increases
continent_plot_daily_cases = pd.pivot_table(df_daily_cases, values = [dates_list[0]], index = 'Continent', aggfunc = np.sum)
for i in range(1, len(dates_list)):
continent_plot_daily_cases[dates_list[i]] = continent_plot_cases[dates_list[i]] - continent_plot_cases[dates_list[i - 1]]
continent_plot_cases = continent_plot_cases.T
continent_plot_daily_cases = continent_plot_daily_cases.T
#Daily Deaths
daily_deaths_url = r'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
df_daily_deaths = pd.read_csv(daily_deaths_url)
df_daily_deaths.insert(2, column = "Continent", value = df_daily_cases['Country/Region'].map(countries_dict))
df_daily_deaths['Death Increase'] = (df_daily_deaths.iloc[:,-1] - df_daily_deaths.iloc[:,-2])
continent_daily_deaths = pd.pivot_table(df_daily_deaths, values = ['Death Increase'], index = 'Continent', aggfunc = np.sum, margins=True)
#plot the first avilable date (1/22/20)
dates_list = list(df_daily_deaths)[5:-1]
continent_plot_deaths = pd.pivot_table(df_daily_deaths, values = [dates_list[0]], index = 'Continent', aggfunc = np.sum)
#loop through the dates
for i in range(1, len(dates_list)):
append_df = pd.pivot_table(df_daily_deaths, values = [dates_list[i]], index = 'Continent', aggfunc = np.sum)
continent_plot_deaths = pd.concat([continent_plot_deaths, append_df], axis=1)
#get the daily increases
continent_plot_daily_deaths = pd.pivot_table(df_daily_deaths, values = [dates_list[0]], index = 'Continent', aggfunc = np.sum)
for i in range(1, len(dates_list)):
continent_plot_daily_deaths[dates_list[i]] = continent_plot_deaths[dates_list[i]] - continent_plot_deaths[dates_list[i - 1]]
continent_plot_deaths = continent_plot_deaths.T
continent_plot_daily_deaths = continent_plot_daily_deaths.T
#Concatenate into a single df the cases/deaths tables
df_daily_concat = pd.concat([table_continent, continent_daily_cases, continent_daily_deaths], axis=1)
max_daily_cases = continent_plot_daily_cases.sum(axis = 1).max()
max_daily_deaths = continent_plot_daily_deaths.sum(axis = 1).max()
max_cont_cases_increase = continent_plot_daily_cases.max(axis = 1).max()
max_cont_deaths_increase = continent_plot_daily_deaths.max(axis = 1).max()
id_max_cases = continent_plot_daily_cases.sum(axis = 1).idxmax()
id_max_deaths = continent_plot_daily_deaths.sum(axis = 1).idxmax()
#set negative daily changes equal to 0
continent_plot_daily_cases[continent_plot_daily_cases < 0] = 0
continent_plot_daily_deaths[continent_plot_daily_deaths < 0] = 0
#get the moving average to smooth the daily curves
continent_plot_av_daily_cases = pd.DataFrame()
continent_plot_av_daily_deaths = pd.DataFrame()
for i in list(continent_plot_daily_cases):
continent_plot_av_daily_cases[f"{i}"] = continent_plot_daily_cases[i].rolling(window = 7).mean()
for i in list(continent_plot_daily_deaths):
continent_plot_av_daily_deaths[f"{i}"] = continent_plot_daily_deaths[i].rolling(window = 7).mean()
#Print Output Information
print("\n")
print(f"Last Updated on {date_url}")
print("\n")
print(f"Total Cases {total_confirmed:,} / total deaths {total_deaths:,}. Global Mortality Rate: {total_deaths / total_confirmed:.2%}.")
print("\n")
print(df_daily_concat)
print(f"World Records: most cases {max_daily_cases:,} on {id_max_cases } - most deaths {max_daily_deaths:,} on {id_max_deaths}.")
#converting date to datetime
continent_plot_cases = continent_plot_cases.set_index(pd.to_datetime(continent_plot_cases.index))
continent_plot_daily_cases = continent_plot_daily_cases.set_index(pd.to_datetime(continent_plot_daily_cases.index))
continent_plot_deaths = continent_plot_deaths.set_index(pd.to_datetime(continent_plot_deaths.index))
continent_plot_daily_deaths = continent_plot_daily_deaths.set_index(pd.to_datetime(continent_plot_daily_deaths.index))
continent_plot_av_daily_cases = continent_plot_av_daily_cases.set_index(pd.to_datetime(continent_plot_av_daily_cases .index))
continent_plot_av_daily_deaths = continent_plot_av_daily_deaths.set_index(pd.to_datetime(continent_plot_av_daily_deaths.index))
downloadFig = input("\nDo you want to download the picture (Y/N)?").upper()
#save dataframes to excel
path = r'C:\Users\Filippo Galanti\Desktop\Python Course\Cool Excercises\Covid19\output.xlsx'
with pd.ExcelWriter(path) as writer:
df_daily_concat.to_excel(writer, sheet_name = 'Daily Output')
continent_plot_cases.to_excel(writer, sheet_name = 'Total Cases')
continent_plot_daily_cases.to_excel(writer, sheet_name = 'Daily Cases')
continent_plot_deaths.to_excel(writer, sheet_name = 'Total Deaths')
continent_plot_daily_deaths.to_excel(writer, sheet_name = 'Daily Deaths')
continent_plot_av_daily_cases.to_excel(writer, sheet_name = 'Mov Avg Cases')
continent_plot_av_daily_deaths.to_excel(writer, sheet_name = 'Mov Avg Deaths')
#graph plotting
fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (14, 7), squeeze = False)
color_list = ['#1C2833', '#7D3C98', '#E74C3C', '#27AE60', '#D4AC0D', '#DAF7A6', '#1B4F72']
fig.patch.set_facecolor('#E5E7E9')
continent_plot_cases.plot.line(title = 'Total Cases', legend = True, linewidth = 1, ax = axes[0, 0], grid = True, color = color_list)
axes[0,0].yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f"{int(x):,}"))
axes[0,0].fmt_xdata = mdates.DateFormatter('%B')
axes[0,0].legend(loc = 'best', frameon = True, fontsize = 'small')
axes[0,0].grid(color = 'k', linestyle = '-', linewidth = 0.1)
axes[0,0].set_facecolor('#F2F3F4')
continent_plot_av_daily_cases.plot.area(title = 'Daily Cases', ax = axes[1, 0], legend = False, ylim = (0, max_daily_cases * 1.1),
linewidth = 0.7, grid = True, color = color_list, stacked = True)
axes[1,0].yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f"{int(x):,}"))
axes[1,0].fmt_xdata = mdates.DateFormatter('%B')
axes[1,0].legend(loc = 'best', frameon = True, fontsize = 'small')
axes[1,0].grid(color = 'k', linestyle = '-', linewidth = 0.1)
axes[1,0].set_facecolor('#F2F3F4')
continent_plot_deaths.plot.line(title = 'Total Deaths', legend = False, linewidth = 1, ax = axes[0, 1], grid = True, color = color_list)
axes[0,1].yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f"{int(x):,}"))
axes[0,1].fmt_xdata = mdates.DateFormatter('%B')
axes[0,1].grid(color = 'k', linestyle = '-', linewidth = 0.1)
axes[0,1].set_facecolor('#F2F3F4')
continent_plot_av_daily_deaths.plot.area(title = 'Daily Deaths', ax = axes[1, 1], legend = False, ylim = (0, max_daily_deaths * 1.1),
linewidth = 0.7, grid = True, color = color_list, stacked = True)
axes[1,1].yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f"{int(x):,}"))
axes[1,1].grid(color = 'k', linestyle = '-', linewidth = 0.1)
axes[1,1].fmt_xdata = mdates.DateFormatter('%B')
axes[1,1].set_facecolor('#F2F3F4')
if downloadFig == 'Y':
plt.savefig(fname="Covid19_Continents.png")
plt.show()
|
TypeScript
|
UTF-8
| 1,080
| 3.640625
| 4
|
[
"MIT"
] |
permissive
|
import { Tuple } from "./tuple";
export class Vector extends Tuple {
constructor(public x = 0, public y = 0, public z = 0, public w = 0) {
super(x, y, z, w);
}
static toVector(t: Tuple): Vector {
return new Vector(t.x, t.y, t.z);
}
magnitude(): number {
return Math.sqrt(
Math.pow(this.x, 2) + Math.pow(this.y, 2) + Math.pow(this.z, 2)
);
}
normalize(): Vector {
const magnitude = this.magnitude();
return new Vector(
this.x / magnitude,
this.y / magnitude,
this.z / magnitude
);
}
dot(v: Vector): number {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
cross(v: Vector): Vector {
return new Vector(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
reflect(normalIn: Vector): Vector {
const dotProduct = normalIn.dot(this);
const normalOut = normalIn.subtract(this.multiply(2).multiply(dotProduct));
console.log("reflect", normalOut.x);
return new Vector(normalOut.x, normalOut.y, normalOut.z);
}
}
|
C#
|
UTF-8
| 969
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
namespace patience.core
{
public interface ICommand
{
void Do(Layout layout);
void Undo(Layout layout);
}
public class DealCommand : ICommand
{
public int From { get; set; }
public int To { get; set; }
public void Do(Layout layout)
{
layout.Step(From, To);
}
public void Undo(Layout layout)
{
layout.Step(To, From);
}
}
public class MoveCommand : ICommand
{
public bool FlipTopCard { get; set; }
public string From { get; set; }
public string To { get; set; }
public void Do(Layout layout)
{
layout.Move(From, 1, To);
if(FlipTopCard)
layout.FlipTopCard(From);
}
public void Undo(Layout layout)
{
if (FlipTopCard)
layout.FlipTopCard(From);
layout.Move(To, 1, From);
}
}
}
|
Markdown
|
UTF-8
| 9,194
| 2.859375
| 3
|
[] |
no_license
|
---
title: Android开发艺术(1)——Activity的生命周期和启动模式
date: 2017-09-06 20:26:22
tags:
categories: 阅读笔记
---
# Activity生命周期的分析
从两种情况来分析
- 典型情况(用户正常参与的情况)
- 异常情况(由于内存不足,被系统杀掉、Configuration改变等)
## 典型情况下的生命周期分析
- onPause不能太耗时,因为上一个Activity执行完之后 下个Activity的onCreate/onStart/onResume/onResume才能执行,所以不要在onPause中执行耗时才做,使新的Activity尽快切到前台
```
从Activity1到Activity2
09-06 20:56:55.190 com.xk.chapter1 D/Activity1: onCreate-->
09-06 20:56:55.210 com.xk.chapter1 D/Activity1: onStart-->
09-06 20:56:55.210 com.xk.chapter1 D/Activity1: onResume-->
09-06 20:56:59.500 com.xk.chapter1 D/Activity1: onPause耗时操作开始-->
09-06 20:57:01.510 com.xk.chapter1 D/Activity1: onPause耗时操作结束-->
Activity2出现
09-06 20:57:01.520 com.xk.chapter1 D/Activity2: onCreate-->
09-06 20:57:01.520 com.xk.chapter1 D/Activity2: onStart-->
09-06 20:57:01.520 com.xk.chapter1 D/Activity2: onResume-->
09-06 20:57:01.990 com.xk.chapter1 D/Activity1: onStop-->
从Activity2返回Activity1
09-06 21:01:13.490 com.xk.chapter1 D/Activity2: onPause耗时操作开始-->
09-06 21:01:15.490 com.xk.chapter1 D/Activity2: onPause耗时操作结束-->
Activity1
09-06 21:01:15.490 com.xk.chapter1 D/Activity1: onRestart-->
09-06 21:01:15.490 com.xk.chapter1 D/Activity1: onStart-->
09-06 21:01:15.490 com.xk.chapter1 D/Activity1: onResume-->
09-06 21:01:15.890 com.xk.chapter1 D/Activity2: onStop-->
09-06 21:01:15.890 com.xk.chapter1 D/Activity2: onDestroy-->
```
- onStop可以做一些稍微重量级的操作,不过也别太耗时
- onDestory中可以做资源的释放等操作
- 弹出一个新的Activity,旧的会调onPause->onStop,特殊的,如果新的Activity是透明主题,那么旧的Activity不会调用onStop,因为它仅仅是失去了焦点,无法交互,还是可见的
- onStart、onStop是从是否可见角度来说的,onPause和onResume是从是否位于前台(可交互)角度来说的,除此之外没啥区别。注意第一条。。。
- 启动Activity的请求由Instrumentation来处理,它通过Binder向AMS发送请求,AMS内部维护着一个ActivityStack并且负责栈内Activity的状态同步,AMS通过ActivityThread去同步Activity的状态,从而完成生命周期的回调
## 异常情况下的生命周期
### 资源相关的系统配置发生改变导致Activity被杀死并重新创建
比如横屏和竖屏会使用不同的资源文件,如果屏幕方向发生改变,activity就会被销毁重建,除非我们指定不要让他销毁重建。当然,这种销毁重建会调用onSaveInstanceState来保存activity的状态,重建的时候会调用onRestoreInstanceState来恢复(onSaveInstanceState保存的数据,在onCreate和onRestoreInstanceState中可以拿到)
onRestoreInstanceState会在onStart之前调用
activity被意外终止的时候,activity会调用onSaveInstanceState,然后委托window,接着window委托他内部的view,也就是顶层View(一般是DecorView),然后DecorView委托子View。。。一直往下到每一个View。每个View都有onSaveInstanceState和onRestoreInstanceState方法的。这种机制类似于***事件分发机制***
onSaveInstanceState只有在activity即将被被销毁,并且有机会重建的时候才会被调用。简单理解为就是异常终止,并且会马上重建,对比按返回键销毁和旋转屏幕销毁就好理解了。actvity销毁后保存的数据在onCreate和onRestoreInstanceState中都可以拿到,但是onCreate中需要做非空判断,onRestoreInstanceState不需要,因为onRestoreInstanceState一调用,一定是有数据需要恢复了
按Home键或者启动新Activity仍然会单独触发onSaveInstanceState的调用。因为Home之后或者新的activity出现之后,旧的activity到了后台,都有可能被杀。
### 资源内存不足导致低优先级Activity被杀
activity的优先级
- 前台Activity
- 可见但非前台,比如弹出dialog,我的理解是onPause之后的,不过不一定对,有待探究
- 后台Activity,我的理解是onStop之后的,任玉刚书中说的是暂停后的,感觉有歧义,不太确定,有待探究
如果一个进程中没有四大组件在执行,很快会被杀,所以后台任务一般要在service中运行。我的理解是,如果在activity中开一个线程去做后台任务,activity不在前台的时候就容易被杀,比如回到桌面
如果不想在屏幕旋转后重建activity可以在清单文件中指定configChanges属性,orientation、keyboardHidden,API13之后还需要指定screenSize。去年学这块就是死记,其实现在看来,所有的config(具体查表)改变都会导致Activity重建,这里配置之后,被配置的选项改变不会使activity重建,但会回调onConfigurationChange方法,通知我们改变了,然后根据自己的需求做一些事情就好了。
# Activity的启动模式
## Activity的LaunchMode
当一个任务栈中没有activity的时候,这个栈就会被回收
几种启动模式:
- standard
- singleTop
栈顶复用,当被复用的时候,会调用onNewIntent,参数中可以取到启动新activity携带的intent,并且onCreate、onStart不会被调用
- singleTask
被启动的activity查看是否存在他想要的任务栈,如果存在,就是那样了。。。不存在,就创建任务栈(默认跟启动他的context一样,可以通过taskaffinity指定)
- singleInstance
> adb shell dumpsys activity 查看栈信息
启动一个activity的时候,一般新的activity会在调用startactivity的context所在的任务栈中,但是applicationcontext不存在于任务栈,所以需要为新的activity指定FLAG_ACTIVITY_NEW_TASK标记,不明白为什么在清单文件中指定不行
**TaskAffinity**(任务相关性)可以指定一个activity所需的栈名(默认为他的包名),他只能和singleTask和allowTaskRepareniting配合使用,其他情况无效
如果没有指定TaskAffinity,新启动的activity会继承启动他activity的栈(singleInstance会进入新的栈,但是实验发现,栈名是一样的,不过不是一个对象,相当于创建一个新的栈名相同的栈)
allowTaskReparenting可以指明一个activity
onNewIntent被调用的那些情况下,onCreate、onStart不会被调用
### Activity的flags
>摘自Android开发艺术图书勘误:第1.2.2小节中,Activity的Flags,这一节的内容直接翻译了Android官方文档(<http://developer.android.com/guide/components/tasks-and-back-stack.html#TaskLaunchModes>),但是经过实例验证,发现书中的描述不准确(或者说官方文档中的描述不准确),结论为:Flags并不能简单地等同于启动模式,这一块内容需要进一步验证。
# IntentFilter的匹配规则
这个直接结合生活就很好理解了
action/data在intent中是set,category是add,所以就知道前两个是唯一的,category是可以配多个的
- action行为、动作
- 在清单文件中配置的时候,action表示“我可以干什么”,所以可以配置多个:我可以展示图片、我可以展示音频
- 在代码中指定意图的时候只能指定一个action:我将要干什么,比如我要展示图片,或者我要播放音频,则分别跳转到相应的activity,不能我又要播放音频又要展示图片
- 所以action就是清单文件中配置多个,指定意图的时候只能制定一个
- category分类
- 在清单文件中配置的时候,配置我属于什么什么,比如:我属于默认分类、运动类、户外类、轮滑类等(注意,这里最好指明自己属于默认类,这样在查找的时候,别人都能找到)
- 在代码中指定意图的时候可以指定我要:运动类并且是户外类,或者轮滑类(注意,系统会自动加上默认类)
- 所以,代码中指明的类别,一定要在清单文件中指明,比如一个activity属于默认分类、运动类、户外类、轮滑类,在代码中我可以直接找运动或者运动以及户外,但是如果我要找游戏,肯定是找不到了
- data数据形式
- 这个跟action类似,他是根据数据的规则来匹配的,action是我要找到"可以干什么"的activity,data是我要找到“可以接收该data”的activity
- data主要分为URI和mimeType两部分,一个代表资源位置,一个代表资源类型
对于Service和BroadcastReceiver,这套匹配规则也适用,不过对于Service,官方推荐使用显示意图
在使用隐式意图的时候,最好先做个判断,判断是否有可以匹配的activity,具体方法查就行了;在清单文件中配置category的时候,最好配置上default,使得intent更容易匹配它,因为每个intent都会默认加上default
|
Java
|
UTF-8
| 1,392
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
package com.easydlna.dlna.dlnaclient;
import android.util.Log;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class DlnaUtil {
static public String TAG = "DlnaUtil";
static public boolean isNetAccesible() {
if (getHostIp() == null)
return false;
return true;
}
static public String getHostIp() {
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface
.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces
.nextElement();
if (!ni.getName().contains("eth") && !ni.getName().contains("wlan"))
continue;
Enumeration<InetAddress> iaddrEnumeration = ni
.getInetAddresses();
ip = null;
while (iaddrEnumeration.hasMoreElements()) {
ip = (InetAddress) iaddrEnumeration.nextElement();
if (ip instanceof Inet4Address) {
break;
} else {
ip = null;
}
}
if (ip == null) {
continue;
} else if (!ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {
Log.e(TAG, "getHostip = " + ip.getHostAddress());
return ip.getHostAddress();
}
}
return null;
} catch (Exception e) {
Log.e(TAG, "fail to get host ip\n");
return null;
}
}
}
|
Java
|
UTF-8
| 1,600
| 3.03125
| 3
|
[] |
no_license
|
package com.lingb.mystudy.datastructure.day08;
import org.junit.Test;
import java.util.HashMap;
/**
* Created by lingb on 9/14/2018
*/
public class MyHashMapTest {
@Test
public void test1() {
HashMap<String, Integer> map = new HashMap<>();
map.put(null, null);
map.put("AA", 1);
map.put("BB", 2);
map.put("CC", 3);
map.put("DD", 4);
map.put("E", 5);
map.put("F", 1);
map.put("G", 2);
map.put("H", 3);
map.put("I", 4);
map.put("J", 5);
map.put("K", 1);
map.put("L", 2);
map.put("M", 3);
System.out.println(map.get("AA"));
}
@Test
public void test() {
MyHashMap7<String, Integer> map = new MyHashMap7<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.put("D", 4);
map.put("E", 5);
map.put("F", 1);
map.put("G", 2);
map.put("H", 3);
map.put("I", 4);
map.put("J", 5);
map.put("K", 1);
map.put("L", 2);
map.put("M", 3);
map.put("N", 4);
map.put("O", 5);
map.put("P", 1);
map.put("Q", 2);
map.put("R", 3);
map.put("S", 4);
map.put("T", 5);
map.put("U", 1);
map.put("V", 2);
map.put("W", 3);
map.put("X", 4);
map.put("Y", 5);
map.put("Z", 5);
map.remove("D");
System.out.println(map.get("D"));
map.put("D", 5);
map.put("D", 6);
System.out.println(map.get("D"));
}
}
|
Java
|
UTF-8
| 966
| 2.109375
| 2
|
[] |
no_license
|
package com.binzhou.zhy.mapper;
import com.binzhou.zhy.entity.Logistics;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
*
* LogisticsMapper数据库操作接口类
*
**/
public interface LogisticsMapper{
/**
*
* 查询(根据主键ID查询)
*
**/
public Logistics selectByPrimaryKey(@Param("id") Long id);
/**
*
* 查询(根据条件查询)
*
**/
public List<Logistics> selectListByOption(Logistics record);
/**
*
* 删除(根据主键ID删除)
*
**/
int deleteByPrimaryKey(@Param("id") Long id);
/**
*
* 添加
*
**/
int insert(Logistics record);
/**
*
* 添加 (匹配有值的字段)
*
**/
int insertSelective(Logistics record);
/**
*
* 修改 (匹配有值的字段)
*
**/
int updateByPrimaryKeySelective(Logistics record);
/**
*
* 修改(根据主键ID修改)
*
**/
int updateByPrimaryKey(Logistics record);
}
|
Java
|
UTF-8
| 337
| 2.46875
| 2
|
[] |
no_license
|
package com.gmail.jarmusik.kamil.impl.number;
public class FibonacciLongObjectNode extends FibonacciNode<Long> {
public FibonacciLongObjectNode(Long[] data) {
super(data);
}
@Override
public FibonacciNode<Long> create(Long a, Long b) {
return new FibonacciLongObjectNode(new Long[]{b, a + b});
}
}
|
Java
|
UTF-8
| 1,516
| 1.84375
| 2
|
[] |
no_license
|
package com.ihelin.car.controller.h5;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ihelin.car.config.CommonConfig;
import com.ihelin.car.db.entity.User;
@Controller
public class H5IndexController extends H5BaseController {
@RequestMapping(value = { "index", "" })
public String index() {
return ftl("index");
}
@RequestMapping(value = "user_center")
public String userCenter(Model model) throws UnsupportedEncodingException {
User wxUser = getWeixinUser();
if (wxUser == null) {
String usercenterUrl = "h5/user_center";
usercenterUrl = URLEncoder.encode(usercenterUrl, "utf-8");
String url = CommonConfig.getDomainUrl()+"/oauth_url?url=REDIRECT_URI";
url = url.replace("REDIRECT_URI",
URLEncoder.encode(CommonConfig.getDomainUrl()+"/weixin_login.do?from=" + usercenterUrl, "utf-8"));
return "redirect:" + url;
}
return ftl("user_center");
}
@RequestMapping(value = "user_info")
public String userInfo() {
return ftl("user_info");
}
@RequestMapping(value = "car_manager")
public String carManager() {
return ftl("car_manager");
}
@RequestMapping(value = "car_list")
public String carList() {
return ftl("car_list");
}
@RequestMapping("get_code")
public String getWxCode(String code, String state) {
System.out.println(code);
return "redirect:/h5/index";
}
}
|
Shell
|
UTF-8
| 295
| 3.21875
| 3
|
[] |
no_license
|
#!/usr/bin/env bash
set -e
INPUT=$(readlink -f "${1}")
# https://unix.stackexchange.com/a/84980
TMP_DIR=$(mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir')
cd $TMP_DIR
ffmpeg -i "${INPUT}" -vf "fps=15" "frame%04d.png"
gifski --fps 20 --quality 80 -o "${INPUT}.gif" frame*.png
rm -r $TMP_DIR
|
C#
|
UTF-8
| 1,419
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Linq.Expressions;
namespace Z3.ObjectTheorem
{
public class ConstraintBuilder
{
private ObjectTheoremContext _objectTheorem;
internal ConstraintBuilder(ObjectTheoremContext objectTheorem)
{
_objectTheorem = objectTheorem;
}
public ConstraintBuilder Assert(Expression<Func<bool>> constraint)
{
_objectTheorem.AddAssertion(constraint);
return this;
}
public ConstraintBuilder AssertAll<T1>(Expression<Func<T1, bool>> constraint)
{
_objectTheorem.AddAllAssertion(constraint);
return this;
}
public ConstraintBuilder AssertAll<T1, T2>(Expression<Func<T1, T2, bool>> constraint)
{
_objectTheorem.AddAllAssertion(constraint);
return this;
}
public Expression<Func<bool>> Assume(Expression<Func<bool>> constraint)
{
_objectTheorem.AddAssumption(constraint);
return constraint;
}
public Expression<Func<T1, T2, bool>> AssumeAll<T1, T2>(Expression<Func<T1, T2, bool>> constraint)
{
_objectTheorem.AddAllAssumption(constraint);
return constraint;
}
public void RemoveAssumption(LambdaExpression assumption)
{
_objectTheorem.RemoveAssumption(assumption);
}
}
}
|
JavaScript
|
UTF-8
| 2,422
| 2.546875
| 3
|
[] |
no_license
|
import React from 'react'
import { convertToRupiah } from '../Helpers'
import { changeJumlah } from '../actions/productActions'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
class ProductListItem extends React.Component {
state = {
id: this.props.product.id,
nama: this.props.product.nama,
harga: this.props.product.harga,
jumlah: this.props.product.jumlah
}
onAmountChange = (index, e) => {
const jumlah = e.currentTarget.value
if (!jumlah || jumlah.match(/^\d{1,}(\.\d{0,2})?$/)) {
this.props.changeJumlah(index, jumlah)
this.setState(() => ({ jumlah }))
}
}
renderSpecial = () =>
this.props.length === this.props.count ? (
<div className="special">
<div className="specialContent">Total Harga</div>
</div>
) : null
// handleChange = (e) => {
// update that fish
// 1. Take a copy of the current fish
// const updatedProduct = {
// ...this.props.product,
// [e.currentTarget.name]: e.currentTarget.value
// this.props.addJumlah(this.props.product, updatedProduct)
// }
render() {
const { id, nama, harga, jumlah } = this.state
return (
<li
key={id}
className={`items ${this.props.count % 2 === 0 ? 'even' : 'odd'}`}
>
<div className="infoWrap">
<div className="cartSection">
<img
className="itemImg"
src="http://pluspng.com/img-png/png-durian-download-1100.png"
alt="PNG Durian"
/>
<h3>{nama}</h3>
<p>
<input
style={{ width: 45 }}
type="number"
name="jumlah"
className="qty"
value={jumlah}
onChange={(e) => this.onAmountChange(this.props.index, e)}
/>
x {convertToRupiah(harga)}
</p>
</div>
<div className="prodTotal cartSection">
<p>{convertToRupiah(harga * jumlah)}</p>
</div>
<div className="cartSection removeWrap">
<a href="" className="remove">
x
</a>
</div>
</div>
{this.renderSpecial()}
</li>
)
}
}
ProductListItem.propTypes = {
changeJumlah: PropTypes.func.isRequired
}
export default connect(
null,
{ changeJumlah }
)(ProductListItem)
|
C
|
UTF-8
| 4,708
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# include "lib/common.h"
# define MAXLINE 4096
/**
*
* @param argc
* @param argv
* @return
*/
int main(int argc, char **argv) {
if (argc != 2) {
error(1, 0, "usage: graceclient <IPaddress>");
}
/* 创建 TCP 套接字,设置 IPv4 地址(清零、设置地址族,指定端口,转换地址),绑定指定的 IP 和端口 */
int socket_fd;
struct sockaddr_in server_addr;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
/* 试用套接字连接 server */
if (connect(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
error(1, errno, "connect failed ");
}
char send_line[MAXLINE], recv_line[MAXLINE + 1];
int n;
fd_set readmask, allreads;
/* 为 select 多路复用做准备,初始化描述字集合:同时处理连接套接字和标准输入两个 I/O 对象 */
FD_ZERO(&allreads);
FD_SET(0, &allreads);
FD_SET(socket_fd, &allreads);
for (;;) {
readmask = allreads;
int rc = select(socket_fd + 1, &readmask, NULL, NULL, NULL);
if (rc <= 0) {
error(1, errno, "select failed");
}
/* 连接套接字上有数据可读,将数据读入到程序缓冲区中 */
if (FD_ISSET(socket_fd, &readmask)) {
n = read(socket_fd, recv_line, MAXLINE);
/* 读取异常,退出 */
if (n < 0) {
error(1, errno, "read error");
}
/* 读取到服务器发送的 EOF,正常退出 */
else if (n == 0) {
error(1, 0, "server terminated \n");
}
recv_line[n] = 0;
fputs(recv_line, stdout);
fputs("\n", stdout);
}
/* 标准输入上有数据可读,读入后判断 */
if (FD_ISSET(0, &readmask)) {
if (fgets(send_line, MAXLINE, stdin) != NULL) {
// 读取到 shutdown,关闭标准输入 I/O 事件感知,调用 shutdown 函数关闭写方向,但此时读方向未关闭,仍然可以接收来自服务端的消息
// shutdown():可选择关闭读方向(悄悄丢弃,不告知对方)、写方向(不管引用计数,直接关闭;最后一次发送缓冲区数据和 FIN 报文),或两个方向都关闭
// 当期望关闭连接其中一个方向时,应该使用 shutdown 函数
if (strncmp(send_line, "shutdown", 8) == 0) {
FD_CLR(0, &allreads);
if (shutdown(socket_fd, 1)) {
error(1, errno, "shutdown failed");
}
}
// 读取到 close,调用 close 函数关闭连接(不能收到应答数据),但未必立即关闭数据(只有当引用计数为 0 才立即关闭)
// close():通过引用计数判断套接字是否可关闭(为 0 关闭),当多个进程共享套接字时,每调用调用 fork 创建子进程计数 +1,每调用一次 close 计数 -1
// 在输入方向,系统内核会将该套接字设置为不可读,任何读操作都会返回异常。
// 在输出方向,系统内核尝试将发送缓冲区的数据发送给对端,最后向对端发送一个 FIN 报文,随后再对该套接字进行写操作会返回异常。
// 如果对端没有检测到套接字已关闭、还继续发送报文,就会收到一个 RST 报文,告知对端停止发送报文。
else if (strncmp(send_line, "close", 5) == 0) {
FD_CLR(0, &allreads);
if (close(socket_fd)) {
error(1, errno, "close failed");
}
sleep(6);
exit(0);
}
/* 处理正常的输入,将回车符截掉,调用 write 函数,通过套接字将数据发送给服务器端 */
else {
size_t i = strlen(send_line);
if (send_line[i - 1] == '\n') {
send_line[i - 1] = 0;
}
printf("now sending %s\n", send_line);
size_t rt = write(socket_fd, send_line, strlen(send_line));
if (rt < 0) {
error(1, errno, "write failed ");
}
printf("send bytes: %zu \n", rt);
}
}
}
}
}
|
C++
|
UTF-8
| 1,445
| 3.4375
| 3
|
[] |
no_license
|
#include"hash_table2.h"
using sfils_csc212::hash_table2;
int main() {
//All requirements completed
// Advantages of this implementation:
/*
For a system like a student information system where the key is a number and the item is an student object
Ex: hash_table2<int,Student> CCNY_STUDENT_SYSTEM ;
searching is one of the most important feature.
We switch from a linked list to a binary search tree when searching becomes inefficient.
Search is O(n) instead of 0(C) due to the large size of the linked list.
A binary search tree deliver O(lgn) search speed.
However, at some point due to removal and/or rehashing the efficiency of a linked list
will go back to O(C) so at that point its best to switch back from a bst to a linked list.
*/
//Implementation Summary:
/*
Once a hash_table2 object is created each index of its table will point to a hash_node.
Each hash node contains an empty linkeded list & binary search tree,
a mode variable indicating the current mode, and a size variable indicating the size of the current structure in use.
When inserting or removing the mode of a hash node may switch to a binary search tree when its size reaches 11,
or switch back to a linked list when its size reduces to 8.
This process happens while also reharshing when a threshold of .75 is reached.
-Value semantics is safe
*/
hash_table2<int, int> a;
a.insert(1, 1);
std::cout << a;
return 0;
}
|
JavaScript
|
UTF-8
| 2,038
| 3.609375
| 4
|
[] |
no_license
|
function Dictionary(cap) {
var buckets = new Array(cap)
var entries = new Array(cap)
var count = 0;
this.add = function (k, v) {
var idx = k % buckets.length;
var next = buckets[idx]
buckets[idx] = count;
var item = {
key: k,
value: v,
next: next
}
entries[buckets[idx]] = item;
count++;
}
this.get = function (k) {
var idx = k % buckets.length;
var entryIdx = buckets[idx];
while (entries[entryIdx] && entries[entryIdx].key != k) {
entryIdx = entries[entryIdx].next;
}
if (entries[entryIdx] && entries[entryIdx].key == k) {
return entries[entryIdx].value;
}
return undefined;
}
this.remove = function (k) {
var idx = k % buckets.length;
var entryIdx = buckets[idx];
var prevEntryIdx;
while (entries[entryIdx] && entries[entryIdx].key != k) {
prevEntryIdx = entryIdx;
entryIdx = entries[entryIdx].next;
}
if (entries[prevEntryIdx]) {
entries[prevEntryIdx].next = entries[entryIdx].next;
} else {
buckets[idx] = entries[entryIdx].next;
}
delete entries[entryIdx];
}
// this.growTo = function (times) {
// var len = buckets.length;
// entries = entries.concat(new Array(len * (times - 1 ) + 1))
// var newBuckets = new Array(entries.length);
// buckets.forEach(function (entryIdx) {
// var entryItem = entries[entryIdx]
// if (entryItem && entryItem.key) {
// newBuckets[entryItem.key % newBuckets.length] = entryItem.key;
// }
// })
// buckets = newBuckets;
// }
}
var dict = new Dictionary(11);
dict.add(1, 'A');
dict.add(4, 'D');
dict.add(15, 'DD');
console.log(dict.get(1))
console.log(dict.get(4))
console.log(dict.get(15))
dict.remove(4)
console.log(dict.get(4))
console.log(dict.get(15))
|
C#
|
UTF-8
| 2,521
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DoNet.Common.DbUtility.Proxy
{
/// <summary>
/// 数据库访问的远程代理
/// </summary>
public class DBHelper:IDBHelper
{
/// <summary>
/// 生成本地访问实例
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
private DbUtility.DbORM CreateDB(DBInfo db)
{
DoNet.Common.IO.Logger.Debug(db);
var dbHelper = DbFactory.CreateDbORM(db.DBType.ToString(), db.ConnectionString);
return dbHelper;
}
public int ExecuteNonQuery(DBInfo dbinfo, string cmdText)
{
return CreateDB(dbinfo).ExecuteNonQuery(cmdText);
}
public int ExecuteNonQueryWithParam(DBInfo dbinfo, string cmdText, string[] paraNames, object[] paraValues)
{
return CreateDB(dbinfo).ExecuteNonQuery(cmdText, paraNames, paraValues);
}
public int ExecuteNonQueryWithParams(DBInfo dbinfo, string cmdText, IDictionary<string, object> dbparams)
{
return CreateDB(dbinfo).ExecuteNonQuery(cmdText, dbparams);
}
public string GetDataSet(DBInfo dbinfo, string cmdText)
{
var ds = CreateDB(dbinfo).GetDataSet(cmdText);
var newds = new Data.DataSet(ds);
return newds.ToString();
}
public string GetDataSetWithParam(DBInfo dbinfo, string cmdText, string[] paraNames, object[] paraValues)
{
var ds = CreateDB(dbinfo).GetDataSet(cmdText,paraNames,paraValues);
var newds = new Data.DataSet(ds);
return newds.ToString();
}
public object ExecuteScalar(DBInfo dbinfo, string cmdText)
{
return CreateDB(dbinfo).ExecuteScalar(cmdText);
}
public object ExecuteScalarWithParam(DBInfo dbinfo, string cmdText, string[] paraNames, object[] paraValues)
{
return CreateDB(dbinfo).ExecuteScalar(cmdText, paraNames,paraValues);
}
public int ExecuteSql(DBInfo dbinfo, ICollection<string> sqls)
{
return CreateDB(dbinfo).ExecuteSql(sqls);
}
public int ExecuteSqlWithParam(DBInfo dbinfo, List<string> sqls, List<string[]> paraNames, List<object[]> paraValues)
{
return CreateDB(dbinfo).ExecuteSql(sqls, paraNames, paraValues);
}
}
}
|
C++
|
UTF-8
| 1,357
| 3.046875
| 3
|
[] |
no_license
|
//
// Copyright (c) 2016 by Voaz Charov. All Rights Reserved.
//
#include <algorithm>
#include "Group.h"
Group::Group(int width) : width(width) {}
bool Group::addIndex(int group, int index) {
auto it = cellGroup.find(group);
if (it != cellGroup.end()) {
if (std::find(it->second.begin(),
it->second.end(),
index) != it->second.end()) {
return false;
}
}
cellGroup.insert(std::make_pair(group, index));
return true;
}
bool Group::removeIndex(int group, int index) {
auto it = cellGroup.find(group);
if (it != cellGroup.end()) {
auto it_index = std::find(it->second.begin(),
it->second.end(),
index);
if (it_index != it->second.end()) {
it->second.erase(it_index);
return true;
}
}
return false;
}
int Group::getGroupSize(int group) {
return cellGroup.find(group)->second.size();
}
int Group::getEmptyGroup() {
for (size_t i = 0; i <= width; i++) {
if (cellGroup.find(i) == cellGroup.end()) {
return i;
}
}
return -1;
}
int Group::getWhichGroupItemIs(int index) {
for (auto it : cellGroup) {
if (std::find(it.second.begin(),
it.second.end(),
index) != it.second.end()) {
return it.first;
}
}
return -1;
}
void Group::clear() {
cellGroup.clear();
}
|
Markdown
|
UTF-8
| 20,688
| 3.25
| 3
|
[] |
no_license
|
四七
瓦西里公爵不去周密地考虑自己的计划,他更少地想到谋求私利和作出危害他人的事。他不过是个上流社会人士,在上流社会中颇有造诣,并且习惯于借取这样的成就。他经常斟酌情形,在与人们建立密切关系时拟订出各种计划,提出自己的见解,他自己虽然不太了解,但是它们却已构成他的生活中的一种情趣。不是一两个,而是几十个这样的计划和设想常常付诸实施,其中有一些在他脑际开始浮现,另一些正在实行,还有一些要被废除。比如,他没有对自己说过这种话:“目前这个人有权有势,我应该获得他的信任,与他建立友谊关系,借助于他捞到一笔津贴;”或者说,他没有对自己说过这种话:“皮埃尔十分富有,我应该勾引他来娶我的幼女,借到我所需要的四万卢布”但他遇见这个有权有势的人时,人的本能就向他暗示,这个人可能大有用途,于是瓦西里公爵就同他接近,他在这方面,精神上毋须乎有所准备,只要一遇有机会,就本能地百般阿谀奉承,对他持有十分亲热的态度,开口说几句应该说的话。
在莫斯科,皮埃尔和瓦西里公爵十分接近,他替皮埃尔谋到一个低级侍从的差事,当时那官阶等于五等文官,他便坚持己见,要皮埃尔和他一道到彼得堡去,住在他家里。瓦西里公爵促使皮埃尔娶他的女儿为妻所必须做的事情,他样样都做,这样行事仿佛是因为他颟颟顸顸,但同时他又显得信心十足。假如瓦西里公爵事先周密地考虑自己的计划,他在态度上就不会这样自然,在对待比他地位更高或更低的人们就不会这样浑厚和亲切。有某种东西经常吸引他趋向那些比他更有权势、更加富有的人;他在把握什么时候必须、什么时候可以利用别人的时机方面,富有非凡的本事。
不久以前,皮埃尔过着无忧无虑的孤寂的生活,他出乎意料地变成了财主和别祖霍夫伯爵,在此之后他觉得自己被杂事纠缠,忙得不可开交,只有躺在床上时才能独自一人安享清闲。他得签署多种公文,和他不熟悉的办公场所打交道,向总管家询问某些事情,去莫斯科附近的领地走走,接见许多人士,他们从前甚至不想知道他的生活情况,如果现在他不想和他们会面,他们就会感到屈辱和痛心。这些形形色色的人士:实业家、亲戚、熟人,都很和善而温柔地对待年轻的继承人,博取他的欢心,显然他们都对皮埃尔的高尚的品格深信不疑。他不时地听到这些话:“以您的分外的仁慈”,或则:“以您的善心”,或则,“伯爵,您本人如此纯洁……”或则:“如果他像您这样聪明”诸如此类,因此他真的相信自己那种分外的仁慈,相信自己与众不同的智慧,而且在灵魂深处,他经常觉得他确实非常仁慈,非常聪明。甚至连那些过去凶狠、显然怀有敌意的人也对他和和气气,爱抚备至。好生气的大公爵小姐,身腰修长,头发弄得很服贴,像个洋娃娃似的。在安葬别祖霍夫之后,她走进皮埃尔的房间。她垂下眼帘,满面通红,对他说,她对过去他们之间的误会深表遗憾,现在她觉得没有理由奢求什么,只请求在她遭受打击之后准许她在这栋住宅中逗留几个星期,因为她深深地爱着这栋住宅,在这里作出了许多贡献。她说这番话时不禁大哭起来。这个雕像似的公爵小姐发生了很大的变化,这使皮埃尔颇为感动,他一把抓住她的手,请求她宽恕,连他自己也不明白为什么要央求她宽恕。从这天起,公爵小姐便替皮埃尔编织有条纹的围巾,她对他的态度完全变了。
“moncher(我亲爱的),你替她办妥这件事吧,她毕竟为死者吃了许多苦啊,”瓦西里公爵对他说,一面要他在一张对公爵小姐有利的文据上签字。
瓦西里公爵拿定了主意,认为这块骨头——三万卢布的期票——还是要扔给可怜的公爵小姐,要她死了心眼,不去谈论瓦西里公爵参与抢夺嵌花皮包的丑事。皮埃尔在期票上签了字,从那时起,公爵小姐变得更加和善了。她的几个妹妹也对他亲热起来,尤其是那个年纪最小、脸上有颗胎痣。长得俊俏的公爵小姐;她笑容可掬,一看见他就觉得不好意思,这常常使得皮埃尔困窘不安。
皮埃尔觉得,大家喜爱他是顺应自然的事情,如果有人不爱他,他就会觉得异乎寻常了,因此,他不能不相信他周围的人都怀有一片诚心。而且他没有功夫去问自己,这些人是否真无二心。他经常忙得不亦乐乎,经常觉得自己处于温柔和欢愉的陶醉之中。他觉得自己是某种重要的公共活动的中心人物,他觉得经常有人对他有所期待,如果不办妥某件事,就会使许多人痛心,就会使他们失望,如果能办妥某件事,那么一切都顺利,因此,如有求于他,他尽力而为,但是这种“顺利”始终是一句后话而已。
起初,瓦西里公爵较诸其他人更多地支配皮埃尔本人和他的各种事情。自从别祖霍夫伯爵去世后,他一直管着皮埃尔,没有放松过。瓦西里公爵摆出那副样子,就像某人负担沉重、精疲力尽似的,但出于怜悯,他终究不能抛弃这个孤立无援的少年,听凭命运和骗子们的摆布,皮埃尔毕竟是他的朋友的儿子,aprèstout①他拥有这么一大笔财富。别祖霍夫伯爵辞世后,他在莫斯科逗留过几天,在这几天中,他常把皮埃尔喊到身边,他也亲自去找皮埃尔,嘱咐他要做什么事,那口气中含有倦意和自信,仿佛他每次都附带说过这席话似的:
“Voussavez,quejesuisaccabléd’affairesetquecen’estqueparpurecharitè,quejem’occupedevous,etpuisvoussavezbien,quecequejevousproposeestlaseulchosefaisable.”②
①法语:归根结底。
②法语:你知道,我负担过重的工作,但把你丢开不管,是冷酷无情的。你也知道,我对你所说的话是唯一可行的。
“喂,我的朋友,我们明日终于要走了。”有一次他闭上眼睛,用指头逐个地抚摸他的胳膊时,对他说,那腔调好像他所说的话是他们之间很早很早以前决定要说的,并且不可能作出别的决定。
“我们明天要走了,我让你坐上我的马车。我感到非常高兴。我们这儿的重要事情都干完了。我早就应当走了。你看,我收到大臣的来信。我为你向他求情,你被编入外交使团,录用为低级侍从。现今你面前展现了一条外交上的康庄大道。”
尽管皮埃尔说了这些话,他那疲倦而自信的腔调强而有力,但是他对自己的功名利禄考虑了很久,心里还想提出异议。可是瓦西里公爵用那低沉的嘟嘟囔囔的声调打断他的话,这种声调排除了别人打断他的话的可能性,通常他是在劝说他人的情况下才应用这种腔调的。
“mais,moncher①我为自己,为我自己的良心才办了这件事,所以,用不着感谢我。从来没有任何人抱怨,说人家溺爱他了,以后你没事了,即使明天不干也行。你在彼得堡什么都会看得一清二楚的。你老早就得摆脱这些可怕的回忆,”瓦西里公爵叹了一口气,“我亲爱的,就是这样的。让我的近侍坐你的车子一同去吧。哎呀,对了,我原来忘记了,”瓦西里公爵又补充地说,“moncher,”②你晓得,我和死者有一笔旧帐,梁赞寄来的一笔钱,我收到了,把它留下来,你眼下不缺钱用,我们以后会把帐目算清的。”
①法语:可是,我亲爱的。
②法语:我的朋友。
瓦西里公爵所提到的“梁赞寄来的一笔钱”,是几千卢布的代役租金,瓦西里公爵把这笔钱留在自己身边了。
在彼得堡像在莫斯科一样,那些宠爱皮埃尔的性情温和的人们所造成的气氛笼罩着他。他不能拒绝瓦西里公爵给他谋到的差事,或者莫如说职位(因为他无所事事),而交游、邀请和社会活动竟是那么多,以致皮埃尔比在莫斯科更多地体会到一种迷迷糊糊的忙忙碌碌的感觉,一种即将来临而尚未实现的幸福的感觉。
他从前那些未婚的伙伴中,许多人都不在彼得堡。近卫军远征去了。多洛霍夫已受到降级处分,阿纳托利在外省军队里服役,安德烈公爵在国外,因此皮埃尔既不能像从前那样喜欢消度良霄,也不能和年纪大的受人尊敬的朋友在畅谈中排解愁闷了。他在午宴上、舞会上,主要是在瓦西里公爵家中——在肥胖的公爵夫人、即是他的妻子和美丽的女郎海伦这个小团体中,消度他的全部时光。
安娜·帕夫洛夫娜·舍利尔,也像其他人一样,对皮埃尔改变了态度,发生了社会对他的看法上所发生的那种变化。
以前,皮埃尔在安娜·帕夫洛夫娜面前经常觉得他所说的话失礼、无分寸,说出一些不宜于说出的话。他在脑海中酝酿发言的时候,总觉得他要说的话都是明智的,可是一当他大声说出来,这些话就变得愚蠢了。与之相反,伊波利特说的至为愚蠢的话,却被人看成是明智而且动听的。而今,无论他说什么话,都被认为charmant①。即令安娜·帕夫洛夫娜不开口,他也会发觉,她想说出这一点,为尊重他的谦逊起见,她才忍住没有把话说出来。
从一八〇五年冬季之初至一八〇六年,皮埃尔接获安娜·帕夫洛夫娜寄来的一封普通的玫瑰色的请帖,请帖上并有补充的话:“VoustrouverezchezmoilabelleHéléne,qu’onneselassejamaisvoir.”②
①法语:十分动听。
②法语:“有个百看不厌的十分标致的海伦要到我这里来。”
皮埃尔念到这个地方的时候,头一次感到他和海伦之间日渐形成别人公认的某种关系。这个念头使他胆寒,好像他正承担着一种他不能履行的义务似的,与此同时,它作为一种有趣的设想,又使他欢喜起来。
安娜·帕夫洛夫娜举办的晚会还和第一次晚会一样,只是安娜·帕夫洛夫娜用以款待客人的一道新菜,现在已经不是莫特马尔,而是一位来自柏林的外交官,他捎来了详细的新闻——亚历山大皇帝在波茨坦逗留、两位至为高贵的朋友在那里立誓永缔牢不可破的联盟,为维护正义事业而反对人类的敌人。皮埃尔受到安娜·帕夫洛夫娜的接待,她流露着一点忧愁,这显然是年轻人不久以前丧父——别祖霍夫伯爵去世之事牵动了安娜的心(大家总是认为,说服皮埃尔,要他对他几乎不认识的父亲的去世深表哀恸,是他们自己的天职),而她流露的一点忧愁宛如她一提到至尊的玛丽亚·费奥多罗夫娜皇太后时流露的哀思一样。这使皮埃尔深感荣幸。安娜·帕夫洛夫娜用她那惯用的方法把她的客厅中的客人编成几个组。瓦西里公爵和几位将军的那个大组用上了一名外交官。另一组人在茶几旁边就座,皮埃尔想加入第一组,可是安娜·帕夫洛夫娜处于激动不安的状态中,就像战场上的将领此时脑海中浮现出千万种上策,但尚未一一实现似的。她望见皮埃尔后,便用指头摸了摸他的袖筒。
“Attendezjáidesvuessurvouspourcesoir.”①她望望海伦,对她微露笑容。
①法语:等一等,今天晚上我打算找您聊聊。
“MabonneHélène,ilfaut,quevoussoyezcharitablepourmapauvretante,quiauneadorationpourvous,Allezluitenircompagniepour10minutes.①为了让您不感到寂寞,这里有个可爱的伯爵,他是乐意关照您的。”
美丽的女郎向姑母跟前走去了,但是安娜·帕夫洛夫娜还把皮埃尔留在自己身边,装出那副样子,好像她还要作出最后一次必要的嘱咐似的。
“她多么惹人喜欢,不是吗?”她对皮埃尔说道,一面指着庄重地慢慢走开的美妙的女郎,“Etquelletenue!②这样年轻的姑娘善长于保持有分寸的态度!这是一种出自内心的表现!谁能占有她,谁就会无比幸福。一个非交际场中的丈夫有了她无形中就会在上流社会占有至为显赫的地位。是不是?我只想知道您的意见。”于是安娜·帕夫洛夫娜让皮埃尔走开了。
①法语:我亲爱的海伦,您要仁慈地对待我可怜的姑母吧,她是宠爱您的。您和她一块呆上十来分钟吧。
②法语:她的举止多么优雅啊!
皮埃尔十分真诚而且肯定地回答了安娜·帕夫洛夫娜有关海伦的行为方式问题。如果他曾经想到海伦,那他所想到的正是她的姿色、她在上流社会中那种十分宁静、保持缄默自尊的本领。
姑母在一个角落里接待了两个年轻人,但是看起来她想隐瞒她对海伦的宠爱,在安娜·帕夫洛夫娜面前她想更多地流露她的惊恐的神态。她注视着她的侄女,仿佛心里在问,她应当怎样对付这几个人。安娜·帕夫洛夫娜在离开他们的当儿,又用指头摸摸皮埃尔的袖筒,说道:
“J’espére,quevousnedirezplusqu’ons’ennuiechezmoi.”①她望了海伦一眼。
①法语:我希望下次您不要再说,在我这儿觉得寂寞无聊。
海伦嫣然一笑,那样子表示,她不容许任何人看见她而有不被勾魂的可能。姑母干咳了几声,清清嗓子,吞下口水,用法国话发言,她看见海伦觉得很高兴,之后把脸转向皮埃尔,用同样的言词问寒问暖,流露着同样的神色。在那枯燥无味、不能继续下去的谈话中间,海伦回头望了望皮埃尔,对他微微一笑,这种微笑安然而妩媚,她在人人面前都这样笑容可掬。皮埃尔看惯了这种微笑,他认为微笑的含义甚微,因此他不予以注意。姑母这时分正在谈论皮埃尔的亡父——别祖霍夫伯爵收集烟壶的事情,并且拿出自己的烟壶给大家瞧瞧。公爵小姐海伦要瞧瞧嵌在这个烟壶上面的姑父的画像。
“这想必是维涅斯所创作的,’皮埃尔说道,同时提到著名的小型彩画家的名字,他向桌前俯下身去,拿起鼻烟壶,继续倾听另外一张桌上的闲谈。
他欠一欠身,想绕过去,可是姑母正从海伦背后把烟壶递过来了。海伦向前弯下腰去让开一下,面露微笑回头看看。她和平素在晚会上那样,穿着一件时髦的袒胸露背的连衣裙,皮埃尔向来认为她的胸部像大理石那样又白又光滑,它现在离他的眼睛很近,所以他情不自禁地用他那对近视眼看清她那十分迷人的肩膀和颈项,并且离她的嘴唇很近,他只要略微弯下腰来,就会碰到他了。他闻到她的身躯的热气、香水味,听到她上身动弹时束腰发出窸窣的响声。他所看见的不是和她那件连衣裙合成一体的大理石般的俊美,他所看见的和所体察到的是她那仅仅散以衣腋的身体的迷人的姿色,他既然看见这一层,就不能去看别的了,就像骗局已被查明,我们不能再上当了。
“您到现在还没发现我长得多么漂亮吗?”海伦好像在说话。“您没发现我是一个女人吗?是的,我是一个女人,可以属于任何人,也可以属于您,”她的目光这样说。也就在这一瞬间,皮埃尔心中觉得,海伦不仅能够,而且应当成为他的妻子,并没有别的可能性。
在这个时候,他很确切地知道这一点,就像他和她正在教堂里举行婚礼似的。这件事应如何办理?何时办理?他不知道,他甚至不知道,这件事是否可取(他甚至感到,这件事不知怎的是不可取的),但是他知道,这件事是要办理的。
皮埃尔垂下眼睛,又抬起眼睛,心里重新想把她看作是一个相距遥远的,使他觉得陌生的美女,正如以前他每天看见的她那样,但是他现在已经不能这样办了。就像某人从前在雾霭中观看野蒿中的一株草,把它看作是一棵树,当他看清这株草以后,再也不能把它看作一棵树了。她和他太接近了。她已经在主宰着他。除开他自己的意志力的障碍而外,他和她之间已经没有任何障碍了。
“Bon,jevouslaissedansvotrepetitcoin.Jevois,quevousyêtestrèsbien.”①可以听见安娜·帕夫洛夫娜的话语声。
①法语:好的,我就把你们留在你们的角落里。我看见,你们在那里觉得蛮好。
皮埃尔很惊恐地回想起,他是否做了什么不体面的事,他满面通红,向四周环顾。他似乎觉得,大家都像他那样,知道他发生了什么事。
俄而,他走到那个大组的客人跟前时,安娜·帕夫洛夫娜对他说道:
“OnditquevousembellissezvotremaisondePétersbourg.”①
(这是实话:建筑师说,他正要办这件事,就连皮埃尔本人也不知道为什么他要装修他在彼得堡的一栋高大的住宅。)
“cestbien,maisnedéménagezpasdechezleprinceBasile.Ilestbond’avoirunamicommeleprince,”她面露笑容对瓦西里公爵说。“J’ensaisquelquechoseN’est-cepas?②可是您这么年轻。您所需要的是忠告。您不要生我的气,说我滥用了老太婆的权利。”她默不作声,就像妇女们平素在谈到自己的年纪之后,想等待什么似的,都不愿开口。
“如果您结婚,那是另一回事。”她于是把他们的视线连接起来。皮埃尔不看海伦,她也不看他。可是她和他的距离还是很近。他发出哞哞声,满面通红。
①法语:据说,您在装修您的彼得堡的住宅。
②法语:这很好。可是您不要从瓦西里公爵家中迁走。有这样一个朋友是件好事。这件事我略知一二。您说说看,是不是?
皮埃尔回家以后,他久久地不能入睡,心里思忖,他出了什么事。他究竟出了什么事呢?没有出什么事。他所明白的只是,在儿时他就认识一个女人,关于这个女人,他漫不经心地说:“是的,很标志。”当别人对他说,海伦是个美妙的女郎,他心里明了,这个女人可能属于他。
“可是她很傻,我自己也说过她很傻,”他心中想道,“她使我产生的一种情感中含有某种鄙劣的应被取缔的东西。有人对我说,她的哥哥阿纳托利钟情于她,她也钟情于他,他们之间有一整段恋爱史,正因为这件事阿纳托利才被逐出家门,伊波利特是她的哥哥……瓦西里公爵是她的父亲……真糟糕……”他想,正当他这样发表议论的时候(这些议论还没有结束),他发觉自己面露微笑,并且意识到,从前面的一系列议论中正在浮现出另一系列议论,他同时想到她的渺小,幻想着她将成为他的妻子,她会爱他,她会变成一个截然不同的女人,他所想到和听到的有关她的情形可能是一派谎言。他又不把她视为瓦西里公爵的女儿,而他所看见的只是她那蔽以灰色连衣裙的躯体。“不对,为什么我脑海中从前没有这种想法呢?”他又对他自己说,这是不可能的事,他仿佛觉得,在这门婚事中含有一种鄙劣的、违反自然的、不正直的东西。他回想起她从前所说的话、所持的观点,他们两人在一起时那些看见他们的人所说的话、所持的观点。他回想起安娜·帕夫洛夫娜对他谈到住宅时所说的话、所持的观点,回想起瓦西里公爵和其他人所作的千万次的这类的暗示,他感到恐怖万分,他是否凭藉什么把自己捆绑起来,去做一件显然是卑劣的、他理应不做的事。但是在他向自己表白这一决心时,从她的灵魂的另一面正浮现出她的整个女性美的形象。
|
C++
|
UTF-8
| 4,944
| 2.875
| 3
|
[] |
no_license
|
#include "algo/stepgen.hpp"
using namespace algo;
void stepgen::stepgen::speedup() {
uint32_t denom = 4 * _speed + 1;
_delay -= ((2 * _delay + denom / 2) / denom);
_speed++;
}
void stepgen::stepgen::slowdown() {
_speed--;
uint32_t denom = 4 * _speed - 1;
_delay += ((2 * _delay + denom / 2) / denom);
}
bool stepgen::stepgen::set_target_speed(uint32_t speed) {
uint64_t delay = (static_cast<uint64_t>(_ticks_per_second) << 16) / speed;
if ((delay >> 24) != 0) {
return false; // Too slow, doesn't fit in in 16.8 format, our timer is only 16 bit.
}
if (delay <= ::algo::stepgen::stepgen::TicksPerUpdate * (1 << 8)) {
// Too fast, less than 10 ticks of a timer. 10 is an arbitrary number,
// just to make sure we have enough time to calculate next delay.
return false;
}
// Convert to 16.16 format. We only need this precision during intermediate calculations.
delay <<= 8;
_tgt_delay.store(delay, std::memory_order_relaxed);
return true;
}
bool stepgen::stepgen::set_acceleration(uint32_t acceleration) {
// c0 = F*sqrt(2/a)*.676 = F*sqrt(2/a)*676/1000 =
// F*sqrt(2*676*676/a)/1000 =
// F*sqrt(2*676*676*1^16)/(1000*1^8)
// We bring as much as we can under square root, to increase accuracy of division
// sqrt(1 << 16) is (1 << 8), which is to convert to 24.8
// We shift 24 bits to the left to adjust for acceleration in 24.8 format plus to convert
// result into 24.8 format, so the resulting shift is 40 bits.
// 676 is used to correct for the first step (see the paper)
uint64_t c0long = ((2ULL * 676 * 676) << 40) / acceleration;
uint64_t c0 = (_ticks_per_second * sqrt(c0long) / 1000) >> 8;
if (c0 >> 24) {
return false; // Doesn't fit in in 16.8 format, our timer is only 16 bit.
}
// Convert to 16.16 format. We only need this precision during intermediate calculations.
_first_delay = static_cast<uint32_t>(c0) << 8;
return true;
}
uint32_t stepgen::stepgen::current_speed() const {
uint32_t d = _slewing_delay ? _slewing_delay : _delay;
d >>= 8; // Convert to 16.8 format
if (d == 0) {
return 0;
}
uint64_t speed = (static_cast<uint64_t>(_ticks_per_second) << 16) / d;
return static_cast<uint32_t>(speed);
}
uint32_t stepgen::stepgen::next() {
// Read latest values once
uint32_t target_step = _tgt_step.load(std::memory_order_relaxed);
uint32_t target_delay = _tgt_delay.load(std::memory_order_relaxed);
uint32_t st = current_step();
if (st >= target_step && _speed <= 1) {
_speed = 0;
return 0;
}
// Stop slewing if target delay was changed
if (_slewing_delay && _slewing_delay != target_delay) {
_slewing_delay = 0;
}
// Steps made so far
_step.fetch_add(1, std::memory_order_relaxed);
if (_speed == 0) {
// First step: load first delay
_delay = _first_delay < target_delay ? target_delay : _first_delay;
_speed = 1;
return (_delay >> 8); // Convert to 16.8 format
}
// Calculate the projected step we would stop at if we start decelerating right now
uint32_t est_stop = st + _speed;
if (est_stop == target_step) {
// We would stop one step earlier than we want, so let's just
// return the same delay as the current one and start deceleration
// on the next step.
} else if (est_stop > target_step) {
// We need to stop at target step, slow down
slowdown();
// We are not slewing even though we could have slowed down below the slewing speed
_slewing_delay = 0;
} else if (!_slewing_delay && _delay < target_delay) {
// Not slewing and running too fast, slow down
slowdown();
// Switch to slewing if we slowed down enough
if (_delay >= target_delay) {
_slewing_delay = target_delay;
}
} else if (!_slewing_delay && _delay > target_delay) {
// Not slewing and running too slow, speed up
speedup();
// Switch to slewing if we have accelerated enough
if (_delay <= target_delay) {
_slewing_delay = target_delay;
}
}
// If slewing, return slew delay. delay should be close enough, but could
// be different due to the accumulated rounding errors
return (_slewing_delay ? _slewing_delay : _delay) >> 8; // Convert to 16.8 format
}
uint64_t stepgen::stepgen::sqrt(uint64_t x) {
uint64_t xr; // result register
uint64_t q2; // scan-bit register
xr = 0; // clear result
q2 = 0x4000000000000000LL; // higest possible result bit
do {
if ((xr + q2) <= x) {
x -= xr + q2;
xr >>= 1;
xr += q2; // test flag
} else {
xr >>= 1;
}
} while (q2 >>= 2); // shift twice
return xr < x ? xr + 1 : xr; // add for rounding
}
|
Markdown
|
UTF-8
| 2,497
| 2.921875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
---
title: JS Bin for Collaborative JavaScript Debugging
date: '2008-10-06 14:54:51'
published: true
tags:
- code
- code
- javascript
- project
- web
modified: '2014-09-03 16:15:12'
---
# JS Bin for Collaborative JavaScript Debugging
The weekend before last (28-Sep 2008) I blitzed through an idea I had on the shelf for about 6 months and put it live under the name [JS Bin](https://jsbin.com).
<!--more-->
## What is it?
JS Bin is a form of paste bin, but with a twist. It allows you to also include the HTML and CSS to provide context to your pasty. As such, it means you can actually run the JavaScript and pass this on to a colleague to help to debug.
A short list of features:
* Save private snippet
* Remote Ajax debugging
* Snippet URLs run entirely on their own (i.e. without the JS Bin framework around them)
* Support to quickly inject major JS libraries
* Saves state within the open window (i.e. refresh and the code doesn't reset)
In addition, any code snippet can be edited.
Take this example: [query string aware JavaScript](https://jsbin.com/utala/) ([https://jsbin.com/utala/](https://jsbin.com/utala/))
...to edit it, you just add '/edit' to the URL and you can modify the snippet yourself and save it as new:
[https://jsbin.com/utala/edit](https://jsbin.com/utala/edit)
## Why?
I had a conversation with [Rey Bango](http://www.reybango.com/) some months ago where he was trying to debug a piece of code that had an Ajax hit. He sent me the code, but without seeing it running I wasn't too much help to him.
I made a start some time ago offline and planned for a system to allow you to create fake Ajax handlers to respond to requests.
In the last couple of weeks I saw [John Resig's learning app](http://ejohn.org/apps/learn/) and the sandbox idea suddenly had legs again. I knew I could write something very quickly, almost entirely in JavaScript (and since it's a JS debugger, there's no point in the extra work to make it degrade).
A small server side php file does the saving work (and maintaining old code snippets) and over the course of a few hours I had a fully working webapp that allows me to create Ajax responders and code snippets that run live and can make real Ajax calls.
## Examples
I've recorded a couple of screencasts showing how it can be used:
* [General introduction](https://jsbin.com/about#video)
* [Ajax debugging](https://jsbin.com/about#ajax)
## Feedback
If anyone has suggestions, feedback, bugs, etc - please let me know!
|
Java
|
UTF-8
| 1,433
| 3.015625
| 3
|
[] |
no_license
|
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package linter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class App {
public String getGreeting() {
return "Hello World!";
}
public static void main(String[] args) {
String path="./app/src/main/resources/gates.js";
ArrayList<String> acceptedArr =errors(path);
for (String item:
acceptedArr) {
System.out.println(item);
}
}
public static ArrayList<String> errors(String path){
ArrayList<String> errorsArr=new ArrayList<String>();
try {
Path acceptedPath = Paths.get(path);
List<String> fileLines = Files.readAllLines(acceptedPath);
int lineNum=0;
for (String line : fileLines) {
lineNum++;
if (line.endsWith("}") || line.endsWith("{") || line.equals("") || line.endsWith(
";") || line.contains("if") || line.contains("else")) {
} else {
errorsArr.add("Line "+lineNum+": Missing semicolon.");
}
}
} catch (IOException exception) {
System.out.println("An error occurred while reading from file");
}
return errorsArr;
}
}
|
Python
|
UTF-8
| 416
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
from constants import *
# creates laser class
class Laser(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((5, 10))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speedy = -30
def update(self):
self.rect.y += self.speedy
|
C++
|
UTF-8
| 1,740
| 3.46875
| 3
|
[] |
no_license
|
//***************************************************************
// File: StockBST.h
//
// Purpose: Header file for Stock Binary Search Tree
//
// BCS 370 - Data Structures Homework #5
//
// Written By: Michael Kruger
//
// Compiler: Visual C++ 2015\
//***************************************************************
#ifndef STOCKBST_H
#define STOCKBST_H
#include <iostream>
#include "StockClass.h"
using namespace std;
class StockBST {
private:
struct StockBSTNode {
StockBSTNode* left;
StockBSTNode* right;
Stock info;
};
StockBSTNode *root;
int length; //Tracks size of the tree
//Helper Functions
void Add(StockBSTNode*& root, Stock s);
void Inorder(StockBSTNode* root);
void Preorder(StockBSTNode* root);
void Postorder(StockBSTNode* root);
void Clear(StockBSTNode* root);
void StockBST::CopyTree(StockBSTNode*& copy, const StockBSTNode* originalTree); //Copies one tree to another
bool RetrieveItem(StockBSTNode * m_root, string s, double &shares);
public:
StockBST(); //Default Constructor
StockBST(const StockBST& rhs); //Copy Constructor
~StockBST(); //Destructor
void Clear(); //Clears the tree
int Size(); //Returns the size of the tree
void Add(Stock s); //Sorted by NAME!
void Preorder(); //Process Node, Left, Right (Runtime: n)
void Inorder(); //Left, Process Node, Right (Runtime: n)
void Postorder(); //Left, Right, Process Node (Runtime: n)
bool getShares(string name, double& shares); //Use a Preoder() to search through the tree
StockBST& operator=(const StockBST& rhs); //Assignment overload for StockBST class
void PrintTree(StockBSTNode *root, ostream& os);
friend ostream& operator<<(ostream& os, StockBST s); //Ostream operator overload for StockBST Class (Friend)
};
#endif
|
C#
|
UTF-8
| 1,990
| 3.578125
| 4
|
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CLOP_TEST
{
class MyDictionary : IEnumerable
{
// Не пригодилось
private List<DictionaryItem> Items = new List<DictionaryItem>();
public List<string> Keys = new List<string>();
public int Count => Items.Count;
public List<int> GetValues()
{
var Values = new List<int>();
foreach (var item in Items)
{
Values.Add(item.Value);
}
return Values;
}
public MyDictionary()
{
}
public void Add(DictionaryItem item)
{
if(Search(item.Key) == true)
{
//Если такого не найдено, то мы добавляем item и Value=1
Keys.Add(item.Key);
Items.Add(item);
item.Value = 1;
}
else if (Search(item.Key) == false)
{
//Если найдено, то мы добавляем ему Value\
item.Value++;
return;
}
}
public void ShowKeys ()
{
foreach (string item in Keys)
{
Console.WriteLine(item);
}
}
public bool Search(string key)
{
foreach (string atribute in Keys)
{
if (key == atribute) return true;
}
return false;
}
public bool CointainsKey(DictionaryItem item)
{
if (Keys.Contains(item.Key))
{
return true;
}
else return false;
}
public IEnumerator GetEnumerator ()
{
return Items.GetEnumerator();
}
}
}
|
Markdown
|
UTF-8
| 3,259
| 4.125
| 4
|
[] |
no_license
|
## 02条件语句和while循环
三目运算
```python
a = 6
#原判断语句
if a > 5:
print(True)
else:
print(False)
#三目运算
print(True if a >5 else False)
```
## 逻辑运算
1. 三种逻辑运算
与逻辑 and
两边为真则为真
或逻辑 or
一边为真则为真
非逻辑
not 逻辑值取反
优先级: not > and > or
2.逻辑短路
```python
# and 逻辑短路
a = 3 #没有对b赋值,但程序不会报错能够正常运行
#左边布尔值为假,右边布尔值的真假性不影响整体布尔值为假
print(a > 4 and b > 4) #输出布尔值为False
# or 逻辑短路
a = 3 #没有对b赋值,但程序不会报错能够正常运行
#左边布尔值为真,右边布尔值的真假性不影响整体布尔值为真
print(a > 2 and b > 2) #输出布尔值为True
# not 没有逻辑短路
```
3.连续判断
```python
#python底层会把连续判断转换成 and 连接的形式
print(1 > 2 > 3) #相当于 1>2 and 2>3, 其值为False
#连续判断的逻辑短路
#由于and存在逻辑短路,所以连续判断也存在逻辑短路
#整数2和字符串'3'类型不同无法比较大小
#左边1>2布尔值为假,右边无需进行判断,所以不会报错
print(1 > 2 > '3') #输出布尔值为False
```
while循环
```python
#循环条件可以为True,但内部必须要有break保证循环能够被终止,否则将陷入死循环
#使用break终止的循环属于非正常结束循环,不会执行else部分
a = 1
while True:
if a % 5 == 0:
break
print(a)
a += 1
else:
print('循环结束')
```
练习
利用while 写出九九乘法表
```python
#使用continue终止的循环不属于非正常结束循环,循环结束后会执行else部分
a = 1
while a < 4:
if a % 2 == 0:
a += 1
continue
print(a)
a += 1
else:
print('循环结束')
```
利用random 的randint 方法写一个猜数字的小游戏
```python
i = 1
while i < 10:
j = 1
while j <= i:
result = '%-3d'%(i*j)
print(f'{j}×{i}={result}', end='')
j += 1
print('\n')
i += 1
```
```python
print('1~100以内整数的猜数字游戏,总共7次机会哦!')
import random
Min = 1
Max = 100
mynumber = random.randint(Min, Max)
i = 1
while i <= 7:
yournumber = int(input('请输入你猜的数字:'))
if yournumber == mynumber:
print('恭喜你,猜对了!你真聪明!')
break
elif yournumber > mynumber:
Max = yournumber
print(f'你猜的太大了,在{Min}~{Max}之间哦!你还有{7-i}次机会!')
i += 1
else:
Min = yournumber
print(f'你猜的太小了,在{Min}~{Max}之间哦!你还有{7-i}次机会!')
i += 1
else:
print('机会已经用完了!很遗憾,你没有猜对!')
```
到此这篇关于详解python 条件语句和while循环的文章就介绍到这了,更多相关python
条件语句和while循环内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
|
Java
|
UTF-8
| 1,845
| 2.375
| 2
|
[] |
no_license
|
package com.developer.edu.app_arco.bd;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB_OpemHelper extends SQLiteOpenHelper {
private static final String nomeBD = "DB01";
private static final int versaoBD = 1;
private String createTableUsuario =
"create table Usuario(" +
"id integer primary key, " +
"nome text, " +
"sobrenome text," +
"escolaridade text," +
"cpf text," +
"data_nasc text," +
"email text," +
"sexo text," +
"bio text," +
"tipo text," +
"situacao text," +
"online text" +
");";
private String createTableEscolaridade =
"create table Escolaridade(" +
"id integer primary key, " +
"instituicao text, " +
"area text," +
"ano text," +
"grupos text," +
"descricao text," +
"id_usuario text" +
");";
private String dropTableUsuario = "drop table Usuario";
private String dropTableEscolaridade = "drop table Escolaridade";
public DB_OpemHelper(Context context) {
super(context, nomeBD, null, versaoBD);
}
@Override
public void onCreate(SQLiteDatabase bd) {
bd.execSQL(createTableUsuario);
bd.execSQL(createTableEscolaridade);
}
@Override
public void onUpgrade(SQLiteDatabase bd, int i, int i1) {
bd.execSQL(dropTableUsuario);
bd.execSQL(dropTableEscolaridade);
onCreate(bd);
}
}
|
C#
|
UTF-8
| 1,464
| 3.59375
| 4
|
[] |
no_license
|
using System;
using System.Globalization;
namespace _05_ExercicioContaBanco
{
public class Conta
{
private int TaxaSaque = 5;
public int Numero { get; private set; }
public string Titular { get; set; }
public double Saldo { get; private set; }
public Conta() {}
public Conta(int numero, string titular)
{
Numero = numero;
Titular = titular;
}
public Conta(int numero, string titular, double saldo) : this(numero, titular)
{
Saldo = saldo;
}
public override string ToString()
{
return "Conta: " + Numero + ", Titular: " + Titular + ", Saldo: $" + Saldo.ToString("F2", CultureInfo.InvariantCulture);
}
public void Deposito(double valor)
{
if(valor > 0)
{
this.Saldo += valor;
}
else
{
Console.WriteLine("Informe um valor válido!");
}
Console.WriteLine("Dados da conta atualizados: " + this);
}
public void Saque(double valor)
{
if(valor > 0)
{
this.Saldo -= (valor + TaxaSaque);
}
else
{
Console.WriteLine("Informe um Valor válido");
}
Console.WriteLine("Dados da conta atualizados: " + this);
}
}
}
|
Python
|
UTF-8
| 3,995
| 3.71875
| 4
|
[] |
no_license
|
'''
Homework-2-CS515
author Zimu Jiao
'''
'''
Q1: dot(L,K): Return the sim of dot product of to list, if the length of two list are different, the result is option-
-al,
Assume the length are equal. And the output should be 0.0 when two list are empty
Example: dot([5,3],[6,4])=> 5*6+3*4=12
Q2: explore(S): Take a string S and return a list of characters in string.
Example: explore("spam")=> ['s','p','a','m'] explore("")=> []
Q3: ind(e,L): Take an element e and a sequence L(List or Sting), return the index of first e in L. Begin at 0.
If e is not in L, return the length of L.
Example: ind(42,[55,77,42,12,42,100])=> 2
ind(42, range(0,100))=> 42
ind('hi',['hello',42,True]=> 3
ind(' ','outer exploration')=> 5
Q4: deepReverse(L):
List as input, return the reverse.
Example: deepReverse([1,2,3])=> [3,2,1]
deepReverse([1,[2,3],4])=>[4,[3,2],1]
deepReverse([1,[2,[3,4],[5,[6,7],8]]])=> [[[8,[7,6],5],[4,3],2],1]
if isinstance(x,list):
# if True
else:
# if False
'''
import types
def dot(L,K):
'''
:param L: list of integer;
:param K: list of integer;
L and K should have same length.
:return: the dot product of L and K, if the length of them are not equal, the result will be depend on the shorter
one.
'''
if(L==[] or K==[]): # When K or L is empty, set sum = 0.0 and return sum.
sum=0.0
return sum
if(L[1:]==[] or K[1:]==[]): # When K or L will end up next turn, the sum end at this turn;
sum=L[0]*K[0]
else:
sum=L[0]*K[0]+dot(L[1:],K[1:]) # Or the sum will calculate the next turn.
return sum
def explore(s):
'''
:param s: String s
:return: A list of each element in s
'''
result=[]
if(s!=""): # When String is not empty:
result.append(s[0]) # Add the first char to result, the return_list
if(s[1:]!=""): # If String s is more than 2 char, do the recursion by shorten it 1.
return result+explore(s[1:])
else:
return result # Or end up.
def ind(e,L):
'''
:param e: An element, can be integer, char, string
:param L: A list
:return: If e in L, return its index; else return the length of L.
Notice: Since the type of range()'s return is not a list, if e is out of L from range(), the result will be error
'''
count=0
if(e==L[0]): # When the e is found in L, return the count
return count
else: # When e is not found yet, count +1
count=count+1
if(L[1:]==[]): # When e is not in L, return the count, which now equal to L-list's length.
return count
else: # When e is not found count, recurse- in L[1:] to find e.
count=count+ind(e,L[1:])
return count
def deepReverse(L):
'''
:param L: A list
:return: A list of reversed L, if elements in L are list, that list will be reversed.
'''
newL=[]
for item in L[::-1]: # Check list from the end to head.
if isinstance(item,list): # Check if item is list:
item=deepReverse(item) # Yes: Set it as reversed.
newL.append(item) # Add it to the new List.
return newL
if __name__ == '__main__':
A=[]
A1=[2,3]
B=[2,4]
print(dot(A,B))
print(dot(A1,B))
s="Hello world!"
print(explore(s))
print(ind(3,range(0,9)))
L1=[1,2,3]
L2=[1,[2,3],4]
L3=[1,[2,[3,4],[5,[6,7],8]]]
print(deepReverse(L1))
print(deepReverse(L2))
print(deepReverse((L3)))
|
PHP
|
UTF-8
| 1,044
| 2.5625
| 3
|
[] |
no_license
|
<?php
namespace Nemundo\Content\App\Website\Content\Webpage;
use Nemundo\Content\App\Website\Data\Webpage\WebpageModel;
use Nemundo\Content\Form\AbstractContentForm;
use Nemundo\Package\Bootstrap\FormElement\BootstrapLargeTextBox;
use Nemundo\Package\Bootstrap\FormElement\BootstrapTextBox;
class WebpageContentForm extends AbstractContentForm
{
/**
* @var WebpageContentType
*/
public $contentType;
/**
* @var BootstrapTextBox
*/
private $pageTitle;
/**
* @var BootstrapTextBox
*/
private $description;
public function getContent()
{
$model=new WebpageModel();
$this->pageTitle=new BootstrapTextBox($this);
$this->pageTitle->label=$model->title->label;
$this->pageTitle->validation=true;
$this->description=new BootstrapLargeTextBox($this);
$this->description->label=$model->description->label;
return parent::getContent();
}
public function onSubmit()
{
$this->contentType->saveType();
}
}
|
C++
|
UTF-8
| 2,017
| 2.796875
| 3
|
[] |
no_license
|
#include "ZMTY.h"
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979
void ZMTY::ZMTYInitial(int newW,int newH,int newn)
{
W=newW;
H=newH;
n=newn;
hfov=2*PI/n;
f=W/2/tan(hfov/2);
}
/////////////////////////////////////////////////
void ZMTY::ZMTYCaculate1(double newx,double newy)
{
x=newx,y=newy;
t=f/sqrt((x-W/2)*(x-W/2)+f*f);
u=f*(x-W/2)/sqrt((x-W/2)*(x-W/2)+f*f);
v=f*(y-H/2)/sqrt((x-W/2)*(x-W/2)+f*f);
w=f*f/sqrt((x-W/2)*(x-W/2)+f*f);
x1=f*hfov/2+f*atan(u/w);
y1=v+H/2;
}
void ZMTY::ZMTYfCaculate1(double newx1,double newy1)
{
x1=newx1;
y1=newy1;
x=f*tan(x1/f-hfov/2)+W/2;
y=(y1-H/2)*sqrt((x-W/2)*(x-W/2)+f*f)/f+H/2;
}
/////////////////////////////////////////////////
void ZMTY::ZMTYCaculate2(double newx,double newy)
{
x=newx,y=newy;
x1=f*sin(hfov/2)+f*sin(atan((x-W/2)/f));
y1=H/2+f*(y-H/2)/sqrt((x-W/2)*(x-W/2)+f*f);
}
void ZMTY::ZMTYfCaculate2(double newx1,double newy1)
{
x1=newx1;
y1=newy1;
x=f*tan(asin(x1/f-sin(hfov/2)))+W/2;
y=(y1-H/2)*sqrt((x-W/2)*(x-W/2)+f*f)/f+H/2;
}
/////////////////////////////////////////////////
void ZMTY::ZMTYfCaculate3(double newx1,double newy1)
{
x1=newx1;
y1=newy1;
// x=f*tan(asin(x1/f-sin(hfov/2)))+W/2;
// y=(y1-H/2)*sqrt((x-W/2)*(x-W/2)+f*f)/f+H/2;
double p = 1.8;
double dx = x - w/2;
double dy = y - H/2;
double r = sqrt(dx*dx + dy *dy);
double z = sqrt((w/2)*(w/2)-r*r);
double beta_x = (1-1/p)* asin(dx/(sqrt(dx*dx+z*z)));
double beta_y = (1-1/p)* asin(dy/(sqrt(dy*dx+z*z)));
x = x1-z*tan(beta_x);
y = y1-z*tan(beta_y);
}
void ZMTY::ZMTYfCaculate4(double newx1,double newy1)
{
x1=newx1;
y1=newy1;
double xc = W/2;
double yc = H/2;
x=f*tan(x1/f-hfov/2)+xc;
//y=(y1-yc)*sqrt((x-xc)*(x-xc)+f*f)/f+yc;
y=f*(y1-yc)/sqrt((x-xc)*(x-xc)+f*f)+yc;
}
void ZMTY::ZMTYfCaculate5(double newx1,double newy1)
{
x1=newx1;
y1=newy1;
double xc = W/2;
double yc = H/2;
x=f*tan(x1/f-hfov/2)+xc;
//y=(y1-yc)*sqrt((x-xc)*(x-xc)+f*f)/f+yc;
double alpha = tan((y1-yc)/sqrt((x-xc)*(x-xc)+f*f));
y=f*alpha+yc;
}
|
Markdown
|
UTF-8
| 1,369
| 2.8125
| 3
|
[
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
---
title: Screen tracking for analytics
---
import { FileTree } from '~/ui/components/FileTree';
Unlike React Navigation, Expo Router always has access to a URL. This means screen tracking is as easy as the web.
1. Create a higher-order component that observes the currently selected URL
2. Track the URL in your analytics provider
<FileTree files={['app/_layout.js']} />
```js app/_layout.js
import { useEffect } from 'react';
import { usePathname, useGlobalSearchParams, Slot } from 'expo-router';
export default function Layout() {
const pathname = usePathname();
const params = useGlobalSearchParams();
// Track the location in your analytics provider here.
useEffect(() => {
analytics.track({ pathname, params });
}, [pathname, params]);
// Export all the children routes in the most basic way.
return <Slot />;
}
```
Now when the user changes routes, the analytics provider will be notified.
## Migrating from React Navigation
React Navigation's [screen tracking guide](https://reactnavigation.org/docs/screen-tracking/) cannot make the same assumptions about the navigation state that Expo Router can. As a result, the implementation requires the use of `onReady` and `onStateChange` callbacks. Avoid using these methods if possible as the root `<NavigationContainer />` is not directly exposed and allows cascading in Expo Router.
|
Java
|
UTF-8
| 976
| 2.515625
| 3
|
[] |
no_license
|
/**
* Copyright © 2013/2014, Veljko Zivkovic
* All rights reserved.
*
* No portion of this file may be reproduced in any form, or by any means, without the prior written
* consent of the author.
*/
package com.tirion.db.sql.parser;
import java.io.File;
import junit.framework.TestCase;
import com.tirion.common.file.FileUtil;
import com.tirion.db.sql.ast.Node;
public class SimpleParserTest extends TestCase {
public void test() {
Parser parser = new SimpleParser();
parser.init();
String text = FileUtil.readTextFileFully(new File("src/test/resources/statements.sql"));
String[] statements = text.split(";");
for(String statement : statements) {
statement = statement.trim();
if(statement.equals("")) {
continue;
}
statement = statement + ";";
try {
Node node = parser.parse(statement);
assertNotNull(node);
} catch (Exception e) {
throw new RuntimeException("Exception while parsing '" + statement + "'", e);
}
}
}
}
|
Java
|
UTF-8
| 3,065
| 2.421875
| 2
|
[] |
no_license
|
/*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2016
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.FurryKingdoms.Registry;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import net.minecraft.world.biome.BiomeGenBase;
import Reika.DragonAPI.Exception.RegistrationException;
import Reika.FurryKingdoms.FurryKingdoms;
import Reika.FurryKingdoms.Base.CityBiome;
public enum SpeciesType {
DRAGON(60, 0.5F),
FELINE(30, 0.8F),
CANINE(30, 0.8F),
VULPINE(20, 0.9F),
SHARK(50, 0.3F),
CETACEAN(50, 0.5F),
REPTILE(30, 0.6F),
AVIAN(20, 0.9F),
EQUES(40, 0.8F);
private int health;
private float damageFactor;
private String name;
public static final SpeciesType[] speciesList = values();
private static final HashMap<SpeciesType, BiomeGenBase> cities = new HashMap();
private SpeciesType(int halfhearts, float dura) {
health = halfhearts;
damageFactor = dura;
}
public String getSpeciesName() {
return this.name().substring(0, 1)+this.name().toLowerCase(Locale.ENGLISH).substring(1);
}
public int getMaxHealth() {
return health;
}
public float getHurtability() {
return damageFactor;
}
public boolean canBeAquatic() {
if (this == CETACEAN)
return true;
if (this == SHARK)
return true;
if (this == DRAGON)
return true;
return false;
}
public boolean canBeTerrestrial() {
return true;
}
public int getCityBiomeID() {
return FurryKingdoms.config.getCityID(this.ordinal());
}
public Class getBiomeClass() {
switch(this) {
default:
return CityBiome.class;
}
}
public void addBiome() {
cities.put(this, this.createBiomeInstance());
}
private CityBiome createBiomeInstance() {
Class b = this.getBiomeClass();
int id = this.getCityBiomeID();
Class[] cs = new Class[]{int.class, SpeciesType.class};
Object[] o = new Object[]{id, this};
try {
Constructor c = b.getConstructor(cs);
return (CityBiome)c.newInstance(o);
}
catch (NoSuchMethodException e) {
throw new RegistrationException(FurryKingdoms.instance, "City biome constructor "+Arrays.toString(cs)+" not found!");
}
catch (SecurityException e) {
throw new RegistrationException(FurryKingdoms.instance, "Security Exception!");
}
catch (InstantiationException e) {
throw new RegistrationException(FurryKingdoms.instance, "Non-Instantiable Class!");
}
catch (IllegalAccessException e) {
throw new RegistrationException(FurryKingdoms.instance, "Private/Protected Constructor!");
}
catch (IllegalArgumentException e) {
throw new RegistrationException(FurryKingdoms.instance, "Invalid Args!");
}
catch (InvocationTargetException e) {
throw new RegistrationException(FurryKingdoms.instance, "Other!");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.