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
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 688 | 2.765625 | 3 |
[] |
no_license
|
import glob
import os
import re
import sys
directory = sys.argv[1]
hand_history_directory = sys.argv[2]
hand_id_to_extract = input("Please enter id of the hand:")
if not hand_id_to_extract.strip():
sys.exit()
hand_history_extract = os.path.join(directory, hand_history_directory + "_hh.txt")
to_write_file = open(hand_history_extract, "a")
for hand_history_file in glob.glob(os.path.join(directory, hand_history_directory + "\**.txt")):
with open(hand_history_file, 'r') as file:
hands = re.split(r'\n(?=Poker Hand)', file.read())
for hand in hands:
if hand_id_to_extract in hand:
to_write_file.write(hand)
to_write_file.close()
|
C#
|
UTF-8
| 1,283 | 2.75 | 3 |
[] |
no_license
|
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NotEnoughDB.Models
{
public class Order
{
[BsonId]//Only for MongoDB
public int ID { get; set; }
public long? ID_pos { get; set; }//Only for OrientDB
public int? UID { get; set; }
public long? UID_pos { get; set; }//Only for OrientDB
public int? SID { get; set; }
public long? SID_pos { get; set; }//Only for OrientDB
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public override string ToString()
{
if((ID_pos ?? UID_pos ?? SID_pos) == null)
return $"ID: {ID,4} User: {UID,4} Server: {SID,4}\nFrom: {DateFrom?.ToString("yyyy-MM-dd"),10} To: {DateTo?.ToString("yyyy-MM-dd"),10}";
return $"ID: {ID,4}{(ID_pos != null ? ":" + ID_pos : "")}" + //Only for OrientDB
$" User: {UID,4}{(UID_pos != null ? ":" + UID_pos : "")}" +
$" Server: {SID,4}{(SID_pos != null ? ":" + SID_pos : "")}" +
$"\nFrom: {DateFrom?.ToString("yyyy-MM-dd"),10} To: {DateTo?.ToString("yyyy-MM-dd"),10}";
}
}
}
|
C++
|
UTF-8
| 4,692 | 2.875 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>
#include <cmath>
#include <numeric>
#include <bitset>
#include "helper_functions.h"
using namespace std;
struct mask_str {
bitset<36> onemask = 0;
bitset<36> zeromask = 0;
bitset<36> xmask = 0;
};
bitset<36> flip_specific_bits(bitset<36> number, bitset<36> mask, bool value);
void write_memory_recursive(int ind, mask_str &mask, bitset<36> memory_location, bitset<36> memory_value, map<long long, long long> &m);
int main(){
// parse input
string filename = "../../data/day14input.txt";
ifstream file;
vector<mask_str> masks;
vector<vector<long long>> memory;
vector<vector<bitset<36>>> values;
map<long long, long long> m;
file.open(filename);
vector<long long> memory_temp;
vector<bitset<36>> values_temp;
if (file.is_open()){
string line;
while(getline(file, line)){
char action[3];
sscanf(line.c_str(), "%s ", action);
if (string(action) == "mask"){
char mask[36];
sscanf(line.c_str(), "%*s = %s", mask);
mask_str mask_temp;
for (int i=0; i<36; i++){
if (mask[i] == 'X'){
mask_temp.xmask[i] = 1;
}
else if (mask[i] == '0'){
mask_temp.zeromask[i] = 1;
}
else if (mask[i] == '1'){
mask_temp.onemask[i] = 1;
}
}
masks.push_back(mask_temp);
if (masks.size() > 1){
values.push_back(values_temp);
memory.push_back(memory_temp);
values_temp.clear();
memory_temp.clear();
}
}
if (string(action).find("mem") != string::npos){
long long mem;
long long value;
sscanf(line.c_str(), "mem[%lli] = %lli", &mem, &value);
values_temp.push_back(value);
memory_temp.push_back(mem);
}
}
values.push_back(values_temp);
memory.push_back(memory_temp);
}
else {
cout << "file not opened" << endl;
}
// part 1
for (int i=0; i<masks.size(); i++){
mask_str mask_temp = masks.at(i);
for (int j=0; j<memory.at(i).size(); j++){
bitset<36> value_temp = values.at(i).at(j);
bitset<36> mem_temp = memory.at(i).at(j);
value_temp = flip_specific_bits(value_temp, mask_temp.onemask, 1);
value_temp = flip_specific_bits(value_temp, mask_temp.zeromask, 0);
m[mem_temp.to_ullong()] = value_temp.to_ullong();
}
}
// sum up hash map
long long sum = 0;
for (map<long long, long long>::iterator it = m.begin(); it != m.end(); it++){
sum += it->second;
}
cout << "part 1: " << sum << endl;
// part 2
m.clear();
for (int i=0; i<masks.size(); i++){
mask_str mask_temp = masks.at(i);
for (int j=0; j<memory.at(i).size(); j++){
bitset<36> value_temp = values.at(i).at(j);
bitset<36> mem_temp = memory.at(i).at(j);
mem_temp = flip_specific_bits(mem_temp, mask_temp.onemask, 1);
write_memory_recursive(0, mask_temp, mem_temp, value_temp, m);
}
}
// sum up hash map
sum = 0;
for (map<long long, long long>::iterator it = m.begin(); it != m.end(); it++){
sum += it->second;
}
cout << "part 2: " << sum << endl;
return 0;
}
bitset<36> flip_specific_bits(bitset<36> number, bitset<36> mask, bool value){
// sets all bits specified by 'mask' to 'value' in variable 'number'
for (int i=0; i<number.size(); i++){
if (mask[i] == 1){
number.set(35-i, value);
}
}
return number;
}
void write_memory_recursive(int ind, mask_str &mask, bitset<36> memory_location, bitset<36> memory_value, map<long long, long long> &m){
// recursively write to hashmap all memory values branching off of original memory value
// as specified by the "floating bits" in xmask
if (ind == 36){
m[memory_location.to_ullong()] = memory_value.to_ullong();
}
else{
write_memory_recursive(ind+1, mask, memory_location, memory_value, m);
if (mask.xmask[ind] == 1){
write_memory_recursive(ind+1, mask, memory_location.flip(35-ind), memory_value, m);
}
}
}
|
Shell
|
UTF-8
| 314 | 3.03125 | 3 |
[] |
no_license
|
#!/bin/bash
MYPATH=$(realpath $0)
cd $(dirname $MYPATH)
db_version=$(python3 manage.py db_version)
cur_version=$(python3 manage.py version)
if [ "$db_version" != "$cur_version" ]
then
echo "Upgrading local database to match the code version"
python3 manage.py upgrade || exit 1
fi
python3 src/fsperf.py "$@"
|
C#
|
UTF-8
| 22,906 | 2.765625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace Exodus.Configuration
{
public static class ConfigFile
{
#region Variables
// xml elems
static XmlDocument doc = new XmlDocument();
static XmlElement xmlRoot = null;
static XmlElement xmlGlobal = null;
static XmlElement xmlNamed = null;
static XmlElement xmlSections = null;
// set values
static string file_name = "application.config";
static string folder = "config";
// xml names
private static readonly string strGlobalRoot = "global_root";
private static readonly string strNamed = "named";
private static readonly string strRoot = "root";
private static readonly string strSections = "sections";
private static readonly string strConfiguration = "configuration";
#endregion
#region Properties
public static string File_Name
{
get { return file_name; }
set
{
if (!Validate_FileName(value)) { throw new Exception("Invalid file name"); }
if (Path.HasExtension(value) && Path.GetExtension(value) != ".config") { throw new Exception("Invalid extinsion"); }
else if (!Path.HasExtension(value)) { value = value + ".config"; }
file_name = value;
}
}
public static string Folder_Name
{
get { return folder; }
set
{
if (!Validate_FolderName(value)) { throw new Exception("Invalid file name"); }
folder = value;
}
}
public static string Full_Path
{
get { return new FileInfo(Path.Combine(Folder_Name, File_Name)).FullName; }
}
public static string Default_Elem_Name { get; } = "add";
public static string Default_File_Name { get; } = "application.config";
public static string Default_Folder_Name { get; } = "config";
public static List<ConfigSection> Sections
{
get
{
if (xmlSections == null) { return null; }
return xmlSections.GetElementsByTagName("*").Cast<XmlElement>().Select(a => new ConfigSection(a)).ToList();
}
}
public static List<ConfigElem> Elems
{
get
{
if (xmlRoot == null) { return null; }
return xmlRoot.GetElementsByTagName(Default_Elem_Name).Cast<XmlElement>().Select(a => new ConfigElem(a)).ToList();
}
}
public static List<ConfigElemNamed> ElemsNamed
{
get
{
if (xmlNamed == null) { return null; }
return xmlNamed.GetElementsByTagName(Default_Elem_Name).Cast<XmlElement>().Select(a => new ConfigElemNamed(a)).ToList();
}
}
public static List<string> Keys
{
get
{
if (xmlRoot == null) { throw new Exception("root of file is null"); }
return xmlRoot.GetElementsByTagName("*").Cast<XmlElement>().Select(a => a.GetAttribute("key")).ToList();
}
}
#endregion
#region Validation
public static bool Validate_Path(string path)
{
if (String.IsNullOrEmpty(path) || String.IsNullOrWhiteSpace(path)) { return false; }
else if (Path.GetFileName(path).IndexOfAny(Path.GetInvalidFileNameChars()) != -1) { return false; }
else if (path.IndexOfAny(Path.GetInvalidPathChars()) != -1) { return false; }
else { return true; }
}
public static bool Validate_FileName(string name)
{
if (String.IsNullOrEmpty(name) || String.IsNullOrWhiteSpace(name)) { return false; }
else if (name.IndexOfAny(Path.GetInvalidFileNameChars()) != -1) { return false; }
else { return true; }
}
public static bool Validate_FolderName(string name)
{
if (String.IsNullOrEmpty(name) || String.IsNullOrWhiteSpace(name)) { return false; }
else if (name.IndexOfAny(Path.GetInvalidPathChars()) != -1) { return false; }
else { return true; }
}
#endregion
#region Create Or Load
public static bool Create(string path)
{
if (String.IsNullOrEmpty(path))
{ throw new FormatException("path is null or empty"); }
try
{
string fName = Path.GetFileName(path);
string folderName = Path.GetDirectoryName(path);
if (String.IsNullOrEmpty(fName)) { File_Name = Default_File_Name; }
else if (Path.GetExtension(fName) != "config") { throw new Exception("Incorrect Extension"); }
else { File_Name = fName; }
if (String.IsNullOrEmpty(folderName)) { Folder_Name = Default_Folder_Name; }
else { Folder_Name = folderName; }
if (File.Exists(Full_Path)) { File.Delete(Full_Path); }
if (!Directory.Exists(Folder_Name)) { Create_Folder(Folder_Name); }
doc = new XmlDocument();
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
// Create the root element
doc.InsertBefore(xmlDeclaration, doc.DocumentElement);
xmlGlobal = new XElement(strGlobalRoot, new XAttribute("id", strGlobalRoot)).ToXmlElement(doc);
xmlRoot = new XElement(strRoot, new XAttribute("id", strRoot)).ToXmlElement(doc);
xmlNamed = new XElement(strNamed, new XAttribute("id", strNamed)).ToXmlElement(doc);
xmlSections = new XElement(strSections, new XAttribute("id", strSections)).ToXmlElement(doc);
xmlGlobal.AppendChild(new XElement(strConfiguration, new XAttribute("creation_time", DateTime.Now.ToString())).ToXmlElement(doc));
xmlGlobal.AppendChild(xmlRoot);
xmlGlobal.AppendChild(xmlNamed);
xmlGlobal.AppendChild(xmlSections);
doc.AppendChild(xmlGlobal);
doc.Save(Full_Path);
return true;
}
catch (Exception ex)
{
xmlSections = xmlNamed = xmlGlobal = xmlRoot = null;
throw ex;
}
}
private static bool Create_Folder(string path)
{
if (!Validate_FolderName(path)) { throw new Exception("Invalid folder path"); }
try
{
string[] path_list = path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
path = "";
foreach (string p in path_list)
{
path += p;
if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
path += '\\';
}
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool Load(string path)
{
if (String.IsNullOrEmpty(path))
{ throw new FormatException("path is null or empty"); }
else if (!File.Exists(path))
{ throw new FileNotFoundException("File not found", Path.GetFileName(path)); }
else
{
Folder_Name = Path.GetDirectoryName(path);
File_Name = Path.GetFileName(path);
}
try
{
doc = new XmlDocument();
doc.Load(path);
xmlRoot = doc.DocumentElement.GetElementsByTagName(strRoot).Cast<XmlElement>().FirstOrDefault();
xmlNamed = doc.DocumentElement.GetElementsByTagName(strNamed).Cast<XmlElement>().FirstOrDefault();
xmlSections = doc.DocumentElement.GetElementsByTagName(strSections).Cast<XmlElement>().FirstOrDefault();
xmlGlobal = doc.DocumentElement;
if (xmlRoot == null || xmlRoot.GetAttribute("id") != strRoot)
{ xmlRoot = null; throw new Exception("Incorrect xml elem " + strRoot + " not found"); ; }
else if (xmlGlobal == null || xmlGlobal.Name != strGlobalRoot || xmlGlobal.GetAttribute("id") != strGlobalRoot)
{ xmlGlobal = null; throw new Exception("Incorrect xml elem " + strGlobalRoot + " not found"); }
else if (xmlNamed == null || xmlNamed.GetAttribute("id") != strNamed)
{ xmlNamed = null; throw new Exception("Incorrect xml elem " + strNamed + " not found"); }
else if (xmlSections == null || xmlSections.GetAttribute("id") != strSections)
{ xmlSections = null; throw new Exception("Incorrect xml elem " + strSections + " not found"); }
else
{ return true; }
}
catch (Exception ex)
{
xmlRoot = xmlGlobal = xmlNamed = xmlSections = null;
throw ex;
}
}
public static bool CreateOrLoad(string path)
{
if (!File.Exists(path))
{ return Create(path); }
else
{ return Load(path); }
}
#endregion
#region Save Delete
public static bool Save(string path)
{
try
{
if (!Validate_Path(path)) { throw new FormatException("Invalid path"); }
if (File.Exists(path)) { File.Delete(path); }
doc.Save(path);
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool Save()
{
return Save(Full_Path);
}
public static bool Remove(string key)
{
try
{
xmlRoot.GetElementsByTagName(Default_Elem_Name)
.Cast<XmlElement>().Where(a => a.GetAttribute("key") == key).ToList()
.ForEach(a => a.ParentNode.RemoveChild(a));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool RemoveNamed(string name)
{
try
{
xmlNamed.GetElementsByTagName(name)
.Cast<XmlElement>().ToList()
.ForEach(a => a.ParentNode.RemoveChild(a));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool Remove_Section(string name)
{
try
{
xmlSections.GetElementsByTagName(name).Cast<XmlElement>().ToList()
.ForEach(a => a.ParentNode.RemoveChild(a));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
#endregion
#region Add Zone
public static bool Add(string key, string value)
{
try
{
var count = xmlRoot.GetElementsByTagName(Default_Elem_Name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key && a.GetAttribute("value") == value).Count();
if (count != 0) { return false; }
xmlRoot.AppendChild(new XElement(Default_Elem_Name, new XAttribute("key", key), new XAttribute("value", value)).ToXmlElement(doc));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool Add_Named(string name, string key, string value)
{
try
{
var count = xmlNamed.GetElementsByTagName(name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key && a.GetAttribute("value") == value).Count();
if (count != 0) { return false; }
xmlNamed.AppendChild(new XElement(name, new XAttribute("key", key), new XAttribute("value", value)).ToXmlElement(doc));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool Add_Section(string name)
{
XmlElement elem = xmlSections.GetElementsByTagName(name).Cast<XmlElement>().FirstOrDefault();
if (elem != null) { return false; }
try
{
var section = new ConfigSection(xmlSections.AppendChild(new XElement(name).ToXmlElement(doc)) as XmlElement);
doc.Save(Full_Path);
return true;
}
catch (Exception ex)
{ throw ex; }
}
#endregion
#region Set Zone
public static bool Set(string key, string value)
{
try
{
xmlRoot.GetElementsByTagName(Default_Elem_Name).Cast<XmlElement>().Where(a => a.GetAttribute("key") == key)
.ToList().ForEach(a => a.SetAttribute("value", value));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public static bool Set_Named(string name, string key, string value)
{
try
{
xmlNamed.GetElementsByTagName(name).Cast<XmlElement>().Where(a => a.GetAttribute("key") == key)
.ToList().ForEach(a => a.SetAttribute("value", value));
doc.Save(Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
#endregion
#region Get Zone
public static ConfigSection GetSection(string sectionName)
{
if (xmlSections == null) { return null; }
XmlElement section = xmlSections.GetElementsByTagName(sectionName).Cast<XmlElement>().FirstOrDefault();
if (section == null)
{ return null; }
else
{ return new ConfigSection(section); }
}
public static List<ConfigElemNamed> GetNamed(string name, string key)
{
if (xmlNamed == null) { return null; }
var named = xmlNamed.GetElementsByTagName(name).Cast<XmlElement>().Where(a => a.GetAttribute("key") == key);
if (named.Count() == 0)
{ return null; }
else
{ return named.Select(a => new ConfigElemNamed(a)).ToList(); }
}
public static List<ConfigElemNamed> GetNamed(string name)
{
if (xmlNamed == null) { return null; }
var named = xmlNamed.GetElementsByTagName(name).Cast<XmlElement>();
if (named.Count() == 0)
{ return null; }
else
{ return named.Select(a => new ConfigElemNamed(a)).ToList(); }
}
public static ConfigElemNamed GetNamedSingle(string name)
{
var elems = GetNamed(name);
return (elems == null) ? null : elems.FirstOrDefault();
}
public static ConfigElemNamed GetNamedSingle(string name, string key)
{
var elems = GetNamed(name, key);
return (elems == null) ? null : elems.FirstOrDefault();
}
public static List<ConfigElem> GetValues(string key)
{
if (xmlRoot == null) { return null; }
var elems = xmlRoot.GetElementsByTagName(Default_Elem_Name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key);
if (elems.Count() == 0)
{ return null; }
else
{ return elems.Select(a => new ConfigElem(a)).ToList(); }
}
public static ConfigElem GetSingle(string key)
{
var elems = GetValues(key);
return (elems == null) ? null : elems.FirstOrDefault();
}
#endregion
#region Exist
public static bool ExistSection(string name)
{
return Sections.Where(a => a.Name == name).Count() != 0 ? true : false;
}
public static bool ExistNamed(string name)
{
return ElemsNamed.Where(a => a.Name == name).Count() != 0 ? true : false;
}
public static bool ExistNamed(string name, string key)
{
return ElemsNamed.Where(a => a.Name == name && a.Key == key).Count() != 0 ? true : false;
}
public static bool ExistKey(string key)
{
return Elems.Where(a => a.Key == key).Count() != 0 ? true : false;
}
public static bool Exists()
{
return File.Exists(Full_Path);
}
#endregion
}
public class ConfigElemNamed
{
public XmlElement Elem { get; private set; }
public XmlDocument Doc { get { return Elem.OwnerDocument; } }
public ConfigElemNamed(XmlElement elem) { Elem = elem; }
public string Name
{
get { return Elem.Name; }
set
{
string _name = Name, _key = Key, _value = Value;
XmlElement parent = Elem.ParentNode as XmlElement;
bool removed = false;
try
{
parent.RemoveChild(Elem);
removed = true;
parent.AppendChild(new XElement(value, new XAttribute("key", _key), new XAttribute("value", _value)).ToXmlElement(Doc));
}
catch (Exception ex)
{
if (removed)
{ parent.AppendChild(new XElement(_name, new XAttribute("key", _key), new XAttribute("value", _value)).ToXmlElement(Doc)); }
throw ex;
}
}
}
public string Key { get { return Elem.GetAttribute("key"); } }
public string Value
{
get { return Elem.GetAttribute("value"); }
set { Elem.SetAttribute("value", value ?? ""); }
}
public bool Remove() { try { Elem.ParentNode.RemoveChild(Elem); return true; } catch (Exception) { return false; } }
}
public class ConfigElem
{
private XmlElement Elem { get; set; }
public XmlDocument Doc { get { return Elem.OwnerDocument; } }
public ConfigElem(XmlElement elem) { Elem = elem; }
public string Key { get { return Elem.GetAttribute("key"); } }
public string Value { get { return Elem.GetAttribute("value"); } set { Elem.SetAttribute("value", value ?? ""); } }
public bool Remove() { try { Elem.ParentNode.RemoveChild(Elem); return true; } catch (Exception) { return false; } }
}
public class ConfigSection
{
public XmlElement Section { get; private set; }
public XmlDocument Doc { get; private set; }
public string Name { get { return Section.Name; } }
public ConfigSection(XmlElement section)
{
Section = section;
Doc = Section.OwnerDocument;
}
public List<ConfigElemNamed> GetNamed(string name)
{
return Section.GetElementsByTagName(name).Cast<XmlElement>().Select(a => new ConfigElemNamed(a)).ToList();
}
public List<ConfigElemNamed> GetNamed(string name, string key)
{
return Section.GetElementsByTagName(name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key).Select(a => new ConfigElemNamed(a)).ToList();
}
public ConfigElemNamed GetNamedSingle(string name)
{
return GetNamed(name).FirstOrDefault();
}
public ConfigElemNamed GetNamedSingle(string name, string key)
{
return GetNamed(name, key).FirstOrDefault();
}
public List<ConfigElem> GetValues(string key)
{
return Section.GetElementsByTagName(ConfigFile.Default_Elem_Name).Cast<XmlElement>().Select(a => new ConfigElem(a)).ToList();
}
public ConfigElem GetSingle(string key)
{
var elem = Section.GetElementsByTagName(ConfigFile.Default_Elem_Name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key).FirstOrDefault();
if (elem == null) { return null; }
return new ConfigElem(elem);
}
public bool Remove() { try { Section.ParentNode.RemoveChild(Section); return true; } catch (Exception) { return false; } }
public bool Add(string key, string value)
{
try
{
var count = Section.GetElementsByTagName(ConfigFile.Default_Elem_Name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key && a.GetAttribute("value") == value).Count();
if (count != 0) { throw new DuplicateWaitObjectException(); }
Section.AppendChild(new XElement(ConfigFile.Default_Elem_Name, new XAttribute("key", key), new XAttribute("value", value)).ToXmlElement(Doc));
Doc.Save(ConfigFile.Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public bool Add_Named(string name, string key, string value)
{
try
{
var count = Section.GetElementsByTagName(name).Cast<XmlElement>()
.Where(a => a.GetAttribute("key") == key && a.GetAttribute("value") == value).Count();
if (count != 0) { throw new DuplicateWaitObjectException(); }
Section.AppendChild(new XElement(name, new XAttribute("key", key), new XAttribute("value", value)).ToXmlElement(Doc));
Doc.Save(ConfigFile.Full_Path);
return true;
}
catch (Exception ex) { throw ex; }
}
public bool ExistNamed(string name)
{
return GetNamed(name).Count() != 0 ? true : false;
}
public bool ExistNamed(string name, string key)
{
return GetNamed(name, key).Count() != 0 ? true : false;
}
public bool ExistKey(string key)
{
return GetValues(key).Count() != 0 ? true : false;
}
}
public static class XElementExtensionsClass
{
public static XmlElement ToXmlElement(this XElement el, XmlDocument ownerDocument)
{
return (XmlElement)ownerDocument.ReadNode(el.CreateReader());
}
}
}
|
Rust
|
UTF-8
| 2,183 | 2.953125 | 3 |
[] |
no_license
|
use crate::parse;
use indicatif::ProgressBar;
pub fn solve() {
println!("PART 1: 372");
let start = parse::parse_day17("input/17.txt");
let mut world = start.clone();
world = process(world);
world = process(world);
world = process(world);
world = process(world);
world = process(world);
world = process(world);
println!("PART 2: {}", count_ones(world));
}
fn process(world: Vec<Vec<Vec<Vec<usize>>>>) -> Vec<Vec<Vec<Vec<usize>>>> {
let mut ret = vec![];
let n = world.len();
let bar = ProgressBar::new(n as u64);
for i in 0..n {
let mut cube = vec![];
for j in 0..n {
let mut matrix = vec![];
for k in 0..n {
let mut line = vec![];
for l in 0..n {
let neigbours = neigbours(i, j, k, l, n)
.into_iter()
.map(|(i, j, k, l)| world[i][j][k][l])
.sum();
match (world[i][j][k][l], neigbours) {
(0, 3) | (1, 2) | (1, 3) => line.push(1),
_ => line.push(0),
}
}
matrix.push(line);
}
cube.push(matrix);
}
ret.push(cube);
bar.inc(1);
}
bar.finish();
ret
}
fn neigbours(
i: usize,
j: usize,
k: usize,
l: usize,
n: usize,
) -> Vec<(usize, usize, usize, usize)> {
let i = i as isize;
let j = j as isize;
let k = k as isize;
let l = l as isize;
let n = n as isize;
let mut ret = vec![];
for di in -1..=1 {
for dj in -1..=1 {
for dk in -1..=1 {
for dl in -1..=1 {
if di == 0 && dj == 0 && dk == 0 && dl == 0 {
continue;
}
let ni = i + di;
let nj = j + dj;
let nk = k + dk;
let nl = l + dl;
if ni >= 0 && nj >= 0 && nk >= 0 && nl >= 0 && ni < n && nj < n && nk < n && nl < n {
ret.push((ni as usize, nj as usize, nk as usize, nl as usize));
}
}
}
}
}
ret
}
fn count_ones(world: Vec<Vec<Vec<Vec<usize>>>>) -> usize {
let mut ret = 0;
let n = world.len();
for i in 0..n {
for j in 0..n {
for k in 0..n {
for l in 0..n {
ret += world[i][j][k][l];
}
}
}
}
ret
}
|
Java
|
UTF-8
| 4,804 | 2.25 | 2 |
[
"MIT"
] |
permissive
|
package io.ogi.boid.simulation;
import io.helidon.messaging.Channel;
import io.helidon.messaging.Emitter;
import io.helidon.messaging.Messaging;
import io.ogi.boid.MessageQueue;
import io.ogi.boid.boidconfig.BoidSimulationConfig;
import io.ogi.boid.corealgorithm.BoidMoves;
import io.ogi.boid.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.logging.Logger;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class BoidSimulationReactive {
private static final Logger LOGGER = Logger.getLogger(BoidSimulationReactive.class.getName());
private final MessageQueue messageQueue = MessageQueue.instance();
private final BoidPositions boidPositions;
private final BoidSimulationConfig boidSimulationConfig;
private BoidModel boidModel;
private Messaging moveBoidsMessaging;
private Messaging drawMessaging;
Channel<BoidAndNeighbours> moveBoidChannel;
Channel<BoidPositions> drawBoidChannel;
private List<Boid> nextPositions;
private final BoidMoves boidMoves = new BoidMoves();
Channel<List<Boid>> channel0 = Channel.create("channel00");
Channel<List<BoidAndNeighbours>> channel01 = Channel.create("channel01");
Channel<List<Boid>> channel02 = Channel.create("channel02");
Channel<List<Boid>> channel05 = Channel.create("channel05");
Channel<List<Boid>> channel3 = Channel.create("channel3");
Emitter<List<Boid>> emitter = Emitter.<List<Boid>>builder()
.channel(channel0)
.channel(channel02)
.channel(channel05)
.channel(channel3)
.build();
public BoidSimulationReactive(BoidSimulationConfig boidSimulationConfig) {
moveBoidChannel = Channel.create("moveBoidChannel");
drawBoidChannel = Channel.create("drawBoidChannel");
this.boidSimulationConfig = boidSimulationConfig;
this.boidPositions = new BoidPositions();
this.boidModel = boidSimulationConfig.getBoidModel();
this.nextPositions = new ArrayList<>();
boidModel = boidSimulationConfig.getBoidModel();
initializeBoids();
}
public void initializeBoids() {
boidModel = boidSimulationConfig.getBoidModel();
LOGGER.info(() -> "model: " + boidModel);
boidPositions.setBoids(
Stream.generate(() -> new Boid(boidModel))
.limit(boidModel.getNumOfBoids())
.collect(toList()));
}
public void initializeMessaging() {
moveBoidsMessaging =
Messaging.builder()
.emitter(emitter)
.processor(
channel0,
channel01,
boids ->
boids.stream()
.map(boid -> BoidAndNeighbours.of(boid, boidPositions.getBoids()))
.peek(b -> System.out.println("current: " + b.getCurrentBoid()))
.collect(toList()))
.processor(
channel01,
channel02,
boidAndN ->
boidAndN.stream()
.map(
boidAndNeighbours ->
boidMoves.moveOneBoidSync(
boidAndNeighbours.getCurrentBoid(),
boidAndNeighbours.getBoids(),
boidModel))
.peek(b -> System.out.println("current boid: " + b.getX()))
.collect(toList()))
.listener(
channel05,
s ->
s.stream()
.limit(2)
.forEach(b -> System.out.println("Intercepted message " + b)))
.build();
drawMessaging =
Messaging.builder()
.emitter(emitter)
.processor(channel3, drawBoidChannel, BoidPositions::new)
.listener(drawBoidChannel, messageQueue::push)
.build();
}
public void startSimReactive() {
LOGGER.info("startSimReactive: " + boidPositions.getBoids().get(0));
moveBoidsMessaging.start();
drawMessaging.start();
emitter.send(boidPositions.getBoids());
}
public void nextSimReactive() {
LOGGER.info("nextSimReactive before send: " + boidPositions.getBoids().get(0));
LOGGER.info("nextSimReactive before send: " + nextPositions.size());
emitter.send(nextPositions);
LOGGER.info("nextSimReactive after send: " + boidPositions.getBoids().get(0));
}
public void stopSimReactive() {
moveBoidsMessaging.stop();
}
public BoidModel getBoidModel() {
return boidModel;
}
void setBoidPositions(List<Boid> boids) {
boidPositions.setBoids(boids);
}
BoidPositions getBoidPositions() {
return boidPositions;
}
MessageQueue getMessageQueue() {
return messageQueue;
}
}
|
Python
|
UTF-8
| 484 | 3.28125 | 3 |
[] |
no_license
|
import math
def prime(n):
if n==1 :
return False
elif n==2:
return True
else:
for i in range(2,n-1):
if n%i==0 :
return False
return True
m,n=raw_input().split()
m,n=eval(m),eval(n)
s=0
count=0
if m==n:
if prime(m):
s=m
count=1
else:
for i in range (m,n+1):
if prime(i):
print i
count=count+1
s=s+i
print count,s
|
C#
|
UTF-8
| 2,999 | 2.78125 | 3 |
[] |
no_license
|
using Api.Common.Repository.Contracts.Core.Entities;
using Api.Common.Repository.Contracts.Core.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Api.Common.Mock.Infrastructure.Data.Repositories
{
public class InMemoryRepository<TEntity> : IRepository<TEntity> where TEntity : IDomainEntity
{
public InMemoryRepository()
{
Repository = new List<TEntity>();
}
public void Dispose()
{
// Cleanup
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Cleanup
Repository = null;
}
public List<TEntity> Repository { get; protected set; }
public void Update(TEntity instance)
{
instance.ModifiedDate = DateTime.UtcNow;
Delete(instance.Id);
Repository.Add(instance);
}
public void Delete(Guid id)
{
Repository.RemoveAll(x => x.Id == id);
}
public void Insert(TEntity instance)
{
if (instance.Id == Guid.Empty)
{
instance.Id = Guid.NewGuid();
}
instance.CreateDate = DateTime.UtcNow;
Repository.Add(instance);
}
public void Insert(IEnumerable<TEntity> instances)
{
foreach (var instance in instances)
{
Insert(instance);
}
}
public void Delete(IEnumerable<Guid> ids)
{
foreach (var id in ids)
{
Delete(id);
}
}
public void Update(IEnumerable<TEntity> instances)
{
foreach (var instance in instances)
{
Update(instance);
}
}
public TEntity Find(Expression<Func<TEntity, bool>> expression)
{
return Repository.Any() ? Repository.AsQueryable().First(expression) : default(TEntity);
}
public IEnumerable<TEntity> All()
{
return Repository;
}
public IEnumerable<TEntity> FindList(Expression<Func<TEntity, bool>> expression)
{
return Repository.AsQueryable().Where(expression);
}
public IEnumerable<TEntity> FindListWithNoTracking(Expression<Func<TEntity, bool>> expression)
{
return Repository.AsQueryable().Where(expression);
}
public TEntity FindById(Guid id)
{
return Repository.AsQueryable().FirstOrDefault(x => x.Id == id);
}
public void Delete(Expression<Func<TEntity, bool>> expression)
{
Repository.RemoveAll(expression.Compile().Invoke);
}
public void BulkInsert(IList<TEntity> instances)
{
Repository.AddRange(instances);
}
}
}
|
Python
|
UTF-8
| 2,586 | 3.796875 | 4 |
[
"MIT"
] |
permissive
|
# Program to showcase PyComb functions.
# This is not a test program. It is just a sample.
# Each function in PyComb has been tested and verified against
# known results in reference tables.
# There are no known bugs.
# Caveat emptor.
import PyComb
print("PyComb.prod(45,100)")
print(PyComb.prod(45,100))
print("PyComb.binomial(450,150)")
print(PyComb.binomial(450,150))
print("PyComb.multinomial([20,50,40,10,10,30])")
print(PyComb.multinomial([20,50,40,10,10,30]))
print("PyComb.catalan(200)")
print(PyComb.catalan(200))
print("PyComb.stirling1(29,15)")
print(PyComb.stirling1(29,15))
print("PyComb.stirling2(85,17)")
print(PyComb.stirling2(85,17))
print("PyComb.bell(70)")
print(PyComb.bell(70))
print("PyComb.lah(75,50)")
print(PyComb.lah(75,50))
print("PyComb.delannoy(180,120)")
print(PyComb.delannoy(180,120))
print("PyComb.motzkin(186)")
print(PyComb.motzkin(186))
print("PyComb.narayana(56,30)")
print(PyComb.narayana(56,30))
print("PyComb.schroder(100)")
print(PyComb.schroder(100))
print("PyComb.eulerian(80,46)")
print(PyComb.eulerian(80,46))
"""
When you run the above program, the following output will be produced:
PyComb.prod(45,100)
35107855920014967941311748817536360245313533127549918530485803045306923223637981174693888000000000000000
PyComb.binomial(450,150)
991275799579461852581870717609886925058980866721833210814091742711258246863091517265111294276237344131556276652899696730064
PyComb.multinomial([20,50,40,10,10,30])
2235761856264821572055996080104680297001293759287559387585261495667531910318510344343699972798287328078848000
PyComb.catalan(200)
512201493211017079467541693136328292324432464582475861864920694407578768023144072628540276213813397768975366156750120
PyComb.stirling1(29,15)
211821088794711294496815
PyComb.stirling2(85,17)
985607117690128874270520922250107369649290441494081144658128523918560345424283513146469415
PyComb.bell(70)
18075003898340511237556784424498369141305841234468097908227993035088029195
PyComb.lah(75,50)
28598072664067214753003261184122656994501416455559817723904000000
PyComb.delannoy(180,120)
64956161681401226028888345597957460942320026409033673361208768598048474741275641649418933325596543399644174529
PyComb.motzkin(186)
31673598644325685295892202605889103138268788536071762890280096344492972753241925006644
PyComb.narayana(56,30)
876493573861628855005777632960
PyComb.schroder(100)
28747611153504860266534250007458881388313583561117443629896620307440340890
PyComb.eulerian(80,46)
479233115556431544590242725604764819710804657716559663474197243072029896491056927532566934037906913449948849894719330
"""
|
Java
|
UTF-8
| 1,260 | 2.125 | 2 |
[] |
no_license
|
package fr.epione.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
public class Patient extends User implements Serializable {
private static final long serialVersionUID = 1L;
private Adresse adresse;
// association parcours patient
@OneToOne
private Parcours parcours ;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "patient")
private List<RendezVous> listeRendezVous = new ArrayList<>();
public void setListeRendezVous(List<RendezVous> listeRendezVous) {
this.listeRendezVous = listeRendezVous;
}
public Patient() {
super();
}
public Adresse getAdresse() {
return adresse;
}
public void setAdresse(Adresse adresse) {
this.adresse = adresse;
}
public Patient(String nom, String prenom, String email, Adresse adresse, int telephone, Date dateDeNaissance,
String motDePasse, List<RendezVous> listeRendezVous) {
super(nom, prenom, email, telephone, dateDeNaissance, motDePasse);
this.listeRendezVous = listeRendezVous;
this.adresse = adresse;
}
}
|
Java
|
UTF-8
| 6,942 | 1.742188 | 2 |
[] |
no_license
|
package com.ca.apm.test.atc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.testng.Assert;
import com.ca.apm.test.atc.common.Canvas;
import com.ca.apm.test.atc.common.UI;
public abstract class CommonMapViewUITest extends UITest {
protected static final String PERSP1 = "Type";
protected static final String PERSP2 = "Application";
protected static final String PERSP1_GROUP1_NAME = "SERVLET";
protected static final String[] PERSP1_GROUP1_POSSIBLE_SUBNODES = {"TradeOptions|service",
"JspServlet|service", "ServletA6|service", "AxisServlet|service", "PlaceOrder|service",
"DefaultServlet|service", "ViewOrder|service"};
protected static final String PERSP1_GROUP1_COMMON_BASIC_ATTR_NAME = "agentDomain";
protected static final String PERSP1_GROUP1_COMMON_BASIC_ATTR_VALUE = "SuperDomain/TomcatDomain";
protected static final String PERSP1_GROUP2_NAME = "GENERICFRONTEND";
protected static final String[] PERSP1_GROUP2_POSSIBLE_SUBNODES = {"Apps|TradeService|URLs|Default",
"Apps|TradeService|URLs|/TradeService/", "Apps|Welcome to Tomcat|URLs|Default",
"Apps|Welcome to Tomcat|URLs|/robots.txt",
"Apps|TradeService|URLs|/TradeService/TradeOptions",
"Apps|AuthenticationService|URLs|/AuthenticationService/",
"Apps|AuthenticationEngine|URLs|/AuthenticationEngine/services/",
"Apps|OrderEngine|URLs|/OrderEngine/services/"};
protected static final String PERSP1_GROUP3_NAME = "INFERRED_DATABASE";
protected static final String[] PERSP1_GROUP3_POSSIBLE_SUBNODES = {"file%order-records (Hypersonic)",
"DATABASE : file%customer-records (Hypersonic)"};
protected static final String PERSP2_GROUP1_NAME = "TradeService - applicationName";
protected static final String[] PERSP2_GROUP1_POSSIBLE_SUBNODES = {"Place Order",
"Options Trading", "ViewOrders|service", "TradeOptions|service", "PlaceOrder|service"};
protected final List<String> persp1group1existingSubnodes = new ArrayList<String>();
protected final List<String> persp1group2existingSubnodes = new ArrayList<String>();
protected final List<String> persp1group3existingSubnodes = new ArrayList<String>();
protected final List<String> persp2group1existingSubnodes = new ArrayList<String>();
protected static String PERSP1_GROUP1_TEST_SUBNODE_NAME;
protected static String PERSP1_GROUP2_TEST_SUBNODE_NAME;
protected static String PERSP1_GROUP2_TEST_SUBNODE2_NAME;
protected static String PERSP1_GROUP3_TEST_SUBNODE_NAME;
protected static String PERSP2_GROUP1_TEST_SUBNODE_NAME;
protected static boolean testSubnodesAssigned = false;
protected UI ui = null;
protected void init() throws Exception {
if (!testSubnodesAssigned) {
initTestNodes();
}
}
private void initTestNodes() throws Exception {
logger.info("Enable live mode");
ui.getTimeline().turnOnLiveMode();
logger.info("Create the perspective '{}' if it does not exist yet", PERSP2);
if (!ui.getPerspectivesControl().isPerspectivePresent(PERSP2)) {
ui.getPerspectivesControl().addPerspective(PERSP2, false);
} else {
ui.getPerspectivesControl().selectPerspectiveByName(PERSP2);
}
logger.info("Filter out nodes that do not exist in this environment");
filterExistingGroupSubnodes(PERSP1, PERSP1_GROUP1_NAME, PERSP1_GROUP1_POSSIBLE_SUBNODES, persp1group1existingSubnodes);
filterExistingGroupSubnodes(PERSP1, PERSP1_GROUP2_NAME, PERSP1_GROUP2_POSSIBLE_SUBNODES, persp1group2existingSubnodes);
filterExistingGroupSubnodes(PERSP1, PERSP1_GROUP3_NAME, PERSP1_GROUP3_POSSIBLE_SUBNODES, persp1group3existingSubnodes);
filterExistingGroupSubnodes(PERSP2, PERSP2_GROUP1_NAME, PERSP2_GROUP1_POSSIBLE_SUBNODES, persp2group1existingSubnodes);
Assert.assertTrue(persp1group1existingSubnodes.size() >= 1, "There should be at least 1 node in the group '" + PERSP1_GROUP1_NAME + "'");
Assert.assertTrue(persp1group2existingSubnodes.size() >= 2, "There should be at least 2 nodes in the group '" + PERSP1_GROUP2_NAME + "'");
Assert.assertTrue(persp1group3existingSubnodes.size() >= 1, "There should be at least 1 node in the group '" + PERSP1_GROUP3_NAME + "'");
Assert.assertTrue(persp2group1existingSubnodes.size() >= 1, "There should be at least 1 node in the group '" + PERSP2_GROUP1_NAME + "'");
PERSP1_GROUP1_TEST_SUBNODE_NAME = persp1group1existingSubnodes.get(0);
PERSP1_GROUP2_TEST_SUBNODE_NAME = persp1group2existingSubnodes.get(0);
PERSP1_GROUP2_TEST_SUBNODE2_NAME = persp1group2existingSubnodes.get(1);
PERSP1_GROUP3_TEST_SUBNODE_NAME = persp1group3existingSubnodes.get(0);
PERSP2_GROUP1_TEST_SUBNODE_NAME = persp2group1existingSubnodes.get(0);
logger.info("PERSP1_GROUP1_TEST_SUBNODE_NAME=" + PERSP1_GROUP1_TEST_SUBNODE_NAME);
logger.info("PERSP1_GROUP1_TEST_SUBNODE_NAME=" + PERSP1_GROUP2_TEST_SUBNODE_NAME);
logger.info("PERSP1_GROUP2_TEST_SUBNODE2_NAME=" + PERSP1_GROUP2_TEST_SUBNODE2_NAME);
logger.info("PERSP1_GROUP3_TEST_SUBNODE_NAME=" + PERSP1_GROUP3_TEST_SUBNODE_NAME);
logger.info("PERSP2_GROUP1_TEST_SUBNODE_NAME=" + PERSP2_GROUP1_TEST_SUBNODE_NAME);
testSubnodesAssigned = true;
}
/**
* Filter the sub-nodes of a group that do exist in the tested APM environment.
*
* @param groupName
* @param potentialSubnodes
* @param existingSubnodes
* @throws Exception
*/
protected void filterExistingGroupSubnodes(String perspective, String groupName, String[] potentialSubnodes, List<String> existingSubnodes) throws Exception {
existingSubnodes.clear();
ui.getPerspectivesControl().selectPerspectiveByName(perspective);
Assert.assertTrue(ui.getPerspectivesControl().isPerspectiveActive(perspective), "The active perspective should be '" + perspective + "'");
Canvas canvas = ui.getCanvas();
canvas.expandGroup(canvas.getNodeByNameSubstring(groupName));
canvas.getCtrl().fitAllToView();
List<String> allNodeNames = Arrays.asList(canvas.getArrayOfNodeNames());
for (String subnode : potentialSubnodes) {
if (allNodeNames.contains(subnode)) {
existingSubnodes.add(subnode);
logger.info("Verified that the group {} contains the subnode {}", groupName, subnode);
} else {
logger.warn("In the group {} there is no subnode {}", groupName, subnode);
}
}
canvas.collapseGroup(canvas.getNodeByNameSubstring(groupName));
canvas.getCtrl().fitAllToView();
}
}
|
PHP
|
UTF-8
| 953 | 3.125 | 3 |
[] |
no_license
|
<?php
namespace App\Models;
use PDO;
class Post extends \Core\Model
{
public function __construct($data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
};
}
public static function getAll()
{
try {
$db = static::getDB();
$statement = $db->query('SELECT id, title, content FROM posts ORDER BY created_at');
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
return $results;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function save()
{
$sql = 'INSERT INTO posts (title, content) VALUES (:title, :content)';
$db = static::getDB();
$stmt= $db->prepare($sql);
$stmt->bindValue(':title', $this->title, PDO::PARAM_STR);
$stmt->bindValue(':content', $this->content, PDO::PARAM_STR);
$stmt->execute();
}
}
|
Java
|
UTF-8
| 729 | 3.390625 | 3 |
[] |
no_license
|
package dsa;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayMinElementPractice {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int size = sc.nextInt();
int arr[] = new int[size];
int min = 0;
System.out.println("Enter the array elements");
for(int i=0; i<arr.length; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Your array is "+ Arrays.toString(arr));
min = arr[0];
for(int i=0; i<arr.length; i++) {
if(arr[i]<min) {
min = arr[i];
}
}
//System.out.println("The minimun element in the array is "+min);
System.out.println("The minimun element in the array is "+min);
}
}
|
Swift
|
UTF-8
| 1,556 | 2.640625 | 3 |
[] |
no_license
|
//
// BaseTitleCell.swift
// AZB_swift
//
// Created by limbo on 2020/4/8.
// Copyright © 2020 limbo. All rights reserved.
//
import Foundation
class BaseTitleCell: BaseTableviewCell {
var titleLabel:UILabel?
var contentLabel:UILabel?
override func createCellUI() {
titleLabel = UILabel.init()
titleLabel?.font = UIFont.systemFont(ofSize: 14)
self.contentView.addSubview(titleLabel!)
titleLabel?.snp.makeConstraints({ (make) in
make.left.equalTo(15)
make.centerY.equalTo(self.snp_centerY)
})
contentLabel = UILabel.init()
contentLabel?.numberOfLines = 0
contentLabel?.textAlignment = .right
contentLabel?.font = UIFont.systemFont(ofSize: 14)
self.contentView.addSubview(contentLabel!)
contentLabel?.snp.makeConstraints({ (make) in
make.right.equalTo(-15)
make.left.greaterThanOrEqualTo(kCommonScreenWidth/2)
make.height.greaterThanOrEqualTo(30)
make.top.equalTo(10)
make.bottom.equalTo(-10)
})
let line = UIView.init()
line.backgroundColor = kCommonLigthGray
self.contentView.addSubview(line)
line.snp.makeConstraints { (make) in
make.size.equalTo(CGSize.init(width: kCommonScreenWidth, height: 1))
make.bottom.equalTo(0)
}
}
func refreshWith(title:String,content:String) {
titleLabel?.text = title
contentLabel?.text = content
}
}
|
JavaScript
|
UTF-8
| 338 | 3.15625 | 3 |
[] |
no_license
|
class Calculate {
static sum(x, y) {
return x + y;
}
sum2(x, y) {
return x + y;
}
multiply(x, y) {
return x * y;
}
}
const CalculateOpject = new Calculate();
const calmultiply = new Calculate();
console.log(Calculate.sum(1, 2));
console.log(CalculateOpject.sum2(2, 3));
console.log(calmultiply.multiply(10, 20));
|
Markdown
|
UTF-8
| 1,684 | 2.609375 | 3 |
[] |
no_license
|
# IGQG (Information Geometry of Quantum Gases)
This repository presentsa library (IGQG.py) for calculations of several functions on statistical mechanics of quantum systems. Mainly, this library calculations are based on the precise calculation of the polylogarithm family of function given by mpmath.
Examples of usage are given as the code generating figures in some of my scientific papers.
The ipython notebooks titled: "Fraction and C_v.ipynb" and "Minimum of c_v derivative.ipynb" generate the figures presented in the article "Bose-Einstein statistics for a finite number of particles" [Phys. Rev. A 104, 043318 (2021)] (published: https://journals.aps.org/pra/accepted/a5074N05Ucf1d42bf02a0978a6e5b39c42156fcf6, preprint: https://arxiv.org/abs/2110.02890).
The ipython notebooks titled: "Bosons Curvature-Fugacity plot.ipynb", "Bosons Metric determinant.ipynb", "Bosons plot curvature.ipynb", and "Fermion plots in Logarithm scale.ipynb" generate the figures presented in the article "Information geometry for Fermi-Dirac and Bose-Einstein quantum statistics" [Physica A 576, 126061 (2021)] (published: https://doi.org/10.1016/j.physa.2021.126061, preprint: https://arxiv.org/abs/2103.00935).
The script "Maximum_BE_curvature.py" calculates the maximum value of geometric curvature of a Bose-Einstein system as a function of the number of particles. While the ipython notebook "Working on BE curvature.ipynb" uses the forementioned calculation to generate figures presented in the article "Information geometry and Bose-Einstein condensation" [Chaos 33(3), 033101 (2023)] (published: https://doi.org/10.1063/5.0136244, preprint: https://arxiv.org/abs/2302.03182).
|
Java
|
UTF-8
| 1,134 | 2.765625 | 3 |
[] |
no_license
|
// code by jph
package ch.alpine.tensor.nrm;
import ch.alpine.tensor.Scalar;
import ch.alpine.tensor.Tensor;
import ch.alpine.tensor.api.TensorUnaryOperator;
import ch.alpine.tensor.sca.pow.Sqrt;
/** Euclidean norm
*
* ||{a, b, c}||_2 = Sqrt[a^2 + b^2 + c^2] */
public enum Vector2Norm {
;
public static final TensorUnaryOperator NORMALIZE = Normalize.with(Vector2Norm::of);
/** @param vector
* @return 2-norm of given vector */
public static Scalar of(Tensor vector) {
try {
// Hypot prevents the incorrect evaluation: Norm_2[ {1e-300, 1e-300} ] == 0
return Hypot.ofVector(vector);
} catch (Exception exception) {
// <- when vector is a scalar
// <- when vector is empty, or contains NaN
}
return Sqrt.FUNCTION.apply(Vector2NormSquared.of(vector));
}
/** inspired by
* <a href="https://reference.wolfram.com/language/ref/EuclideanDistance.html">EuclideanDistance</a>
*
* @param v1 vector
* @param v2 vector
* @return 2-norm of vector difference || v1 - v2 || */
public static Scalar between(Tensor v1, Tensor v2) {
return of(v1.subtract(v2));
}
}
|
Java
|
UTF-8
| 709 | 2.609375 | 3 |
[] |
no_license
|
package com.magine.spy.spyclient.monitor;
import com.magine.spy.spyclient.monitor.impl.SimpleSystemCpuMonitor;
/**
* Factory class to create monitor instances
*/
public class MonitorFactory {
/**
* Create a SimpleSystemCpuMonitor instance
*
* @param interval
* int health check interval in seconds
* @param threshold
* double threshold value for the system state to be monitored,
* if exceeded, system unhealthy event will be triggered
* @return Monitor an instance of SimpleSystemCpuMonitor class
*/
public static Monitor createSimpleSystemCpuMonitor(int interval, double threshold) {
return new SimpleSystemCpuMonitor(interval, threshold);
}
}
|
JavaScript
|
UTF-8
| 1,150 | 2.640625 | 3 |
[] |
no_license
|
function MainPage() {
};
MainPage.prototype._currentPageId = null;
MainPage.prototype._pages = null;
MainPage.prototype.loggedin = false;
MainPage.prototype.header = new Header();
MainPage.prototype.footer = new Footer();
MainPage.prototype.homePage = new HomePage();
MainPage.prototype.loginPage = new LoginPage();
MainPage.prototype.uploadPage = new UploadPage();
MainPage.prototype.init = function() {
log('init-MainPage');
this._pages = new Array();
this._pages.push(this.homePage);
this._pages.push(this.uploadPage);
return this;
};
MainPage.prototype.setLogin = function(loggedin) {
this.loggedin = loggedin;
if (this.loggedin == false) {
// show login page
this.loginPage.init();
}
return this;
};
MainPage.prototype.setCurrentPage = function(pageId) {
if (this.loggedin == false) {
this.loginPage.init();
return false;
}
if (this._currentPageId == null) {
var layout = new Layout();
layout.init();
}else if (this._currentPageId == pageId) {
return false;
}
this.header.init(this.loggedin);
this.footer.init(this.loggedin);
this._currentPageId = pageId;
this._pages[pageId].init();
};
|
C#
|
UTF-8
| 2,610 | 3.484375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _6.ConnectedComponents
{
class ConnectedComponents
{
static List<int>[] graph;
static HashSet<int[]> components;
static bool[] visitedVertices;
private static int[] FindConnectedComponent(int startVertex)
{
Stack<int> componentVertices = new Stack<int>();
FindConnectedComponentDFS(startVertex, componentVertices);
return componentVertices.ToArray();
}
private static void FindConnectedComponentDFS(int startVertex, Stack<int> componentVertices)
{
componentVertices.Push(startVertex);
visitedVertices[startVertex] = true;
foreach (var vertex in graph[startVertex])
{
if (!visitedVertices[vertex])
{
FindConnectedComponentDFS(vertex, componentVertices);
}
}
}
static void Main(string[] args)
{
graph = new List<int>[]
{
new List<int>(new int[]{1,3}),
new List<int>(new int[]{0,2,6}),
new List<int>(new int[]{1,9,7,3}),
new List<int>(new int[]{0,2,7,10,4}),
new List<int>(new int[]{3}),
new List<int>(new int[]{6}),
new List<int>(new int[]{5,8}),
new List<int>(new int[]{2,3}),
new List<int>(new int[]{6}),
new List<int>(new int[]{2,10}),
new List<int>(new int[]{9,3}),
new List<int>(new int[]{12,13,14}),
new List<int>(new int[]{11,14}),
new List<int>(new int[]{11,14}),
new List<int>(new int[]{12,11,13}),
new List<int>(new int[]{15}),
};
components = new HashSet<int[]>();
visitedVertices = new bool[graph.Length];
for (int i = 0; i < visitedVertices.Length; i++)
{
if (!visitedVertices[i])
{
components.Add(FindConnectedComponent(i));
}
}
foreach (var component in components)
{
foreach (var vertex in component)
{
Console.Write("{0} ",vertex);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
|
Shell
|
UTF-8
| 1,907 | 2.953125 | 3 |
[] |
no_license
|
#!/bin/bash
sudo touch ~/cloudwatch.log
cd ~
sudo -s
sudo echo Y | apt-get install python >> ~/cloudwatch.log
echo "downloading awslogs-agent-setup.." >> ~/cloudwatch.log
echo "modifying permissions for setup" >> ~/cloudwatch.log
cd /etc/systemd/system
sudo touch awslogs.service
sudo chmod 777 awslogs.service
sudo echo [Unit] > awslogs.service
sudo echo Description=Service for CloudWatch Logs agent >> awslogs.service
sudo echo After=rc-local.service >> awslogs.service
sudo echo [Service] >> awslogs.service
sudo echo Type=simple >> awslogs.service
sudo echo Restart=always >> awslogs.service
sudo echo KillMode=process >> awslogs.service
sudo echo TimeoutSec=infinity >> awslogs.service
sudo echo PIDFile=/var/awslogs/state/awslogs.pid >> awslogs.service
sudo echo "ExecStart=/var/awslogs/bin/awslogs-agent-launcher.sh --start --background --pidFile $PIDFILLE --user awslogs --chuid awslogs &" >> awslogs.service
sudo echo [Install] >> awslogs.service
sudo echo WantedBy=multi-user.target >> awslogs.service
sudo systemctl daemon-reload
sleep 2
sudo systemctl start awslogs.service
sleep 2
sudo systemctl enable awslogs.service
sudo touch ~/awslogs.conf
cd ~
sudo echo [general] > ~/awslogs.conf
sudo echo "state_file= /var/awslogs/state/agent-state" >> ~/awslogs.conf
sudo echo [/var/lib/tomcat8/logs/catalina.out] >> ~/awslogs.conf
sudo echo file = /var/lib/tomcat8/logs/catalina.out >> ~/awslogs.conf
sudo echo "log_group_name = myloggroup" >> ~/awslogs.conf
sudo echo "log_stream_name = myweblogstream" >> ~/awslogs.conf
sudo echo "datetime_format = %d/%b/%Y:%H:%M:%S" >> ~/awslogs.conf
cd ~
sudo curl https://s3.amazonaws.com/aws-cloudwatch/downloads/latest/awslogs-agent-setup.py -O >> ~/cloudwatch.log
sudo chmod 777 ~/awslogs-agent-setup.py >> ~/awslogs.conf
sudo python ~/awslogs-agent-setup.py --region us-east-1 -c ~/awslogs.conf --non interactive
sudo systemctl restart awslogs.service
|
Swift
|
UTF-8
| 6,332 | 2.71875 | 3 |
[] |
no_license
|
import UIKit
extension CGAffineTransform : Printable {
public var description : String {
return NSStringFromCGAffineTransform(self)
}
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
class ViewController : UIViewController {
@IBOutlet var lab: UILabel!
@IBOutlet var v: UIView!
var shouldRotate = false
func adjustLabel() {
self.lab.text = shouldRotate ? "On" : "Off"
}
override func viewDidLoad() {
self.adjustLabel()
}
override func supportedInterfaceOrientations() -> Int {
// aha, this explains why we are called 10 times;
// the first 9 times, the device doesn't have an orientation yet
let orientation = UIDevice.currentDevice().orientation
println("supported, device \(orientation.rawValue)")
if orientation != .Unknown {
println("self \(self.interfaceOrientation.rawValue)")
// but the above is deprecated in iOS 8; ask about the status bar instead
println("status bar \(UIApplication.sharedApplication().statusBarOrientation.rawValue)")
}
return Int(UIInterfaceOrientationMask.All.rawValue)
// but not really, because the app is only portrait and the two landscapes
// if we add upside-down, we crash when the app tries to rotate upside-down
}
override func shouldAutorotate() -> Bool {
let orientation = UIDevice.currentDevice().orientation
println("should, device \(orientation.rawValue)")
if orientation != .Unknown {
println("self \(self.interfaceOrientation.rawValue)")
// but the above is deprecated in iOS 8; ask about the status bar instead
println("status bar \(UIApplication.sharedApplication().statusBarOrientation.rawValue)")
}
// return true
return self.shouldRotate
}
// rotate and tap the button to test attemptRotation and shouldAutorotate
@IBAction func doButton(sender:AnyObject?) {
self.shouldRotate = !self.shouldRotate
self.adjustLabel()
delay(0.1) {
UIViewController.attemptRotationToDeviceOrientation()
}
// there's a bug here (at least I take it to be a bug) in iOS 8 only:
// if you rotate the device and then tap the button,
// we rotate but the app does not resize itself to fit the new orientation
// if you run in iOS 7 it works fine
// aaaah, looks like they fixed this bug in time
}
// rotation events (willAnimateRotation, willRotateTo, didRotateFrom) deprecated in iOS 8
// instead, use this:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// call super
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
println("will transition size change to \(size)")
println("with target transform \(coordinator.targetTransform())") // *
// apparently does not mean that anyone will actually have this transform ultimately
// it's just a way of describing what the effective rotation is?
println("screen bounds: \(UIScreen.mainScreen().bounds)")
println("screen native bounds: \(UIScreen.mainScreen().nativeBounds)")
println("screen coord space bounds: \(UIScreen.mainScreen().coordinateSpace.bounds)") // *
println("screen fixed space bounds: \(UIScreen.mainScreen().fixedCoordinateSpace.bounds)") // *
let r = self.view.convertRect(self.lab.frame, toCoordinateSpace: UIScreen.mainScreen().fixedCoordinateSpace)
println("label's frame converted into fixed space: \(r)")
println("window frame: \(self.view.window!.frame)")
println("window bounds: \(self.view.window!.bounds)")
println("window transform: \(self.view.window!.transform)")
println("view transform: \(self.view.transform)")
coordinator.animateAlongsideTransition({
_ in
println("transitioning size change to \(size)")
// arrow keeps pointing to physical top of device
self.v.transform = CGAffineTransformConcat(CGAffineTransformInvert(coordinator.targetTransform()), self.v.transform)
}, completion: {
_ in
// showing that in iOS 8 the screen itself changes "size"
println("did transition size change to \(size)")
println("screen bounds: \(UIScreen.mainScreen().bounds)")
println("screen native bounds: \(UIScreen.mainScreen().nativeBounds)")
// screen native bounds do not change and are expressed in scale resolution
println("screen coord space bounds: \(UIScreen.mainScreen().coordinateSpace.bounds)")
println("screen fixed space bounds: \(UIScreen.mainScreen().fixedCoordinateSpace.bounds)")
// concentrate on the green label and think about these numbers:
// the fixed coordinate space's top left is glued to the top left of the physical device
let r = self.view.convertRect(self.lab.frame, toCoordinateSpace: UIScreen.mainScreen().fixedCoordinateSpace)
println("label's frame converted into fixed space: \(r)")
println("window frame: \(self.view.window!.frame)")
println("window bounds: \(self.view.window!.bounds)")
// showing that in iOS 8 rotation no longer involves application of transform to view
println("window transform: \(self.view.window!.transform)")
println("view transform: \(self.view.transform)")
println(CGAffineTransformIdentity)
})
}
// layout events check
override func viewWillLayoutSubviews() {
println(__FUNCTION__)
}
override func viewDidLayoutSubviews() {
println(__FUNCTION__)
}
override func updateViewConstraints() {
println(__FUNCTION__)
super.updateViewConstraints()
}
}
|
Markdown
|
UTF-8
| 1,718 | 3.578125 | 4 |
[] |
no_license
|
### Program 1 - Coding Practice 
---------------------------------------------------------------------------------------------------------------------------------------------------
***For a given dataset [x,y] on Receiver Operating Characteristics (ROC) curve, find the area under ROC using Simpson's Rule (Approximation with Parabola):***
- [ ] The function defined for calculation should have two input parameters X,Y (of array size N)
- [ ] Considering every k<sup>th</sup> point in dataset, estimate area under ROC curve.
- [ ] Can only use standard defined python libraries (No import allowed)
***Testing Case (General):***
* X = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
* Y = [0, 0.25, 0.33, 0.43, 0.56, 0.65, 0.77, 0.84, 0.87, 0.92, 1]
* The answer should be 0.614
***Testing Case (General):***
* X = [-4,-2,0,2,4,6,8]
* Y = [1,3,4,4,6,9,14]
* The answer should be 66
***Testing Case (e<sup>x</sup>) :***
* X = [0,0.25,0.5,0.75,1,1.25]
* Y = [1,1.2840,1.6487,2.1170,2.7183]
* The answer should be 1.7183
***Testing Case [ln(x)]:***
* X = [1,2,3,4,5]
* Y = [0,0.6931,1.0986,1.3863,1.6094]
* The answer should be 4.0414
------------------------------------------------------------------------------------------------------------------------------------------------
***Links:***
[Problem Understanding and Algorithm Flow](https://github.com/worklifesg/Daily-Coding-Challenges-Practice/blob/main/Mathematics/Program%201%20-%20Simpson's%20Rule/1_Problem_Understanding_Algorithm.md)
[Program Code](https://github.com/worklifesg/Daily-Coding-Challenges-Practice/blob/main/Mathematics/Program%201%20-%20Simpson's%20Rule/2_Program1_Code.py)
|
Rust
|
UTF-8
| 3,903 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
use crate::data::shader::*;
use crate::shd_interface;
use crate::data::LumTextureBinding;
use crate::types::{Shader, UniformParameter};
use std::collections::HashMap;
pub const LIGHT_CHUNKS: u32 = 250;
shd_interface![
LightPassShader,
camera_pos, [f32; 3],
normal_texture, LumTextureBinding,
position_texture, LumTextureBinding,
rms_texture, LumTextureBinding,
light_count, i32
];
impl Shader<LightPassShader> for LightPassShader {
fn vertex_source() -> String {
r#"
in vec3 position;
in vec3 normal;
in vec3 color;
out vec2 uv;
void main() {
vec2 l_uv = (position.xy + 1.0) / 2.0;
uv = l_uv;
gl_Position = vec4(position, 1.);
}
"#.to_string()
}
fn fragment_source() -> String {
r#"
in vec2 uv;
uniform vec3 camera_pos;
uniform sampler2D normal_texture;
uniform sampler2D position_texture;
uniform sampler2D rms_texture;
uniform vec3 light_pos[LIGHT_CHUNKS];
uniform vec3 light_color[LIGHT_CHUNKS];
uniform float light_intensity[LIGHT_CHUNKS];
uniform float light_linear[LIGHT_CHUNKS];
uniform float light_quadratic[LIGHT_CHUNKS];
uniform float light_radius[LIGHT_CHUNKS];
uniform int light_count;
out vec4 frag_color;
void main() {
vec3 frag_pos = texture(position_texture, uv).rgb;
vec3 normal = texture(normal_texture, uv).rgb;
vec3 rms = texture(rms_texture, uv).rgb;
float specular = rms.z;
vec3 lighting = vec3(0.0, 0.0, 0.0);
vec3 view_dir = normalize(camera_pos - frag_pos);
for (int i = 0; i < light_count; i++) {
float distance = length(light_pos[i] - frag_pos);
if(distance < light_radius[i]) {
vec3 light_dir = normalize(light_pos[i] - frag_pos);
vec3 diffused = dot(normal, light_dir) * (light_color[i] * light_intensity[i]);
vec3 halfway_dir = normalize(light_dir + view_dir);
float spec = pow(max(dot(normal, halfway_dir), 0.0), 16.0);
vec3 speculared = light_color[i] * spec * specular;
float attenuation = 1.0 / (1.0 + light_linear[i] * distance + light_quadratic[i] * distance * distance);
diffused *= attenuation;
speculared *= attenuation;
lighting += diffused + speculared;
}
}
frag_color = vec4(lighting, 1.0);
}
"#.to_string().replace("LIGHT_CHUNKS", &LIGHT_CHUNKS.to_string())
}
fn parameters(&self) -> HashMap<String, UniformParameter> {
let mut map = HashMap::new();
map.insert("camera_pos".to_string(), UniformParameter::Vector3(&self.camera_pos));
map.insert("normal_texture".to_string(), UniformParameter::Texture(&self.normal_texture));
map.insert("position_texture".to_string(), UniformParameter::Texture(&self.position_texture));
map.insert("rms_texture".to_string(), UniformParameter::Texture(&self.rms_texture));
map.insert("light_pos".to_string(), UniformParameter::Vector3Array(LIGHT_CHUNKS));
map.insert("light_color".to_string(), UniformParameter::Vector3Array(LIGHT_CHUNKS));
map.insert("light_intensity".to_string(), UniformParameter::FloatArray(LIGHT_CHUNKS));
map.insert("light_linear".to_string(), UniformParameter::FloatArray(LIGHT_CHUNKS));
map.insert("light_quadratic".to_string(), UniformParameter::FloatArray(LIGHT_CHUNKS));
map.insert("light_radius".to_string(), UniformParameter::FloatArray(LIGHT_CHUNKS));
map.insert("light_count".to_string(), UniformParameter::Integer(&self.light_count));
map
}
}
|
Java
|
UTF-8
| 2,214 | 3.4375 | 3 |
[] |
no_license
|
import java.util.ArrayList;
import java.util.Comparator;
public class AStarSearch {
public AStarSearch() {
}
public ArrayList<Node> aStar(Node root) {
ArrayList<Node> pathToSolution = new ArrayList<>();
ArrayList<Node> openList = new ArrayList<>();
ArrayList<Node> closedList = new ArrayList<>();
int counter = 0;
openList.add(root);
boolean goalFound = false;
if (root.isBoardValid()) {
System.out.println("The given board is valid");
goalFound = true;
pathTrace(pathToSolution, root);
}
while (openList.size() > 0 && !goalFound) {
counter++;
System.out.println("Computing ticks: " + counter);
Node currentNode = openList.stream()
.min(Comparator.comparingInt(Node::heuristicBoard))
.get();
openList.remove(currentNode);
closedList.add(currentNode);
if (currentNode.isBoardValid()) {
System.out.println("Goal found. ");
System.out.println("CL: " + closedList.size());
System.out.println("OL: " + openList.size());
pathTrace(pathToSolution, currentNode);
goalFound = true;
break;
}
currentNode.expandNode();
for (Node currentChild : currentNode.children) {
if (closedList.contains(currentChild)) {
continue;
}
//currentChild.printResult(currentChild.board);
for (Node node : openList) {
if (currentChild == node && currentChild.heuristicBoard() > node.heuristicBoard()) {
continue;
}
}
openList.add(currentChild);
}
}
return pathToSolution;
}
public void pathTrace(ArrayList<Node> path, Node n) {
System.out.println("Tracing path: ");
Node current = n;
path.add(current);
while (current.parent != null) {
current = current.parent;
path.add(current);
}
}
}
|
Markdown
|
UTF-8
| 4,077 | 2.609375 | 3 |
[] |
no_license
|
---
date: 2016-10-13T19:15:05+08:00
title: CentOS 安装 Erlang
permalink: /install-erlang-on-centos
tags:
- CentOS
- Erlang
---
## 软件仓库
从 CentOS 软件仓库安装 Erlang 是最简单、最省事的。
不过 CentOS 默认仓库中没有 Erlang,需要我们预先安装 [Extra Packages for Enterprise Linux 项目](https://fedoraproject.org/wiki/EPEL)。
1. 安装 `epel-release`
```bash
$ sudo yum install epel-release -y
```
2. 之后便可以安装 Erlang
```bash
$ yum install erlang -y
```
安装完成后,在命令行下输入 `erl`:
```bash
$ erl
Erlang R16B03-1 (erts-5.10.4) [source] [64-bit] [smp:2:2] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V5.10.4 (abort with ^G)
```
就可以查看当前安装的 Erlang 版本 - 显然,版本还比较老旧。
如果你嫌弃 CentOS 软件仓库中的 Erlang 版本过低,我们还可以尝试 Unix/Linux 均可使用的 [kerl](https://github.com/kerl/kerl),又或自己下载源码编译。
## kerl
首先请确保你的操作系统上已经安装 `curl` 与 `git`。
下载 `kerl`:
```bash
$ curl -O https://raw.githubusercontent.com/kerl/kerl/master/kerl
```
然后将 `kerl` 改成可执行:
```bash
$ chmod a+x kerl
```
执行 `kerl list releases` 可以查看 Erlang 所有发行版本:
```bash
$ ./kerl list releases
./kerl list releases
R10B-0 R10B-10 R10B-1a R10B-2 R10B-3 R10B-4 R10B-5 R10B-6 R10B-7 R10B-8 R10B-9 R11B-0 R11B-1 R11B-2 R11B-3 R11B-4 R11B-5 R12B-0 R12B-1 R12B-2 R12B-3 R12B-4 R12B-5 R13A R13B01 R13B02-1 R13B02 R13B03 R13B04 R13B R14A R14B01 R14B02 R14B03 R14B04 R14B R14B_erts-5.8.1.1 R15B01 R15B02 R15B02_with_MSVCR100_installer_fix R15B03-1 R15B03 R15B R16A_RELEASE_CANDIDATE R16B01 R16B02 R16B03-1 R16B03 R16B 17.0-rc1 17.0-rc2 17.0 17.1 17.3 17.4 17.5 18.0 18.1 18.2 18.2.1 18.3 19.0 19.1 19.2 19.3 20.0 20.1 20.2
Run './kerl update releases' to update this list from erlang.org
```
有了,最新版本是 20.2,尝试安装:
```bash
$ ./kerl install 20.2
```
> No build named 20.2
很遗憾,报错。出人意料的是,使用 kerl 安装 Erlang 前,我们需要先编译 Erlang,命令结构是 `kerl build <release> <build_name>`:
```bash
$ ./kerl build 20.2 20.2
```
很快你就发现该命令报告大量错误。
这里又是一个意外:kerl 不负责安装[编译 Erlang 必需的依赖](https://github.com/erlang/otp/blob/maint/HOWTO/INSTALL.md#required-utilities),需要我们自己安装:
```bash
$ sudo yum install -y which perl openssl-devel make automake autoconf ncurses-devel gcc
```
安装完编译所需依赖后,重新执行 `kerl build`:
```bash
$ ./kerl build 20.2 20.2
```
待构建成功后,将新构建出的 20.2 安装到指定目录:
```bash
$ ./kerl install 20.2 ~/erlang
Installing Erlang/OTP 20.2 (20.2) in /home/sam/erlang...
You can activate this installation running the following command:
. /home/sam/erlang/activate
Later on, you can leave the installation typing:
kerl_deactivate
```
请注意**提示**,我们还需要执行 `. /home/sam/erlang/activate` 激活 Erlang。
你可能会说,看起来 kerl 没比自己编译源代码简单。从定位上说,kerl 更像 Ruby 的 RVM、rbenv 或是 Node.js 的 nvm,能够管理多个 Erlang 版本 - 而自己编译源码的话,就没这么方便。
## 编译源代码
如果你决定要[自行编译 Erlang 源代码](https://github.com/erlang/otp/blob/maint/HOWTO/INSTALL.md#required-utilities),那么请按以下步骤操作。
1. 安装构建依赖:
```bash
$ sudo yum install -y which wget perl openssl-devel make automake autoconf ncurses-devel gcc
```
2. 从 [Erlang 官网](http://www.erlang.org/downloads)下载源代码
```bash
$ curl -O http://erlang.org/download/otp_src_20.2.tar.gz
```
4. 解压 tar.gz 包
```bash
$ tar zxvf otp_src_20.2.tar.gz
```
4. 安装
```bash
$ cd otp_src_20.2
$ ./otp_build autoconf
$ ./configure && make && sudo make install
```
5. 验证
```bash
$ erl
```
|
JavaScript
|
UTF-8
| 314 | 2.8125 | 3 |
[] |
no_license
|
var fs = require('fs');
var input = process.argv;
var pathname = input[2];
var ext = input[3];
fs.readdir(pathname, function(err, list) {
if(err) throw err;
var output = [];
for(var i = 0; i < list.length; i ++) {
if(list[i].split('.')[1] == ext) {
output.push(list[i]);
}
}
console.log(output);
});
|
JavaScript
|
UTF-8
| 1,732 | 2.546875 | 3 |
[] |
no_license
|
const util = require("util");
const { MongoClient } = require("mongodb");
const newListing = require("./airbnb.data.json");
const main = async () => {
const uri = "mongodb://renderws.local:27017";
const client = new MongoClient(uri);
try {
await client.connect();
//await updateListingByName(client, "Infinite Views", { guestRooms: 3 });
//await upsertListingByName(client, "Cozy Cottage", { bathrooms: 1 });
await updateAllListingToHavePropType(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
console.log("done");
}
};
main().catch(console.error);
async function updateListingByName(client, name, update) {
const result = await client
.db("sample_airbnb")
.collection("listingsAndReviews")
.updateOne({ name }, { $set: update });
if (result) {
console.log(util.inspect(result, false, null, true));
} else {
console.log("No update done for name of", name);
}
}
async function upsertListingByName(client, name, update) {
const result = await client
.db("sample_airbnb")
.collection("listingsAndReviews")
.updateOne({ name }, { $set: update }, { upsert: true });
if (result) {
console.log(util.inspect(result, false, null, true));
} else {
console.log("No update done for name of", name);
}
}
async function updateAllListingToHavePropType(client) {
const result = await client
.db("sample_airbnb")
.collection("listingsAndReviews")
.updateMany(
{ property_type: { $exists: false } },
{ $set: { property_type: "residential" } }
);
if (result) {
console.log(util.inspect(result, false, null, true));
} else {
console.log("No update done for name of", name);
}
}
|
PHP
|
UTF-8
| 3,895 | 2.53125 | 3 |
[] |
no_license
|
<?php
/**
*--------------------------------------------------------------------------------------
* iZhanCMS 爱站内容管理系统 (http://www.izhancms.com)
*
* 商品类别
*
*
* @author 佟新华<tongxinhua@mail.b2b.cn> 2013-3-11 下午5:22:39
* @filename CategoryModel.php UTF-8
* @copyright Copyright (c) 2004-2012 Mainone Technologies Inc. (http://www.b2b.cn)
* @license http://www.izhancms.com/license/ iZhanCMS 1.0
* @version iZhanCMS 1.0
* @link http://www.izhancms.com
* @link http://www.b2b.cn
* @since 1.0.0
*-------------------------------------------------------------------------------------
*/
class igoodssort extends BaseTag
{
public $defaultParam = array(
'id' => '0', //分类id ,id=0 或者空 表示取全部分类
'level' => '0', //取到第几级
'return' => 'data', //返回标志
'type' => 'all', //此参数在id!=0时才有效 son(当id不等于0时 只取子集) all(当id不等于0时 也包含自己)
'struct' => 'relation' //返回结果的数据结构形式 等于relation就是父子级关系的数据结构,但是只能显示3层
);
/**
* 获取商品无限分类信息
* @param 标签参数
* @return 二维array()
*/
function lib_igoodssort($datas)
{
$param = $this -> mergeDefaultParam($datas);
$level = $param['level'];
if($param['id'] && $param['type'] == 'all')
{
$level = $param['level'] - 1;
}
$tree = $this -> getGoodsSortByPid($param['id'],-1,$level);
if($param['id'] && $param['type'] == 'all')
{
$sort = $this -> getGoodsSortById($param['id']);
$sort['level'] = 0;
array_unshift($tree,$sort);
foreach ($tree as $key => $val ) $tree[$key]['level'] += 1;
}
$tmp = array();
foreach ($tree as $key => $val ) $tmp[$val['sortid']] = $val;
if($param['struct'] == 'relation')
$tmp = $this ->formateParentChild($tmp);
return array($param['return']=>$tmp);
}
/**
*格式化成子父级关系的数据结构
* @param递归出来的分类信息
* @return array()父子级关系的N维数组
*/
function formateParentChild($data)
{
if(empty($data))
return array();
$first = array();
foreach($data as $key1 => $val1)
{
if($val1['level'] == 1)
$first[] = $val1;
}
foreach($first as $key2 => $val2)
{
foreach($data as $key3 => $val3)
{
if($val2['sortid'] == $val3['pid'])
{
$first[$key2]['child'][$key3] = $val3;
foreach($data as $key4 => $val4)
{
if($val4['pid'] == $first[$key2]['child'][$key3]['sortid'])
{
$first[$key2]['child'][$key3]['child'][$key4] = $val4;
}
}
!isset($first[$key2]['child'][$key3]['child']) && ($first[$key2]['child'][$key3]['child'] = array());
}
}
!isset($first[$key2]['child']) && ($first[$key2]['child'] = array());
}
return $first;
}
/**
* 获取商品无限极分类
* @param pid
* @param
* @param 查取深度
* @return 二维array()
*/
function getGoodsSortByPid ($pid,$t=-1,$level='0')
{
$pid = abs(intval($pid));
$level = abs(intval($level));
$t++;
static $sort_temp;
if($level && ($t == $level))
return $sort_temp;
$sql = 'SELECT * FROM `'.$this->tablePrefix.'goods_sort` WHERE (`pid` = '.$pid.') AND (`isdefault` = 2) ORDER BY ordernum ASC,created DESC';
$data = $this -> query($sql);
if(!empty($data))
{
foreach ($data as $key => $val )
{
$val['level'] = $t+1;
$sort_temp[] = $val;
$this -> getGoodsSortByPid($val['sortid'],$t,$level);
}
}
return $sort_temp;
}
/**
* 通过分类ID获取该条信息
* @param sortiid
* @return 一维array()
*/
function getGoodsSortById ($id)
{
$sql = 'SELECT * FROM `'.$this->tablePrefix.'goods_sort` WHERE `sortid` = '.$id.'';
$res = $this -> query($sql);
return !empty($res) ? array_pop($res) : array();
}
}
|
Markdown
|
UTF-8
| 5,199 | 3.6875 | 4 |
[] |
no_license
|
## Zombies and orphaned processes
### Zombies
Give a process A, whenever it creates a child process B, it is A's reponsibility to wait for B to exit, take its
exit details, such as exit code etc. To do this A performs a __wait__ operation.
In psuedocode
```
1. create A
2. A creates child B
3. A waits for child B
4. B exits
5. A gets B's exit details
6. A exits
```
In a scenario where B exits before A gets a chance to wait for it, there is no way A can consistently get B's information.
To solve this problem, the kernel turns every child process into a zombie. Zombies are what they are in real life (they cannot be killed, :P, even with a SIGKILL).
This allows A to eventually to a wait for B, and get information such as child's process ID, termination status, and resource usage statistics.
Given that every child will always be turned into a zombie until the parent performs a wait operation, what happens when parent fails to perform wait? In this case the child will indefinitely remain
in the kernel's process table.
E.g.
Create a file called `create_zombie.sh`
```
#!/bin/sh
sleep 1 & exec sleep 30
```
Before invoking script run
ps aux
```
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 4452 1584 pts/0 Ss 00:26 0:00 sh
root 50 0.0 0.0 4452 660 pts/1 Ss 00:41 0:00 sh
root 63 0.0 0.0 15576 2204 pts/1 R+ 00:59 0:00 ps aux
#
```
top # to capture there are no zombies
```
top - 01:00:29 up 2:42, 0 users, load average: 0.00, 0.00, 0.00
Tasks: 3 total, 1 running, 2 sleeping, 0 stopped, 0 zombie
...
```
execute it
```
# sh create_zombie.sh
```
Check
ps aux
```
# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 4452 1584 pts/0 Ss 00:26 0:00 sh
root 50 0.0 0.0 4452 1504 pts/1 Ss 00:41 0:00 sh
root 71 0.0 0.0 4352 652 pts/0 S+ 01:01 0:00 sleep 10
root 72 0.0 0.0 0 0 pts/0 Z+ 01:01 0:00 [sleep] <defunct>
root 75 0.0 0.0 15576 2108 pts/1 R+ 01:02 0:00 ps aux
```
Creation of zombie
```
# top
top - 01:01:28 up 2:43, 0 users, load average: 0.00, 0.00, 0.00
Tasks: 3 total, 1 running, 2 sleeping, 0 stopped, 1 zombie
```
What happened here?
1. From within the shell script we ran `sleep 1 &` in background.
2. Now normally this process would be inherited by the process created when we invoked `sh create_zombie.sh`, but what instead happened here
was, we ran `exec sleep 10`. Running sleep with __exec__ took over the PID of `sh create_zombie.sh`, and it won't know when sleep exited.
Just to show what exec did, I've remove __exec__ from `create_zombie.sh`.
```
# sh create_zombie.sh
#
# # in another shell
# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 4452 1584 pts/0 Ss 00:26 0:00 sh
root 50 0.0 0.0 4452 1504 pts/1 Ss 00:41 0:00 sh
root 79 0.0 0.0 4452 740 pts/0 S+ 01:17 0:00 sh create_zombie.sh
root 81 0.0 0.0 4352 644 pts/0 S+ 01:17 0:00 sleep 10
root 82 0.0 0.0 15576 2144 pts/1 R+ 01:17 0:00 ps aux
#
```
This time we see that `sh create_zombie.sh` and `sleep 10` have different PIDs.
Note: running sleep with __exec__ is not making `sleep 1 &` an orphan, because it was originally called from within the script, and the script continues to run.
([orphaned](https://en.wikipedia.org/wiki/Orphan_process) process is a process whose parent process has terminated, and the child continues to run. An orphaned process is adopted by init (PID 1))
### Orphaned processes
Whenever a parent process exits before its child, the child process becomes orphaned, and becomes the child of init (PID 1).
Script `create_orphan.sh` to create an orphan process
```
#!/bin/sh
sleep 20 &
sleep 10
exit
```
Run the script
```
# sh create_orphan.sh
```
From another shell run
```
# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 4452 1584 pts/0 Ss 00:26 0:00 sh
root 50 0.0 0.0 4452 1504 pts/1 Ss 00:41 0:00 sh
root 157 0.0 0.0 4452 752 pts/0 S+ 01:50 0:00 sh create_orphan.sh
root 158 0.0 0.0 4352 652 pts/0 S+ 01:50 0:00 sleep 20
root 159 0.0 0.0 4352 740 pts/0 S+ 01:50 0:00 sleep 10
root 160 0.0 0.0 15576 2116 pts/1 R+ 01:50 0:00 ps aux
# ps -p 158 -o ppid
PPID
157
# ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 4452 1584 pts/0 Ss+ 00:26 0:00 sh
root 50 0.0 0.0 4452 1504 pts/1 Ss 00:41 0:00 sh
root 158 0.0 0.0 4352 652 pts/0 S 01:50 0:00 sleep 20
root 162 0.0 0.0 15576 2072 pts/1 R+ 01:50 0:00 ps aux
# ps -p 158 -o ppid
PPID
1
#
```
In the second call to `ps -p 158 -o ppid` we observe that child is adopted by init (PID 1).
### References
- [stackoverflow - create zombie in bash](https://unix.stackexchange.com/questions/217507/zombies-in-bash)
|
Java
|
UTF-8
| 1,438 | 2.671875 | 3 |
[] |
no_license
|
package extremefilter.commands;
import extremefilter.main.ExtremeFilter;
import extremefilter.storage.MainStorage;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
/**
* Created by root on 04.03.2017.
*/
public class CMD_Mute implements CommandExecutor {
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if(!cs.hasPermission("ex.mute")){
cs.sendMessage(ExtremeFilter.getInstance().getNoPerm());
}
if(args.length != 1){
cs.sendMessage("§c/mute <Player>");
return true;
}
try{
if(Bukkit.getPlayer(args[0]).isOnline()){
if(MainStorage.getInstance().muted.contains(Bukkit.getPlayer(args[0]))){
cs.sendMessage("§5The Player " + args[0] + " was already muted!");
return true;
}
MainStorage.getInstance().muted.add(Bukkit.getPlayer(args[0]));
cs.sendMessage("§cMuted the Player §5" + args[0]);
}else{
cs.sendMessage("§cThe Players §5" + args[0] + "§c isn't online!");
}
}catch(NullPointerException ex){
cs.sendMessage("§cThe players " + args[0] + " is not online!");
}
return true;
}
}
|
Markdown
|
UTF-8
| 5,709 | 2.953125 | 3 |
[] |
no_license
|
---
layout: post
title: "Node JS"
description: "Node JS"
tagline: "Node JS"
category: programming
tags: [programming, digital services]
---
The landscape of writing web applications has come a long way over the years. At 23 years old, Javascript is in it's prime, the language of the web. Years ago Javascript was once synonymous with JQuery, back when the focus was on using it as a platform for DOM manipulation and events. Not long after came patterns for building the entire front-end, data binding frameworks like [Handlebars](https://handlebarsjs.com/) started to gain traction, Twitter came along with [Bootstrap](https://getbootstrap.com/) and suddenly everyone's personal projects started looking a lot more slick.
Eventually MVC frameworks came around unifying the whole approach, you had Javascript models and controllers feeding into data-binded HTML and with the likes of [Angular](https://angularjs.org/) or [Ember](https://emberjs.com/) it all became pretty straight-forward. I remember evaluating both of these frameworks for a project in Kainos about 5 years ago, Angular is still heavily in use on that project and going strong.
For me, the next evolution in the way I write and think about Javascript has come in the form of [NodeJS](https://nodejs.org/en/). With the ability to write server-side code in Javascript I can have my routing, state-management, validation, client-side controls and even my database interactions all written in one single language. Node describe themselves as an _asynchronous event driven JavaScript runtime, designed to build scalable network applications_. With it's single threaded event loop and HTTP focused design, it's great for building scalable micro-service API and front-end applications.
Node itself has many frameworks out there designed to save you stress and time getting up and running. Although each framework may vary slightly in it's foundational aspirations, patterns and guidelines, it's all Node. Some of the stars of the show are:
1. [Adonis](https://adonisjs.com/)
2. [Express](https://expressjs.com/)
3. [Meteor](https://www.meteor.com/)
4. [Nest](https://nestjs.com/)
I've personally been working with Express for about 14 months on a large microservice architecture processing around 3 million transactions every year. We've used it to drive APIs, front-ends, message brockers, you name it. It's minimalistic, non-opinionated and as a result easy to shape towards your particular needs. It reminds me a lot of Python's [Flask](https://www.fullstackpython.com/flask.html).
If you're thinking about using Node.JS in an upcoming project hopefully these next few sections are for you, we'll talk about tools and patterns to enchance the quality of your solution and increase productivity.
## NPM
Node Package Manager comes with Node.JS out of the box so you won't get very far before you bump into it. As world's largest open source software registry, NPM is used to fetch any javascript libraries that your application needs for development and production. More often that not if you're thinking of writing some sort of component, there's a node module for that. Not only is it simple to use, it's fast even in mature projects.
## Typescript
If you're working with Node or any serious Javascript that you plan to release into a production environment, Typescript is a no brainer. Applying a bit of static typing to your project, especially a team project, goes a long way. Using interfaces in your code not only improves readability and maintainability, it allows you to utilize tools that will catch problems in your code automatically and this in turn allows you to build and refactor quicker. Furthermore, static typing allows you to utilize dependancy injection/IoC libraries like [InversifyJS](https://github.com/inversify/InversifyJS), taking you one step forward towards predictable, testable, easily maintainable code. At the end of the day, it all compiles down to Javascript anyway so you've got the dynamic aspects of the language when you need it.
## Swagger
Building an API? Need documentation? [Swagger UI](https://swagger.io/tools/swagger-ui/) in particular is a great option as it provides a visual interface that allows you to interact with your API endpoints. This is all fueled by a `swagger.json` file which can be generated automatically as you make changes to your code, so it's kept up to date with no effort. This is great for testing API endpoints manually and serves as an interactive specification of your API that can be sent to customers. As you might have guessed, there's a [package](https://www.npmjs.com/package/swagger-ui) on NPM for it too.
## Inversify
As I touched on in the Typescript section, Inversify is an Inversion of Control container that works well with Typescript. If you're not sure what Inversion of Control containers are, essentially the idea here is if you write your code in such a way where individual components depend on abstractions/interfaces as opposed to concrete implementations, this is what's called [dependancy inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle). An IoC container allows you to take that one step further where you're not even responsible for instantiating any implementations of these interfaces yourself. You just tell the IoC container how you want things wired up, i.e. which implementations should be injected for which abstractions, then the container can do the heavy lifting.
The benefit you get is that all your implementation instantiations can be defined in a single file, but as a side effect of your code adhering to SOLID principles it's extremely easy to change and test different implementations.
|
PHP
|
UTF-8
| 3,193 | 2.6875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Some class description here...
*
* @package KAWANI
* @subpackage subpackage
* @category category
* @author SMTI-RDaludado
* @link http://systemantech.com
*/
class Violation_level_model extends MY_Model {
protected $_table = 'violation_levels';
protected $primary_key = 'id';
protected $return_type = 'array';
/**
* Callbacks or Observers
*/
protected $before_create = ['generate_date_created_status'];
protected $after_get = ['set_default_data'];
protected $after_create = ['write_audit_trail(0, add_site)'];
protected $after_update = ['write_audit_trail(1, edit_site)'];
protected function generate_date_created_status($violation_level)
{
$violation_level['created'] = date('Y-m-d H:i:s');
$violation_level['active_status'] = 1;
$violation_level['created_by'] = $this->ion_auth->user()->row()->id;
return $violation_level;
}
protected function set_default_data($violation_level)
{
$violation_level['status_label'] = ($violation_level['active_status'] == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
$violation_level['status_url'] = ($violation_level['active_status'] == 1) ? 'deactivate' : 'activate';
$violation_level['status_action'] = ($violation_level['active_status'] == 1) ? 'Deactivate' : 'Activate';
$violation_level['status_icon'] = ($violation_level['active_status'] == 1) ? 'fa-times text-red' : 'fa-check text-green';
return $violation_level;
}
public function get_many_violation_level_by($param)
{
$query = $this->db;
$query->select('*');
// $query->join('employee_info', 'employee_info.violation_level_id = violation_levels.id');
return $this->get_many_by($param);
}
public function get_violation_level_by($param)
{
$query = $this->db;
$query->select('violation_levels.*, companies.name as company_name');
$query->join('system_users', 'system_users.employee_id=violation_levels.created_by','left');
$query->join('companies', 'violation_levels.company_id = companies.id', 'left');
$query->order_by('violation_levels.name', 'asc');
return $this->get_by($param);
}
public function get_details($method, $where)
{
$this->db->select('
violation_levels.*,
violation_levels.name as name,
violation_levels.description as description,
companies.name as company_name,
')
->join('companies', 'companies.id=violation_levels.company_id', 'left')
->order_by('created', 'asc');
return $this->{$method}($where);
}
// public function get_violation_level($where = '')
// {
// $this->db->select('
// violation_levels.*,
// violation_levels.name as name
// ')
// ->join('employee_violation_levels', 'violation_levels.id = employee_violation_levels.violation_level_id', 'left');
// return $this->get_by($where);
// }
}
|
Go
|
UTF-8
| 709 | 2.59375 | 3 |
[] |
no_license
|
package caches
import (
"github.com/go-redis/redis"
"github.com/gw123/GMQ/core/interfaces"
)
type CacheRule struct {
KeyPatten interfaces.CacheKey
Callback func(arg ...interface{}) (interface{}, error)
Client *redis.Client
}
func NewCacheRule(keyPatten interfaces.CacheKey, callback func(arg ...interface{}) (interface{}, error), client *redis.Client) *CacheRule {
return &CacheRule{KeyPatten: keyPatten, Callback: callback, Client: client}
}
func (c CacheRule) GetCacheKey() interfaces.CacheKey {
return c.KeyPatten
}
func (c CacheRule) GetCallback() func(arg ...interface{}) (interface{}, error) {
return c.Callback
}
func (c CacheRule) GetRedisClient() *redis.Client {
return c.Client
}
|
C++
|
UTF-8
| 632 | 2.8125 | 3 |
[] |
no_license
|
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <chrono>
using namespace std;
using namespace chrono;
unsigned long int sum=0;
void *runner(void *param);
int main(int argc, char *argv[]){
system_clock::time_point start = system_clock::now();
int x = 0;
for (int i = 1; i <= 50000; i++)
{
for (int j = 1; j <= 50000; j++)
{
x = (i + j) * 2 + (i / j);
sum += x;
}
}
cout<<sum<<endl;
system_clock::time_point end = system_clock::now();
microseconds microSec = duration_cast<microseconds>(end - start);
cout<<microSec.count()<<endl;
return 0;
}
|
JavaScript
|
UTF-8
| 476 | 2.609375 | 3 |
[] |
no_license
|
let initState = {
counterBar: 12,
tableForTwo: 4,
tableForFour: 6,
tableForEight: 2,
}
const tableReducer = (state = initState, action) => {
switch (action.type) {
case 'UPDATE_INCREASE_TABLE':
return { ...state, [action.prop]: state[action.prop] + action.reserveCount }
case 'UPDATE_DECREASE_TABLE':
return { ...state, [action.prop]: state[action.prop] - action.reserveCount }
default:
return state
}
}
export default tableReducer
|
Swift
|
UTF-8
| 1,446 | 2.765625 | 3 |
[] |
no_license
|
//
// NewsRow.swift
// NewsFeedAppSwiftUI
//
// Created by Maksim Kalik on 8/22/22.
//
import SwiftUI
import Kingfisher
struct NewsRow: View {
@Environment(\.colorScheme) var colorScheme
let viewModel: ArticleViewModel
var body: some View {
HStack(spacing: 10) {
// KFImage(viewModel.imageUrl)
// .resizable()
// .placeholder {
// ProgressView()
// }
// .frame(maxWidth: 64, maxHeight: 64)
// .aspectRatio(contentMode: .fill)
// .cornerRadius(32)
UserpicStackView(userpicURLs: [viewModel.imageUrl, nil], width: 76)
.padding(.leading, 10)
.animation(nil)
VStack(alignment: .leading, spacing: 5) {
Text(viewModel.title)
.font(.system(size: 14, weight: .medium))
.foregroundColor(colorScheme == .dark ? .orange : .black)
// if let description = viewModel.description {
// Text(description)
// .font(.system(size: 15))
// }
Text(viewModel.published)
.font(.system(size: 12))
.foregroundColor(.gray)
}
}
// .padding(.vertical, 5)
}
}
|
C++
|
UTF-8
| 2,230 | 3.25 | 3 |
[] |
no_license
|
#pragma once
#include <algorithm>
#include "board.hpp"
class Computer{
public:
std::pair<int, int> chooseMove(Board);
void makeMove(Board&);
private:
bool isOnCorner(std::pair<int, int>, int, int);
};
std::pair<int, int> Computer::chooseMove(Board board){
std::vector<std::pair<int, int>> possibleMoves;
for(int j = 0; j < board.l; ++j){
for(int i = 0; i < board.b; ++i){
if(board.isValidMove(j, i)){
possibleMoves.push_back(std::make_pair(i, j));
}
}
}
std::random_shuffle(possibleMoves.begin(), possibleMoves.end());
for(auto move : possibleMoves){
std::cout << move.first << " " << move.second << "\n";
if(isOnCorner(move, board.l, board.b)) return move;
}
int bestScore = -1;
std::pair<int, int> bestMove;
for(auto move: possibleMoves){
Board copy = board;
copy.x = move.first;
copy.y = move.second;
copy.isValidMove(copy.y, copy.x);
copy.placeDisk();
copy.draw();
for(int k = 0; k < 9; ++k){
if(copy.dirs[k]){
int dir_y = copy.setDirY(k);
int dir_x = copy.setDirX(k);
copy.flipDiscs(copy.cells[copy.y][copy.x].state, copy.y+dir_y, copy.x+dir_x, dir_y, dir_x);
}
}
if(bestScore < copy.noOfWhiteDisks){
bestScore = copy.noOfWhiteDisks;
bestMove = move;
}
}
return bestMove;
}
void Computer::makeMove(Board &board){
Board copy = board;
auto move = chooseMove(board);
board.x = move.first;
board.y = move.second;
board.isValidMove(board.y, board.x);
board.placeDisk();
for(int k = 0; k < 9; ++k){
if(board.dirs[k]){
int dir_y = board.setDirY(k);
int dir_x = board.setDirX(k);
board.flipDiscs(board.cells[board.y][board.x].state, board.y+dir_y, board.x+dir_x, dir_y, dir_x);
}
}
}
bool Computer::isOnCorner(std::pair<int, int> coords, int l, int b){
return (coords.first == 0 && coords.second == 0 ) ||
(coords.first == 0 && coords.second == b-1) ||
(coords.first == l-1 && coords.second == 0 ) ||
(coords.first == l-1 && coords.second == b-1);
}
|
Java
|
UTF-8
| 295 | 1.601563 | 2 |
[] |
no_license
|
package org.apache.flink.runtime.operators.coordination;
import java.io.Serializable;
/**
* Root interface for all requests from the client to a {@link OperatorCoordinator}
* which requests for a {@link CoordinationResponse}.
*/
public interface CoordinationRequest extends Serializable {}
|
JavaScript
|
UTF-8
| 185 | 3.71875 | 4 |
[] |
no_license
|
function fibonacci(n) {
let arr = [1, 1];
for (i = 2; i < n; i++) {
arr.push(arr[i - 2] + arr[i - 1]);
}
console.log(arr);
return arr[n - 1];
}
console.log(fibonacci(9));
|
C++
|
UTF-8
| 266 | 2.890625 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <list>
#include <string>
using namespace std;
int main(){
list<string> slst={"1","2","3","3","2","4"};
cout<<count(slst.begin(),slst.end(),"2")<<endl;
cout<<count(slst.begin(),slst.end(),"3")<<endl;
return 0;
}
|
Java
|
UTF-8
| 1,211 | 2.046875 | 2 |
[] |
no_license
|
package ch.quickorder.util;
import com.clusterpoint.api.CPSConnection;
import com.clusterpoint.api.CPSRequest;
import com.clusterpoint.api.CPSResponse;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.util.HashMap;
import java.util.Map;
public class ClusterPointConnectionFactory {
private static ClusterPointConnectionFactory instance;
public static ClusterPointConnectionFactory getInstance() {
if (instance == null) {
instance = new ClusterPointConnectionFactory();
}
return instance;
}
private static Map< String, CPSConnection> dbConnections = new HashMap<>();
public ClusterPointConnectionFactory() {
}
public CPSConnection getConnection( String database) {
CPSConnection cpsConnection = dbConnections.get( database);
if (cpsConnection == null) {
try {
cpsConnection = new CPSConnection("tcp://cloud-eu-1.clusterpoint.com:9007", database,
"testuser", "Test42", "1302", "document", "//document/id");
} catch (Exception e) {
e.printStackTrace();
}
}
return cpsConnection;
}
}
|
TypeScript
|
UTF-8
| 3,388 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
import {Component} from '@layr/component';
import {Storable} from './storable';
import {primaryIdentifier, secondaryIdentifier, attribute, loader, method} from './decorators';
import {Index} from './index-class';
describe('Index', () => {
test('Creation', async () => {
class Movie extends Storable(Component) {
@primaryIdentifier() id!: string;
@secondaryIdentifier() slug!: string;
@attribute('string') title!: string;
@attribute('number') year!: number;
@loader(async function (this: Movie) {
await this.load({year: true});
return this.year <= new Date().getFullYear();
})
@attribute('boolean')
isReleased!: boolean;
@method() play() {}
}
let index = new Index({title: 'asc'}, Movie.prototype);
expect(Index.isIndex(index)).toBe(true);
expect(index.getAttributes()).toStrictEqual({title: 'asc'});
expect(index.getParent()).toBe(Movie.prototype);
expect(index.getOptions().isUnique).not.toBe(true);
index = new Index({title: 'desc'}, Movie.prototype, {isUnique: true});
expect(Index.isIndex(index)).toBe(true);
expect(index.getAttributes()).toStrictEqual({title: 'desc'});
expect(index.getOptions().isUnique).toBe(true);
index = new Index({year: 'desc', id: 'asc'}, Movie.prototype);
expect(Index.isIndex(index)).toBe(true);
expect(index.getAttributes()).toStrictEqual({year: 'desc', id: 'asc'});
expect(() => new Index({}, Movie.prototype)).toThrow(
"Cannot create an index for an empty 'attributes' parameter (component: 'Movie')"
);
// @ts-expect-error
expect(() => new Index('title', Movie.prototype)).toThrow(
"Expected a plain object, but received a value of type 'string'"
);
// @ts-expect-error
expect(() => new Index({title: 'asc'}, Movie)).toThrow(
"Expected a storable component instance, but received a value of type 'typeof Movie'"
);
expect(() => new Index({country: 'asc'}, Movie.prototype)).toThrow(
"Cannot create an index for an attribute that doesn't exist (component: 'Movie', attribute: 'country')"
);
expect(() => new Index({play: 'asc'}, Movie.prototype)).toThrow(
"Cannot create an index for a property that is not an attribute (component: 'Movie', property: 'play')"
);
expect(() => new Index({id: 'asc'}, Movie.prototype)).toThrow(
"Cannot create an index for an identifier attribute because this type of attribute is automatically indexed (component: 'Movie', attribute: 'id')"
);
expect(() => new Index({slug: 'asc'}, Movie.prototype)).toThrow(
"Cannot create an index for an identifier attribute because this type of attribute is automatically indexed (component: 'Movie', attribute: 'slug')"
);
expect(() => new Index({isReleased: 'asc'}, Movie.prototype)).toThrow(
"Cannot create an index for a computed attribute (component: 'Movie', attribute: 'isReleased')"
);
// @ts-expect-error
expect(() => new Index({title: 'ASC'}, Movie.prototype)).toThrow(
"Cannot create an index with an invalid sort direction (component: 'Movie', attribute: 'title', sort direction: 'ASC')"
);
// @ts-expect-error
expect(() => new Index({title: 'asc'}, Movie.prototype, {unknownOption: 123})).toThrow(
"Did not expect the option 'unknownOption' to exist"
);
});
});
|
Java
|
UTF-8
| 3,437 | 2.140625 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
/***************************************************************************
* Copyright (c) 2013, Rapid7 Inc
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of Rapid7 nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
package com.rapid7.component.messaging.relay.amqp;
import com.rapid7.component.messaging.relay.MessageHandler;
import com.rapid7.component.messaging.relay.encoding.MessageRelayEncoding.EncodedMessage;
import java.io.IOException;
/**
* A MessageHandler instance that intercepts encoded AMQP Ack messages and executes the
* ack operation on the specified BusMessageRetriever (thus closing an end-to-end message
* acknowledgment chain).
*/
public class AckHandler implements MessageHandler
{
public static String ACK_DEST = "__relay_ack_";
private BusMessageRetriever m_ackRetriever;
/**
* Create a ControlMessageHandler instance.
* @param clientID The uniqueID of the client on whose behalf the request is being made.
* @param controlRetriever The BusMessageRetriever to configure.
*/
public AckHandler(BusMessageRetriever ackRetriever) {
m_ackRetriever = ackRetriever;
}
@Override
public boolean handle(EncodedMessage message) {
if (AckHandler.isAckMessage(message)) {
// It's an ack message. Process it.
try {
m_ackRetriever.doAck(message.getEnvelope().getDeliveryTag(), message.getChannelID());
} catch (IOException e) {
System.err.println("Unable to complete end-to-end ack for message "
+ message.getEnvelope().getDeliveryTag() + " : " + e.getMessage());
}
return false;
} else {
// It's not an ack. Return true so it can be processed by downstream handlers.
return true;
}
}
public static boolean isAckMessage(EncodedMessage message) {
return message.getEnvelope().getExchange().equals(ACK_DEST)
|| message.getEnvelope().getRoutingKey().equals(ACK_DEST);
}
}
|
Ruby
|
UTF-8
| 647 | 2.6875 | 3 |
[] |
no_license
|
# This class is from the ruby-sync gem
class Local < Base
def initialize()
end
def file_list
files = []
dirs = ['.']
dirs += dir_list
dirs.each do |d|
files += Dir.entries(d).map { |f| d=='.' ? f : "#{d}/#{f}"}.select { |f| not File.directory?(f) }
end
files
end
def dir_list
in_dirs = ['.']
out_dirs = []
while (not in_dirs.empty?) do
dir = in_dirs.pop
new_dirs = Dir.entries(dir).select { |f| f != '.' && f != '..' }.map{ |f| dir=='.' ? f : "#{dir}/#{f}" }.select { |f| File.directory?(f) }
out_dirs += new_dirs
in_dirs += new_dirs
end
out_dirs
end
end
|
Java
|
UTF-8
| 413 | 1.898438 | 2 |
[] |
no_license
|
package swu.xl.contentprovider;
public class URIList {
public static final String CONTENT = "content://";
public static final String AUTHORITY = "swu.xl.contentprovider";
//调用者使用
public static final String URI_USER = CONTENT + AUTHORITY + "/" + DatabaseHelper.USER_TABLE_NAME;
public static final String URI_LESSON = CONTENT + AUTHORITY + "/" + DatabaseHelper.LESSON_TABLE_NAME;
}
|
C#
|
UTF-8
| 1,399 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
namespace Sender
{
public class DateFormatter
{
public List<string> DayList { get; set; }
public List<string> MonthList { get; set; }
public List<string> YearList { get; set; }
public bool IsDateFormatted { get; set; }
public DateFormatter(List<string> dateList)
{
this.DayList = new List<string>();
this.MonthList = new List<string>();
this.YearList= new List<string>();
this.GetFormattedDate(dateList);
}
private void GetFormattedDate(List<string> dateList)
{
try
{
int sizeOfDateList = dateList.Count;
for (int index = 1; index < sizeOfDateList; index++)
{
string date = dateList[index];
string[] dd_mm_yyyy = date.Split('/');
this.DayList.Add(dd_mm_yyyy[0]);
this.MonthList.Add(dd_mm_yyyy[1]);
this.YearList.Add(dd_mm_yyyy[2]);
}
IsDateFormatted = true;
}
catch (Exception e)
{
Console.WriteLine(e+" Can not Split Into day Month Year!! Check DataFormatter");
IsDateFormatted = false;
throw;
}
}
}
}
|
Java
|
UTF-8
| 2,302 | 2.265625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.compguide.web.Persistence.SessionBeans;
import com.compguide.web.Persistence.Entities.MedicationTask;
import com.compguide.web.Persistence.Entities.ScheduleTask;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author António
*/
@Stateless
public class MedicationTaskFacade extends AbstractFacade<MedicationTask> {
@PersistenceContext(unitName = "com.compguide_CompGuide-Web_war_1.0-SNAPSHOTPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public MedicationTaskFacade() {
super(MedicationTask.class);
}
public List<MedicationTask> findByScheduleTask(ScheduleTask scheduleTask) {
List<MedicationTask> medicationtasks = new ArrayList<>();
try {
Query query = em.createNamedQuery("MedicationTask.findByScheduleTaskID", MedicationTask.class);
query.setParameter("scheduleTaskID", scheduleTask);
medicationtasks = query.getResultList();
} catch (javax.ejb.EJBException | javax.persistence.NoResultException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return medicationtasks;
}
public MedicationTask findByActiveIngredient(String activeIngredient) {
MedicationTask medicationtask = null;
try {
Query query = em.createNamedQuery("MedicationTask.findByActiveIngredient", MedicationTask.class);
query.setParameter("activeIngredient", activeIngredient);
medicationtask = (MedicationTask) query.getSingleResult();
} catch (javax.ejb.EJBException | javax.persistence.NoResultException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return medicationtask;
}
}
|
Markdown
|
SHIFT_JIS
| 70,657 | 2.625 | 3 |
[] |
no_license
|
#zɂqI̊mۂɊւ@
zɂqI̊mۂɊւ@
ial\ܔNl\l@\jŏIFZNZO@Z㍆iŏI܂ł̖{s@߁j\ZNZ\O@Z\㍆i{sj@
@́@i\Oj
@́@茚z̈ێǗil\\j
@Ó@zɂqI̊mۂɊւ鎖Ƃ̓o^i\̓\\̌܁j
@ĺ@o^Ǝғ̒ĉ̎wi\̘Z\\̋j
@́@Gi\̏\\\lj
@Ź@i\l̓\\j
@
@@@́@
##iړIj
@̖@́A̎҂gpA͗p錚z̈ێǗɊւqKvȎ߂邱ƂɂǍzɂqIȊ̊mۂ}AČOq̌yёiɎ邱ƂړIƂB
##i`j
@̖@ɂāu茚zvƂ́AsASݓXAX܁AAwZAZ̗pɋ鑊x̋K͂L錚ziz@
ia\ܔN@Sꍆjꍆ
Ɍf錚zBȉBjŁA̎҂gpA͗pAÄێǗɂĊqɔzKvȂ̂ƂĐ߂Œ߂̂B
Q
@O̐߂ɂẮAz̗prAזʐϓɂ茚z߂̂ƂB
##iی̋Ɩj
O
@ی́A̖@̎{sɊւA̋ƖsȂ̂ƂB
@̎҂gpA͗p錚z̈ێǗɂāAq̐m̕y}邱ƁB
@̎҂gpA͗p錚z̈ێǗɂāAq̑kɉAyъqKvȎwsȂƁB
@@@́@茚z̈ێǗ
##izqǗj
l
@茚z̏LҁAL҂̑̎҂œY茚z̈ێǗɂČL̂́A߂Œ߂iȉuzqǗvƂBjɏ]ēY茚z̈ێǗȂȂȂB
Q
@zqǗ́AC̒Ayєr̊ǗA|A˂݁A̖h̑qǍDȏԂێ̂ɕKvȑ[uɂĒ߂̂ƂB
R
@茚zȊǑző̎҂gpA͗p̂̏LҁAL҂̑̎҂œYz̈ێǗɂČL̂́AzqǗɏ]ēYz̈ێǗ悤ɓw߂ȂȂȂB
##i茚zɂĂ̓͏oj
@茚z̏LҁiL҈ȊOɓY茚z̑S̊ǗɂČL҂Ƃ́AYLҁjiȉu茚zLғvƂBj́AY茚zgpɎƂ́A̓ӌȓɁAJȗ߂̒߂ƂɂAY茚z̏ݏꏊAprAזʐϋyэ\ݔ̊TvAzqǗZp҂̎̑Jȗ߂Œ߂鎖s{miیݒus͓ʋɂẮAs͋撷Bȉ͕̏тɑ\OyёOɂēBjɓ͂oȂȂȂB
Q
@ŐḰAɎgpĂ錚zAꍀ̐߂鐭߂̎{sɔA͗pr̕ύXAzɂ鉄זʐς̑ɂAVɓ茚zɊY邱ƂƂȂꍇɂďpB̏ꍇɂāAOuY茚zgpɎƂvƂ̂́Auz茚zɊY邱ƂƂȂƂvƓǂݑւ̂ƂB
R
@茚zLғ́AŐKɂ͏oɕύXƂA͓Y茚zpr̕ύXɂ茚zɊYȂƂƂȂƂ́A̓ӌȓɁA̎|s{mɓ͂oȂȂȂB
##izqǗZp҂̑ICj
Z
@茚zLғ́AY茚z̈ێǗqKɍsȂ悤Ɋē邽߁AJȗ߂̒߂ƂɂAzqǗZpҖƏL҂̂猚zqǗZp҂ICȂȂȂB
Q
@zqǗZp҂́AY茚z̈ێǗzqǗɏ]čsȂ悤ɂ邽ߕKvƔF߂Ƃ́AY茚z̏LҁAL҂̑̎҂œY茚z̈ێǗɂČL̂ɑAӌqׂ邱ƂłB̏ꍇɂẮAYL҂́ÄӌdȂȂȂB
##izqǗZpҖƏj
掵
@zqǗZpҖƏ́ÅêꂩɊY҂ɑAJbtB
@Jȗ߂Œ߂wyю̌oLҖ͌Jȗ߂̒߂Ƃɂ肱Ɠȏ̒myыZ\LƔF߂҂ŁAJb̓o^҂suKiȉuuKvƂBj̉ےC
@zqǗZpҎɍi
Q
@Jb́ÅêꂩɊY҂ɑẮAzqǗZpҖƏ̌tsȂȂƂłB
@ŐKɂ茚zqǗZpҖƏ̕Ԕ[𖽂A̓NZĈNo߂Ȃ
@̖@̖͂@ɊÂɈᔽĔ̌Yɏꂽ҂ŁA̎sIA͎s邱ƂȂȂNZēNo߂Ȃ
R
@Jb́AzqǗZpҖƏ̌tĂ҂A̖@̖͂@ɊÂɈᔽƂ́ǍzqǗZpҖƏ̕Ԕ[𖽂邱ƂłB
S
@s{ḿAzqǗZpҖƏ̌tĂ҂ɂāAȌsȂKvƔF߂Ƃ́A̎|Jbɐ\oȂȂȂB
T
@zqǗZpҖƏ̌t͍Čt̎萔͐߂ŁAzqǗZpҖƏ̌tAČt̑zqǗZpҖƏɊւ葱I͌Jȗ߂Œ߂B
##io^j
掵̓
@Oꍀꍆ̓o^́AJȗ߂Œ߂ƂɂAuKsƂ҂̐\ɂsB
##iij
掵̎O
@̊êꂩɊY҂́A掵ꍀꍆ̓o^邱ƂłȂB
@̖@̖͂@ɊÂ߂ɈᔽAȏ̌YɏA̎sIA͎s邱ƂȂȂNo߂Ȃ
@掵̏\ŐKɂo^A̎̓No߂Ȃ
O
@@lłāA̋ƖŝɑÔꂩɊY҂
##io^j
掵̎l
@Jb́A掵̓̋Kɂo^\҂Ɍfvׂ̂ĂɓKĂƂ́A̓o^ȂȂȂB
@ʕ\̏㗓ɌfȖڂA̎Ԑ\̉Ɍf鎞Ԑȏł邱ƁB
@Ɍf邢ꂩ̏ɓKmoL҂ỎȖڂ̂ł邱ƁBC@wZ@
ia\N@\ZjɊÂwႵ͍wZɂČz̊qɊւȖڂS鋳AyႵ͍ut̐EɂҖ͂̐Eɂ
@wZ@
ɊÂw͍wZɂėȌn̐K̉ےC߂đƂ҂ŁǍ\Nȏ㌚z̊q̈ێǗɊւɏ]oL
n@C̓Ɍf҂Ɠȏ̒moL
Q
@o^́AuK@֓o^ɓo^҂͖̎́AZAo^̔Nyѓo^ԍLڂĂ̂ƂB
##io^̍XVj
掵̌
@掵ꍀꍆ̓o^́AܔNȏ\NȓɂĐ߂Œ߂ԂƂɂ̍XVȂÅԂ̌o߂ɂāǍ͂B
Q
@OŐḰAO̓o^̍XVɂďpB
##iuK̎{`j
掵̘Z
@掵ꍀꍆ̓o^ҁiȉuo^uK@ցvƂBj́AȗRꍇAƔNxAuK̎{Ɋւv쐬Aɏ]čuKsȂȂȂB
Q
@o^uK@ւ́AɁAAJȗ߂Œ߂ɓK@ɂuKsȂȂȂB
R
@o^uK@ւ́AƔNx̊JnOɁAꍀ̋Kɂ쐬vJbɓ͂oȂȂȂBύX悤ƂƂAlƂB
##iύX̓͏oj
掵̎
@o^uK@ւ́A̎Ⴕ͖̖͏ZύX悤ƂƂ́AύX悤Ƃ̓TԑO܂łɁAJbɓ͂oȂȂȂB
##iƖKj
掵̔
@o^uK@ւ́AuK̋ƖɊւKiȉuƖKvƂBj߁AuK̋Ɩ̊JnOɁAJbɓ͂oȂȂȂBύX悤ƂƂAlƂB
Q
@ƖKɂ́AuK̎{@AuKɊւ闿̑̌Jȗ߂Œ߂鎖߂ĂȂȂȂB
##iƖ̋xp~j
掵̋
@o^uK@ւ́AuK̋Ɩ̑S͈ꕔx~A͔p~悤ƂƂ́AJȗ߂Œ߂ƂɂA炩߁A̎|Jbɓ͂oȂȂȂB
##i\̔tyщ{j
掵̏\
@o^uK@ւ́AƔNxoߌOȓɁA̎ƔNx̍Yژ^AݎؑΏƕ\yёvvZ͎xvZтɉcƕ͎ƕi̍쐬ɑウēdIL^idqIACȊ̐l̒moɂĂ͔F邱ƂłȂōL^łāAdqvZ@ɂ̗pɋ̂Bȉ̏ɂēBj̍쐬Ăꍇɂ铖YdIL^܂ށByё\ɂāu\vƂBj쐬AܔNԎƏɔĒuȂȂȂB
Q
@uKu悤Ƃ҂̗̑QWĺAo^uK@ւ̋Ɩԓ́AłAɌf鐿邱ƂłBA͑l̐ɂ́Ao^uK@ւ̒߂pxȂȂȂB
@\ʂč쐬ĂƂ́AYʂ̉{͓ʂ̐
@Ȍʂ̓{͏{̐
O
@\dIL^č쐬ĂƂ́AYdIL^ɋL^ꂽJȗ߂Œ߂@ɂ\̂̉{͓ʂ̐
l
@O̓dIL^ɋL^ꂽdI@łČJȗ߂Œ߂̂ɂ邱Ƃ͓̐YLڂʂ̌t̐
##iK߁j
掵̏\
@Jb́Ao^uK@ւ掵̎lꍀêꂩɓKȂȂƔF߂Ƃ́A̓o^uK@ւɑA̋KɓK邽ߕKvȑ[uƂׂƂ𖽂邱ƂłB
##iP߁j
掵̏\
@Jb́Ao^uK@ւ掵̘Zꍀ͑̋KɈᔽĂƔF߂Ƃ́A̓o^uK@ւɑAuKsׂƖ͍uK̎{@̑̋Ɩ̉PɊւKvȑ[uƂׂƂ𖽂邱ƂłB
##io^̎j
掵̏\O
@Jb́Ao^uK@ւ̊êꂩɊYƂ́A̓o^A͊Ԃ߂čuK̋Ɩ̑SႵ͈ꕔ̒~𖽂邱ƂłB
@掵̎Oꍆ͑OɊYɎƂB
@掵̘ZOA掵̎掵̋܂ŁA掵̏\ꍀ͎̋KɈᔽƂB
O
@ȗRȂ̂ɑ掵̏\e̋Kɂ鐿ƂB
l
@掵̏\ꖔ͑ŐKɂ閽߂ɈᔽƂB
@s̎iɂ掵ꍀꍆ̓o^ƂB
##i̔tj
掵̏\l
@o^uK@ւ́AJȗ߂Œ߂ƂɂAAuKɊւJȗ߂Œ߂鎖LڂAۑȂȂȂB
##iAj
掵̏\
@Jb́A̖@̎{sɊւKvƔF߂Ƃ́Ao^uK@ւɑAƖɊւĕKvȕA͂̐EɁAo^uK@ւ̋ƖsꏊɗA돑ނ̑̕AႵ͊W҂Ɏ₳邱ƂłB
Q
@ŐKɂ藧sÉA̐gؖgтAW҂̐Ƃ́AȂȂȂB
R
@ꍀ̋Kɂ錠́Aƍߑ{̂߂ɔF߂ꂽ̂ƉĂ͂ȂȂB
##ij
掵̏\Z
@Jb́Ȁꍇɂ́A̎|ɌȂȂȂB
@掵ꍀꍆ̓o^ƂB
@掵̎̋Kɂ͏oƂB
O
@掵̋̋Kɂ͏oƂB
l
@掵̏\ŐKɂ掵ꍀꍆ̓o^A͍uK̋Ɩ̒~𖽂ƂB
##izqǗZpҎj
攪
@zqǗZpҎ́Az̈ێǗɊւqKvȒmɂčsȂB
Q
@zqǗZpҎ́AJbsȂB
R
@Jb́AJȗ߂Œ߂ƂɂA̎w肷ҁiȉuw莎@ցvƂBjɁAzqǗZpҎ̎{Ɋւ鎖iȉuvƂBj̑S͈ꕔs킹邱ƂłB
S
@Jb́AŐKɂw莎@ւɎ̑S͈ꕔs킹邱ƂƂƂ́AY̑S͈ꕔsȂ̂ƂB
T
@zqǗZpҎ́ANȏJȗ߂Œ߂ɏ]҂łȂA邱ƂłȂB
U
@zqǗZpҎ̉ȖځA葱̑zqǗZpҎɊւKvȎ́AJȗ߂Œ߂B
##izqǗZpҎψj
@s킹邽߁AJȂɌzqǗZpҎψuBAOŐKɂw莎@ւɎ̑Ss킹邱ƂƂꍇ́ǍłȂB
Q
@zqǗZpҎψ́AJbA̐E͊wô҂̂CB
R
@Oɒ߂̂̂قAzqǗZpҎψɊւKvȎ́A߂Œ߂B
##iw莎@ւ̎wj
̓
@攪O̎ẃAsƂ҂̐\ɂsB
Q
@Jb́AɎw҂ȂAA\҂AʎВc@l͈ʍc@lłāAKmɎ{邱ƂłƔF߂̂ƂČJȗ߂Œ߂vɊY҂łȂA攪O̎wĂ͂ȂȂB
##ȋICyщCj
̎O
@w莎@ւ̖̑ICyщĆAJb̔FȂǍ͂ȂB
Q
@Jb́Aw莎@ւ̖A̖@iɊÂߖ͏܂ށBjႵܑ͑̌ꍀɋK肷鎎KɈᔽsׂƂA͎ɊւsKȍsׂƂ́Aw莎@ւɑAYCׂƂ𖽂邱ƂłB
##iψj
̎l
@w莎@ւ́ÂAzqǗZpҖƏ̌t҂ƂĕKvȒmL邩ǂ̔Ɋւ鎖sꍇɂ́Aψɂ̎s킹ȂȂȂB
Q
@w莎@ւ́AψIC悤ƂƂ́AJȗ߂Œ߂v҂̂ICȂȂȂB
R
@ŐḰAψ̉CɂďpB
##iKj
̌
@w莎@ւ́ÅJnOɁA̎{ɊւKiȉuKvƂBj߁AJb̔FȂȂȂBύX悤ƂƂAlƂB
Q
@KŒ߂ׂ́AJȗ߂Œ߂B
R
@Jb́Aꍀ̔FK̓KmȎ{sKƂȂƔF߂Ƃ́Aw莎@ւɑAύXׂƂ𖽂邱ƂłB
##i閧ێ`j
̘Z
@w莎@ւ̖Ⴕ͐Eiψ܂ށBɂēBj͂̐Eɂ҂́AɊւĒm蓾閧R炵Ă͂ȂȂB
Q
@ɏ]w莎@ւ̖͐ÉAY@
il\N@l\܍j̑̔̓KpɂẮA@߂ɂɏ]EƂ݂ȂB
##iē߁j
̎
@Jb́A̖@̎{sɊւKvƔF߂Ƃ́Aw莎@ւɑAɊւēKvȖ߂邱ƂłB
##i̋xp~j
̔
@w莎@ւ́AJb̋ȂȂS͈ꕔx~A͔p~Ă͂ȂȂB
##iw̎j
̋
@Jb́Aw莎@ւ̊êꂩɊYɎƂ́A̎wA͊Ԃ߂Ď̑SႵ͈ꕔ̒~𖽂邱ƂłB
@̓̌Jȗ߂Œ߂vɊYȂȂƂB
@̎Oi̎lOɂďpꍇ܂ށBjǍܑO͑̎̋Kɂ閽߂ɈᔽƂB
O
@̎lꍀႵ͑͑ŐKɈᔽƂB
l
@ܑ̌ꍀ̋KɂFKɂȂŎsƂB
##iJbɂ鎎̎{j
̏\
@Jb́Aw莎@ւ̔̋KɂJb̋Ď̑SႵ͈ꕔx~ƂAŐKɂJbw莎@ւɑ̑SႵ͈ꕔ̒~𖽂ƂA͎w莎@ւVЂ̑̎Rɂ莎̑SႵ͈ꕔ{邱ƂƂȂꍇɂĕKvƔF߂Ƃ́AY̑SႵ͈ꕔŝƂB
##i̔tj
̏\
@w莎@ւ́AJȗ߂Œ߂ƂɂAɊւ鎖ŌJȗ߂Œ߂̂LڂAۑȂȂȂB
##iAj
̏\
@Jb́A̖@̎{sɊւKvƔF߂Ƃ́Aw莎@ւɑA̋ƖɊւĕKvȕA͂̐EɁA̋ƖsꏊɗA돑ނ̑̕AႵ͊W҂Ɏ₳邱ƂłB
Q
@掵̏\ܑyёŐḰAŐKɂ闧ɂďpB
##ij
̏\O
@Jb́Ȁꍇɂ́AJȗ߂Œ߂ƂɂA̎|ɌȂȂȂB
@攪O̎wƂB
@̔̋ƂB
O
@̋̋KɂwȂ͎SႵ͈ꕔ̒~𖽂ƂB
l
@̏\̋KɂJb̑SႵ͈ꕔŝƂƂA͓̋KɂJbsĂ̑SႵ͈ꕔsȂ̂ƂƂB
##i萔j
̏\l
@zqǗZpҎ悤Ƃ҂́Aiw莎@ւ̑SsꍇɂẮAw莎@ցjɁAĂĐ߂Œ߂z̎萔[tȂȂȂB
Q
@ŐKɂw莎@ւɔ[߂ꂽ萔́Aw莎@ւ̎ƂB
##iJȗ߂ւ̈ϔCj
̏\
@̖@ɋK肷̂̂قAw莎@yт̍sтɎ̈pɊւKvȎ́AJȗ߂Œ߂B
##i돑ނ̔tj
\
@茚zLғ́AJȗ߂̒߂ƂɂAY茚z̈ێǗɊւqKvȎLڂ돑ނĂȂȂȂB
##iAj
\
@s{ḿAJȗ߂Œ߂ꍇɂāA̖@̎{sɊւKvƔF߂Ƃ́A茚zLғɑAKvȕA͂̐EɁA茚zɗA̐ݔA돑ނ̑̕Ⴕ͂̈ێǗ̏AႵ͊W҂Ɏ₳邱ƂłBAZɗꍇɂẮA̋Z҂̏ȂȂȂB
Q
@掵̏\ܑyёŐḰAŐKɂ闧ɂďpB
##iPߓj
\
@s{ḿAJȗ߂Œ߂ꍇɂāA茚z̈ێǗzqǗɏ]čsȂĂ炸AAY茚zɂľNȂA͂Ȃ̂鎖Ԃ̑q㒘sKȎԂƔF߂Ƃ́AY茚z̏LҁAL҂̑̎҂œY茚z̈ێǗɂČL̂ɑAYێǗ̕@̉P̑̕Kvȑ[uƂׂƂ𖽂A͓YԂȂȂ܂ł̊ԁAY茚z̈ꕔ̎gpႵ͊Wݔ̎gp~AႵ͐邱ƂłB
@@@Ó@zɂqI̊mۂɊւ鎖Ƃ̓o^
##io^j
\̓
@̊eɌf鎖Ƃcł҂́AYeɌf鎖Ƃ̋敪ɏ]ẢcƏƂɁȀݒnNJs{m̓o^邱ƂłB
@zɂ鐴|s
@zɂC̑s
O
@z̋Cap_Ng̐|s
l
@zɂ̐s
@z̈̒̐|s
Z
@z̔rǂ̐|s
@zɂ˂݂̑̐ľNȂԂ邨̂铮ƂČJȗ߂Œ߂铮̖hs
@zɂ鐴|AC̒yёAyєr̊ǗтɈ̐łāAzɂqȊIǗɕKvȌJȗ߂Œ߂x̂̂s
Q
@s{ḿAO̓o^̐\ꍇɂāA̐\ɌWcƏ̂̓o^ɌW鎖Ƃs߂̋@B̑̐ݔA̎Ƃɏ]҂̎ȋ̎Jȗ߂Œ߂ɓKƔF߂Ƃ́Ao^ȂȂȂB
R
@O̊́A̎҂gpA͗p錚zɂđꍀeɌf鎖Ƃ̋ƖŝɕKv\Ȃ̂łȂȂȂB
S
@o^̗LԂ́AZNƂB
T
@OeɋK肷̂̂قAo^̐\̑o^ɊւKvȎ́AJȗ߂Œ߂B
##io^̕\j
\̎O
@Oꍀ̓o^ҁiȉuo^ƎҁvƂBj́A̓o^ɌWcƏiȉuo^cƏvƂBjɂāAꍆɌf鎖ƂɌŴɂĂ͓o^z|ƂƁAɌf鎖ƂɌŴɂĂ͓o^zCƂƁAOɌf鎖ƂɌŴɂĂ͓o^zCap_Ng|ƂƁAlɌf鎖ƂɌŴɂĂ͓o^zƂƁA܍Ɍf鎖ƂɌŴɂĂ͓o^z|ƂƁAZɌf鎖ƂɌŴɂĂ͓o^zrǐ|ƂƁA掵Ɍf鎖ƂɌŴɂĂ͓o^z˂ݍhƂƁA攪Ɍf鎖ƂɌŴɂĂ͓o^zqǗƂƕ\邱ƂłB
##io^̎j
\̎l
@s{ḿAo^cƏA\̓̊ɓKȂȂƂ́A̓o^ƂłB
##iAj
\̌
@s{ḿA̖@̎{sɊւKvƔF߂Ƃ́Ao^Ǝ҂ɑA̋ƖɊւĕKvȕA͂̐EɁAo^cƏɗA̐ݔA돑ނ̑̕AႵ͊W҂Ɏ₳邱ƂłB
Q
@掵̏\ܑyёŐḰAŐKɂ闧ɂďpB
@@@ĺ@o^Ǝғ̒ĉ̎w
##iwj
\̘Z
@Jb́Ao^Ǝ҂̋Ɩ̉P}邱ƂړIƂAAo^ƎҖ͓o^Ǝ҂̒ĉЈƂʎВc@lłāAɋK肷ƖKɍsƂłƔF߂̂A\̓ꍀeɌf鎖ƂƂɁA̐\oɂAꂼAɋK肷ƖSIɍs҂ƂĎw肷邱ƂłB
Q
@O̎w@liȉuwćvƂBj́ÅeɌfƖŝƂB
@o^Ǝ҂̋ƖKɍsߕKvȋZp̊̐ݒ
@o^Ǝ҂̋߂ɉčsƖ̎w
O
@o^Ǝ҂̋Ɩɏ]҂ɑ邻̋ƖɕKvȒmyыZ\ɂĂ̌C
l
@o^Ǝ҂̋Ɩɏ]҂̕Ɋւ{
R
@wĉ́A̋Ɩ̈ꕔAJb̏FāA̎҂Ɉϑ邱ƂłB
##iP߁j
\̎
@Jb́Awĉ̍sŐƖ̉^cɊւKvƔF߂Ƃ́A̕Kv̌xɂāA̎wĉɑA̎wĉ̋Ɩ̉^cP邽ߕKvȑ[ûׂƂ𖽂邱ƂłB
##iw̎j
\̔
@Jb́AwĉŐKɂ閽߂ɈᔽƂ́A̎wƂłB
##iAj
\̋
@Jb́Awĉ̍s\̘Z̋Ɩ̉^cɊւKvƔF߂Ƃ́A̎wĉɑA̋ƖɊւĕKvȕA͂̐EɁA̋ƖsꏊɗA돑ނ̑̕AႵ͊W҂Ɏ₳邱ƂłB
Q
@掵̏\ܑyёŐḰAŐKɂ闧ɂďpB
@@@́@G
##i\̐j
\̏\
@lA\̓ꍀeɌf鎖Ƃɂ̓o^ȂŁAYƂɌWcƏɂ\̎OɋK肷\͂ɗގ\Ă͂ȂȂB
##i͒nĉ̗pɋ茚zɊւj
\O
@\̋ḰA茚z͒nĉ̌p̗͌pɋ̂łꍇɂẮAKpȂB
Q
@s{ḿA̖@̎{sɊւKvƔF߂Ƃ́A͒nĉ̌p̗͌pɋ茚zɂāAYႵ͒nĉ̋@ւ̒͂̈ϔC҂ɑAKvȐ͎̒o߂邱ƂłB
R
@\̋ḰA茚z͒nĉ̌p̗͌pɋ̂łꍇɂẮAKpȂBAs{ḿAY茚zɂāAɋK肷鎖ԂƔF߂Ƃ́AYႵ͒nĉ̋@ւ̒͂̈ϔC҂ɑA̎|ʒmƂƂɁAYێǗ̕@̉P̑̕Kvȑ[ûׂƂ邱ƂłB
##is\āj
\O̓
@w莎@ւsɌW鏈ǐʂɂĂ̏Bj͕sׂɂẮAJbɑAssR@
iaO\N@SZ\jɂR邱ƂłB
##ioߑ[uj
\l
@̖@̋KɊÂ߂𐧒肵A͉pꍇɂẮA̖߂ŁA̐薔͉pɔIɕKvƔf͈͓ɂāAv̌oߑ[uiɊւoߑ[u܂ށBj߂邱ƂłB
@@@Ź@
\l̓
@̊êꂩɊY҂́ANȉ͕̒S~ȉ̔ɏB
@掵̏\ŐKɂuK̋Ɩ̒~̖߂Ɉᔽ
@̘Zꍀ̋KɈᔽ
\l̎O
@̋̋Kɂ鎎̒~̖߂ɈᔽƂ́Äᔽsׂw莎@ւ̖͐ÉANȉ͕̒S~ȉ̔ɏB
\l̎l
@̊êꂩɊY҂́A\~ȉ̔ɏB
@掵̋̋Kɂ͏oA͋U̓͏o
@掵̏\l̋KɈᔽĒAɋLڂAႵ͋ŰLڂA͒ۑȂ
O
@掵̏\ܑꍀ̋KɂAႵ͋U̕A̋KɂE̗݁AWAႵ͊A͓̋Kɂ鎿ɑāAȗRȂ̂ɓقAႵ͋U̓ق
\
@̊êꂩɊYƂ́Äᔽsׂw莎@ւ̖͐ÉA\~ȉ̔ɏB
@̏\̋KɈᔽĒAɋLڂAႵ͒ɋŰLڂA͒ۑȂƂB
@̏\ꍀ̋KɂAႵ͋U̕A̋KɂE̗݁AWAႵ͊A͓̋Kɂ鎿ɑāAȗRȂ̂ɓقAႵ͋U̓قƂB
\Z
@̊êꂩɊY҂́AO\~ȉ̔ɏB
@ꍀO܂ł̋Kɂ͏oA͋U̓͏o
@Zꍀ̋KɈᔽ
O
@\̋KɈᔽĒ돑ނA͂ɋLڂAႵ͋ŰLڂ
l
@\ꍀA\ܑ̌ꍀႵ͑\̋ꍀ̋KɂAႵ͋U̕A̋KɂE̗݁AWAႵ͊A͂̋Kɂ鎿ɑāAȗRȂ̂ɓقAႵ͋U̓ق
@\̋Kɂ閽ߖ͏Ɉᔽ
Z
@\̎̋Kɂ閽߂Ɉᔽ
\
@@l̑\Җ͖@lႵ͐l̑㗝lAgpl̑̏]Ǝ҂A̖@l͐l̋ƖɊւA\l̓ꍆA\l̎l͑ÖᔽsׂƂ́As҂قA̖@l͐lɑĂAe{̌YȂB
\
@̊êꂩɊY҂́A\~ȉ̉ߗɏB
@ȗRȂ̂ɁA掵ŐKɂ閽߂ɈᔽČzqǗZpҖƏԔ[Ȃ
@掵̏\ꍀ̋KɈᔽč\ĒuA\ɋLڂׂLڂAႵ͋ŰLڂA͐ȗRȂ̂ɓe̋Kɂ鐿
O
@\̏\̋KɈᔽ
@@@@@
##i{sj
P
@̖@́Az̓NZĘZӌȂ͈͓ɂĐ߂Œ߂{sB
@@@@@ia܌ܔN܌Z@llj@
##i{sj
P
@̖@́Az̓{sBA͒\ȎOɈKyё\̉ḰAz̓NZĈNo߂{sB
##ioߑ[uj
Q
@̖@̎{s̓NZĈNԂ́As{ḿA̖@ɂ̌zɂqI̊mۂɊւ@\̓̋Kɂ炸Ao^邱ƂłȂB
@@@@@iaܔN@掵j
P
@̖@iBj́Aa\N{sB
Q
@̖@̎{s̓̑OɂĖ@̋KɂuĂ@֓ŁA̖@̎{s̓Ȍ͍ƍsgD@̖͂@ɂ̊W@̋KɊÂ߁iȉuW߁vƂBj̋Kɂu邱ƂƂȂ̂ɊւKvƂȂoߑ[ȗ̖@̎{sɔW߂̐薔͉pɊւKvƂȂoߑ[úA߂Œ߂邱ƂłB
@@@@@iaܔNZ@攪Oj@
##i{sj
@̖@́Az̓{sBÅeɌfḰAꂼꓖYeɒ߂{sB
yѓ
@
O
@\lA\ZA\yё\̋KA\̋KifÕːZtyѐfÃGcNXZt@\\܂ł̉KBjтɑ\̋KтɕlAA\yё\̋K@a\N\
##ȋ̏A\ɌWoߑ[uj
\l
@̖@ieɌfKɂẮAYeKBȉ̏yё\ZɂēBj̎{sOɉÔꂼ̖@̋Kɂ肳ꂽ̏̑̍sׁiȉ̏ɂāu̍sׁvƂBj̖͂@̎{s̍یɉÔꂼ̖@̋Kɂ肳Ă鋖̐\̑̍sׁiȉ̏ɂāu\̍sׁvƂBjŁA̖@̎{s̓ɂĂ̍sׂɌWssׂ҂قȂ邱ƂƂȂ̂́AO܂ł̋K薔͉̂ꂼ̖@iɊÂ߂܂ށBǰoߑ[uɊւKɒ߂̂A̖@̎{s̓Ȍɂ̂ꂼ̖@̓KpɂẮÂꂼ̖@̑Kɂ肳ꂽ̍sז͐\̍sׂƂ݂ȂB
##iɊւoߑ[uj
\Z
@̖@̎{sOɂsyѕOA܍A攪A͑\̋Kɂ]O̗ɂ邱ƂƂꍇɂ\A\AO\ZAO\͑O\̋K̎{sɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
@@@@@iܔNꌎ@攪㍆j@
##i{sj
@̖@́As葱@iܔN@攪\j̎{s̓{sB
##iⓙꂽsvɊւoߑ[uj
@̖@̎{sOɖ@߂ɊÂRc̑̍c̋@ւɑs葱@\OɋK肷钮͕ٖ̋@̕t^̎葱̑̈ӌq̂߂̎葱ɑ葱ׂƂ̎₻̑̋߂ꂽꍇɂẮAY₻̑̋߂ɌWsv̎葱ɊւẮA̖@ɂ̊W@̋Kɂ炸AȂ]O̗ɂB
##iɊւoߑ[uj
\O
@̖@̎{sOɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
##iɊւK̐ɔoߑ[uj
\l
@̖@̎{sOɖ@̋KɂsꂽAႵ͒isvɌŴBj͂̂߂̎葱́A̖@ɂ̊W@̑Kɂsꂽ̂Ƃ݂ȂB
##i߂ւ̈ϔCj
\
@O܂łɒ߂̂̂قA̖@̎{sɊւĕKvȌoߑ[úA߂Œ߂B
@@@@@iZN@攪lj@
##i{sj
@̖@́Az̓{sB
##ȋ̏A\ɌWoߑ[uj
\O
@̖@iɋK肷KɂẮAYKBȉ̏yюɂēBj̎{sOɉÔꂼ̖@̋Kɂ肳ꂽ̏̑̍sׁiȉ̏ɂāu̍sׁvƂBj̖͂@̎{s̍یɉÔꂼ̖@̋Kɂ肳Ă鋖̐\̑̍sׁiȉ̏ɂāu\̍sׁvƂBjɑ邱̖@̎{s̓Ȍɂ̂ꂼ̖@̓KpɂẮA\܂ł̋K薔͉̂ꂼ̖@iɊÂ߂܂ށBǰoߑ[uɊւKɒ߂̂Âꂼ̖@̑Kɂ肳ꂽ̍sז͐\̍sׂƂ݂ȂB
##iɊւoߑ[uj
\l
@̖@̎{sOɂsyт̖@̕ɂď]O̗ɂ邱ƂƂꍇɂ邱̖@̎{sɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
##ȋ̌oߑ[u̐߂ւ̈ϔCj
\
@̕ɋK肷̂̂قA̖@̎{sɔKvȌoߑ[u͐߂Œ߂B
@@@@@iNꌎ@Z܍j@
##i{sj
P
@̖@́Az̓{sB
##izɂqI̊mۂɊւ@̈ꕔɔoߑ[uj
Q
@ŐK̎{s̍یɌzɂqI̊mۂɊւ@\̓ꍀ̓o^Ă҂̓Yo^̗LԂɂẮAŐKɂ̓@\̓܍̋Kɂ炸AȂ]O̗ɂB
@@@@@iNZ@攪j@
##i{sj
@̖@́A\Nl{sBÅeɌfḰAYeɒ߂{sB
@𒆒n@S\̎ɌAߖтɓyъKi@S\̋ꍀɌW镔ic@̓ӂ邱ƂɌW镔ɌBjɌBjAl\𒆎R@㍀yё\̉Ki@\ɌW镔ɌBjASl\l̋Ki_ƉǏ@\l̎ỎKɌW镔BjтɑlS\̋Kis̍̓Ɋւ@ZA攪yё\̉KɌW镔Bjтɕ掵A\A\A\AZ\lyё܍A掵\OA掵\AS\lZ܂ŁASZ\ASZ\OASZ\lтɑS̋K@z̓
##i]O̗ɂ鎖Ɋւoߑ[uj
Z\
@N@̈ꕔ@iaZ\N@O\ljO\ꍀA掵\ꍀтɑ攪\ꍀyё\ŐKɂȂ]O̗ɂ邱ƂƂꂽɌWs{m̎A͐Eiȉ̏ɂāuvƂBjɂẮA̖@ɂ̍N@ANی@yёDی@̖͂@ɊÂ߂̋Kɂ蓖Yɑ鎖͌sƂƂꂽbႵ͎Љی͂̎҂ϔCnЉیǒႵ͂̒nЉیǒϔCЉی̎͌ƂB
##iVn@S\Zl̓Kp̓j
掵\
@SZ\Z̋Kɂ̌Ȑݒu@\l̒nЉیNjyюЉیłāA̖@̎{s̍ۋn@攪̎邽߂̓s{̋@ցiЉیW舵̂ɌBj̈ʒuƓ̈ʒuɐ݂́inЉیǂɂẮAs{̒uĂsiʋ܂ށBjɐ݂̂ɌBjɂẮAVn@S\Zl̋ḰAKpȂB
##iЉیWnɊւoߑ[uj
掵\
@̖@̎{s̍یɋn@攪ɋK肷Eib͂̈ϔC҂ɂCꂽ҂ɌBS\ɂāuЉیWnvƂBjł҂́AʂɎ߂ȂA̒nЉیǖ͎Љی̐EƂȂ̂ƂB
##inЉیËcɊւoߑ[uj
掵\
@SZ\̋KɂO̎ЉیËc@̋KɂnЉیËcтɂ̉Aψyѐψ́A̒nЉیǂ̒nЉیËcтɂ̉AψyѐψƂȂAꐫđ̂ƂB
##isׁj
掵\O
@S̋Kɂ̍N@\̎Oꍀ̋Kɂwyѓ̋Kɂ́AS̋K̎{sOɂĂsƂłB
##ibɑĐRɌWoߑ[uj
掵\l
@{sOɂꂽs̏ɌWSl\S\܂ŁAS\AS\ASZ\ASZ\AS\AS\AS\OAS\AS\ZAS\OAS\AS\ASASAS\lAS\S\܂ŁAS\͑SO\̋KɂO̎@\̎lA}cT[WwtA͂tA䂤tɊւ@\̎lAHiq@\̎lAًƖ@̎OAO@掵̎OAÖ@掵\̎OAg̏Qҕ@l\O̓A_یyѐ_QҕɊւ@\̏\AN[jOƖ@\l̓Aa\h@\̓AЉƖ@攪\O̓Aj\h@Z\Aƒ{@\AȋZHm@\̓AՏZtAqZtɊւ@\̔̓AmIQҕ@O\AVl@O\lAqی@\ZA_t@\OAzɂqI̊mۂɊւ@\lAp̏yѐ|Ɋւ@\lAH̎Ƃ̋KyѐHɊւ@l\O͊ǂ̗\hyъǂ̊҂ɑÂɊւ@Z\̋KɊÂĐRɂẮAȂ]O̗ɂB
##ib͓s{m̑̒nĉ̋@ւƂ̒~߂̑̏Ɋւoߑ[uj
掵\
@̖@ɂO̎@l\ZlႵ͑\ꍀႵ͑OA}cT[WwtA͂tA䂤tɊւ@攪ꍀi@\̓ɂďpꍇ܂ށBjAHiq@\AÖ@Ⴕ͑\ꍀAŕyь@\ꍀi@\lyё܍ŏpꍇ܂ށBjANی@SꍀA@O\ꍀAN@SZ@ꍀA@Z\ꍀႵ͑掵\͏_t@\ꍀ̋Kɂb͓s{m̑̒nĉ̋@ւƂ̒~߂̑̏́AꂼA̖@ɂ̎@l\ZlႵ͑\ꍀႵ͑OA}cT[WwtA͂tA䂤tɊւ@攪ꍀi@\̓ɂďpꍇ܂ށBjAHiq@\Ⴕ͑\OAÖ@Ⴕ͑\ꍀAŕyь@\ꍀႵ͑i@\lyё܍ŏpꍇ܂ށBjANی@SꍀA@O\ꍀႵ͑AN@SZꍀA@Z\ꍀႵ͑Ⴕ͑掵\͏_t@\ꍀ̋Kɂb͒nĉƂ̒~߂̑̏Ƃ݂ȂB
##i̎j
S\
@̖@ɂÔꂼ̖@ɋK肷̂̂قA̖@̎{sOɂāAnĉ̋@ւ@͂ɊÂ߂ɂǗ͎s鍑A̒nĉ̑ĉ̎iSZ\ɂāu̎vƂBj́A̖@̎{śAnĉ@͂ɊÂ߂ɂ蓖Ynĉ̎Ƃď̂ƂB
##iA\Ɋւoߑ[uj
SZ\
@̖@ieɌfKɂẮAYeKBȉ̏yѕSZ\OɂēBj̎{sOɉÔꂼ̖@̋Kɂ肳ꂽ̏̑̍sׁiȉ̏ɂāu̍sׁvƂBj̖͂@̎{s̍یɉÔꂼ̖@̋Kɂ肳Ă鋖̐\̑̍sׁiȉ̏ɂāu\̍sׁvƂBjŁA̖@̎{s̓ɂĂ̍sׂɌWssׂ҂قȂ邱ƂƂȂ̂́AO܂ł̋K薔͉̂ꂼ̖@iɊÂ߂܂ށBǰoߑ[uɊւKɒ߂̂A̖@̎{s̓Ȍɂ̂ꂼ̖@̓KpɂẮÂꂼ̖@̑Kɂ肳ꂽ̍sז͐\̍sׂƂ݂ȂB
Q
@̖@̎{sOɉÔꂼ̖@̋Kɂ荑͒nĉ̋@ւɑA͏oAȏ̎葱ȂȂȂŁA̖@̎{s̓Oɂ̎葱ĂȂ̂ɂẮA̖@yтɊÂ߂ɕʒi̒߂̂̂قAÂꂼ̖@̑Kɂ荑͒nĉ̑̋@ւɑĕA͏oAȏ̎葱ȂȂȂɂĂ̎葱ĂȂ̂Ƃ݂ȂāA̖@ɂ̂ꂼ̖@̋KKpB
##is\ĂɊւoߑ[uj
SZ\
@{sOɂꂽ̎ɌW鏈łāAYsiȉ̏ɂāuvƂBjɎ{sOɍssR@ɋK肷㋉siȉ̏ɂāu㋉svƂBĵɂĂ̓@ɂs\ĂɂẮA{sȌɂĂAYɈ㋉ŝƂ݂ȂāAssR@̋KKpB̏ꍇɂāAY̏㋉sƂ݂ȂśA{sOɓY̏㋉słsƂB
Q
@ȌꍇɂāA㋉sƂ݂Ȃsnĉ̋@ւłƂ́AY@ւssR@̋Kɂ菈邱ƂƂ鎖́AVn@㍀ꍆɋK肷ꍆ@ƂB
##i萔Ɋւoߑ[uj
SZ\
@{sOɂĂ̖@ɂÔꂼ̖@iɊÂ߂܂ށBj̋Kɂ[tׂł萔ɂẮA̖@yтɊÂ߂ɕʒi̒߂̂̂قAȂ]O̗ɂB
##iɊւoߑ[uj
SZ\O
@̖@̎{sOɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
##ȋ̌oߑ[u̐߂ւ̈ϔCj
SZ\l
@̕ɋK肷̂̂قA̖@̎{sɔKvȌoߑ[uiɊւoߑ[u܂ށBj́A߂Œ߂B
Q
@\A\yёS\l̋K̓KpɊւĕKvȎ́A߂Œ߂B
##ij
S\
@Vn@㍀ꍆɋK肷ꍆ@ɂẮAłVɐ݂邱Ƃ̂Ȃ悤ɂƂƂɁAVn@ʕ\Ɍf̋yѐVn@ɊÂ߂Ɏ̂ɂẮAn𐄐iϓ_猟AKXAKȌŝƂB
S\
@{́AnĉyюƂIIɎsł悤AƒnĉƂ̖Sɉnō̏[mۂ̕rɂāAoϏ̐ړĂǍʂɊÂĕKvȑ[uûƂB
S\
@{́AÕیxANx̉vɔAЉی̎̑̐Aɏ]E݂̍ɂāAیғ̗̊mہǍ̎_ɗāAAKvƔF߂Ƃ́ǍʂɊÂďv̑[uûƂB
@@@@@iN@ZZj@
##i{sj
@̖@iyёOBj́A\ONꌎZ{sB
@@@@@iONl@ܘZj
##i{sj
@̖@́A\lNl{sB
##ioߑ[uj
@̖@̎{s̍یɂ̖@ɂǑzɂqI̊mۂɊւ@iȉu@vƂBj\̓ꍀ̓o^Ăҋyт̖@̎{s̍یɓYo^̐\ĂҁiɋK肷҂BjɂẮAYo^ɊւɂāAȂ]O̗ɂB
O
@̖@̎{s̍یɋ@\̓ꍀZɌf鎖ƂɌW铯̓o^Ăҋyт̖@̎{s̍یɓYo^̐\Ă҂ɂẮAYo^ɌW鎖ƂɊւɂāA̖@̎{s̓iȉu{svƂBjNZĘZNԂ́A@i\̘Z\̏\܂ŋyт̋KɌW锱Bj̋ḰAȂ̌͂LB
l
@̖@ɂ̌zɂqI̊mۂɊւ@iȉuV@vƂBj\̘Z̋K̓KpɂẮA@\̓ꍀ̋KiŐKɂȂ̌͂L邱ƂƂꍇ܂ށBjɂ蓯ZɌf鎖ƂɌWo^Ă҂́AV@\̓ꍀ̋Kɂ蓯攪Ɍf鎖ƂɌWo^Ă҂Ƃ݂ȂB
@{sNZĘZNԂ́AV@\̏\u\̓ꍀevƂ̂́u\̓ꍀe͌zɂqI̊mۂɊւ@̈ꕔ@i\ON@S\ZjŐKɂȂ̌͂L邱ƂƂ铯@ɂȎ\̓ꍀZvƁAuvƂ̂́u\̓ꍀ͓@ŐKɂȂ̌͂L邱ƂƂ铯@ɂȎ\̓ꍀvƁAu\͂vƂ̂́u\Ⴕ͓o^zqʊǗƂ̕\͂vƂB
Z
@@\̓ꍀ̋KiŐKɂȂ̌͂L邱ƂƂꍇ܂ށBjɂĂ铯ZɌf鎖ƂɌWo^́AYo^Ă҂Yo^ɌWcƏɂĐV@\̓ꍀ攪Ɍf鎖ƂɌW铯̓o^Ƃ́AŐKɂȂ̌͂L邱ƂƂ鋌@\̓l̋Kɂ炸Ǎ͂B
掵
@̖@̎{sOɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
攪
@̕ɋK肷̂̂قA̖@̎{sɔKvȌoߑ[uiɊւoߑ[u܂ށBj́A߂Œ߂B
@@@@@iܔN@Zj@
##i{sj
@̖@́A\ZNOO\܂ł̊ԂɂĐ߂Œ߂{sBAZ̋K͕\ZNlAꍀAOꍀAlꍀAꍀyёZꍀ̋K͌z̓{sB
##izɂqI̊mۂɊւ@̈ꕔɔoߑ[uj
l
@̖@ɂ̌zɂqI̊mۂɊւ@iȉuVzq@vƂBj掵ꍀꍆ̓o^悤Ƃ҂́A̖@̎{sOɂĂA̐\sƂłBVzq@掵̘ZŐKɂv̓͏oyѐVzq@掵̔ꍀ̋KɂƖK̓͏oɂĂAlƂB
Q
@̖@̎{s̍یɂ̖@ɂǑzɂqI̊mۂɊւ@iȉuzq@vƂBj掵ꍀꍆ̎wĂ҂́A̖@̎{s̓NZĘZo߂܂ł̊Ԃ́AVzq@掵ꍀꍆ̓o^Ă̂Ƃ݂ȂB
R
@̖@̎{s̍یɋzq@掵ꍀꍆ̍uK̉ےCĂ҂ɑ錚zqǗZpҖƏ̌tɂẮAȂ]O̗ɂB
##i̓KpɊւoߑ[uj
掵
@̖@̎{sOɂsyт̋̕KɂȂ]O̗ɂ邱ƂƂꍇɂ邱̖@̎{sɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
##ȋ̌oߑ[u̐߂ւ̈ϔCj
攪
@O܂łɒ߂̂̂قA̖@̎{sɊւKvƂȂoߑ[uiɊւoߑ[u܂ށBj́A߂Œ߂B
##ij
@{́A̖@̎{sܔNo߂ꍇɂāA̖@̎{s̏ĂAKvƔF߂Ƃ́A̖@̋KɂČǍʂɊÂĕKvȑ[uûƂB
@@@@@iꎵNܓ@攪Oj@
##i{sj
@̖@́A\Nl{sB
@@@@@iꔪNZ@܁Zj@
@̖@́AʎВcEc@l@̎{s̓{sB
@@@@@iONZl@掵lj@
##i{sj
@̖@́Az̓NZē\o߂{sB
@@@@@iܔNZl@llj@
##i{sj
@̖@́Az̓{sB
##iɊւoߑ[uj
\
@̖@ieɌfKɂẮAYKj̎{sOɂsׂɑ锱̓KpɂẮAȂ]O̗ɂB
##i߂ւ̈ϔCj
\
@̕ɋK肷̂̂قA̖@̎{sɊւKvȌoߑ[uiɊւoߑ[u܂ށBj́A߂Œ߂B
@@@@@iZNZO@Z㍆j@
##i{sj
@̖@́AssR@i\ZN@Z\j̎{s̓{sB
ʕ\@i掵̎lWj
zqsT_
\
z̍\T_
z̊q
\
C̒
\Z
yєr̊Ǘ
\
|
\Z
˂݁A̖h
|
Java
|
UTF-8
| 594 | 2.21875 | 2 |
[] |
no_license
|
package com.election.hacking.model;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.io.Serializable;
import static com.election.hacking.ServiceConstants.KEY_TOKEN;
public class IdentityVerificationResponse implements Serializable {
@SerializedName(KEY_TOKEN)
private String mToken;
public String getToken() {
return mToken;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("mToken", mToken)
.toString();
}
}
|
Java
|
UTF-8
| 8,126 | 1.992188 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2015 Loic Merckel
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package lh.api.showcase.client.operations;
import lh.api.showcase.client.JsonParserUtils;
import lh.api.showcase.shared.FlightStatusCode;
import lh.api.showcase.shared.TimeStatusCode;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
public class JsonParserFlightUtils {
private JsonParserFlightUtils () { super () ; throw new IllegalStateException () ; }
public static Flight getFlightInfo (JSONObject jsFlightObj) {
if (jsFlightObj == null) {
return null ;
}
// departure
JSONObject jsDepartureObj = jsFlightObj.get("Departure").isObject() ;
Flight.FlightNode flightNodeDeparture = getFlightNodeInfo (jsDepartureObj) ;
Flight.Departure departure = null ;
if (flightNodeDeparture != null) {
departure = new Flight.Departure (flightNodeDeparture) ;
}
// arrival
JSONObject jsArrivalObj = jsFlightObj.get("Arrival").isObject() ;
Flight.FlightNode flightNodeArrival = getFlightNodeInfo (jsArrivalObj) ;
Flight.Arrival arrival = null ;
if (flightNodeDeparture != null) {
arrival = new Flight.Arrival (flightNodeArrival) ;
}
// aircraft code
String aircraftCode = JsonParserUtils.getAircraftCode (jsFlightObj.get("Equipment").isObject().get("AircraftCode")) ;
//MarketingCarrier
JSONObject jsMarketingCarrierObj = jsFlightObj.get("MarketingCarrier").isObject() ;
JSONString jsAirlineIdStr = jsMarketingCarrierObj.get("AirlineID").isString() ;
JSONString jsFlightNumberStr = jsMarketingCarrierObj.get("FlightNumber").isString() ;
JSONNumber jsFlightNumberNum = jsMarketingCarrierObj.get("FlightNumber").isNumber() ;
String flightNumber = (jsFlightNumberStr!=null)?(jsFlightNumberStr.toString().replace("\"", ""))
:((jsFlightNumberNum!=null)?(String.valueOf(jsFlightNumberNum.doubleValue())):("")) ;
// details
JSONValue jsDetailsVal = jsFlightObj.get("Details") ;
JSONObject jsDetailsObj = null ;
if (jsDetailsVal != null) {
jsDetailsObj = jsDetailsVal.isObject() ;
}
// flight status
JSONString jsFlightStatusCodeStr = getStringIfExist (jsFlightObj, "FlightStatus", "Code") ;
JSONString jsFlightStatusDefinitionStr = getStringIfExist (jsFlightObj, "FlightStatus", "Definition") ;
return new Flight (
departure,
arrival,
aircraftCode,
(jsAirlineIdStr==null)?(""):(jsAirlineIdStr.toString().replace("\"", "")),
flightNumber,
getDetailsInfo(jsDetailsObj),
new Flight.StatusCodeDefinition(
(jsFlightStatusCodeStr==null)?(FlightStatusCode.NA.toString()):(jsFlightStatusCodeStr.toString().replace("\"", "")),
(jsFlightStatusDefinitionStr==null)?(""):(jsFlightStatusDefinitionStr.toString().replace("\"", "")))) ;
}
private static JSONString getStringIfExist (JSONObject jsObj, String object, String property) {
JSONValue jsObjectVal = jsObj.get(object) ;
JSONString jsStr = null ;
if (jsObjectVal != null) {
JSONValue jsObjectPropVal = jsObjectVal.isObject().get(property) ;
if (jsObjectPropVal != null) {
jsStr = jsObjectPropVal.isString () ;
}
}
return jsStr ;
}
private static JSONNumber getNumberIfExist (JSONObject jsObj, String object, String property) {
JSONValue jsObjectVal = jsObj.get(object) ;
JSONNumber jsNum = null ;
if (jsObjectVal != null) {
JSONValue jsObjectPropVal = jsObjectVal.isObject().get(property) ;
if (jsObjectPropVal != null) {
jsNum = jsObjectPropVal.isNumber () ;
}
}
return jsNum ;
}
private static JSONString getStringIfExist (JSONObject jsObj, String object, String alternativeObject, String property) {
JSONValue jsVal = jsObj.get(object) ;
if (jsVal == null) {
jsVal = jsObj.get(alternativeObject) ;
}
JSONString jsStr = null ;
if (jsVal != null) {
JSONValue jsObjectPropVal = jsVal.isObject().get(property) ;
if (jsObjectPropVal != null) {
jsStr = jsObjectPropVal.isString () ;
}
}
return jsStr ;
}
private static Flight.Details getDetailsInfo (JSONObject jsDetailsObj) {
if (jsDetailsObj == null) {
return null ;
}
JSONNumber jsStopsNumber = jsDetailsObj.get("Stops").isObject().get("StopQuantity").isNumber() ;
JSONNumber jsDaysOfOperationNumber = jsDetailsObj.get("DaysOfOperation").isNumber() ;
JSONObject jsDatePeriodObj = jsDetailsObj.get("DatePeriod").isObject() ;
JSONString jsEffectiveStr = jsDatePeriodObj.get("Effective").isString() ;
JSONString jsExpirationStr = jsDatePeriodObj.get("Expiration").isString() ;
Flight.Details.Builder detailsBuilder = new Flight.Details.Builder() ;
detailsBuilder.setStopQuantity(Long.valueOf((long) jsStopsNumber.doubleValue()))
.setDaysOfOperation(String.valueOf(jsDaysOfOperationNumber.doubleValue()))
.setEffectiveDateStr((jsEffectiveStr==null)?(""):(jsEffectiveStr.toString().replace("\"", "")))
.setExpirationDateStr((jsExpirationStr==null)?(""):(jsExpirationStr.toString().replace("\"", ""))) ;
return detailsBuilder.build() ;
}
private static Flight.FlightNode getFlightNodeInfo (JSONObject jsNodeObj) {
if (jsNodeObj == null) {
return null ;
}
JSONString jsAirportCodeStr = jsNodeObj.get("AirportCode").isString() ;
JSONString jsScheduledTimeLocalStr = jsNodeObj.get("ScheduledTimeLocal").isObject().get("DateTime").isString() ;
JSONString jsScheduledTimeUtcStr = getStringIfExist (jsNodeObj, "ScheduledTimeUTC", "DateTime") ;
JSONString jsEstimatedOrActualTimeLocalStr = getStringIfExist (jsNodeObj, "EstimatedTimeLocal", "ActualTimeLocal", "DateTime") ;
JSONString jsEstimatedOrActualTimeUtcStr = getStringIfExist (jsNodeObj, "EstimatedTimeUTC", "ActualTimeUTC", "DateTime") ;
JSONString jsTimeStatusCodeStr = getStringIfExist (jsNodeObj, "TimeStatus", "Code") ;
JSONString jsTimeStatusDefinitionStr = getStringIfExist (jsNodeObj, "TimeStatus", "Definition") ;
JSONString jsTerminalGateStr = getStringIfExist (jsNodeObj, "Terminal", "Gate") ;
JSONString jsTerminalStr = getStringIfExist (jsNodeObj, "Terminal", "Name") ;
JSONNumber jsTerminalNum = getNumberIfExist (jsNodeObj, "Terminal", "Name") ;
String terminal = (jsTerminalStr!=null)?(jsTerminalStr.toString().replace("\"", ""))
:((jsTerminalNum!=null)?(String.valueOf(jsTerminalNum.doubleValue())):("")) ;
Flight.FlightNode.Builder flightNodeBuilder = new Flight.FlightNode.Builder();
flightNodeBuilder.setAirportCode((jsAirportCodeStr==null)?(""):(jsAirportCodeStr.toString().replace("\"", "")))
.setScheduledTimeLocal((jsScheduledTimeLocalStr==null)?(""):(jsScheduledTimeLocalStr.toString().replace("\"", "")))
.setScheduledTimeUtc((jsScheduledTimeUtcStr==null)?(""):(jsScheduledTimeUtcStr.toString().replace("\"", "")))
.setEstimatedOrActualTimeLocal((jsEstimatedOrActualTimeLocalStr==null)?(""):(jsEstimatedOrActualTimeLocalStr.toString().replace("\"", "")))
.setEstimatedOrActualTimeUtc((jsEstimatedOrActualTimeUtcStr==null)?(""):(jsEstimatedOrActualTimeUtcStr.toString().replace("\"", "")))
.setTimeStatus(new Flight.StatusCodeDefinition(
(jsTimeStatusCodeStr==null)?(TimeStatusCode.NO.toString()):(jsTimeStatusCodeStr.toString().replace("\"", "")),
(jsTimeStatusDefinitionStr==null)?(""):(jsTimeStatusDefinitionStr.toString().replace("\"", ""))))
.setTerminal(terminal)
.setTerminalGate((jsTerminalGateStr==null)?(""):(jsTerminalGateStr.toString().replace("\"", "")));
return flightNodeBuilder.build();
}
}
|
C
|
UTF-8
| 1,558 | 2.6875 | 3 |
[] |
no_license
|
#include <libgccjit.h>
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, const char *argv[]) {
gcc_jit_context *ctxt;
gcc_jit_result *result;
int ch;
ctxt = gcc_jit_context_acquire ();
if (!ctxt) {
printf ("can't get gcc context");
exit (1);
}
gcc_jit_type *int_type =
gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
gcc_jit_param *n =
gcc_jit_context_new_param (ctxt, NULL, int_type, "n");
gcc_jit_function *func =
gcc_jit_context_new_function (ctxt, NULL,
GCC_JIT_FUNCTION_EXPORTED,
int_type,
"plus1",
1, &n,
0);
gcc_jit_block *curblock =
gcc_jit_function_new_block (func, NULL);
gcc_jit_rvalue *int_one = gcc_jit_context_new_rvalue_from_int (ctxt, int_type, 1);
gcc_jit_block_end_with_return (
curblock,
NULL,
gcc_jit_context_new_binary_op (
ctxt,
NULL,
GCC_JIT_BINARY_OP_PLUS,
int_type,
gcc_jit_param_as_rvalue (n),
int_one) );
result = gcc_jit_context_compile (ctxt);
if (!result) {
fprintf (stderr, "NULL result");
exit (1);
}
typedef int (*fn_type) (int);
fn_type plus1 =
(fn_type)gcc_jit_result_get_code (result, "plus1");
int input;
scanf ("%d", &input);
int val = plus1 (input);
printf ("%d\n", val);
gcc_jit_context_release (ctxt);
gcc_jit_result_release (result);
return 0;
}
|
Python
|
UTF-8
| 2,370 | 2.671875 | 3 |
[] |
no_license
|
from datetime import datetime, timedelta
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase
from sp_display import read_float
ROUND_ML_PER_H_RATIO = 5
#get user parameters
diameter = read_float("Enter the syringe-diameter.", 5, 1)
flow_rate = read_float("Enter the flow-rate [ml/h].", 1, 0.1)
time = read_float("Enter the run-time in h.", 5, 1)
#init syringe
# Initialize a motor at port B.
syringe_motor = Motor(Port.B)
brick.display.clear()
brick.display.text("Press Left/Right to move syringe manually.")
brick.display.text("Press Enter to continue.")
while Button.enter:
pass
while not Button.enter:
_print_float(message, retVal)
if Button.left:
syringe_motor.run_to_rel_pos(5)
if Button.right:
syringe_motor.run_to_rel_pos(-5)
endtime = datetime.datetime.now() + timedelta(hours=time)
brick.display.clear()
brick.display.text("Press Esc. to exit.")
#todo: calculate the time of motor-rotations.
rotation_per_second = flow_rate / ROUND_ML_PER_H_RATIO / 3600
seconds_per_degree = 1 / (rotation_per_second * 360)
while not Button.escape and datetime.datetime.now() < endtime:
syringe_motor.run_to_rel_pos(1)
time.sleep(seconds_per_degree)
#
# Displays the message. Prompts the user to enter a float number.
#
def read_float(message, retVal, increment):
while Button.enter:
pass
while not Button.enter:
_print_float(message, retVal)
if Button.left:
increment *= 10
while Button.left:
pass
if Button.right:
increment *= 10
while Button.right:
pass
if Button.up:
retVal += increment
while Button.up:
pass
if Button.down:
retVal -= increment
while Button.down:
pass
return retVal
def _print_float(message, value):
brick.display.clear()
brick.display.text(message)
brick.display.text(str(value))
|
Ruby
|
UTF-8
| 1,387 | 3.90625 | 4 |
[] |
no_license
|
def sluggish_octopus(fish_arr)
fish_arr.each_with_index do |fish1, i1|
max_length = true
fish_arr.each_with_index do |fish2, i2|
next if i1 == i2
max_length = false if fish2.length > fish1.length
end
return fish1 if max_length
end
end
def dominant_octopus(arr)
arr.merge_sort
arr.last
end
class Array
def merge_sort(&prc)
prc ||= Proc.new { |x, y| x <=> y }
return self if count <= 1
mid_i = self.length / 2
sorted_left = self.take(mid_i).merge_sort(&prc)
sorted_right = self.drop(mid_i).merge_sort(&prc)
self.merge(sorted_left, sorted_right, &prc)
end
def self.merge(left, right, &prc)
merged = []
until left.empty? || right.empty?
case prc.call(left.first, right.first)
when -1
merged << left.shift
when 0
merged << left.shift
when 1
merged << right.shift
end
end
merged + left + right
end
end
def clever_octopus(fish_arr)
biggest = fish_arr[0]
fish_arr.each do |fish|
biggest = fish if fish.length > biggest.length
end
biggest
end
def slow_dance(direction, tiles_array)
tiles_array.each_with_index do |tile, index|
return index if tile == direction
end
end
tiles_hash = Hash.new(0)
tiles_array.each_with_index do |tile, index|
tiles_hash[tile] += index
end
def fast_dance(direction, tiles_hash)
tiles_hash[direction]
end
|
Python
|
UTF-8
| 5,444 | 3.25 | 3 |
[] |
no_license
|
class LogisticRegression():
def __init__(self, scorefunc=sigmoid, optimizor=BGD, fit_intercept=True, penalty="L2", gamma=0):
'''
参数:
scorefuc:激活函数
optimizor:梯度优化函数
fit_intercept:是否在X前面加一列1,将b内置到theta
penalty:正则化,可选"L1","L2"
gamma:正则化项的系数
'''
self.optimizor = optimizor
self.scorefunc = scorefunc
self.theta = None
self.fit_intercept = fit_intercept
self.penalty = penalty
self.gamma = gamma
def fit(self, X, y, epoch=500, lr=0.01, tol=1e-7):
if self.fit_intercept:
X = np.c_[np.ones(X.shape[0]), X]
theta, loss_data= self.optimizor(X, y, self.scorefunc, epoch, lr, tol, self.penalty, self.gamma)
self.theta = theta
return loss_data
def predict(self, X):
if self.fit_intercept:
X = np.c_[np.ones(X.shape[0]), X]
prob = self.scorefunc(np.dot(X, self.theta))
predictions = get_predictions(prob)
return predictions
def sigmoid(X):
return 1 / (1 + np.exp(-X))
def get_predictions(prob):
prob[prob>0.5] = 1
prob[prob<0.5] = 0
return prob.astype(int)
def cross_entropy_loss(prob, y):
return np.mean(-y * np.log(prob) - (1 - y) * np.log(1 - prob))
def get_gradient(predictions, X, y):
return np.dot(X.T, predictions - y) / X.shape[0]
def BGD(X, y, scorefunc, epoch=500, lr=0.01, tol=1e-7, penalty="L2", gamma=0):
'''
用梯度下降拟合线性回归
返回参数和代价
'''
m, n = X.shape
loss_data = []
theta = np.random.randn(n)
for i in range(epoch):
y_prob = scorefunc(np.dot(X, theta))
loss = cross_entropy_loss(y_prob, y)
order = 2 if penalty == "L2" else 1
loss += 0.5 * gamma * np.linalg.norm(theta, ord=order) ** 2 / m
loss_data.append(loss)
if loss < tol:
return theta, loss_data
gradient_theta = get_gradient(y_prob, X, y)
theta -= lr * gradient_theta
if i%100==99:
print('epoch %d: loss:%f' % (i, loss))
return theta, loss_data
def SGD(X, y, scorefunc, epoch=500, lr=0.01, tol=1e-7, penalty="L2", gamma=0, batch_num=5):
m,n = X.shape
loss_data = []
theta = np.random.randn(n)
indexs = np.arange(m)
for i in range(epoch):
np.random.shuffle(indexs)
indices = np.array_split(indexs, batch_num)
for index in indices:
X_index = X[index]
y_index = y[index]
y_prob = scorefunc(np.dot(X_index, theta))
loss = cross_entropy_loss(y_prob, y_index)
order = 2 if penalty == "L2" else 1
loss += 0.5 * gamma * np.linalg.norm(theta, ord=order) ** 2 / m
loss_data.append(loss)
if loss < tol:
return theta, loss_data
gradient_theta = get_gradient(y_prob, X_index, y_index)
theta -= lr * gradient_theta
if i%100==99:
print('epoch %d: loss:%f' % (i, loss))
return theta, loss_data
def momentum(X, y, scorefunc,epoch=500, lr=0.01, tol=1e-7, penalty="L2", gamma=0, beta=0.9):
m, n = X.shape
loss_data = []
theta = np.random.randn(n)
v = np.zeros(n)
for i in range(epoch):
y_prob = scorefunc(np.dot(X, theta))
loss = cross_entropy_loss(y_prob, y)
order = 2 if penalty == "L2" else 1
loss += 0.5 * gamma * np.linalg.norm(theta, ord=order) ** 2 / m
loss_data.append(loss)
if loss < tol:
return theta, loss_data
gradient_theta = get_gradient(y_prob, X, y)
v = v * beta + gradient_theta
theta -= lr * v
if i%100==99:
print('epoch %d: loss:%f' % (i, loss))
return theta, loss_data
def nesterov(X, y, scorefunc, epoch=500, lr=0.01,tol=1e-7, penalty="L2", gamma=0, beta=0.9):
m,n = X.shape
loss_data = []
theta = np.random.randn(n)
v = np.zeros(n)
for i in range(epoch):
y_prob = scorefunc(np.dot(X, theta - lr * beta * v))
loss = cross_entropy_loss(y_prob, y)
order = 2 if penalty == "L2" else 1
loss += 0.5 * gamma * np.linalg.norm(theta, ord=order) ** 2 / m
loss_data.append(loss)
if loss < tol:
return theta, loss_data
gradient_theta = get_gradient(y_prob, X, y)
v = v * beta + gradient_theta
theta -= v * lr
if i%100==99:
print('epoch %d: loss:%f' % (i, loss))
return theta, loss_data
def adaGrad(X, y, scorefunc, epoch=500, lr=0.01, tol=1e-7, penalty="L2", gamma=0):
m, n = X.shape
loss_data = []
theta = np.random.randn(n)
G = np.zeros(n)
eps = 1e-7
for i in range(epoch):
y_prob = scorefunc(np.dot(X, theta))
loss = cross_entropy_loss(y_prob, y)
order = 2 if penalty == "L2" else 1
loss += 0.5 * gamma * np.linalg.norm(theta, ord=order) ** 2 / m
loss_data.append(loss)
if loss < tol:
return theta, loss_data
gradient_theta = get_gradient(y_prob, X, y)
G += gradient_theta ** 2
theta -= lr/(np.sqrt(G + eps)) * gradient_theta
if i%100==99:
print('epoch %d: loss:%f' % (i, loss))
return theta, loss_data
def RMSprop():
pass
def Adam():
pass
|
PHP
|
ISO-8859-1
| 1,271 | 2.625 | 3 |
[] |
no_license
|
<?php
/**
* Cuida da monitorao dos equipamentos
*
* @author apssouza
*/
class Monitor extends Model
{
const TB_NAME = 'radio';
private $allEqFora;
public function ping($ip)
{
$pingando = shell_exec("ping -c 1 $ip");
if (preg_match('/bytes from/', $pingando)) {
return true;
}
return false;
}
public function monitora()
{
$manutencao = new Manutencao();
if (!$manutencao->isEmManutencao()) {
$oEquipamento = new Equipamento();
$all = $oEquipamento->getAllAtivos();
foreach ($all as $eq) {
$this->verificaStatus($eq->id);
}
}
return true;
}
private function verificaStatus($epId)
{
shell_exec("php ".DIR_ROOT."/bgmonitora.php {$epId} > /dev/null &");
}
public function estaFora($id)
{
if (!$this->allEqFora) {
$oQueda = new Queda();
$this->allEqFora = $oQueda->getEquipamentosFora();
}
return in_array($id, $this->allEqFora);
}
public function registrarQueda($eq, $idChamado)
{
$oQueda = new Queda();
return $oQueda->inicio($eq, $idChamado);
}
public function abrirChamado($eq)
{
$oChamado = new Chamado();
return $oChamado->abrirAutomatico($eq);
}
public function semiFecharChamado($eq)
{
$oChamado = new Chamado();
return $oChamado->semiFecharChamado($eq);
}
}
?>
|
Python
|
UTF-8
| 3,121 | 3.796875 | 4 |
[] |
no_license
|
#
# @lc app=leetcode.cn id=1181 lang=python3
#
# [1181] 前后拼接
#
# https://leetcode-cn.com/problems/before-and-after-puzzle/description/
#
# algorithms
# Medium (37.01%)
# Likes: 12
# Dislikes: 0
# Total Accepted: 1.5K
# Total Submissions: 3.9K
# Testcase Example: '["writing code","code rocks"]'
#
# 给你一个「短语」列表 phrases,请你帮忙按规则生成拼接后的「新短语」列表。
#
# 「短语」(phrase)是仅由小写英文字母和空格组成的字符串。「短语」的开头和结尾都不会出现空格,「短语」中的空格不会连续出现。
#
# 「前后拼接」(Before and After puzzles)是合并两个「短语」形成「新短语」的方法。我们规定拼接时,第一个短语的最后一个单词 和
# 第二个短语的第一个单词 必须相同。
#
# 返回每两个「短语」 phrases[i] 和 phrases[j](i != j)进行「前后拼接」得到的「新短语」。
#
# 注意,两个「短语」拼接时的顺序也很重要,我们需要同时考虑这两个「短语」。另外,同一个「短语」可以多次参与拼接,但「新短语」不能再参与拼接。
#
# 请你按字典序排列并返回「新短语」列表,列表中的字符串应该是 不重复的 。
#
#
#
# 示例 1:
#
# 输入:phrases = ["writing code","code rocks"]
# 输出:["writing code rocks"]
#
#
# 示例 2:
#
# 输入:phrases = ["mission statement","a quick bite to eat","a chip off the old block","chocolate bar","mission impossible","a man on a mission","block party","eat my words","bar of soap"]
# 输出:["a chip off the old block party",
# "a man on a mission impossible",
# "a man on a mission statement",
# "a quick bite to eat my words",
# "chocolate bar of soap"]
#
#
# 示例 3:
#
# 输入:phrases = ["a","b","a"]
# 输出:["a"]
#
#
#
#
# 提示:
#
#
# 1 <= phrases.length <= 100
# 1 <= phrases[i].length <= 100
#
#
#
# @lc code=start
from collections import defaultdict
class Solution:
def build(self, phrases: list[str], pair: tuple[int, int]):
a, b = phrases[pair[0]], phrases[pair[1]]
return " ".join(a.split(' ') + b.split(' ')[1:])
def beforeAndAfterPuzzles(self, phrases: list[str]) -> list[str]:
first_words, last_words = defaultdict(set), defaultdict(set)
pairs = set()
for i, p in enumerate(phrases):
words = p.split(' ')
first, last = words[0], words[-1]
for matched_first in first_words[last]:
pairs.add((i, matched_first))
for matched_last in last_words[first]:
pairs.add((matched_last, i))
first_words[first].add(i)
last_words[last].add(i)
result = list(set(self.build(phrases, pair) for pair in pairs))
result.sort()
return result
# @lc code=end
l = ["mission statement","a quick bite to eat","a chip off the old block","chocolate bar","mission impossible","a man on a mission","block party","eat my words","bar of soap"]
print(Solution().beforeAndAfterPuzzles(l))
|
PHP
|
UTF-8
| 2,668 | 2.6875 | 3 |
[] |
no_license
|
<?php
session_start();
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '' );
if(isset($_POST['pseudo'], $_POST['password'])){
$_SESSION['pseudo']= $_POST['pseudo'];
$_SESSION['password']= $_POST['password'];
$utilisateurs = $bdd->query("SELECT * FROM login");
foreach ($utilisateurs as $key => $login) {
if($login['pseudo'] == ucfirst($_SESSION['pseudo']) AND $login['password'] == $_SESSION['password']){
$connect = true;
$_SESSION['droit'] = $login['droit'];
}
}
if($connect == false){
session_unset();
session_destroy();
}
}
?>
<?php
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '' ); // Connexion à la base de données
$contenu = $bdd->query("SELECT * FROM chat ORDER BY id DESC");// Selectionne tout le contenu du tableau 'chat' par id décroissant
?>
<!DOCTYPE html>
<html>
<head>
<title>Le chat de la fabrik !</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function message() {
$.ajax({
type: "GET",
url: "messages.php"
}).done(function (html) {
$('#messages').html(html); // Retourne dans #maDiv le contenu de ta page
setTimeout(message, 5000);
});
}
message();
</script>
</head>
<body>
<div id="body">
<?php
if(isset($_SESSION["pseudo"], $_SESSION["password"])){
echo "<form action='traitement.php' method='post' style='padding-bottom:16px;'>";
echo "<label>Message : </label><input type='text' name='message' placeholder='Message' >";
echo "<input type='submit' name='bouton'>";
echo "</form>";
}else{
echo "<form action='index.php' method='post'>";
echo "<label>Votre pseudo : </label><input type='text' name='pseudo' placeholder='Pseudo' >";
echo "<label>Mot de Passe : </label><input type='password' name='password' placeholder='Mot de passe' >";
echo "<button type='submit' name='bouton'>Connexion</button>";
echo "<a href='inscription.php'><input type='button' value='INSCRIPTION' style='margin-left: 15px;height:50px;width:120px;' ></a>";
echo "</form>";
}
if(isset($_SESSION["pseudo"], $_SESSION["password"])){
echo "<a href='deconnexion.php'><input type='button' name='bouton' value='Déconnexion'></a>";
}
?>
</div>
<?php
// if(isset($_SESSION['droit'])){
// if($_SESSION['droit'] == 'admin'){
// echo "<form action='admin.php' method='post'>";
// echo "<input type='text' name='message_cible' placeholder='Message à modifier' style='width:150px'>";
// echo "<input type='submit' name='boutonDroit'>";
// }
// }
?>
<div id="messages"></div>
</body>
</html>
|
Python
|
UTF-8
| 10,982 | 2.8125 | 3 |
[] |
no_license
|
print("\n" * 5)
import datetime #SHOW THE Real Date data andinformation.
import os #OS checking the OS best compatibility
foodlist = [] #Variable both foodlist, drinklist names + prices.
drinklist = []
pricelist = [0] * 100 #Variable for pricelist
var_commission_2 = 200
vardiscount2 = 0.20
navigator_symbol = "/"
if os.name == "nt":
navigator_symbol = "\\" # making theprogram runnable on Windows
def def_default():
global foodlist,drinklist,orderlist, pricelist
orderlist = [0] * 100
def_default()
def defmain():
while True : #menu is repeated
print("*" * 31 + "RESTAURANT ORDERING SYSTEM MENU" + "*" * 32 + "\n" #Design of restaurant ordering ordering system menu.
"\t(O) ORDER\n"
"\t(P) PAYMENT\n"
"\t(C) CANCEL\n"
"\t(E) EXIT\n" +
"_" * 72)
inputx = str(input("Select Your Operation: ")).upper()
if (len(inputx) == 1):
if (inputx == 'O'):
print("\n" * 10)
def_ordermenu()
break
elif (inputx == 'P'):
print("\n" * 10)
def_payment()
break
elif (inputx == 'C'):
print ("*" * 32 + "CANCEL THE ORDER" + "*" * 31 + "\n")
break
elif (inputx == 'E'):
print("*" * 32 + "THANK YOU,WELCOME" + "*" * 31 + "\n")
break
else:
print("\n" * 10 + "ERROR: WRONG Input (" + str(inputx) + "). Try again!")
else:
print("\n" * 10 + "ERROR: WRONG Input (" + str(inputx) + "). Try again!")
def def_ordermenu():
while True:
print("*" * 31 + "ORDER MENU PAGE" + "*" * 31 + "\n"
"\t(F) FOODS AND DRINKS\n"
"\t(R) RESTAURANT ORDERING SYSTEM MENU\n"
"\t(C) CANCEL\n"
"\t(E) EXIT\n" +
"_" * 72)
input_1 = str(input(" Select Your Operation: ")).upper()
if len(input_1) == 1:
if (input_1 == 'F'):
print("\n" * 10)
def_food_drink_order()
break
elif (input_1 == 'R'):
print("\n" * 10)
defmain()
break
elif (input_1 == 'C'):
print("*" * 32 + "CANCEL THE ORDER" + "*" * 31 + "\n")
break
elif (input_1 == 'E'):
print("*" * 32 + "THANK YOU,WELCOME" + "*" * 31 + "\n")
break
else:
print("\n" * 10 + "ERROR: WRONG Input (" + str(inputy) + "). Try again!")
else:
print("\n" * 10 + "ERROR: WRONG Input (" + str(inputy) + "). Try again!")
def def_full_file_reader():
file_foods = open('files'+navigator_symbol+'foodlist.fsd', 'r') #reading foodlist
for i in file_foods:
foodlist.append(str(i.strip()))
file_foods.close()
file_drinks = open('files'+navigator_symbol+'drinklist.fsd', 'r') #reading drinklist
for i in file_drinks:
drinklist.append(str(i.strip()))
file_drinks.close()
i = 0
while i <= (len(foodlist) - 1):
if 'MR' in foodlist[i]:
foodlist[i] = str(foodlist[i][:foodlist[i].index('MR') - 1]) + ' ' * (20 - (foodlist[i].index('MR') - 1)) + str(foodlist[i][foodlist[i].index('MR'):])
i += 1
i = 0
while i <= (len(drinklist) - 1):
if 'MR' in drinklist[i]:
drinklist[i] = str(drinklist[i][:drinklist[i].index('MR') - 1]) + ' ' * (20 - (drinklist[i].index('MR') - 1)) + str(drinklist[i][drinklist[i].index('MR'):])
i += 1
def_full_file_reader()
def def_file_sorter():
global foodlist, drinklist
foodlist = sorted(foodlist)
drinklist = sorted(drinklist)
i = 0
while i < len(foodlist):
pricelist[i] = float(foodlist[i][int(foodlist[i].index("MR") + 3):])
i += 1
i = 0
while i < len(drinklist):
pricelist[40 + i] = float(drinklist[i][int(drinklist[i].index("MR") + 3):])
i += 1
i = 0
def_file_sorter()
def def_food_drink_order():
while True:
print("*" * 26 + "ORDER FOODS & DRINKS" + "*" * 20)
print(" |NO| |FOOD NAME| |PRICE| | |NO| |DRINK NAME| |PRICE|")
i = 0
while i < len(foodlist) or i < len(drinklist):
var_space = 1
if i <= 8:
var_space = 2
if i < len(foodlist):
food = " (" + str(i + 1) + ")" + " " * var_space + str(foodlist[i]) + " | "
else:
food = " " * 40 + "| "
if i < len(drinklist):
drink = "(" + str(41 + i) + ")" + " " + str(drinklist[i])
else:
drink = ""
print(food, drink)
i += 1
print("\n (R) RESTAURANT ORDERING SYSTEM MENU (P) PAYMENT (C)CANCEL (E) EXIT\n" + "_" * 72)
input_1 = input("Select Your Operation: ").upper()
if (input_1 == 'R'):
print("\n" * 10)
defmain()
break
if (input_1 == 'C'):
print("*" * 32 + "CANCEL THE ORDER" + "*" * 31 + "\n")
break
if (input_1 == 'E'):
print("*" * 32 + "THANK YOU,WELCOME" + "*" * 31 + "\n") # says Exit and prints thank you
break
if (input_1 == 'P'):
print("\n" * 10)
def_payment()
break
try:
int(input_1)
if ((int(input_1) <= len(foodlist) and int(input_1) > 0) or (int(input_1) <= len(drinklist) + 40 and int(input_1) > 40)):
try:
print("\n" + "_" * 72 + "\n" + str(foodlist[int(input_1) - 1]))
except:
pass
try:
print("\n" + "_" * 72 + "\n" + str(drinklist[int(input_1) - 41]))
except:
pass
input_2 = input("How Many Do You Want to Order?: ").upper()
if int(input_2) > 0:
orderlist[int(input_1) - 1] += int(input_2)
print("\n" * 10)
print("Success Ordered!")
def_food_drink_order()
break
else:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_2) + "). Try again!")
except:
print("\n" * 10 + "ERROR: Invalid Input (" + str(input_1) + "). Try again!")
def def_payment():
while True:
print("*" * 32 + "PAYMENT" + "*" * 33 + "\n")
total_price = 0
report_new = "\n\n\n" + " " * 17 + "*" * 35 + "\n" + " " * 17 + "DATE: " + str(datetime.datetime.now())[:19] + "\n" + " " * 17 + "-" * 35
i = 0
while i < len(orderlist):
if(orderlist[i] != 0):
if (i >= 0) and (i < 40):
report_new += "\n" + " " * 17 + str(foodlist[i]) + " x " + str(orderlist[i])
print(" " * 17 + str(foodlist[i]) + " x " + str(orderlist[i]))
total_price += pricelist[i] * orderlist[i]
if (i >= 40) and (i < 80):
report_new += "\n" + " " * 17 + str(drinklist[i - 40]) + " x " + str(orderlist[i])
print(" " * 17 + str(drinklist[i - 40]) + " x " + str(orderlist[i]))
total_price += pricelist[i] * orderlist[i]
i += 1
else:
i += 1
if total_price > var_commission_2:
total_price -= total_price * vardiscount2
report_new += "\n" + " " * 17 + "-" * 35 + "\n" \
"" + " " * 17 + "DISCOUNT: % " + str(vardiscount2 * 100) + "\n" \
"" + " " * 17 + "DISCOUNT AMOUNTS: MR " + str(round(total_price * vardiscount2, 2)) + "\n" + " " * 17 + "_" * 35 + "\n" \
"" + " " * 17 + "TOTAL PRICES: MR " + str(round(total_price, 2)) + "\n" + " " * 17 + "*" * 35
print(" " * 17 + "-" * 35 + "\n"
"" + " " * 17 + "DISCOUNT: % " + str(vardiscount2 * 100) + "\n"
"" + " " * 17 + "DISCOUNT AMOUNTS: MR " + str(round(total_price * vardiscount2, 2)) + "\n" + " " * 17 + "_" * 35 + "\n"
"" + " " * 17 + "TOTAL PRICES: MR " + str(round(total_price, 2)))
else:
report_new += "\n" + " " * 17 + "-" * 35 + "\n" + " " * 17 + "TOTAL PRICES: MR " + str(round(total_price, 2)) + "\n" + " " * 17 + "*" * 35
print(" " * 17 + "_" * 35 + "\n" + " " * 17 + "TOTAL PRICES: MR " + str(round(total_price, 2)))
print("\n (P) PAY (R) RESTAURANT ORDERING SYSTEM MENU (E) EXIT\n" + "_" * 72)
input_1 = str(input("Select Your Operation: ")).upper()
if (input_1 == 'P'):
print("\n" * 10)
print("Successfully Paid,THANK YOU!")
def_default()
elif (input_1 == 'R'):
print("\n" * 10)
defmain()
break
elif ('E' in input_1) or ('e' in input_1):
print("*" * 32 + "THANK YOU,WELCOME" + "*" * 31 + "\n")
break
else:
print("\n" * 10 + "ERROR: WRONG Input (" + str(input_1) + "). Try again!")
defmain() # Execute the restaurant ordering system
|
Markdown
|
UTF-8
| 943 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
---
layout: post
title: leetcode刷题
subtitle: 整数反转
date: 2019-02-28
author: HK
header-img: img/post-bg-ios9-web.jpg
catalog: true
tags:
- leetcode(simple)
---
# leetcode刷题记录
## 整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
*示例 1:*<br>
输入: 123 输出: 321 <br>
*示例 2:*<br>
输入: -123 输出: -321 <br>
*示例 3*:<br>
输入: 120 输出: 21<br>
#### 解题思路:
重复弹出x的最后一位数字,在没有堆栈/数组的帮助下,可以用数学方法。注意检查结果是否溢出。如果逆序整型数溢出的话就返回0。
``` java
class Solution {
public int reverse(int x) {
long res = 0;
for(; x != 0; x /= 10)
res = res*10 + x % 10;
return res>Integer.MAX_VALUE || res< Integer.MIN_VALUE ? 0:(int)res;
}
}
```
耗时:43ms
|
C++
|
UTF-8
| 2,273 | 2.828125 | 3 |
[] |
no_license
|
#include "encoder.h"
unsigned int slot_R = 0; // a flag to remember the state of Right Slot
unsigned int slot_L = 0; // a flag to remember the state of Left Slot
unsigned int r_encoder_count = 0;
unsigned int l_encoder_count = 0;
const int ONE_SECOND = 1000;
unsigned int ms_counter = 0;
unsigned int l_slot_count=0;
unsigned int r_slot_count=0;
unsigned int L_E_count_1s=0;
unsigned int R_E_count_1s=0;
/*
* encoder_update() is 1ms Timer ISR; ie it is called on every millisecond
*/
void encoder_update()
{
if ( slot_L ) // slot_L is 1 ( ie not 0 )
{ // capture the falling edge change
if (digitalRead(ENC_L_PIN)==0)
{
slot_L=0;
}
}
else // slot_L is 0
{
if (digitalRead(ENC_L_PIN))
{ // the rising edg is detected
l_slot_count++; // increment the per second left-slot counter
l_encoder_count++;
slot_L=1;
}
}
// repeat on the RIGHT ENCODER -----------------------
if ( slot_R ) // slot_R is 1 ( ie not 0 )
{
if (digitalRead(ENC_R_PIN)==0)
{
slot_R=0;
}
}
else // slot_R is 0
{
if (digitalRead(ENC_R_PIN))
{
r_slot_count++; // increment the per second right-slot counter
r_encoder_count++;
slot_R=1;
}
}
ms_counter++;
if (ms_counter >= ONE_SECOND)
{
ms_counter = 0;
// Serial.print(" l_slot_count= ");Serial.print(l_slot_count);
// Serial.print(" r_slot_count= ");Serial.println(r_slot_count);
L_E_count_1s = l_slot_count ; // capture the per second left-slot counter
R_E_count_1s = r_slot_count ; // capture the per second right-slot counter
l_slot_count = r_slot_count = 0; // clear both per second counters
}
}
void reset_encoder_count()
{
l_encoder_count = 0;
r_encoder_count = 0;
}
/*
* get_encoder() will put both encoder counter value to the caller supplied struct encoder;
* it returns the diff between l and r encoder; ie l_encoder_count - r_encoder_count
*/
int get_encoder( encoder_Struct *encoder )
{
encoder->l_encoder_count = l_encoder_count;
encoder->r_encoder_count = r_encoder_count;
encoder->L_E_count_1s = L_E_count_1s;
encoder->R_E_count_1s = R_E_count_1s;
encoder->encoder_ts = millis();
return ( l_encoder_count - r_encoder_count );
}
|
Python
|
UTF-8
| 1,820 | 3.359375 | 3 |
[] |
no_license
|
class CollisionError(Exception):
pass
def Up(map, row, column, indicesOfPath):
for x in range(row - 1, row - 21, -1):
row = x
if x < 0 or x >= 120:
break
if map[x][column] == 'a' or map[x][column] == 'b':
raise CollisionError()
if map[x][column] == 1:
map[x][column] = 'a'
elif map[x][column] == 2:
map[x][column] = 'b'
indicesOfPath.append((x, column))
return row, column
def Left(map, row, column, indicesOfPath):
for y in range(column - 1, column - 21, -1):
column = y
if y < 0 or y >= 160:
break
if map[row][y] == 'a' or map[row][y] == 'b':
raise CollisionError()
if map[row][y] == 1:
map[row][y] = 'a'
elif map[row][y] == 2:
map[row][y] = 'b'
indicesOfPath.append((row, y))
return row, column
def Right(map, row, column, indicesOfPath):
for y in range(column + 1, column + 21):
column = y
if y < 0 or y >= 160:
break
if map[row][y] == 'a' or map[row][y] == 'b':
raise CollisionError()
if map[row][y] == 1:
map[row][y] = 'a'
elif map[row][y] == 2:
map[row][y] = 'b'
indicesOfPath.append((row, y))
return row, column
def Down(map, row, column, indicesOfPath):
for x in range(row + 1, row + 21):
row = x
if x < 0 or x >= 120:
break
if map[x][column] == 'a' or map[x][column] == 'b':
raise CollisionError()
if map[x][column] == 1:
map[x][column] = 'a'
elif map[x][column] == 2:
map[x][column] = 'b'
indicesOfPath.append((x, column))
return row, column
|
Markdown
|
UTF-8
| 820 | 2.84375 | 3 |
[] |
no_license
|
# Multiplayer_Yahtzee
A simple text based multiplayer Yahtzee game built using the network sockets api and multithreading api in JAVA.
The class decriptions are as follows:
1. YServer – The Server Class, hosts game
2. YThread – The Server Thread Class, manages clients
3. YState – The Server State Class, stores and process data
4. YClient – The Client Class, plays the game

The overall architecture of the game can be seen in the above process diagram.
To play the game, run the server class first then the client classes. By default the number of players is 4 and the network settings have been configured. These can be changed in the YServer and YClient classes respectively.
|
Java
|
UTF-8
| 700 | 2.234375 | 2 |
[
"MIT"
] |
permissive
|
package net.sengjea.calibre;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
public class ServiceReceiver extends BroadcastReceiver {
public ServiceReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Intent service_intent = new Intent(context,CalibreService.class);
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
context.startService(service_intent);
}
}
}
}
|
Java
|
UTF-8
| 2,227 | 2.484375 | 2 |
[] |
no_license
|
package ddwucom.mobile.activitiy_test;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
final static int SUB_ACTIVITY_CODE = 100;
final static String TAG = "subActivity2";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
// Intent intent = new Intent(MainActivity.this, SubActivity1.class);
//묵시적(implicit) 인텐트
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com"));
// Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:012-3456-7890"));
Intent intent = new Intent(MainActivity.this, SubActivity2.class);
// String id="cooling";
// ArrayList<String> foods = new ArrayList<String>();
//// *List는 Serializable 구현 X
// foods.add("사과");
// foods.add("배");
// foods.add("오렌지");
//
// intent.putExtra("id", id);
// intent.putExtra("foods", foods);
// startActivity(intent);
startActivityForResult(intent, SUB_ACTIVITY_CODE);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case SUB_ACTIVITY_CODE:
if (resultCode==RESULT_OK){
String result = data.getStringExtra("result_data");
Toast.makeText(this, "Result "+result, Toast.LENGTH_SHORT).show();
}
else
Log.d(TAG, "canceled");
break;
}
}
}
|
Java
|
UTF-8
| 774 | 2.890625 | 3 |
[] |
no_license
|
class CMaxInOneRow{
static void maxInOneRow(int x[][]){
for(int i=0;i<x.length;i++)
for(int j=0;j<x[i].length;j++)
if(x[i][j]!=1&&x[i][j]!=0)
return;
int a[]=new int[x.length];
for(int i=0;i<x.length;i++)
for(int j=0;j<x[i].length;j++)
if(x[i][j]==1)
a[i]++;
int maxval=a[0],k=0;
for(int i=1;i<a.length;i++){
if(a[i]>maxval){
maxval=a[i];
k=i;
}
}for(int i=0;i<x.length;i++){
if(i==k){
for(int j=0;j<x[i].length;j++)
System.out.print(x[i][j]+"\t");
System.out.print("->"+a[k]);
}else{
for(int j=0;j<x[i].length;j++)
System.out.print(x[i][j]+"\t");
}System.out.println("");
}
}public static void main(String... args){
maxInOneRow(new int[][]{{0,0,0,1},{1,0,1,0},{1,1,0,1},{1,1,1,1}});
}
}
|
Java
|
UTF-8
| 2,126 | 2.9375 | 3 |
[] |
no_license
|
/**
* @author Richard Shepard
* @version Mar 25, 2015
*/
package com.rshepard.simulation;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicArrowButton;
public class BattleDisplay implements ActionListener{
private BattleDisplayPanel battleDisplayPanel;
private BattleStatsPanel battleStatsPanel;
private JButton start;
private boolean gameStart;
private static final int WIDTH = 765;
private static final int HEIGHT = 585;
private static final String TITLE = "Battle Arena";
public BattleDisplay(CreatureMap arena) {
gameStart = false;
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setLayout(new BorderLayout(5, 5));
frame.setTitle(TITLE);
battleDisplayPanel = new BattleDisplayPanel(arena);
battleDisplayPanel.setBorder(BorderFactory.createLineBorder(Color.black, 5));
battleStatsPanel = new BattleStatsPanel(arena);
start = new JButton("Start");
start.setPreferredSize(new Dimension(70, 20));
start.setLocation(10, 200);
start.addActionListener(this);
battleStatsPanel.add(start);
frame.add(battleDisplayPanel, BorderLayout.CENTER);
frame.add(battleStatsPanel, BorderLayout.EAST);
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setVisible(true);
}
public void updateDisplay() {
battleDisplayPanel.repaint();
battleStatsPanel.repaint();
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
JButton testButton = (JButton)e.getSource();
if(testButton == start) {
gameStart = !gameStart;
System.out.println(gameStart);
}
}
public boolean getGameStart() {
return gameStart;
}
}
|
Python
|
UTF-8
| 544 | 3.53125 | 4 |
[] |
no_license
|
#!/usr/bin/python3
# makes O(n log n) comparisons on avg
# O(n^2) worst case comparisons (rare)
A = [56,93,65,34,13,19,88,84,67,48,51,21]
def quicksort(a):
if len(a) <= 1:
return a
end = len(a)-1
pivot = a[end]
less = []
more = []
pivots = []
for i in a:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
pivots.append(i)
less = quicksort(less)
more = quicksort(more)
return less + pivots + more
print(quicksort(A))
|
Java
|
ISO-8859-1
| 2,410 | 3.53125 | 4 |
[] |
no_license
|
package es.argenis.proyectofinal;
import java.util.ArrayList;
import java.util.Scanner;
/*
* CLASS LISTAMUSICA: define atributos y metodos para el objeto listaMusica.
* EXTIENDE a la clase MUSICA porque guarda objetos de tipo MUSICA.
* IMPLEMENTA la interface ACCION porque, al ser una lista, existen acciones que
* debe poder efectuar (tanto esta clase como cualquier otra que se pudiese aadir
* del mismo tipo) de manera estandarizada
*
*/
public class listaMusica extends Musica implements Accion {
static Scanner teclado= new Scanner(System.in);
ArrayList<Musica> listadoMusica= new ArrayList<Musica>();
//Para pedir UN UNICO codigo
@Override
public int leeCodigo() {
System.out.println("Codigo del artculo(msica):");
int codigoleido= teclado.nextInt();
return codigoleido;
}
//Para AADIR un objeto musica VALIDO
public void crear() {
Musica musicaValida= Musica.leeDatos();
if(musicaValida!=null)
listadoMusica.add(musicaValida);
}
//Para imprimir en pantalla los objetos musica
@Override
public void listar() {
System.out.println("");
if (listadoMusica.isEmpty()) {
System.out.println("No existen productos de msica que mostrar.");
} else {
for (int j = 0; j < listadoMusica.size(); j++) {
System.out.println(listadoMusica.get(j)); }
}
System.out.println("");
}
//Para eliminar UN unico objeto musica y ensear su informacion en pantalla
@Override
public Musica eliminar(int codigo) {
System.out.println("Eliminado el artculo de msica con cdigo "+codigo+" descrito a continuacin:");
for (int i = 0; i < listadoMusica.size(); i ++){
Musica musicaselecta = listadoMusica.get(i);
if (musicaselecta.getCodigoMusica()==(codigo)) {
System.out.println(musicaselecta);
System.out.println("");
listadoMusica.remove(i);
}
}
return null;
}
//Para buscar UN unico objeto musica
@Override
public Musica buscar(int codigo) {
for (int i = 0; i<listadoMusica.size(); i ++){
Musica musicaselecta= listadoMusica.get(i);
if (musicaselecta.getCodigoMusica()==(codigo)) {
listadoMusica.get(i);
return musicaselecta;
}
}
return null;
}
}
|
Python
|
UTF-8
| 3,870 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
import logging
import acapy_wallet_facade as wallet_facade
import ledger_facade
from schemas import DidCreationResponse
from aries_cloudcontroller import AriesAgentControllerBase
from fastapi import HTTPException
logger = logging.getLogger(__name__)
async def get_taa(controller: AriesAgentControllerBase):
"""
Obtains the TAA from the ledger
Parameters:
-----------
controller: AriesController
The aries_cloudcontroller object
Returns:
--------
taa: dict
The TAA object
"""
taa_response = await controller.ledger.get_taa()
logger.info(f"taa_response:\n{taa_response}")
if "result" not in taa_response or not taa_response["result"]:
logger.error("Failed to get TAA:\n{taa_response}")
raise HTTPException(
status_code=404,
detail=f"Something went wrong. Could not get TAA. {taa_response}",
)
taa = taa_response["result"]["taa_record"]
taa["mechanism"] = "service_agreement"
return taa
async def accept_taa(controller: AriesAgentControllerBase, taa):
"""
Accept the TAA
Parameters:
-----------
controller: AriesController
The aries_cloudcontroller object
TAA:
The TAA object we want to agree to
Returns:
--------
accept_taa_response: {}
The response from letting the ledger know we accepted the response
"""
accept_taa_response = await controller.ledger.accept_taa(taa)
logger.info(f"accept_taa_response: {accept_taa_response}")
if accept_taa_response != {}:
logger.error(f"Failed to accept TAA.\n{accept_taa_response}")
raise HTTPException(
status_code=404,
detail=f"Something went wrong. Could not accept TAA. {accept_taa_response}",
)
return accept_taa_response
async def get_did_endpoint(controller: AriesAgentControllerBase, issuer_nym):
"""
Obtains the public DID endpoint
Parameters:
-----------
controller: AriesController
The aries_cloudcontroller object
issuer_nym: str
The issuer's Verinym
Returns:
--------
issuer_endpoint_response: dict
The response from getting the public endpoint associated with
the issuer's Verinym from the ledger
"""
issuer_endpoint_response = await controller.ledger.get_did_endpoint(issuer_nym)
if not issuer_endpoint_response:
logger.error(f"Failed to get DID endpoint:\n{issuer_endpoint_response}")
raise HTTPException(
status_code=404,
detail=f"Something went wrong. Could not obtain issuer endpoint.",
)
return issuer_endpoint_response
async def create_pub_did(
aries_controller: AriesAgentControllerBase = None,
) -> DidCreationResponse:
"""
Create a new public DID and
write it to the ledger and
receive its public info.
Returns:
* DID object (json)
* Issuer verkey (str)
* Issuer Endpoint (url)
"""
generate_did_res = await wallet_facade.create_did(aries_controller)
did_object = generate_did_res["result"]
await ledger_facade.post_to_ledger(did_object=did_object)
taa_response = await get_taa(aries_controller)
await accept_taa(aries_controller, taa_response)
await wallet_facade.assign_pub_did(aries_controller, did_object["did"])
get_pub_did_response = await wallet_facade.get_pub_did(aries_controller)
issuer_nym = get_pub_did_response["result"]["did"]
issuer_verkey = get_pub_did_response["result"]["verkey"]
issuer_endpoint = await get_did_endpoint(aries_controller, issuer_nym)
issuer_endpoint_url = issuer_endpoint["endpoint"]
final_response = DidCreationResponse(
did_object=get_pub_did_response["result"],
issuer_verkey=issuer_verkey,
issuer_endpoint=issuer_endpoint_url,
)
return final_response
|
JavaScript
|
UTF-8
| 782 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
var stringifyStyle = require('./stringify-style');
var stringifyClass = require('./stringify-class');
/**
* Returns a `'key1='value1' key2='value2' ...'` string from
* a `{ key1: 'value1', key2: 'value2' }` object.
*
* @param Object attrs The keys/values object to stringify.
* @return String The corresponding string.
*/
function stringifyAttrs(attrs, tagName) {
if (!attrs) {
return '';
}
var attributes = [], value;
for (var key in attrs) {
value = attrs[key];
if (key === 'style') {
value = stringifyStyle(value);
} else if (key === 'class') {
value = stringifyClass(value);
}
attributes.push(key + '="' + String(value).replace(/"/g, '\\"') + '"');
}
return attributes.join(' ');
}
module.exports = stringifyAttrs;
|
Java
|
UTF-8
| 380 | 2.578125 | 3 |
[] |
no_license
|
package capitulo_20_programacao_funcional_e_expressoes_lambda.util;
import capitulo_20_programacao_funcional_e_expressoes_lambda.entities.Product_function;
import java.util.function.Function;
public class UpperCaseName implements Function<Product_function, String> {
@Override
public String apply(Product_function p) {
return p.getName().toUpperCase();
}
}
|
Java
|
UTF-8
| 2,866 | 2.078125 | 2 |
[] |
no_license
|
package com.ttech.jwt.security;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import com.ttech.jwt.security.utils.JwtUtils;
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt);
String userRole = jwtUtils.getRoleFromJwtToken(jwt);
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(userRole.substring(1, userRole.length() - 1)));
// UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null,
authorities);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
//adding to log information
String mdcData = String.format("[%s | %s | %s ]", "USER_ID:"+username, "TRANSACTION_ID:"+UUID.randomUUID().toString(), "URI:"+request.getRequestURI());
MDC.put("common-log-data", mdcData);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String accessToken = request.getHeader("Authorization");
if (StringUtils.hasText(accessToken) && accessToken.startsWith("Bearer ")) {
return accessToken.substring(7, accessToken.length());
}
return null;
}
}
|
Java
|
UTF-8
| 3,906 | 3.1875 | 3 |
[] |
no_license
|
/**
*
*/
package assignBSTSpellCheck;
/**
* @author C.M.
*Implements a binary search tree.
*/
public class BST<type extends Comparable<? super type>>{
private BNode<type> root;
private int size;
public boolean add(type item) {
if(isEmpty()) {
BNode<type> temp = new BNode<type>(null, null, item);
size++;
return true;
}
BNode<type> temp = finds(item);
int status = temp.item.compareTo(item);
if(status == 0)
return false;
if(status > 0)
temp.l = new BNode<type>(null, null, item);
else
temp.l = new BNode<type>(null, null, item);
size++;
return true;
}
public boolean remove(type item) {
if(isEmpty())
return false;
BNode<type> temp = root;
int status = temp.item.compareTo(item);
if(status == 0 && temp.l == null && temp.r == null) {
root = null;
size--;
return true;
}
BNode<type> parent = root;
while(status != 0) {
parent = temp;
if(status > 0)
temp = temp.l;
if(status < 0)
temp = temp.r;
if(temp == null)//item is not in tree
return false;
status = temp.item.compareTo(item);
}
//case 1 temp is leaf.
if(temp.l == null && temp.r == null) {
if(temp == parent.l)
parent.l = null;
else if (temp == parent.r)
parent.r = null;
size--;
return true;
}
//case2 temp has one left child -- replace by left child
if(temp.l != null && temp.r ==null) {
temp.item = temp.l.item;
temp.r = temp.l.r;
temp.l = temp.l.l;
size --;
return true;
}
//case3 temp has one right child -- replace by right child
if(temp.l == null && temp.r !=null) {
temp.item = temp.r.item;
temp.l = temp.r.l;
temp.r = temp.r.r;
size--;
return true;
}
//case4 temp has both right and left children. replace temp
//by smallest of right subtree.
BNode <type> psmallest = temp;
BNode<type> smallest = temp.r;
while(smallest.l != null) {
psmallest = smallest;
smallest = smallest.l;
//replace temp by smallest
temp.item = smallest.item;
} if(psmallest.r == smallest) {
psmallest.r = smallest.r;
}else
psmallest.l = smallest.r; //smallest.l must be null
size--;
return true;
}
/**
*
* @param item
* @return
*/
private BNode<type> finds (type item)
{
BNode<type> temp = root;
int status = temp.item.compareTo(item);
while(status != 0) {
if(status > 0)
if(temp.l != null)
temp = temp.l;
else
break;
if(status < 0)
if(temp.r != null)
temp = temp.r;
else
break;
status = temp.item.compareTo(item);
}
return temp;
}
/**
* @return
*/
private boolean isEmpty ()
{
return size == 0;
}
static class BNode<type>{
private type item;
private BNode<type> l;
private BNode<type> r;
public BNode (BNode<type> l, BNode<type> r, type i) {
this.l = l;
this.r = r;
item = i;
}
public int height() {
int hl = 0;
int hr = 0;
if(l != null)
hl = l.height();
if(r != null)
hr = r.height();
if(hl > hr)
return hl;
else
return hr;
}
}
}
|
Java
|
UTF-8
| 2,468 | 2.390625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.openapi2puml.openapi;
import org.apache.commons.lang3.StringUtils;
import org.openapi2puml.CliArgs;
import org.openapi2puml.openapi.plantuml.PlantUMLGenerator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class OpenApi2PlantUML {
private static final Logger LOGGER = LogManager.getLogger(OpenApi2PlantUML.class);
// TODO - rewrite usage
private static final String USAGE = new StringBuilder()
.append(" Usage: ")
.append(OpenApi2PlantUML.class.getName()).append(" <options> \n")
.append(" -i <spec file> ")
.append(" -o <output directory> ")
.append(" -generateDefinitionModelOnly true/false; Default=false ")
.append(" -includeCardinality true/false; Default=true ")
.append(" -generateSvg true/false; Default=true ")
.append(" -generatePng true/false; Default=true ")
.toString();
public OpenApi2PlantUML() {
}
/**
* @param args
*/
public static void main(String[] args) {
OpenApi2PlantUML openApi2PlantUML = new OpenApi2PlantUML();
openApi2PlantUML.init(args);
}
/**
* @param args
*/
private void init(String args[]) {
CliArgs cliArgs = new CliArgs(args);
String specFile = cliArgs.getArgumentValue("-i", "");
String output = cliArgs.getArgumentValue("-o", "");
boolean generateDefinitionModelOnly = Boolean.parseBoolean(
cliArgs.getArgumentValue("-generateDefinitionModelOnly", "false"));
boolean includeCardinality = Boolean.parseBoolean(cliArgs.getArgumentValue("-includeCardinality", "true"));
boolean generateSvg = Boolean.parseBoolean(cliArgs.getArgumentValue("-generateSvg", "true"));
boolean generatePng = Boolean.parseBoolean(cliArgs.getArgumentValue("-generatePng", "true"));
if (StringUtils.isNotEmpty(specFile) && StringUtils.isNotEmpty(output)) {
process(specFile, output, generateDefinitionModelOnly, includeCardinality, generateSvg, generatePng);
} else {
LOGGER.error(USAGE);
}
}
/**
* @param specFile
* @param output
*/
private void process(String specFile, String output, boolean generateDefinitionModelOnly, boolean includeCardinality,
boolean generateSvg, boolean generatePng) {
PlantUMLGenerator generator = new PlantUMLGenerator();
generator.transformOpenApi2Puml(specFile, output, generateDefinitionModelOnly, includeCardinality, generateSvg, generatePng);
}
}
|
Python
|
UTF-8
| 3,676 | 2.53125 | 3 |
[] |
no_license
|
"""
gas
===
Functions for plotting gas quantities
"""
import logging
import matplotlib.pyplot as plt
import numpy as np
from ..analysis import angmom, halo, profile
from ..units import Unit
from .generic import hist2d
logger = logging.getLogger('pynbody.plot.gas')
def rho_T(sim, rho_units=None, rho_range=None, t_range=None, two_phase='split', **kwargs):
"""
Plot Temperature vs. Density for the gas particles in the snapshot.
**Optional keywords:**
*rho_units*: specify the density units (default is the same units as the current 'rho' array)
*t_range*: list, array, or tuple
``size(t_range)`` must be 2. Specifies the temperature range.
*rho_range:* tuple
``size(rho_range)`` must be 2. Specifies the density range.
*two_phase*: if two-phase particles are detected, either plot each phase separately ('split'), or merge them ('merge')
See :func:`~pynbody.plot.generic.hist2d` for other plotting keyword options
"""
if rho_units is None:
rho_units = sim.gas['rho'].units
if t_range is not None:
kwargs['y_range'] = t_range
assert len(kwargs['y_range']) == 2
if rho_range is not None:
kwargs['x_range'] = rho_range
assert len(kwargs['x_range']) == 2
else:
rho_range = False
if 'xlabel' in kwargs:
xlabel = kwargs['xlabel']
del kwargs['xlabel']
else:
xlabel = r'log$_{10}$($\rho$/$' + Unit(rho_units).latex() + '$)'
if 'ylabel' in kwargs:
ylabel = kwargs['ylabel']
del kwargs['ylabel']
else:
ylabel = r'log$_{10}$(T/$' + sim.gas['temp'].units.latex() + '$)'
if 'Tinc' in sim.loadable_keys() and two_phase == 'merge':
return hist2d(sim.gas['rho'].in_units(rho_units),sim.gas['Tinc'],
xlogrange=True,ylogrange=True,xlabel=xlabel,
ylabel=ylabel, **kwargs)
if 'uHot' in sim.loadable_keys() and 'MassHot' in sim.loadable_keys() and two_phase == 'split':
E = sim.g['uHot']*sim.g['MassHot']+sim.g['u']*(sim.g['mass']-sim.g['MassHot'])
rho = np.concatenate((sim.g['rho'].in_units(rho_units)*E/(sim.g['mass']*sim.g['u']),
sim.g['rho'].in_units(rho_units)*E/(sim.g['mass']*sim.g['uHot'])))
temp = np.concatenate((sim.g['temp'], sim.g['temp']/sim.g['u']*sim.g['uHot']))
temp = temp[np.where(np.isfinite(rho))]
rho = rho[np.where(np.isfinite(rho))]
return hist2d(rho, temp, xlogrange=True,ylogrange=True,xlabel=xlabel,
ylabel=ylabel, **kwargs)
return hist2d(sim.gas['rho'].in_units(rho_units),sim.gas['temp'],
xlogrange=True,ylogrange=True,xlabel=xlabel,
ylabel=ylabel, **kwargs)
def temp_profile(sim, center=True, r_units='kpc', bin_spacing='equaln',
clear=True, filename=None, **kwargs):
"""
Centre on potential minimum, align so that the disk is in the
x-y plane, then plot the temperature profile as a
function of radius.
"""
if center:
angmom.sideon(sim)
if 'min' in kwargs:
min_r = kwargs['min']
else:
min_r = sim['r'].min()
if 'max' in kwargs:
max_r = kwargs['max']
else:
max_r = sim['r'].max()
pro = profile.Profile(sim.gas, type=bin_spacing, rmin =min_r, rmax =max_r)
r = pro['rbins'].in_units(r_units)
tempprof = pro['temp']
if clear:
plt.clf()
plt.semilogy(r, tempprof)
plt.xlabel("r / $" + r.units.latex() + "$")
plt.ylabel("Temperature [K]")
if (filename):
logger.info("Saving %s", filename)
plt.savefig(filename)
|
Rust
|
UTF-8
| 1,490 | 3 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use super::ByteSet;
use core::{mem, slice};
/// Operations over the internal memory representation.
///
/// There are currently no stability guarantees over the internal bytes. This is
/// being tracked in [#8](https://github.com/nvzqz/byte-set-rs/issues/8).
impl ByteSet {
const SIZE: usize = mem::size_of::<Self>();
/// Returns the underlying bytes of `self`.
#[inline]
pub fn into_raw_bytes(self) -> [u8; Self::SIZE] {
unsafe { mem::transmute(self) }
}
/// Returns a shared reference to the underlying bytes of `self`.
#[inline]
pub fn as_raw_bytes(&self) -> &[u8; Self::SIZE] {
unsafe { &*self.0.as_ptr().cast() }
}
/// Returns a mutable reference to the underlying bytes of `self`.
#[inline]
pub fn as_raw_bytes_mut(&mut self) -> &mut [u8; Self::SIZE] {
unsafe { &mut *self.0.as_mut_ptr().cast() }
}
/// Returns a shared reference to the underlying bytes of `slice`.
#[inline]
pub fn slice_as_raw_bytes(slice: &[Self]) -> &[u8] {
let ptr = slice.as_ptr().cast::<u8>();
let len = slice.len() * Self::SIZE;
unsafe { slice::from_raw_parts(ptr, len) }
}
/// Returns a mutable reference to the underlying bytes of `slice`.
#[inline]
pub fn slice_as_raw_bytes_mut(slice: &mut [Self]) -> &mut [u8] {
let ptr = slice.as_mut_ptr().cast::<u8>();
let len = slice.len() * Self::SIZE;
unsafe { slice::from_raw_parts_mut(ptr, len) }
}
}
|
Markdown
|
UTF-8
| 940 | 2.90625 | 3 |
[] |
no_license
|
# What does this do?
This script installs the recently released & stable versions of rubies including all their fix versions from the ruby community. The number of recent versions can be optionally provided in the argumen to this scripts, otherwise, the number of recent versions defaults to 2
# Why do I need this?
This script is mostly required in production environments of rails applications to maintain a limited set of recent versions of rubies at a given time. This is to promote teams to use only the latest versions of rubies when they are building their application on Jenkins or Spork
# How do I make use of this?
For now, put this script in your <YOUR_APPLICATION>_chef-repo/files/ and call this script with `ruby <YOUR_APPLICATION>_chef-repo/files/recent_rubies.rb <NO_OF_RECENT_VERSIONS>`. This will install, suppose for <NO_OF_RECENT_VERSIONS> = 2:
``` ruby
# rubies
=> ["2.5.0", "2.4.3", "2.4.2", "2.4.1", "2.4.0"]
```
|
C++
|
UTF-8
| 4,242 | 2.703125 | 3 |
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_SIGNABLE_HPP
#define IROHA_SIGNABLE_HPP
#include "interfaces/base/model_primitive.hpp"
#include <boost/functional/hash.hpp>
#include <optional>
#include <unordered_set>
#include "cryptography/default_hash_provider.hpp"
#include "interfaces/common_objects/range_types.hpp"
#include "interfaces/common_objects/signature.hpp"
#include "interfaces/common_objects/string_view_types.hpp"
#include "interfaces/common_objects/types.hpp"
#include "utils/string_builder.hpp"
namespace shared_model {
namespace interface {
/**
* Interface provides signatures and adds them to model object
* @tparam Model - your model
*/
template <typename Model,
typename HashProvider = shared_model::crypto::Sha3_256>
class Signable : public ModelPrimitive<Model> {
public:
/**
* @return attached signatures
*/
virtual types::SignatureRangeType signatures() const = 0;
/**
* Attach signature to object
* @return true, if signature was added
*/
virtual bool addSignature(types::SignedHexStringView signed_blob,
types::PublicKeyHexStringView public_key) = 0;
/**
* @return time of creation
*/
virtual types::TimestampType createdTime() const = 0;
/**
* @return object payload (everything except signatures)
*/
virtual const types::BlobType &payload() const = 0;
/**
* @return blob representation of object include signatures
*/
virtual const types::BlobType &blob() const = 0;
/**
* Provides comparison based on equality of objects and signatures.
* @param rhs - another model object
* @return true, if objects totally equal
*/
bool operator==(const Model &rhs) const override {
return equalsByValue(rhs)
// is_permutation consumes ~O(N^2)
and std::is_permutation(signatures().begin(),
signatures().end(),
rhs.signatures().begin(),
rhs.signatures().end());
}
/**
* Provides comaprison based on equality objects only
* @param rhs - another model object
* @return true, if hashes of objects are equal
*/
bool equalsByValue(const Model &rhs) const {
return this->hash() == rhs.hash();
}
virtual const types::HashType &hash() const = 0;
// ------------------------| Primitive override |-------------------------
std::string toString() const override {
return detail::PrettyStringBuilder()
.init("Signable")
.appendNamed("created_time", std::to_string(createdTime()))
.append(signatures())
.finalize();
}
protected:
/**
* Type of set of signatures
*
* Note: we can't use const SignatureType due to unordered_set
* limitations: it requires to have write access for elements for some
* internal operations.
*/
protected:
class SignatureSetTypeOps {
public:
/**
* @param sig is item to find hash from
* @return calculated hash of public key
*/
template <typename T>
size_t operator()(const T &sig) const {
return std::hash<std::string>{}(sig.publicKey());
}
/**
* Function for set elements uniqueness by public key
* @param lhs
* @param rhs
* @return true, if public keys are the same
*/
template <typename T>
bool operator()(const T &lhs, const T &rhs) const {
return lhs.publicKey() == rhs.publicKey();
}
};
template <typename T>
using SignatureSetType =
std::unordered_set<T, SignatureSetTypeOps, SignatureSetTypeOps>;
protected:
static auto makeHash(const types::BlobType &payload) {
return HashProvider::makeHash(payload);
}
};
} // namespace interface
} // namespace shared_model
#endif // IROHA_SIGNABLE_HPP
|
Ruby
|
UTF-8
| 1,121 | 2.671875 | 3 |
[] |
no_license
|
require 'erubis'
require 'tempfile'
require 'corporeal/config'
# Provide instance method to flatten hash
Hash.send(:include, Module.new do
def stringify
self.inject("") do |str, kv|
str << " " unless str.length == 0
str << kv[0]
str << "=#{kv[1]}" unless kv[1].nil?
str
end
end
end)
module Corporeal
module Template
class Base
attr_reader :vars
attr_reader :template
class << self
def render(vars, template)
t = new(vars, template)
t.to_s
end
def render_to_file(vars, template, &blk)
t = new(vars, template)
t.render_to_file &blk
end
end
def initialize(vars, template)
@vars = vars
@template = template
end
def to_s
render
end
def render_to_file &blk
Tempfile.open("corporeal-rendered-template") do |tempfile|
tempfile.print(render)
tempfile.close
yield tempfile
end
end
private
def render
eruby = Erubis::Eruby.new(template)
context = context_klass.new(vars)
eruby.evaluate(context)
end
# Override
def context_klass
Erubis::Context
end
end
end
end
|
C++
|
UTF-8
| 991 | 3.796875 | 4 |
[] |
no_license
|
//Print matrix in Spiral form
#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
void spiral(int a[3][6])
{
int m=3;
int n=6;
int row_start=0,col_start=0,row_end=m-1,col_end=n-1;
while(row_start<=row_end && col_start<=col_end)
{
for(int i=col_start;i<=col_end;i++)
cout<<a[row_start][i]<<" ";
row_start++;
for(int i=row_start;i<=row_end;i++)
cout<<a[i][col_end]<<" ";
col_end--;
if(row_start<=row_end)
{
for(int i=col_end;i>=col_start;i--)
cout<<a[row_end][i]<<" ";
row_end--;
}
if(col_start<=col_end)
{
for(int i=row_end;i>=row_start;i--)
cout<<a[i][col_start]<<" ";
col_start++;
}
}
}
int main()
{
int a[3][6]={
{ 1, 2, 3, 4, 5, 6 },
{ 7, 8, 9, 10, 11, 12 },
{ 13, 14, 15, 16, 17, 18 }
};
spiral(a);
}
|
Python
|
UTF-8
| 845 | 2.8125 | 3 |
[] |
no_license
|
#!/usr/bin/python
import sys
def universe(queries, engines):
if len(queries) == 0:
return 0
indices = []
for engine in engines:
try:
indices.append(queries.index(engine))
except ValueError:
return 0
switch = universe(queries[max(indices):], engines)
return switch + 1
f = open("A-small-attempt4.in","rb")
casos = int(f.readline())
for i in xrange(casos):
engines = []
queries = []
engs = int(f.readline())
for j in range(engs):
engines.append(f.readline())
ques = int(f.readline())
if ques == 0:
print "Case #%d: 0" % (int(i)+1)
continue
for k in range(ques):
queries.append(f.readline())
switchs = universe(queries, engines)
print "Case #%d: %d" % (int(i)+1, switchs)
|
Shell
|
UTF-8
| 3,545 | 4.25 | 4 |
[] |
no_license
|
#!/bin/sh
#
# by bohoomil
# A simple script that will repeat
# the chrooting routine for you.
# Drop it somewhere in your $PATH.
# --- colours
cres="\e[00m"
cred="\e[01;31m"
cyel="\e[01;33m"
cgre="\e[01;32m"
cblu="\e[01;34m"
usage() {
echo -e ""
echo -e "Usage:"
echo -e " cr a|b|c|...|X -- Chroot to a predefined OS"
echo -e ""
echo -e "Arguments:"
echo -e " a -- Arch Linux on /dev/sda2"
echo -e " b -- Arch32 chroot on /dev/sda1"
echo -e " X -- Do nothing and exit"
echo -e " -h, help -- Print this help"
echo -e ""
}
# --- systems
case "$1" in
a) osname="Arch Linux"
ospart="/mnt/sda2"
osdev="/dev/sda2"
;;
b) osname="Arch32"
ospart="/opt/arch32"
osdev="/dev/sda1"
;;
X) echo "Nothing chosen. Exiting."
exit 1
;;
-h) usage
exit 1
;;
*) usage
exit 1
;;
esac
fs=$(fsck -N $osdev | awk 'FNR == 2 { gsub("fsck.", ""); print $5 }')
# ---
if [[ $UID -ne 0 ]]; then
sudo -p 'Enter root password to continue: ' bash $0 "$@"
exit $?
fi
echo -e "${cyel}Preparing to enter ${osname} ...${cres}"
# --- mount chroot partition
echo -e "Mounting $osname partition and system directories ..."
if [ ! -d ${ospart} ]; then
echo -e "Mount point $ospart doesn't exist. Creating:"
mkdir -pv "${ospart}"
fi
mntch=$(cat /proc/mounts | grep "${osdev}")
mntchex="$?"
# -- check if the filesystem is already mounted
if [ "$mntchex" -eq 0 ]; then
echo -e "${cred} $osdev already mounted:${cres}"
echo -e "$mntch"
else
echo -e "Mounting $ospart ..."
mount -t ${fs} ${osdev} ${ospart}
echo -e "${cgre}Done.${cres}"
fi
if [ "$?" -ne 0 ]; then
echo -e "${cred}Couldn't create $ospart. Exiting.${cres}"
exit 1
fi
# --- mount chroot filesystems
for dir in ${ospart}{/proc,/sys,/dev,/dev/pts}; do
if [ ! -d ${dir} ]; then
echo -e "Mount point $dir doesn't exist. Creating:"
mkdir -pv "${dir}"
if [ "$?" -ne 0 ]; then
echo -e "${cred}Couldn't create $dir. Exiting.${cres}"
exit 1
fi
fi
done
cd ${ospart}
mount -t proc proc proc/
mount -t sysfs sys sys/
mount -o bind /dev dev/
#mount -t devpts pts dev/pts/
sudo mount -o gid=5 -t devpts pts dev/pts
#mount -t devpts -o rw,nosuid,noexec,gid=5,mode=620,ptmxmode=000 devpts dev/pts
if [ $? -eq 0 ]; then
echo -e "${cgre}Done.${cres}"
fi
echo -e "Making host's network accessible in chroot ..."
if [ -f /etc/resolv.conf ]; then
cp -L /etc/resolv.conf etc/resolv.conf
if [ $? -eq 0 ]; then
echo -e "${cgre}Done.${cres}"
else
echo -e "${cred}resolv.conf couldn't be copied${cres}"
fi
fi
# --- additional steps
echo -e "Entering $osname ..."
echo -e ""
echo -e " After you have successfully entered the new environment,"
echo -e " you may want to set its variables. In order to do so,"
echo -e " issue the following commands:"
echo -e " source /etc/profile"
echo -e " export PS1='[$osname] \$PS1'"
echo -e ""
echo -e " In case you need to run chroot X server,"
echo -e " you should additionaly issue"
echo -e " xhost +"
echo -e " export DISPLAY=:0.0"
echo -e ""
echo -e " If necessary, mount mount the partitions you need."
echo -e ""
# --- get in
chroot . /usr/bin/bash
# --- exit the chroot environment and clean up
echo -e "${cyel}Leaving chroot ....${cres}"
echo -e "Unmounting system directories ..."
umount ${ospart}/{proc,sys,dev/pts,dev}
if [ $? -eq 0 ]; then
echo -e "${cgre}Done.${cres}"
fi
#echo -e "Unmounting chroot partition ..."
cd $HOME
#umount ${ospart}
#if [ $? -eq 0 ]; then
# echo -e "${cgre}Done.${cres}"
#fi
exit 0
|
JavaScript
|
UTF-8
| 523 | 3.09375 | 3 |
[] |
no_license
|
var divs = document.querySelectorAll(".imageDiv");
var num = 0;
function getImage() {
if (num===divs.length){
num=0;
}
divs[num].setAttribute("class", "appear imageDiv");
var max = divs.length - 1;
var previousNode = "";
if (num === 0) {//当这个等于0,最大下标是max
previousNode = divs[max];
} else {
previousNode = divs[num - 1];
}
previousNode.setAttribute("class", "disappear imageDiv");
num++;
}
setInterval(function(){
getImage();
},1000);
|
Java
|
UTF-8
| 1,798 | 2.890625 | 3 |
[] |
no_license
|
import javax.swing.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class GuiImageTest extends JFrame implements MouseListener,MouseMotionListener {
private JButton buttonArray[];
private Container c;
private ImageIcon blackIcon, whiteIcon, boardIcon;
public GuiImageTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("aiueo");
setSize(400,400);
c = getContentPane();
c.setLayout(null);
whiteIcon = new ImageIcon("White.jpg");
blackIcon = new ImageIcon("Black.jpg");
boardIcon = new ImageIcon("GreenFrame.jpg");
buttonArray = new JButton[5];
for(int i=0;i<5;i++){
buttonArray[i] = new JButton(boardIcon);
c.add(buttonArray[i]);
buttonArray[i].setBounds(i*45,10,45,45);
buttonArray[i].addMouseListener(this);
buttonArray[i].addMouseMotionListener(this);
buttonArray[i].setActionCommand(String.valueOf(i));
}
}
public static void main(String[] args) {
GuiImageTest gui = new GuiImageTest();
gui.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
System.out.println("aiueo");
JButton theButton = (JButton)e.getComponent();
String theArrayIndex = theButton.getActionCommand();
Icon theIcon = theButton.getIcon();
System.out.println(theIcon);
if(theIcon.equals(boardIcon)) {
theButton.setIcon(whiteIcon);
} else if (theIcon.equals(whiteIcon)) {
theButton.setIcon(blackIcon);
} else {
theButton.setIcon(boardIcon);
}
repaint();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
|
Java
|
UTF-8
| 2,253 | 4.375 | 4 |
[] |
no_license
|
/**
* Area Calculator
* https://programmingbydoing.com/a/area-calculator.html
* Write a program to calculate the area of four different geometric shapes: triangles, squares, rectangles, and circles.
* You must use functions.
* Your program should present a menu for the human to choose which shape to calculate, then ask them for the appropriate values (length, width, radius, etc.).
* Then it should pass those values to the appropriate function and display the resulting area.
*/
import java.util.Scanner;
public class AreaCalculator{
private static int area_triangle( int base, int height ){
return base * height / 2;
}
private static int area_rectangle( int length, int width ){
return length * width;
}
private static int area_square(int side){
return side * side;
}
private static double area_circle(double radius){
return Math.PI * Math.pow(radius, 2);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int shape = 0;
while(shape != 5){
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
System.out.println(" ");
System.out.println("1) Triangle \n2) Rectangle \n3) Circle \n4) Square \n5) Quit");
System.out.println("which shape: ");
shape = keyboard.nextInt();
if(shape == 1){
System.out.println("Base: ");
int base = keyboard.nextInt();
System.out.println("Height: ");
int height = keyboard.nextInt();
System.out.println("The area is " + area_triangle(base, height) + ".");
}
if(shape == 2){
System.out.println("Length: ");
int length = keyboard.nextInt();
System.out.println("Width: ");
int width = keyboard.nextInt();
System.out.println("The area is " + area_rectangle(length, width) + ".");
}
if(shape == 3){
System.out.println("Radius: ");
double radius = keyboard.nextInt();
System.out.println("The area is " + area_circle(radius) + ".");
}
if(shape == 4){
System.out.println("side: ");
int side = keyboard.nextInt();
System.out.println("The area is " + area_square(side) + ".");
}
if(shape == 5){
System.out.println("Goodbye");
}
}
}
}
|
Python
|
UTF-8
| 1,330 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
def validSolution(board):
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(9):
x = sorted(board[i])
if x != lst:
return False
w = [*zip(*board)]
for i in range(9):
x = sorted(w[i])
if x != lst:
return False
for i in range(0, 9, 3):
for j in range(0, 9, 3):
m = board[i][j:j + 3] + board[i + 1][j:j + 3] + board[i + 2][j:j + 3]
l = sorted(m)
if l != lst:
return False
return True
def validSolution2(board):
boxes = validate_boxes(board)
cols = validate_cols(board)
rows = validate_rows(board)
return boxes and cols and rows
def validate_boxes(board):
for i in range(0, 9, 3):
for j in range(0, 9, 3):
nums = board[i][j:j + 3] + board[i + 1][j:j + 3] + board[i + 2][j:j + 3]
if not check_one_to_nine(nums):
return False
return True
def validate_cols(board):
transposed = zip(*board)
for row in transposed:
if not check_one_to_nine(row):
return False
return True
def validate_rows(board):
for row in board:
if not check_one_to_nine(row):
return False
return True
def check_one_to_nine(lst):
check = range(1, 10)
return sorted(lst) == check
|
Shell
|
UTF-8
| 1,571 | 3.0625 | 3 |
[] |
no_license
|
#!/bin/bash
echo "#########################################################################"
echo File Name: runla.sh
echo Author: rehemanyidiresi
echo mail: rehemanyidiresi@novogene.com
echo Created Time: `ls -l|grep runla.sh |awk '{print $6,$7,$8}'`
echo "#########################################################################"
source /ALBNAS09/rhm/software/bashrc
scripts=/ALBNAS09/rhm/software/scripts
genome=$1
left=$2
right=$3
#motif=AAGCTT
motif=$4
clusterN=$5
qs="qsub -cwd -l vf=0G,p=0 -q plant.q -P aliyun -V "
path=`pwd`"/"
bwa index $genome
sh ${scripts}/work.shell $genome $left $right
#SYNTAX: make_bed_around_RE_site.pl <fasta> <motif> <range>
#fasta: A fasta file representing a genome (reference or draft assembly.)
#motif: A motif, typically a restriction site sequence (e.g., HindIII = AAGCTT, NcoI = CCATGG, Dpn1 = GATC).
#range: A number representing how many bp around the sequence to include. Recommend 500 based on Yaffe & Tanay, Nat.
mkdir breakfile
cd breakfile
sh ${scripts}/runbreak.sh $genome ${path}"01.bam/all.bam"
samtool faidx asm.cleaned.fasta &
make_bed_around_RE_site.pl asm.cleaned.fasta $motif 500 &
CountMotifsInFasta.pl asm.cleaned.fasta $motif &
wait
#samtools view -H breaked_filt.bam|cut -f2|awk -F ':' '{print $2}' > asm.cleaned.fasta.names
sh /ALBNAS09/rhm/software/scripts/RE_site.sh "asm.cleaned.fasta.counts_"`echo $motif|perl -pe 's/^//g'`".txt" "asm.cleaned.fasta.fai"
cd ..
mkdir la
cd la
python ${scripts}/autorun.py ${path}"breakfile/asm.cleaned.fasta" ${path}"breakfile/" $motif $clusterN `echo $qs|perl -pe 's/ /^/g'`
|
C#
|
UTF-8
| 3,177 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
/* Attributions
* Mike DePaul
* https://github.com/mdepaul/XConvert.git
* **/
using System;
using System.Collections.Generic;
using System.Text;
namespace MD.RandoCalrissian
{
/// <summary>
/// Conversion utilities as extention methods
/// </summary>
public static class XConvert
{
public static int ToInt32(this byte byteValue)
{
return Convert.ToInt32(byteValue);
}
public static string ToBase64String(this byte[] bytes)
{
return Convert.ToBase64String(bytes);
}
public static byte[] FromBase64String(this string input)
{
return Convert.FromBase64String(input);
}
public static string ToSafeBase64String(this byte[] bytes)
{
return ToBase64String(bytes).Replace("/", ".").Replace("+", "_").Replace("==", "--");
}
public static byte[] FromSafeBase64String(this string input)
{
return Convert.FromBase64String(input.Replace(".", "/").Replace("_", "+").Replace("--", "=="));
}
public static string ToHex(this byte[] bytes)
{
StringBuilder hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString().ToUpper();
}
public static byte[] FromHex(this string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
public static string Sort(this string value)
{
StringBuilder sb = new StringBuilder(value.Length);
SortedSet<char> set = GetSortedSet(value);
foreach (var item in set)
{
sb.Append(item);
}
return sb.ToString();
}
public static string Reverse(this string value)
{
StringBuilder sb = new StringBuilder("".PadRight(value.Length, ' '), value.Length);
int pos = value.Length - 1;
foreach (var theCharacter in value.ToCharArray())
{
sb[pos] = theCharacter;
pos--;
}
return sb.ToString();
}
private static SortedSet<char> GetSortedSet(string value)
{
SortedSet<char> sortedSet = new SortedSet<char>();
foreach (var theCharacter in value.ToCharArray())
{
sortedSet.Add(theCharacter);
}
return sortedSet;
}
/// <summary>
/// Encodes all the characters in the specified string into a sequence of bytes.
/// </summary>
/// <param name="value">The string </param>
/// <returns></returns>
public static byte[] GetBytes(this string value)
{
return Encoding.ASCII.GetBytes(value);
}
}
}
|
C++
|
GB18030
| 845 | 3.34375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//int main()
//{
// int *p=(int*)malloc(10*sizeof(int));
// if(p==NULL)
// printf("%s\n",strerror(errno));
// else
// {
// int i=0;
// for(i=0;i<10;i++)
// {
// *(p+i)=i;
// printf("%d ",*(p+i));
// }
// }
// free(p);//ֻmallocֶ̬ڴfree
// p=NULL;
//
// return 0;
//}
int main()
{
//ڴΪ10*sizeofint
int *p=(int*)calloc(10,sizeof(int)); //callocĿռֽڳʼΪ0
if(p==NULL) //ַһҪжpǷΪָ
printf("%s\n",strerror(errno));
else
{
int i=0;
for(i=0;i<10;i++)
printf("%d ",*(p+i));
}
free(p);
return 0;
}
//reallocڵ̬ڴռ
|
Ruby
|
UTF-8
| 1,542 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# This class will retreive some information according to param
module CorreosChile
require 'correos_chile/order'
require 'httparty'
require 'nokogiri'
def self.extract_useless_spaces(str)
composed_word = ''
partial_word = str.gsub(/[[:space:]]/, '')
length = partial_word.length
str.split(partial_word[length]).each_with_index do |word, i|
next if word.nil? || word.strip.gsub(/[[:space:]]/, '').empty?
composed_word += i + 1 == length ? word : "#{word} "
end
composed_word
end
def self.find(tracking_number)
form_url = 'http://seguimientoweb.correos.cl/ConEnvCorreos.aspx'
form_data = {
obj_key: 'Cor398-cc',
obj_env: tracking_number
}
response = HTTParty.post(form_url, body: form_data, options: { headers: { 'Content-Type' => 'application/x-www-form-urlencoded' } } )
doc = Nokogiri::HTML.parse(response)
return "The order doesn't exist" unless doc.css('.titulo').text.include?('Numero de envio')
attributes = shipping_info(doc)
Order.new(attributes)
end
def self.shipping_info(html_doc)
table = html_doc.css('.tracking')[0]
tr = table.css('tr')[1]
return "Website's structure has change" unless tr
tr_status = tr.css('td')[0].text.to_s.strip.gsub(/\A\p{Space}*/, '')
tr_datetime = tr.css('td')[1].text.to_s.strip.gsub(/\A\p{Space}*/, '')
{
status: extract_useless_spaces(tr_status).strip,
datetime: extract_useless_spaces(tr_datetime).strip
}
rescue
"Website's structure has change"
end
end
|
Python
|
UTF-8
| 493 | 4.96875 | 5 |
[] |
no_license
|
# Making For Loops
# Step 1: Use a for loop to print out each color in the list colors
colors = ["red", "orange", "blue", "green", "purple"]
# Step 2: There are 2 ways that you could solve step 1 in Python ... can you solve it the other way now? (Hint: If you used the keyword in last time, try using len() this time, or vice versa)
# Step 3: Create a list of names with three of your favorite people's names. Use a for loop to print out each name with " is awesome!" added after each name.
|
JavaScript
|
UTF-8
| 574 | 2.53125 | 3 |
[] |
no_license
|
function loaddashboard() {
document.getElementById("userName").innerHTML = localStorage.getItem("dbusername");
document.getElementById("role").innerHTML = localStorage.getItem("dbusertype");
disablelinks();
}
function disablelinks(){
// alert("disable links")
//document.getElementById("history").removeAttribute("href");
if(localStorage.getItem("dbusertype") === "admin"){
document.getElementById("change").removeAttribute("href");
}else if(localStorage.getItem("dbusertype") === "user"){
document.getElementById("review").removeAttribute("href");
}
}
|
Java
|
UTF-8
| 208 | 1.523438 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
package com.boloutaredoubeni.clamshell.apis.owm.models;
import com.google.gson.annotations.SerializedName;
/**
* Copyright 2016 Boloutare Doubeni
*/
public class Snow { @SerializedName("3h") public double volume; }
|
JavaScript
|
UTF-8
| 314 | 3.53125 | 4 |
[] |
no_license
|
/*function RandomListNode(x){
this.label = x;
this.next = null;
this.random = null;
}*/
function Clone (pHead) {
// write code here
if (pHead === null) return null
let newnode = new RandomListNode(pHead.label)
newnode.random = pHead.random
newnode.next = Clone(pHead.next)
return newnode
}
|
Python
|
UTF-8
| 7,071 | 2.71875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
Author: Deepak Kumar, 73217151
SDG: Good health and Well Being
"""
import numpy as np
import pandas as pd
import seaborn as sb
import matplotlib.pyplot as plt
import csv
#indicators = pd.read_csv('WDI_Data.csv');
infile = open('WDI_Data.csv','r');
csvdata = csv.reader(infile);
##------------------------ Maternal Mortality ratio(per 100,000 live births)----------
wc = 0;
headersData = [];
wy = [];
wd = [];
ssa = [];
sa = [];
mena = [];
eca = [];
eap = [];
hi = [];
lac = [];
for row in csvdata:
if(wc==0):
headersData = row;
wc=wc+1;
if (row[3]=="SH.STA.MMRT") and (row[0]=="World"):
wr = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="Sub-Saharan Africa"):
ssar = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="South Asia"):
sar = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="Middle East & North Africa"):
menar = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="Europe & Central Asia"):
ecar = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="East Asia & Pacific"):
eapr = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="High income"):
hir = row;
if (row[3]=="SH.STA.MMRT") and (row[0]=="Latin America & Caribbean"):
lacr = row;
for i in range(4,len(wr)):
if(wr[i] !="") and (ssar[i]!="") and (sar[i]!="") and (menar[i]!="") and (ecar[i]!="") and (eapr[i]!="") and (hir[i]!="") and (lacr[i]!=""):
wy.append(headersData[i]);
wd.append(float(wr[i]));
ssa.append(float(ssar[i]));
sa.append(float(sar[i]));
mena.append(float(menar[i]));
eca.append(float(ecar[i]));
eap.append(float(eapr[i]));
hi.append(float(hir[i]));
lac.append(float(lacr[i]));
sb.set_palette("bright")
sb.set_style("darkgrid")
sb.set_context("notebook",rc={"lines.linewidth":4.3})
fig = plt.figure(figsize=(20,10),dpi=300);
plt.plot(wy,wd,label="World Data")
plt.plot(wy,ssa,label="Sub-Saharan Africa")
plt.plot(wy,sa,label="South Asia")
plt.plot(wy,mena,label="Middle East and North Africa")
plt.plot(wy,eca,label="Europe and Central Asia")
plt.plot(wy,eap,label="East Asia and Pacific")
sb.set_context("notebook",rc={"lines.linewidth":2.7})
plt.plot(wy,hi,label="High Income")
plt.plot(wy,lac,label="Latin America & Caribbean")
plt.xlabel("Years")
plt.ylabel(wr[2])
plt.legend();
plt.title(wr[2] + "Vs Years")
fig.savefig('wbsdgghwb1.jpg',format='jpg')
infile.close();
##-------------- Adolescent fertility rate -----------------------------
infile = open('WDI_Data.csv','r');
csvdata = csv.reader(infile);
wy = [];
wd = [];
li = [];
lm = [];
um = [];
hi = [];
for row in csvdata:
if (row[3]=="SP.ADO.TFRT"):
if (row[0]=="World"):
wr = row;
if (row[0]=="Lower middle income"):
lmr = row;
if (row[0]=="Low income"):
lir = row;
if (row[0]=="Upper middle income"):
umr = row;
if (row[0]=="High income"):
hir = row;
for i in range(4,len(wr)):
if(wr[i] !="") and (lmr[i]!="") and (lir[i]!="") and (umr[i]!="") and (hir[i]!=""):
wy.append(headersData[i]);
wd.append(float(wr[i]));
lm.append(float(lmr[i]));
li.append(float(lir[i]));
um.append(float(umr[i]));
hi.append(float(hir[i]));
sb.set_palette("colorblind")
sb.set_style("darkgrid")
sb.set_context("notebook",rc={"lines.linewidth":4.3})
fig = plt.figure(figsize=(20,10),dpi=300);
plt.plot(wy,wd,label="World Data")
plt.plot(wy,lm,label="Lower middle income")
plt.plot(wy,li,label="Low income")
plt.plot(wy,um,label="Upper middle income")
plt.plot(wy,hi,label="High Income")
plt.xlabel("Years")
plt.ylabel(wr[2])
plt.legend();
plt.title(wr[2] + "Vs Years")
fig.savefig('wbsdgghwb2.jpg',format='jpg')
infile.close();
##------------- under five mortality rate -----------------------------------
infile = open('WDI_Data.csv','r');
csvdata = csv.reader(infile);
wy = [];
wd = [];
ssa = [];
sa = [];
mena = [];
eca = [];
eap = [];
hi = [];
lac = [];
for row in csvdata:
if (row[3]=="SH.DYN.MORT"):
if (row[0]=="World"):
wr = row;
if (row[0]=="Sub-Saharan Africa"):
ssar = row;
if (row[0]=="South Asia"):
sar = row;
if (row[0]=="Middle East & North Africa"):
menar = row;
if (row[0]=="Europe & Central Asia"):
ecar = row;
if (row[0]=="East Asia & Pacific"):
eapr = row;
if (row[0]=="High income"):
hir = row;
if (row[0]=="Latin America & Caribbean"):
lacr = row;
for i in range(4,len(wr)):
if(wr[i] !="") and (ssar[i]!="") and (sar[i]!="") and (menar[i]!="") and (ecar[i]!="") and (eapr[i]!="") and (hir[i]!="") and (lacr[i]!=""):
wy.append(headersData[i]);
wd.append(float(wr[i]));
ssa.append(float(ssar[i]));
sa.append(float(sar[i]));
mena.append(float(menar[i]));
eca.append(float(ecar[i]));
eap.append(float(eapr[i]));
hi.append(float(hir[i]));
lac.append(float(lacr[i]));
sb.set_palette("Set1")
sb.set_style("darkgrid")
sb.set_context("notebook",rc={"lines.linewidth":4.3})
fig = plt.figure(figsize=(20,10),dpi=300);
plt.plot(wy,wd,label="World Data")
plt.plot(wy,ssa,label="Sub-Saharan Africa")
plt.plot(wy,sa,label="South Asia")
plt.plot(wy,mena,label="Middle East and North Africa")
plt.plot(wy,eca,label="Europe and Central Asia")
plt.plot(wy,eap,label="East Asia and Pacific")
sb.set_context("notebook",rc={"lines.linewidth":2.7})
plt.plot(wy,hi,label="High Income")
plt.plot(wy,lac,label="Latin America & Caribbean")
plt.xlabel("Years")
plt.ylabel(wr[2])
plt.legend();
plt.title(wr[2] + "Vs Years")
fig.savefig('wbsdgghwb3.jpg',format='jpg')
infile.close();
##---------- Mortality coused by traffic Injury --------------------------
infile = open('WDI_Data.csv','r');
csvdata = csv.reader(infile);
wy = [];
wd = [];
li = [];
lm = [];
um = [];
hi = [];
for row in csvdata:
if (row[3]=="SH.STA.TRAF.P5"):
if (row[0]=="World"):
wr = row;
if (row[0]=="Lower middle income"):
lmr = row;
if (row[0]=="Low income"):
lir = row;
if (row[0]=="Upper middle income"):
umr = row;
if (row[0]=="High income"):
hir = row;
for i in range(4,len(wr)):
if(headersData[i]=="2013"):
wd=float(wr[i]);
lm=float(lmr[i]);
li=float(lir[i]);
um=float(umr[i]);
hi=float(hir[i]);
sb.set_style("darkgrid")
sb.set_context("notebook",rc={"lines.linewidth":2.3})
fig = plt.figure(figsize=(20,10),dpi=300);
xdata = ["Low income", "Lower middle income", "Upper middle income", "High income", "World"];
ydata = [li,lm,um,hi,wd];
sb.barplot(xdata,ydata)
plt.xlabel("Years")
plt.ylabel(wr[2])
plt.legend();
plt.title(wr[2] + " in 2013")
fig.savefig('wbsdgghwb4.jpg',format='jpg')
infile.close();
|
TypeScript
|
UTF-8
| 4,191 | 2.625 | 3 |
[] |
no_license
|
import { pb } from "./pb/scene";
interface Draco {
module: any;
}
let dracoDecoderType = {};
// This function loads a JavaScript file and adds it to the page. "path" is
// the path to the JavaScript file. "onLoadFunc" is the function to be called
// when the JavaScript file has been loaded.
function loadJavaScriptFile(path, onLoadFunc) {
const head = document.getElementsByTagName('head')[0];
const element = document.createElement('script');
element.type = 'text/javascript';
element.src = path;
if (onLoadFunc !== null)
element.onload = onLoadFunc;
head.appendChild(element);
}
function loadWebAssemblyDecoder(result: (value: Draco) => void) {
dracoDecoderType['wasmBinaryFile'] = 'draco_decoder.wasm';
const xhr = new XMLHttpRequest();
xhr.open('GET', './assets/protocols/draco_decoder.wasm', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
// For WebAssembly the object passed into DracoModule() must contain a
// property with the name of wasmBinary and the value must be an
// ArrayBuffer containing the contents of the .wasm file.
dracoDecoderType['wasmBinary'] = xhr.response;
createDecoderModule(result);
};
xhr.send(null)
}
let dracoModule: any;
function createDecoderModule(result: (value: Draco) => void) {
// draco_decoder.js or draco_wasm_wrapper.js must be loaded before
// DracoModule is created.
if (typeof dracoDecoderType === 'undefined')
dracoDecoderType = {};
let moduleLoaded = false;
dracoDecoderType['onModuleLoaded'] = () => {
moduleLoaded = true;
if (dracoModule) {
result({module: dracoModule});
}
};
dracoModule = (window as any).DracoDecoderModule(dracoDecoderType);
if (moduleLoaded) {
result({module: dracoModule});
}
}
// This function will test if the browser has support for WebAssembly. If it
// does it will download the WebAssembly Draco decoder, if not it will download
// the asmjs Draco decoder.
export function loadDracoDecoder() {
return new Promise<Draco>(resolver => {
if (dracoModule) {
resolver({module: dracoModule});
} else if (typeof (window as any).WebAssembly !== 'object') {
// No WebAssembly support. DracoModule must be called with no parameters
// or an empty object to create a JavaScript decoder.
loadJavaScriptFile('./assets/protocols/draco_decoder.js', _ => createDecoderModule(resolver));
} else {
loadJavaScriptFile('./assets/protocols/draco_wasm_wrapper.js', _ => loadWebAssemblyDecoder(resolver));
}
})
}
export function decodeMesh(decoderModule, mesh: pb.Geometry.IGrid) {
const buffer = new decoderModule.DecoderBuffer();
buffer.Init(mesh.draco, mesh.draco.length);
const decoder = new decoderModule.Decoder();
const geometryType = decoder.GetEncodedGeometryType(buffer);
if (geometryType === decoderModule.TRIANGULAR_MESH) {
let dracoGeometry = new decoderModule.Mesh();
decoder.DecodeBufferToMesh(buffer, dracoGeometry);
let numFaces = dracoGeometry.num_faces();
mesh.index = [];
let ia = new decoderModule.DracoInt32Array();
for (let i = 0; i < numFaces; ++i) {
decoder.GetFaceFromMesh(dracoGeometry, i, ia);
mesh.index.push(ia.GetValue(0), ia.GetValue(1), ia.GetValue(2));
}
decoderModule.destroy(ia);
let loadAttribute = (id) => {
let posAttId = decoder.GetAttributeId(dracoGeometry, id);
let posAttribute = decoder.GetAttribute(dracoGeometry, posAttId);
let numComponents = posAttribute.num_components();
let numPoints = dracoGeometry.num_points();
let numValues = numPoints * numComponents;
let attributeData = new decoderModule.DracoFloat32Array();
decoder.GetAttributeFloatForAllPoints(dracoGeometry, posAttribute, attributeData);
let data: number[] = [];
for (let i = 0; i < numValues; i++) {
data.push(attributeData.GetValue(i));
}
decoderModule.destroy(attributeData);
return data;
}
mesh.position = loadAttribute(decoderModule.POSITION);
mesh.normal = loadAttribute(decoderModule.NORMAL);
mesh.texture = loadAttribute(decoderModule.TEX_COORD);
return dracoGeometry;
}
}
|
C++
|
UTF-8
| 999 | 3.15625 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
#define FILE "6_2_text-1.txt"
int main() {
char ch;
bool activeScript = false; //Ik gebruik een array met 2 ofstreams, 0 en 1. Ik gebruik een bool om tussen deze twee te wisselen.
std::ifstream in_stream;
in_stream.open(FILE);
if (!in_stream)
{
std::cout << "Kan geen .txt bestand vinden..." << std::endl;
exit(1);
}
std::ofstream out_stream[2];
out_stream[0].open("6_2_text-2.txt");
if (!out_stream[0])
{
std::cout << "Kan geen .txt bestand openen..." << std::endl;
exit(1);
}
out_stream[1].open("6_2_text-3.txt");
if (!out_stream[1])
{
std::cout << "Kan geen .txt bestand openen..." << std::endl;
exit(1);
}
std::noskipws(in_stream);
while (!in_stream.eof())
{
in_stream >> ch;
if (ch == '.')
{
activeScript = !activeScript; // Als er een '.' gevonden veranderd het active script door 0 naar 1 en 1 naar 0 te veranderen met !activescript
}
out_stream[activeScript] << ch;
}
return 0;
}
|
Java
|
UTF-8
| 2,682 | 2.5 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
Copyright (C) 2013-2015 The Open University
Copyright (C) 2017 Simon Butler
SPDX-FileCopyrightText: 2013-2015 The Open University
SPDX-FileCopyrightText: 2017 Simon Butler
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package uk.ac.open.crc.nominal.information;
import java.util.ArrayList;
import java.util.List;
/**
* Summarises information about abbreviations in a name. Indicates where
* recognised abbreviations are found in the name
*/
public class AbbreviationSummaryInformation extends IdentifierInformation {
private final List<Boolean> isAbbreviationList;
private final List<Integer> abbreviationIndices;
/**
* Creates a summary of the abbreviations found in a name's tokens.
* @param informationList a list of token abbreviation objects
*/
public AbbreviationSummaryInformation(
final List<AbbreviationInformation> informationList ) {
super( InformationClassification.ABBREVIATION_SUMMARY );
this.isAbbreviationList = new ArrayList<>();
this.abbreviationIndices = new ArrayList<>();
for ( int i = 0; i < this.isAbbreviationList.size(); i++ ) {
AbbreviationInformation information = informationList.get( i );
this.isAbbreviationList.add( information.isCorrect() );
if ( information.isCorrect() ) {
this.abbreviationIndices.add( i );
}
}
informationList.stream()
.forEach( information -> this.isAbbreviationList.add( information.isCorrect() ) );
}
@Override
public boolean isCorrect() {
// there is really no notion of correctness, other than the
// abbreviations being recognised
throw new UnsupportedOperationException(
"No notion of correctness for AbbreviationSummaryInformation" );
}
/**
* A list of indices of tokens containing a known abbreviation.
* @return a list which is empty if there are no abbreviations in the name
*/
public List<Integer> abbreviationIndices() {
return this.abbreviationIndices;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.