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
568
2.84375
3
[]
no_license
#13 : Red / 19 : Green / 26 : Blue , led RGB를 번갈아 키는 실습 import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(13,GPIO.OUT) #Red GPIO.setup(19,GPIO.OUT) #Green GPIO.setup(26,GPIO.OUT) #Blue try: while True: GPIO.output(13,True) time.sleep(0.5) GPIO.output(13,False) GPIO.output(19,True) time.sleep(0.5) GPIO.output(19,False) GPIO.output(26,True) time.sleep(0.5) GPIO.output(26,False) except KeyboardInterrupt: GPIO.cleanup() finally: GPIO.cleanup()
JavaScript
UTF-8
2,553
3.453125
3
[]
no_license
// from data.js ufo_data = data; // Use d3 to create a bootstrap striped table var table = d3.select("table"); // Use d3 to create a bootstrap striped table...This is already done in html file but is a good practice to have this piece of code // http://getbootstrap.com/docs/3.3/css/#tables-striped table.attr("class", "table table-striped"); // Create a row every time the function is called function create_row(){ var tbody = d3.select('#tbody'); var row = tbody.append('tr'); return row; } // Fills the table with ufo_data function fill_table(_data){ for (var i = 0; i < _data.length; i++){ // Calls create_row function to create a single row row = create_row() //append elements to each column row.append("td").text(_data[i].datetime); row.append("td").text(_data[i].city.replace( /\b./g, function(a){ return a.toUpperCase(); } )); row.append("td").text(_data[i].state.toUpperCase()); row.append("td").text(_data[i].country.toUpperCase()); row.append("td").text(_data[i].shape.toUpperCase()); row.append("td").text(_data[i].durationMinutes); row.append("td").text(_data[i].comments); } } // Erase data on table once the filter_button clicked function erase_table(){ // Remove elements in table before populating filtered data table = d3.select("#tbody") rows = table.selectAll("tr").remove(); } // Checks if date belongs to datetime values in ufo_data object. Returns true or false. function date_check(date){ for (var i = 0; i < ufo_data.length; i++){ if (ufo_data[i].datetime === date){ return true; } } return false; } var button = document.getElementById("filter-btn"); var input = document.getElementById("datetime"); //fills the table based on input date. if date is not valid, alerts user and provides list of available dates. button.addEventListener("click", function() { if(input.value.length > 0 && date_check(input.value)) { erase_table(); var filtered_data = ufo_data.filter(function(_data) { return _data.datetime === input.value; }); fill_table(filtered_data); } else { var available_dates = ufo_data.map(item => item.datetime).filter((value, index, self) => self.indexOf(value) === index) // alert_str = 'The date is not valid. Please select the available date. Available dates are {}'.format(available_dates); alert("Your input date is not present in our database. Please choose from available dates below: \n" + available_dates.join("\n")); } }) // Call the fill table function first time when the page is loaded. fill_table(ufo_data);
C++
UTF-8
1,777
2.6875
3
[ "MIT" ]
permissive
#include "WebNotificationEngine.h" #include "DHASLogging.h" #include <sstream> // This is used for Server Sent Events WebNotificationEngine::WebNotificationEngine() { pthread_mutex_init(&mSocketListLock,0); } WebNotificationEngine::~WebNotificationEngine() { pthread_mutex_destroy(&mSocketListLock); } void WebNotificationEngine::sendData(int socket, const std::string& data) { std::stringstream payload; payload << std::hex << (data.size()+2) << "\r\n" << data << "\n\n\r\n"; send(socket,payload.str().c_str(),payload.str().size(),0); } void WebNotificationEngine::activateSubscription(int socket) { pthread_mutex_lock(&mSocketListLock); if (mSocketList.find(socket) != mSocketList.end()) { mSocketList[socket] = true; } pthread_mutex_unlock(&mSocketListLock); sendData(socket,"retry: 1000"); } void WebNotificationEngine::subscribe(int socket) { LOG("A client is subscribing to notifications "<<socket); pthread_mutex_lock(&mSocketListLock); mSocketList[socket]= false; pthread_mutex_unlock(&mSocketListLock); } void WebNotificationEngine::unsubscribe(int socket) { pthread_mutex_lock(&mSocketListLock); if (mSocketList.find(socket) != mSocketList.end()) { mSocketList.erase(socket); LOG("A client is unsubscribing to notifications "<<socket); } pthread_mutex_unlock(&mSocketListLock); } void WebNotificationEngine::notifyEvent(const Dumais::JSON::JSON& json) { std::string jsonEvent = json.stringify(false); std::string st = "data: "; st += jsonEvent; for (std::map<int,bool>::iterator it = mSocketList.begin(); it!=mSocketList.end();it++) { if (it->second == true) { sendData(it->first,st); } } }
C#
UTF-8
487
2.59375
3
[]
no_license
using System; using System.ComponentModel.DataAnnotations; namespace BattleshipContestFunc { public class AbsoluteUriAttribute : ValidationAttribute { public AbsoluteUriAttribute() { } public override bool IsValid(object? objValue) { if (objValue == null) return true; if (objValue is string value) return value == string.Empty || Uri.TryCreate(value, UriKind.Absolute, out var _); return false; } } }
Java
UTF-8
3,021
2.375
2
[ "Apache-2.0" ]
permissive
package com.contentful.tea.java.services.http; import com.contentful.tea.java.services.contentful.Contentful; import com.contentful.tea.java.services.settings.Settings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import static com.contentful.tea.java.services.http.Constants.EDITORIAL_FEATURES_DISABLED; import static com.contentful.tea.java.services.http.Constants.EDITORIAL_FEATURES_ENABLED; @Component public class SessionParser { private static final int TIME_48_HOURS = 48 * 60 * 60; @Autowired @SuppressWarnings("unused") private Contentful contentful; @Autowired @SuppressWarnings("unused") private Settings settings; private final Map<String, Manipulator> manipulatorsByNameMap; public SessionParser() { manipulatorsByNameMap = new HashMap<>(); manipulatorsByNameMap.put(Constants.NAME_SPACE_ID, new Manipulator<String>() { @Override public String get() { return contentful.getSpaceId(); } @Override public void set(String value) { contentful.setSpaceId(value); } }); manipulatorsByNameMap.put(Constants.NAME_DELIVERY_TOKEN, new Manipulator<String>() { @Override public String get() { return contentful.getDeliveryAccessToken(); } @Override public void set(String value) { contentful.setDeliveryAccessToken(value); } }); manipulatorsByNameMap.put(Constants.NAME_PREVIEW_TOKEN, new Manipulator<String>() { @Override public String get() { return contentful.getPreviewAccessToken(); } @Override public void set(String value) { contentful.setPreviewAccessToken(value); } }); manipulatorsByNameMap.put(Constants.NAME_EDITORIAL_FEATURES, new Manipulator<String>() { @Override public String get() { return settings.areEditorialFeaturesEnabled() ? EDITORIAL_FEATURES_ENABLED : EDITORIAL_FEATURES_DISABLED; } @Override public void set(String value) { settings.setEditorialFeaturesEnabled(value != null && value.toLowerCase().equals(EDITORIAL_FEATURES_ENABLED)); } }); } public void loadFromSession(HttpSession session) { final Enumeration<String> names = session.getAttributeNames(); for (; names.hasMoreElements(); ) { final String name = names.nextElement(); final Manipulator manipulator = manipulatorsByNameMap.get(name); if (manipulator != null) { final Object value = session.getAttribute(name); manipulator.set(value); } } session.setMaxInactiveInterval(TIME_48_HOURS); } public void saveToSession(HttpSession session) { manipulatorsByNameMap .keySet() .forEach(name -> session.setAttribute(name, manipulatorsByNameMap.get(name).get())); } interface Manipulator<T> { T get(); void set(T value); } }
Markdown
UTF-8
565
2.5625
3
[]
no_license
# API_Project NASA APIs used: MARS MAAS & APOD (Astronomy Picture Of The Day) Project title- NASAPI Using the NASA {MAAS} API and the APOD API This project is a fully functional web application that has user inputs which will show information from JPLs Mars Rovers Curiosity, Spirit, and Opportunity. The web app also contains a music player from a javascript library API to create an interactive user experience. Lastly, using the APOD Api We want to have a user input of any date they want in the format of yyyy-mm-dd to see NASAs Astronomy Picture Of The Day.
Python
UTF-8
621
3.5
4
[]
no_license
from Binary_Trees_utils import binary_tree_to_string, equal_binary_trees class BinaryTreeNode: def __init__(self, data=None, left=None, right=None, size=None): self.data = data self.left = left self.right = right self.size = size def __eq__(self, other): return equal_binary_trees(self, other) def __repr__(self): return str(binary_tree_to_string(self)) def __str__(self): return self.__repr__() b = BinaryTreeNode(1, BinaryTreeNode(2, BinaryTreeNode(5)), BinaryTreeNode(3)) #print(b) #print(b.left.right) #print(b.right)
C#
UTF-8
4,415
2.953125
3
[]
no_license
using Microsoft.Kinect; using System; using System.Windows.Media.Imaging; using System.Windows.Controls; using System.Windows; using System.Windows.Media; namespace Kinect_Recorder { class DepthRenderer { #region instance variables /// <summary> /// Size of the RGB pixel in the bitmap /// </summary> private readonly int cbytesPerPixel = (PixelFormats.Bgr32.BitsPerPixel + 7) / 8; /// <summary> /// Active Kinect sensor /// </summary> private KinectSensor kinectSensor = null; /// <summary> /// Reader for depth frames /// </summary> private DepthFrameReader reader = null; /// <summary> /// Bitmap to display /// </summary> private WriteableBitmap bitmap = null; /// <summary> /// Intermediate storage for receiving frame data from the sensor /// </summary> public ushort[] frameData = null; /// <summary> /// Intermediate storage for frame data converted to color /// </summary> private byte[] pixels = null; /// <summary> /// Image that will view depth data /// </summary> private Image Image; #endregion /// <summary> /// Gets the bitmap to display /// </summary> public ImageSource ImageSource { get { return bitmap; } } public DepthRenderer(Image image, KinectSensor sensor) { // Set the Kinect sensor kinectSensor = sensor; FrameDescription frameDescription = kinectSensor.DepthFrameSource.FrameDescription; // open the reader for the depth frames reader = kinectSensor.DepthFrameSource.OpenReader(); // allocate space to put the pixels being received and converted frameData = new ushort[frameDescription.Width * frameDescription.Height]; pixels = new byte[frameDescription.Width * frameDescription.Height * cbytesPerPixel]; // create the bitmap to display bitmap = new WriteableBitmap(frameDescription.Width, frameDescription.Height, 96.0, 96.0, PixelFormats.Bgr32, null); // Initialize the image Image = image; // Set the image we display to point to the bitmap where we'll put the image data Image.Source = bitmap; } public void RenderDepthFrame(DepthFrameArrivedEventArgs e) { DepthReader_FrameArrived(e); } private void DepthReader_FrameArrived(DepthFrameArrivedEventArgs e) { DepthFrameReference frameReference = e.FrameReference; try { DepthFrame frame = frameReference.AcquireFrame(); if (frame != null) { // DepthFrame is IDisposable using (frame) { FrameDescription frameDescription = frame.FrameDescription; // verify data and write the new depth frame data to the display bitmap if (((frameDescription.Width * frameDescription.Height) == frameData.Length) && (frameDescription.Width == bitmap.PixelWidth) && (frameDescription.Height == bitmap.PixelHeight)) { // Copy the pixel data from the image to a temporary array frame.CopyFrameDataToArray(frameData); // Get the min and max reliable depth for the current frame ushort minDepth = frame.DepthMinReliableDistance; ushort maxDepth = frame.DepthMaxReliableDistance; // Convert the depth to RGB int colorPixelIndex = 0; for (int i = 0; i < frameData.Length; ++i) { // Get the depth for this pixel ushort depth = frameData[i]; // To convert to a byte, we're discarding the most-significant // rather than least-significant bits. // We're preserving detail, although the intensity will "wrap." // Values outside the reliable depth range are mapped to 0 (black). byte intensity = (byte)(depth >= minDepth && depth <= maxDepth ? depth : 0); // Write out blue byte pixels[colorPixelIndex++] = intensity; // Write out green byte pixels[colorPixelIndex++] = intensity; // Write out red byte pixels[colorPixelIndex++] = intensity; // We're outputting BGR, the last byte in the 32 bits is unused so skip it // If we were outputting BGRA, we would write alpha here. ++colorPixelIndex; } bitmap.WritePixels( new Int32Rect(0, 0, frameDescription.Width, frameDescription.Height), pixels, frameDescription.Width * cbytesPerPixel, 0); } } } } catch (Exception) { // ignore if the frame is no longer available } } } }
JavaScript
UTF-8
602
2.53125
3
[]
no_license
import axios from 'axios' const GET_NOTIFICATIONS = 'GET_NOTIFICATIONS' export function getNotifications(userId) { return { type: GET_NOTIFICATIONS, payload: axios .get(`/api/notification/${userId}`) .then(res => { return res.data }) .catch(err => { console.log('err', err) return [] }), } } const initialState = [] export default function notificationsReducer(state = initialState, action) { switch (action.type) { case `${GET_NOTIFICATIONS}_FULFILLED`: return [...action.payload] default: return state } }
C++
UTF-8
3,128
2.96875
3
[]
no_license
#include "Mesh.h" #if BUILD_DIRECTX #include "VBO_DX.h" #endif #if BUILD_OPENGL #include "VBO_GL.h" #endif #include "Vector4.h" #include <iostream> #include <fstream> using namespace std; /******************************************************************************************************************/ Mesh::Mesh() : _locked(false), _vbo(NULL) { } /******************************************************************************************************************/ Mesh::~Mesh() { delete _vbo; _vbo = NULL; } /******************************************************************************************************************/ bool Mesh::AddVertex(Vertex v) { if (!_locked) { _vertices.push_back(v); return true; } else { return false; } } /******************************************************************************************************************/ bool Mesh::DeleteVertex(int i) { if (!_locked) { _vertices.erase(_vertices.begin() + i); return true; } else { return false; } } /******************************************************************************************************************/ bool Mesh::Clear() { if (!_locked) { _vertices.clear(); return true; } return false; } /******************************************************************************************************************/ void Mesh::Reset() { delete _vbo; _vbo = NULL; _locked = false; } /******************************************************************************************************************/ VBO* Mesh::CreateVBO(Renderer* renderer) { _locked = true; #if BUILD_DIRECTX _vbo = new VBO_DX(); #else _vbo = new VBO_GL(); #endif _vbo->Create(renderer, _vertices.data(), NumVertices()); return _vbo; } /******************************************************************************************************************/ float Mesh::CalculateMaxSize() { float max = 0; for (int i = 0; i < NumVertices(); i++) { Vertex& v = _vertices[i]; Vector4 vec(v.x, v.y, v.z, 1); float dist = vec.lengthSquared(); if (dist > max) { max = dist; } } return sqrt(max); } /******************************************************************************************************************/ bool Mesh::LoadFromFile(std::string filename) { ifstream in(filename); if (in) { int numVertices; in >> numVertices; for (int i = 0; i < numVertices; i++) { Vertex v; in >> v.x; in >> v.y; in >> v.z; in >> v.r; in >> v.g; in >> v.b; in >> v.a; AddVertex(v); } return true; } else { // Could not open file return false; } } /******************************************************************************************************************/ bool Mesh::LoadFromStream(std::ifstream& in) { int numVertices; in >> numVertices; for (int i = 0; i < numVertices; i++) { Vertex v; in >> v.x; in >> v.y; in >> v.z; in >> v.r; in >> v.g; in >> v.b; in >> v.a; AddVertex(v); } return true; } /******************************************************************************************************************/
C#
UTF-8
167
2.71875
3
[]
no_license
#pragma warning disable 1998 public async Task<string> PullText()() #pragma warning restore 1998 { return Task.Run(() => "hello world"); }
Python
UTF-8
384
3.3125
3
[]
no_license
# function drawLine(p1, p2, varargin) # %DRAWLINE Draws a line from point p1 to point p2 # % DRAWLINE(p1, p2) Draws a line from point p1 to point p2 and holds the # % current figure # # plot([p1(1) p2(1)], [p1(2) p2(2)], varargin{:}); # # end import matplotlib.pyplot as plt def drawLine(p1, p2): plt.plot( (p1[0], p2[0]), (p1[1], p2[1]), 'k-' )
Java
UTF-8
2,443
2.171875
2
[]
no_license
package com.group6.service.impl; import com.group6.service.OBSService; import com.obs.services.ObsClient; import com.obs.services.model.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.util.List; /** * @author weirwei 2021/1/8 22:54 */ @Service public class OBSServiceImpl implements OBSService { @Value("${obs.sust-cloud.endpoint}") private String endPoint; @Value("${obs.sust-cloud.ak}") private String ak; @Value("${obs.sust-cloud.sk}") private String sk; @Value("${obs.sust-cloud.bucketname}") private String bucketName; /** * 创建 ObsClient 实例 */ private ObsClient obsClient = null; private ObsClient getInstance() { if (obsClient == null) { return new ObsClient(ak, sk, endPoint); } return obsClient; } @Override public PutObjectResult put(String objectKey, File file) { ObsClient obsClient = getInstance(); return obsClient.putObject(bucketName, objectKey, file); } @Override public ObsObject get(String objectKey) { ObsClient obsClient = getInstance(); boolean flag = obsClient.doesObjectExist(bucketName, objectKey); if (flag) { return obsClient.getObject(bucketName, objectKey); } return null; } @Override public List<ObsObject> getAllFileInfo() throws IOException { ObsClient obsClient = getInstance(); ObjectListing objectList = obsClient.listObjects(bucketName); List<ObsObject> list = objectList.getObjects(); obsClient.close(); return list; } @Override public String share(String objectKey, long expires) throws IOException { ObsClient obsClient = getInstance(); // 300 有效时间 TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expires); request.setBucketName(bucketName); request.setObjectKey(objectKey); TemporarySignatureResponse response = obsClient.createTemporarySignature(request); obsClient.close(); return response.getSignedUrl(); } @Override public DeleteObjectResult delete(String objectName) { ObsClient obsClient = getInstance(); return obsClient.deleteObject(bucketName, objectName); } }
C#
UTF-8
2,354
2.59375
3
[]
no_license
using MC_Server_Test.Network; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace MC_Server_Test.Minecraft { public class MinePacket : DataBuffer { private const int ReservedHeaderBytes = 24; public override int Offset { get { return base.Offset - ReservedHeaderBytes; } set { base.Offset = ReservedHeaderBytes + value; } } public override int Length { get { return base.Length - ReservedHeaderBytes; } } private int _headerBytesCount = 0; private OutHeader _header; private bool _isDirty = true; public MinePacket(OutHeader header) { Reset(header); } protected override void OnDataChanged() { _isDirty = true; } public override void Reset() { base.Reset(); var bytes = new byte[ReservedHeaderBytes]; Write(bytes, 0, bytes.Length); } public void Reset(OutHeader header) { _header = header; Reset(); } public override void Remove(int bytes) { throw new InvalidOperationException("Cannot perform remove on a MinePacket instance."); } public void Update() { var bytes = new byte[20]; var headerVarIntLength = GetVarIntBytes((int)_header, bytes, 0); var lengthVarIntLength = GetVarIntBytes(Length + headerVarIntLength, bytes, 10); Buffer.BlockCopy(bytes, 0, InternalBuffer, ReservedHeaderBytes - headerVarIntLength, headerVarIntLength); Buffer.BlockCopy(bytes, 10, InternalBuffer, ReservedHeaderBytes - headerVarIntLength - lengthVarIntLength, lengthVarIntLength); _headerBytesCount = lengthVarIntLength + headerVarIntLength; } public void Send(User user) { if (_isDirty) { Update(); _isDirty = false; } user.Socket.Send( InternalBuffer, ReservedHeaderBytes - _headerBytesCount, Length + _headerBytesCount, SocketFlags.None); } } }
TypeScript
UTF-8
810
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import { RicardianContractRenderError } from './RicardianContractRenderError' describe('RicardianContractRenderError', () => { it('constructs message from string properly', () => { const expected = 'Danger, Will Robinson!' const error = new RicardianContractRenderError(expected) expect(error.message).toEqual(expected) expect(error.tag).toBeNull() expect(error.reason).toBeNull() }) it('constructs message from HtmlValidationErrorArgs properly', () => { const tag = 'body' const reason = `"${tag}" tag is present` const error = new RicardianContractRenderError({ tag, reason }) expect(error.message) .toEqual(`Invalid or unexpected HTML found near "${tag}" tag. Reason: ${reason}`) expect(error.tag).toEqual(tag) expect(error.reason).toEqual(reason) }) })
JavaScript
UTF-8
7,432
2.921875
3
[ "MIT" ]
permissive
/** * Board viewer UI generator * * Copyright (c) 2016-2017, Evan Moritz. * Licensed under the MIT license. See accompanying LICENSE file for terms. */ define( ["board"], function(Board) { "use strict"; var WIDTH_MAX = 30; var HEIGHT_MAX = 24; var Viewer = function(form, grid, output, board) { var painters = []; drawOptions(painters, form, board); drawGrid(painters, grid, board); drawImage(painters, output, board); repaint(painters); }; function repaint(painters) { painters.forEach(function(painter) { painter(); }); }; function drawOptions(painters, container, board) { container.appendChild((function() { var div = document.createElement("DIV"); var label = document.createElement("LABEL"); label.appendChild(document.createTextNode("Smily:")); div.appendChild(label); Board.smilys.forEach(function(smily) { var radio = document.createElement("INPUT"); radio.type = "radio"; radio.checked = smily === board.smily; radio.name = "smilys"; radio.onclick = function() { board.smily = smily; repaint(painters); }; div.appendChild(radio); var image = document.createElement("IMG"); image.src = "images/smily-" + smily + ".png"; image.alt = smily; image.title = smily; image.onclick = function() { radio.click(); }; image.setAttribute("smily", ""); div.appendChild(image); }); return div; })()); container.appendChild((function() { var div = document.createElement("DIV"); var label = document.createElement("LABEL"); label.appendChild(document.createTextNode("Fill:")); div.appendChild(label); var normal = document.createElement("BUTTON"); normal.appendChild(document.createTextNode("Normal")); normal.onclick = function() { board.fill(Board.NORMAL); board.data = Board.NORMAL; repaint(painters); }; div.appendChild(normal); var empty = document.createElement("BUTTON"); empty.appendChild(document.createTextNode("Empty")); empty.onclick = function() { board.fill(Board.EMPTY); board.data = Board.EMPTY; repaint(painters); }; div.appendChild(empty); return div; })()); container.appendChild((function() { var div = document.createElement("DIV"); var label = document.createElement("LABEL"); label.appendChild(document.createTextNode("Use frame?")); div.appendChild(label); var checkbox = document.createElement("INPUT"); checkbox.type = "checkbox"; checkbox.checked = board.frame; checkbox.onclick = function() { board.frame = checkbox.checked; repaint(painters); }; div.appendChild(checkbox); return div; })()); drawNumberEditor(container, painters, "mines", board, 0, 999); drawNumberEditor(container, painters, "time", board, 0, 999); drawNumberEditor(container, painters, "width", board, 9, WIDTH_MAX); drawNumberEditor(container, painters, "height", board, 9, HEIGHT_MAX); } function drawNumberEditor(container, painters, name, board, min, max) { var div = document.createElement("DIV"); div.className = "number-editor"; var label = document.createElement("LABEL"); label.appendChild(document.createTextNode(name[0].toUpperCase() + name.slice(1) + ':')); div.appendChild(label); var textbox = document.createElement("INPUT"); textbox.type = "number"; textbox.value = board[name]; textbox.max = "" + max; textbox.min = "" + min; textbox.onfocus = function() { this.select(); }; textbox.onchange = function() { if (this.value < min) { this.value = min; } else if (this.value > max) { this.value = max; } board[name] = this.value; repaint(painters); }; div.appendChild(textbox); container.appendChild(div); } function drawGrid(painters, container, board) { var table = document.createElement("TABLE"); var tbody = drawGridBase(painters, board); table.appendChild(tbody); container.appendChild(table); painters.push(function() { table.removeChild(tbody); tbody = drawGridBase(painters, board); table.appendChild(tbody); }); } function drawGridBase(painters, board) { var tbody = document.createElement("TBODY"); for (var y = 0; y < board.height; ++y) { var tr = document.createElement("TR"); tbody.appendChild(tr); for (var x = 0; x < board.width; ++x) { var td = document.createElement("TD"); tr.appendChild(td); var entry = drawGridEditor(painters, x, y, board); td.appendChild(entry); } } return tbody; } function drawGridEditor(painters, x, y, board) { var input = document.createElement("INPUT"); input.type = "textbox"; input.maxlength = "1"; input.minlength = "1"; input.value = board.getCell(x, y); input.style.width = "1em"; input.onfocus = function() { this.select(); }; input.onchange = function() { if (Board.valid[this.value] !== true) { this.value = Board.EMPTY; } board.setCell(x, y, this.value); repaint(painters); }; return input; } function drawImage(painters, container, board) { var image = document.createElement("IMG"); image.src = generateUrl(board); image.alt = "Board"; container.appendChild(image); painters.push(function() { image.src = generateUrl(board); }); } function generateUrl(board) { return "generator.php?board=" + board.encode(); } return Viewer; } );
JavaScript
UTF-8
3,163
2.671875
3
[ "ISC" ]
permissive
/* global describe, it */ const CovSource = require('../lib/source') require('tap').mochaGlobals() require('should') describe('Source', () => { describe('relativeToOffset', () => { it('returns an offset in the middle of a file', () => { const sourceRaw = `const a = 99 const b = 33 for (var i = 0; i < 99; i++) { console.info('hello world') } return a` const source = new CovSource(sourceRaw, 0) source.relativeToOffset(3, 8).should.equal(42) }) it('returns EOF if line is greater than lines in file', () => { const sourceRaw = ` const a = 99` const source = new CovSource(sourceRaw, 0) source.relativeToOffset(5, 8).should.equal(21) }) it('returns end of line, if column offset greater than line length', () => { const sourceRaw = `a const a = 99` const source = new CovSource(sourceRaw, 0) source.relativeToOffset(2, 50).should.equal(22) source.relativeToOffset(1, Infinity).should.equal(1) }) it('returns empty object for out of range params', () => { const sourceRaw = '' const source = new CovSource(sourceRaw, 0) source.offsetToOriginalRelative(undefined, Infinity, Infinity).should.deepEqual({}) }) }) describe('ignore', () => { it('ignores the next line if /* c8 ignore next */ is on its own line', () => { const sourceRaw = ` const a = 33 /* c8 ignore next */ const a = 99 ` const source = new CovSource(sourceRaw, 0) source.lines[1].ignore.should.equal(false) source.lines[2].ignore.should.equal(true) source.lines[3].ignore.should.equal(true) }) it('ignores the next N lines if /* c8 ignore next N */ is used', () => { const sourceRaw = ` /* c8 ignore next 2 */ const a = 33 const a = 99 ` const source = new CovSource(sourceRaw, 0) source.lines[1].ignore.should.equal(true) source.lines[2].ignore.should.equal(true) source.lines[3].ignore.should.equal(true) }) it('ignores a line that contains /* c8 ignore next */', () => { const sourceRaw = ` const a = foo ? true /* c8 ignore next */ : false const b = 99 ` const source = new CovSource(sourceRaw, 0) source.lines[1].ignore.should.equal(true) source.lines[2].ignore.should.equal(false) }) it('ignores lines between start and stop', () => { const sourceRaw = ` /* c8 ignore start */ function ignoreMe() { // ... } /* c8 ignore stop */ function doNotIgnoreMe() { // ... } ` const source = new CovSource(sourceRaw, 0) source.lines[1].ignore.should.equal(true) source.lines[2].ignore.should.equal(true) source.lines[3].ignore.should.equal(true) source.lines[4].ignore.should.equal(true) source.lines[5].ignore.should.equal(true) source.lines[6].ignore.should.equal(false) source.lines[7].ignore.should.equal(false) source.lines[8].ignore.should.equal(false) source.lines[9].ignore.should.equal(false) }) }) })
Java
UTF-8
5,022
1.960938
2
[]
no_license
package com.example.eventplanner.controller; import com.example.eventplanner.model.Course; import com.example.eventplanner.model.User; import com.example.eventplanner.model.appliedcourse; import com.example.eventplanner.repository.Courserepository; import com.example.eventplanner.repository.UserRepository; import com.example.eventplanner.repository.appliedRepository; import com.example.eventplanner.repository.enquiryRepository; import com.example.eventplanner.service.Courseservice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; import java.util.Set; /////////////////////////////////////This controller deals with both user and admin functions @Controller public class usercontroller { @Autowired Courserepository courserepository; @Autowired appliedRepository appliedrepository; @Autowired enquiryRepository enquiryrepository; @Autowired Courseservice service; @Autowired UserRepository userRepository; @PostMapping("/user/signup") public String signupLogin(@ModelAttribute User user,Model model) throws Exception { user.setUid(Long.parseLong("1")); userRepository.save(user); List entity=service.getActiveCourse(); model.addAttribute("activecourse",entity); return "Login.html"; } @GetMapping("/userpage") public String getuserhomepage() { return "userpage"; } @GetMapping("/home/admin") public String getAdmin() { return "adminhome.html"; } @GetMapping("home/admin/logout") public String afterLogout() { return "home.html"; } @RequestMapping(path = {"/admin/activate/{uemail}"}) public String activateasAdmin(Model model,@PathVariable ("uemail") Optional<String> email) throws Exception { if(email.isPresent()) { User enitity = service.getUserbyId(email.get()); enitity.setUid(Long.parseLong("2")); userRepository.save(enitity); } return "redirect:/admin/userlist"; } @RequestMapping(path = {"/admin/deactivate/{uemail}"}) public String deactivateasAdmin(@PathVariable ("uemail") Optional<String> email) throws Exception { if(email.isPresent()) { User enitity = service.getUserbyId(email.get()); enitity.setUid(Long.parseLong("1")); userRepository.save(enitity); } return "redirect:/admin/userlist"; } @GetMapping("home/forgetpasswordhome") public String gethome() { return "forgetpasswordhome.html"; } @RequestMapping (path={"/forgetpassword/"},method = RequestMethod.POST) public String getforgetpassword(@RequestParam("useremail")Optional<String> mail,Model model,@RequestParam("useremail") String mail1) throws Exception { if(userRepository.findById(mail1).isPresent()) {User entity = service.getUserbyId(mail.get()); model.addAttribute("user", entity); return "forgetpassword"; } else return "405.html"; } @PostMapping("/admin/signuppass") public String userLogin1(@ModelAttribute User user) { userRepository.save(user); return "redirect:/home/"; } @GetMapping("/admin/userlist") public String getAdminUserList(Model model) { List<User>entity =userRepository.findAll(); model.addAttribute("user",entity); return "adminuserlist.html"; } @GetMapping("/admin/enquirydetails") public String getEnquiry (Model model){ model.addAttribute( "enquiry",enquiryrepository.findAll()); return "enquirydetails"; } @GetMapping("/enquiry/delete/{eid}") public String deleteEnquiry(Model model, @PathVariable("eid") Long id){ enquiryrepository.deleteById((id)); return "redirect:/admin/enquirydetails"; } @GetMapping("/appliedcourse") public String getAppliedCoursesListUser(Model model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String currentPrincipalName = authentication.getName(); Optional <User> entity =userRepository.findById(currentPrincipalName); if (entity.isPresent()) { User newuser=entity.get(); Set<Course> c1= newuser.getCourses(); model.addAttribute("userappliedcourse",c1); } return "userappliedcourse.html"; } @GetMapping("/admin/appliedcourse") public String getAppliedCoursesListAdmin(Model model) { List<appliedcourse>entity=appliedrepository.findAll(); model.addAttribute("userdetails",entity); return "adminappliedcourse.html"; } }
Java
UTF-8
2,494
3.0625
3
[]
no_license
package com.study.seventyseven.websecutity.day001; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import cn.hutool.core.io.file.FileReader; /** * @author SeventySeven * @Title: HttpAddressTest * @Package com.study.seventyseven.websecutity.day001; * @Description: 用于测试day001域名爆破原理测试 * @email SeventySevenChina@protonmail.com * @date 2021/4/25 13:35 */ public class HttpAddressTest { public static void main(String[] args) throws IOException { File file = new File("D://webSecurityTest/address.txt"); //文件简单使用","风格这里就用,进行切割了 String[] split = new FileReader(file).readString().split(","); Map<Integer, Set<String>> addressMap = new HashMap<>(); //两个集合来装一会开两个线程来ping for (int i = 0; i < split.length; i++) { //这里之所以使用i%number 主要是如果文件较大 仅需要增加number的值即可创建多个set也就是开启多个线程提升效率 Set<String> set = getSet(addressMap, i % 2); set.add(split[i]); addressMap.put(i % 2, set); } //新建两个线程出来ping addressMap.forEach((k, v) -> { tes(v); }); /** * 运行结果 这里可以看到所有能够ping通的即为有效二级域名 * news.baidu.com * a.baidu.com * a.baidu.com * i.baidu.com * u.baidu.com * baike.baidu.com * y.baidu.com * .. */ } private static void tes(Set<String> set) { new Thread(() -> { String e = ".baidu.com"; for (String s : set) { String result = s + e; boolean reachable = false; try { reachable = InetAddress.getByName(result).isReachable(60); } catch (IOException ignored) { } if (reachable) { System.out.println(result); } } }).start(); } private static Set<String> getSet(Map<Integer, Set<String>> addressMap, Integer number) { Set<String> strings = addressMap.get(number); if (strings != null) { return strings; } return new HashSet<>(); } }
Markdown
UTF-8
195
2.84375
3
[]
no_license
# portfolioSite First step: recreate a mockup of a responsive website (mobile, tablet, desktop), then Second step: adapt it with our own resources (images, contents) to personalize the portfolio.
Python
UTF-8
621
4.09375
4
[]
no_license
# версия 1, с числом a= 9 print("Молодец ты угадал! Да это число", a) # ответ Молодец ты угадал! Да это число 9 # версия 2, со строкой # num = 10 num = str(num) end = ("Молодец ты угадал! Да это число ") print(end + num) # ответ Молодец ты угадал! Да это число 10 # версия 3, с f-строкой # num = 20 print(f"Молодец ты угадал! Да это число {num} ") # ответ Молодец ты угадал! Да это число 20 input("q")
Python
UTF-8
2,599
2.96875
3
[]
no_license
import os def get_time_id(timestamp): t = timestamp.split()[1].split(':') return int(t[0]) * 6 + int(t[1]) / 10 + 1 def get_timestamp_by_id(id): return "{0:0>2}:{1:0>2}:00".format(id / 6, (id % 6) * 10) def fill_data(dic): sorted(dic.items(), key=lambda i: i[0]) tmp = {} itr = iter(dic.items()) ptr1 = itr.next() while True: try: ptr2 = itr.next() except StopIteration: break if ptr2[0] - ptr1[0] == 1: ptr1 = ptr2 continue for time in range(ptr1[0] + 1, ptr2[0]): v1, v2 = ptr1[1], ptr2[1] data = [] # append the region id data.append(ptr1[1][0]) # append the road info with type 1,2,3,4 for i in range(4): r1, r2 = int(v1[i + 1].split(':')[1]), int(v2[i + 1].split(':')[1]) target1 = (r1 * (ptr2[0] - time) + r2 * (time - ptr1[0])) / (ptr2[0] - ptr1[0]) data.append('{0}:{1}'.format(i + 1, int(target1))) # append the time info data.append(get_timestamp_by_id(time)) # add the data into tmp tmp[time] = data ptr1 = ptr2 for k, v in tmp.items(): dic[k] = v sorted(dic.items(), key=lambda i: i[0]) for filename in os.listdir("./training_data/traffic_data"): if filename == '.DS_Store': continue f = open('./training_data/traffic_data/' + filename) line = f.readline() dic = {} ''' dic = { '1ecbb52d73c522f184a6fc53128b1ea1': { 1: [], 2: [], 3: [], 4: [], 5: [], ... 144: [], }, '1ecbb52d73c522f184a6fc53128b1ea1': { }, } ''' while line: words = line.split('\t') if words[0] not in dic: dic[words[0]] = {} dic[words[0]][get_time_id(words[5])] = words line = f.readline() for k, v in dic.items(): fill_data(v) if not os.path.exists("./processed_data/traffic_data/"): os.makedirs("./processed_data/traffic_data/") target_file = open("./processed_data/traffic_data/" + filename, 'w') for road_id, road_data in dic.items(): for time_segment, value in road_data.items(): target_file.write('{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\n'.format( value[0], value[1], value[2], value[3], value[4], value[5].strip(), time_segment )) target_file.close() f.close()
C++
UTF-8
1,140
3.046875
3
[]
no_license
// // Created by gzq on 4/26/19. // #include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; class Solution { public: int splitArray(vector<int> &nums, int m) { int n = nums.size(); vector<vector<long long>> dp(m, vector<long long>(n + 1, 0)); vector<long long> sum(n + 1); sum[0] = 0; for (int i = 1; i <= n; i++) { dp[0][i] = dp[0][i - 1] + nums[i - 1]; sum[i] = sum[i - 1] + nums[i - 1]; } for (int i = 1; i < m; i++) { for (int j = i; j <= n; j++) { dp[i][j] = INT32_MAX; for (int k = i - 1; k < j; k++) { dp[i][j] = min(dp[i][j], max(dp[i - 1][k], sum[j] - sum[k])); } } } //返回分割长度为n的数组分割m-1次 各自和的最大值最小 return dp[m - 1][n]; } }; int main() { Solution s; vector<int> input1{7, 2, 5, 10, 8}; cout << s.splitArray(input1, 2) << endl; vector<int> input2{1, 2147483647}; cout << s.splitArray(input2, 2) << endl; return 0; }
Markdown
UTF-8
1,329
2.828125
3
[]
no_license
# for P.I WORKS ![UI Description](C:\Users\ASUS\Desktop) (We write the image link here.) ## This is the interface to add a user and show these added users. --- Let's examine the details of this interface. ___ To add a new user, click the "+New User" button at the top left of the page and enter the required data for the new user in the newly opened window. Within the scope of this information, the user's username, Display Name, phone, email and user roles information should be selected. Within these options, - Only integer value assignment should be made to the phone part. - Selection must be provided from the options in the user roles dropbox. The user's enable option should be checked according to the circumstances. Then it is saved with the Save User button in the upper left corner and the ID will be created automatically for each user. ___ Registered users can be viewed on the left side of the page. users simply click on their titles to use various rankings. It can be set to; - end or reverse for the id part, - alphabetically or reverse alphabetical for user name, - alphabetical or reverse alphabetic for mail, - alphabetical or reverse alphabetic for enabled. When the Hide Disable User section next to the "+New User" button section is checked, the users that are not enabled will be hidden.
Java
UTF-8
874
2.5
2
[]
no_license
package com.app.runner; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import com.app.model.Product; import com.app.repo.ProductRepository; @Component public class ConsoleRunner implements CommandLineRunner { @Autowired private ProductRepository repo; @Override public void run(String... args) throws Exception { repo.save(new Product(100,"A",3.4,"abc")); repo.save(new Product(101,"D",5.4,"tbc")); repo.save(new Product(102,"G",6.4,"jbc")); repo.save(new Product(103,"H",2.4,"ahc")); repo.save(new Product(104,"J",5.4,"agc")); List<Product> list=repo.findAll(); list.forEach(System.out::println); int count =repo.removeData(100); System.out.println(count); } }
Java
UTF-8
779
2.375
2
[]
no_license
package com.penzgtuar; import android.content.Context; import android.content.res.Resources; import rajawali.Object3D; import rajawali.materials.textures.TextureManager; import rajawali.parser.LoaderOBJ; public class MeshObject extends ARObject { public MeshObject(String entname, String meshname, Context mContext, TextureManager mTextureManager) { super(mContext); Resources res = mContext.getResources(); int meshID = res.getIdentifier(meshname, "raw", mContext.getPackageName()); try { LoaderOBJ meshObjParser = new LoaderOBJ(mContext.getResources(), mTextureManager, meshID); meshObjParser.parse(); mEntity = (Object3D) meshObjParser.getParsedObject(); mEntity.setName(entname); } catch (Exception e) { e.printStackTrace(); } } }
C++
UTF-8
1,500
3.40625
3
[]
no_license
#include "MyInt.hpp" #include "Array.hpp" #include <iostream> #include <utility> #include <assert.h> int main() { std::size_t before; // Creates an array. The contained element should be of type MyInt. cs540::Array a1{1, 2, 3}; std::cout << a1 << std::endl; // Both a2 and a1 should be identical after the copy ctor. std::cout << "Testing copy ctor: " << std::endl; before = MyInt::count; cs540::Array a2{a1}; // At least 3 MyInt objects should be created. assert(MyInt::count - before >= 3); std::cout << " " << a2 << std::endl; std::cout << " " << a1 << std::endl; std::cout << "Testing move ctor: " << std::endl; before = MyInt::count; cs540::Array a3{std::move(a2)}; // No new MyInt objects should be created here. assert(MyInt::count - before == 0); std::cout << " " << a3 << std::endl; std::cout << "Testing copy assignment: " << std::endl; cs540::Array a4{1}; before = MyInt::count; a4 = a1; // At least 3 MyInt objects should be created. assert(MyInt::count - before >= 3); std::cout << " " << a4 << std::endl; std::cout << " " << a1 << std::endl; std::cout << "Testing move assignment: " << std::endl; cs540::Array a5{1}; before = MyInt::count; a5 = std::move(a4); // No new MyInt objects should be created here. assert(MyInt::count - before == 0); std::cout << " " << a5 << std::endl; cs540::Array::move_performance_test(); }
Python
UTF-8
205
3.40625
3
[ "Python-2.0", "BSD-3-Clause", "MIT" ]
permissive
def classify(number): """ A perfect number equals the sum of its positive divisors. :param number: int a positive integer :return: str the classification of the input integer """ pass
Java
UTF-8
7,228
2.875
3
[]
no_license
//@author Ethan Young package edu.wm.cs.cs301.EthanYoung.generation; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; public class MazeBuilderEller extends MazeBuilder implements Runnable { /** * constructor for MazeBuilderEller.java */ public MazeBuilderEller() { super(); System.out.println("MazeBuilderPrim uses Eller's algorithm to generate maze."); } /** * constructor for MazeBuilderEller.java * @param det is used to determine if the maze is made deterministic */ public MazeBuilderEller(boolean det) { super(det); System.out.println("MazeBuilderPrim uses Eller's algorithm to generate maze."); } private int numOfSets; @Override protected void generatePathways() { Random rand = new Random(); int ranInt; Wall currWall; //cells.initialize(); //ArrayList<Wall> walls = new ArrayList<Wall>(); //updateListOfWalls(0, 0, walls); Map<Integer, ArrayList<Integer>> sets = new HashMap<Integer, ArrayList<Integer>>(); int setNum; int[][] names = new int[height][width]; int count = 1; for(int row = 0; row < height; row++) { for(int col = 0; col < width; col++) { names[row][col] = count; count++; } } sets = setUpRooms(sets, names); int setNum2; //Boolean onePerRow; ArrayList<Integer> setsWithVertConns; //System.out.println("H: " + height + " W: " + width); Boolean switchOn; for(int row = 0; row < height - 1; row++) { //onePerRow = false; setsWithVertConns = new ArrayList<Integer>(); for(int col = 0; col < width; col++) { if(cells.getSetNum(row, col) == -1) { setNum = names[row][col]; cells.setSetNum(row, col, setNum); sets.put(setNum, new ArrayList<Integer>()); sets.get(setNum).add(names[row][col]); } else { setNum = cells.getSetNum(row, col); } ranInt = rand.nextInt(2); //System.out.println(ranInt); currWall = new Wall(col, row, CardinalDirection.East); if(col != width - 1 && setNum != cells.getSetNum(row, col + 1) && ranInt == 0 && cells.canGo(currWall)) { setNum2 = cells.getSetNum(row, col + 1); //System.out.println(names[row][col] + " in set " + setNum + " grabs Right: " + names[row][col+1] + "--- setNum: " + setNum2); cells.deleteWall(currWall); //cells.deleteWall(row, col, 0, 1); if(setNum2 == -1) { //System.out.println(names[row][col+1]); //System.out.println(sets.size()); sets.get(setNum).add(names[row][col + 1]); cells.setSetNum(row, col + 1, setNum); } else { sets = mergeSets(setNum, setNum2, sets); } } ranInt = rand.nextInt(2); //System.out.println(ranInt); currWall = new Wall(col, row, CardinalDirection.South); if(setNum != cells.getSetNum(row + 1, col) && (ranInt == 0 || !setsWithVertConns.contains(setNum))) { switchOn = true; if(!cells.canGo(currWall)) { if(!setsWithVertConns.contains(setNum)) { switchOn = true; } else { switchOn = false; } } if(switchOn) { setNum2 = cells.getSetNum(row + 1, col); //System.out.println(names[row][col] + " in set " + setNum + " grabs Down: " + names[row+1][col] + "--- setNum: " + setNum2); cells.deleteWall(currWall); //cells.deleteWall(row, col, 1, 0); if(setNum2 == -1) { //System.out.println(names[row+1][col]); //System.out.println(sets.size()); //System.out.println(sets.get(setNum)); sets.get(setNum).add(names[row + 1][col]); cells.setSetNum(row + 1, col, setNum); } else { //System.out.println("What? " + setNum2); sets = mergeSets(setNum, cells.getSetNum(row + 1, col), sets); } //onePerRow = true; setsWithVertConns.add(setNum); } } } } for(int col = 0; col < width - 1; col++) { if(cells.getSetNum(height - 1, col) == -1) { setNum = names[height - 1][col]; cells.setSetNum(height - 1, col, setNum); sets.put(setNum, new ArrayList<Integer>()); sets.get(setNum).add(names[height - 1][col]); } else { setNum = cells.getSetNum(height - 1, col); } if(setNum != cells.getSetNum(height - 1, col + 1)) { //System.out.println(names[height - 1][col + 1] + " in set " + setNum + " grabs Down: " + names[height - 1][col + 1] + "--- setNum: " + cells.getSetNum(height - 1, col + 1)); cells.deleteWall(new Wall(col, height - 1, CardinalDirection.East)); //cells.deleteWall(height - 1, col, 1, 0); setNum2 = cells.getSetNum(height - 1, col + 1); if(setNum2 == -1) { sets.get(setNum).add(names[height - 1][col + 1]); cells.setSetNum(height - 1, col + 1, setNum); } else { sets = mergeSets(setNum, cells.getSetNum(height - 1, col + 1), sets); } } } /*for(int i : sets.keySet()) { System.out.println(i + ": " + sets.get(i)); }*/ //System.out.println(sets.size()); //cells.setExitPosition(0, 0); //setNums = cells.getSetNums(); numOfSets = sets.size(); //System.out.println(numOfSets); /*for(int row = 0; row < height; row++) { System.out.println(); for(int col = 0; col < width; col++) { System.out.print(cells.getSetNum(row, col) + "\t"); } System.out.println(); }*/ } /** * helper method for generatePathways() * deals with the merging of sets * looks through which cells are in which sets * and changes their markers if two sets need to be combined * @param setNum is the set number for the set thats receiving the new cells * @param setNum2 is the set number for the set thats giving away its cells * @param sets is the map that shows which cells are in which set */ private Map<Integer, ArrayList<Integer>> mergeSets(int setNum, int setNum2, Map<Integer, ArrayList<Integer>> sets) { // TODO Auto-generated method stub //System.out.println("1: " + setNum + " --- 2: " + setNum2 + " --- Size: " + sets.size()); sets.get(setNum).addAll(sets.get(setNum2)); //System.out.println(sets.size()); sets.remove(setNum2); //System.out.println(sets.size()); int temp; for(int row = 0; row < height; row++) { for(int col = 0; col < width; col++) { temp = cells.getSetNum(row, col); if(temp == setNum2) { cells.setSetNum(row, col, setNum); } } } return sets; } /** * returns the number of different sets */ public int getSetNums() { return numOfSets; } /** * sets up the map of different sets to include the rooms * rooms get their own sets at the start of the generation * @param sets is the map that shows which cells are in which set * @param names is the 2d array that shows what each cell is named */ public Map<Integer, ArrayList<Integer>> setUpRooms(Map<Integer, ArrayList<Integer>> sets, int[][] names) { int setNum; for(int row = 0; row < height; row++) { for(int col = 0; col < width; col++) { setNum = cells.getSetNum(row, col); if(setNum != -1) { if(!sets.keySet().contains(setNum)) { sets.put(setNum, new ArrayList<Integer>()); sets.get(setNum).add(names[row][col]); } else { sets.get(setNum).add(names[row][col]); } } } } return sets; } }
Java
UTF-8
10,040
1.640625
2
[]
no_license
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2011 Sun Microsystems, Inc. */ package org.netbeans.modules.j2ee.persistence.spi.jpql; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.List; import org.eclipse.persistence.jpa.jpql.tools.spi.IType; import org.eclipse.persistence.jpa.jpql.tools.spi.ITypeDeclaration; import org.eclipse.persistence.jpa.jpql.tools.spi.ITypeRepository; /** * TODO: rewrite * @author sp153251 */ public class TypeDeclaration implements ITypeDeclaration { /** * Determines whether the type declaration represents an array. */ private boolean array; /** * The actual type that contains the generics, if any is present. */ private Object genericType; /** * The cached {@link ITypeDeclaration ITypeDeclarations} representing the generics of the {@link * Type}. */ private ITypeDeclaration[] genericTypes; /** * The external form of the Java type. */ private final IType type; /** * The repository of {@link IType ITypes}. */ private ITypeRepository typeRepository; private int dimensionality=-1; /** * Creates a new <code>TypeDeclaration</code>. * * @param typeRepository The repository of {@link IType ITypes} * @param type The external form of the Java type * @param genericType The actual type that contains the generics, if any is present * @param array Determines whether the type declaration represents an array */ TypeDeclaration(ITypeRepository typeRepository, IType type, Object genericType, boolean array) { this.type = type; this.array = array; this.genericType = genericType; this.typeRepository = typeRepository; } TypeDeclaration(IType type, ITypeDeclaration[] genericTypes, int dimensionality){ this.type = type; this.genericTypes = genericTypes; this.dimensionality = dimensionality; this.array = dimensionality>0; } private String buildArrayTypeName(String arrayTypeName) { StringBuilder sb = new StringBuilder(); int index = arrayTypeName.indexOf('['); int dimens = (arrayTypeName.length() - index) / 2; String typeName = arrayTypeName.substring(0, index); while (--dimens >= 0) { sb.append("["); } String elementType = elementType(typeName); sb.append(elementType); sb.append(typeName); if (elementType.equals("L")) { sb.append(";"); } return sb.toString(); } private ITypeDeclaration[] buildParameterTypes() { List<ITypeDeclaration> parameterTypes = new ArrayList<ITypeDeclaration>(); // Example: Class<T> if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; for (java.lang.reflect.Type tp : parameterizedType.getActualTypeArguments()) { ITypeDeclaration typeParameter = buildTypeDeclaration(tp); parameterTypes.add(typeParameter); } } // T[] else if (genericType instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) genericType; parameterTypes.add(buildTypeDeclaration(genericArrayType.getGenericComponentType())); } // Example: Class else if (genericType.getClass() == Class.class) { ITypeDeclaration typeParameter = new TypeDeclaration(typeRepository, typeRepository.getType((Class<?>)genericType), null, ((Class<?>)genericType).isArray()); parameterTypes.add(typeParameter); } // Example: <K, V> else if (genericType.getClass() == Class[].class) { for (Class<?> javaType : ((Class<?>[]) genericType)) { ITypeDeclaration typeParameter = new TypeDeclaration(typeRepository, typeRepository.getType(javaType), null, javaType.isArray()); parameterTypes.add(typeParameter); } } // Example: <K, V> else if (genericType.getClass() == IType[].class) { for (IType tp : ((IType[]) genericType)) { ITypeDeclaration typeParameter = new TypeDeclaration(typeRepository, tp, null, false); parameterTypes.add(typeParameter); } } return parameterTypes.toArray(new ITypeDeclaration[parameterTypes.size()]); } private TypeDeclaration buildTypeDeclaration(Object genericType) { // <T1, ..., Tn> if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; return buildTypeDeclaration(parameterizedType.getRawType()); } // <T> if (genericType instanceof TypeVariable) { TypeVariable<?> typeVariable = (TypeVariable<?>) genericType; for (java.lang.reflect.Type tp : typeVariable.getBounds()) { return buildTypeDeclaration(tp); } return new TypeDeclaration(typeRepository, typeRepository.getType((Object.class)), null, (Object.class).isArray()); } // ? if (genericType instanceof WildcardType) { WildcardType wildcardType = (WildcardType) genericType; for (java.lang.reflect.Type tp : wildcardType.getUpperBounds()) { return buildTypeDeclaration(tp); } return new TypeDeclaration(typeRepository, typeRepository.getType((Object.class)), null, (Object.class).isArray()); } // T[] if (genericType instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) genericType; String arrayTypeName = buildArrayTypeName(genericArrayType.toString()); IType arrayType = typeRepository.getType(arrayTypeName); return new TypeDeclaration( typeRepository, arrayType, genericArrayType.getGenericComponentType(), true); } return new TypeDeclaration(typeRepository, typeRepository.getType(((Class<?>) genericType)), null, ((Class<?>) genericType).isArray()); } private String elementType(String typeName) { if (typeName.equals("boolean")) {//NOI18N return "Z"; } if (typeName.equals("byte") || typeName.equals("char") || typeName.equals("double") || typeName.equals("float") || typeName.equals("int") || typeName.equals("short")) {//NOI18N return (Character.toString(typeName.charAt(0))).toUpperCase();//just first char in upper case } if (typeName.equals("long")) {//NOI18N return "J"; } return "L"; } /** * {@inheritDoc} */ @Override public int getDimensionality() { if(dimensionality <0){ if (array) { String name = type.getName(); dimensionality = 0; while (name.charAt(dimensionality) == '[') { dimensionality++; } } } return dimensionality; } /** * {@inheritDoc} */ @Override public IType getType() { return type; } /** * {@inheritDoc} */ @Override public ITypeDeclaration[] getTypeParameters() { if (genericTypes == null) { if (genericType == null) { genericTypes = new ITypeDeclaration[0]; } else { genericTypes = buildParameterTypes(); } } return genericTypes; } /** * {@inheritDoc} */ @Override public boolean isArray() { return array; } }
C#
UTF-8
2,987
2.796875
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace VeeamTaskLib { public class ChunkManager : IDisposable { private List<IChunk> _chunkList = new List<IChunk>(); public Result Status = Result.Ok(); private int _processorCount = 1; public ChunkManager(int processorCount) { _processorCount = processorCount; } public Result AddBlockAndTryToProcess(IBlockProcessor workBlockForProcessing) { if (Status.IsFailure) { return Status; } try { var chunkThread = new Thread(ProcessChunk); var chunk = new Chunk(chunkThread, workBlockForProcessing); _chunkList.Add(chunk); if (RunningChunkCount(_chunkList) <= _processorCount) { chunk.ChunkThread.Start(workBlockForProcessing); } return Result.Ok(); } catch (Exception ex) { return Result.Fail($"Thread processing exception: {ex.Message}"); } } private void ProcessChunk(object objectBlockForProcessing) { if (Status.IsFailure) { return; } var block = (IBlockProcessor)objectBlockForProcessing; Status = block.Process(); } public void WaitingUnfinishedChunks() { foreach (var thread in _chunkList) { if (thread.ChunkThread.IsAlive) { thread.ChunkThread.Join(); } } } public int StartUnstartedChunksAndCountRemained() { if (Status.IsFailure) { return -1; } foreach (var chunk in _chunkList.FindAll(p => p.ChunkThread.ThreadState == ThreadState.Unstarted)) { if (RunningChunkCount(_chunkList) <= _processorCount) { chunk.ChunkThread.Start(chunk.Block); } else { break; } } return _chunkList.FindAll(p => p.ChunkThread.ThreadState == ThreadState.Unstarted).Count; } public void RemoveWrittenChunks() { _chunkList.RemoveAll(p => p.ChunkThread.ThreadState != ThreadState.Running && p.Block.IsWritten); } private int RunningChunkCount(List<IChunk> threadQueue) { return threadQueue.FindAll(p => p.ChunkThread.ThreadState == ThreadState.Running).Count; } public void Dispose() { _chunkList.Clear(); } } interface IChunk { Thread ChunkThread { get; } IBlockProcessor Block { get; } } public class Chunk : IChunk { public Thread ChunkThread { get; } public IBlockProcessor Block { get; } public Chunk(Thread thread, IBlockProcessor block) { ChunkThread = thread; Block = block; } } }
C++
UTF-8
958
2.65625
3
[]
no_license
#include <algorithm> #include <cassert> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <iomanip> #include <limits> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <unordered_map> #include <vector> using namespace std; // My templates struct reverse { bool operator()(const int &left, const int &right){ return (right < left); } }; struct custom { bool operator()(const pair<int,int> &left, const pair<int,int> &right){ return (left.first > right.first); } }; void solve(){ queue<int> myqueue; for (int i = 0; i < 10; ++i) { myqueue.push(i); } for (int i = 0; i < 10; ++i) { cout << myqueue.front() << ' '; myqueue.pop(); } cout << endl; } int main(int argc, char const *argv[]){ // freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); solve(); return 0; }
Java
UTF-8
2,178
2.609375
3
[]
no_license
package org.beccaria.hub; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.util.logging.Logger; public class MessagePublisher { private static final Logger logger = Logger.getLogger("org.domotics"); private static final String TOPIC = "domotics/commands"; private static final String BROKER_HOST = "192.168.1.41"; private static final int BROKER_PORT = 1883; private static final String CLIENT_ID = "domus.hub"; private static final int QOS = 0; MemoryPersistence persistence; String broker; String topic; int port; public MessagePublisher(){ MemoryPersistence persistence = new MemoryPersistence(); broker = BROKER_HOST; port = BROKER_PORT; topic = TOPIC; } public MessagePublisher setBrokerHost(String host){ this.broker = host; return this; } public MessagePublisher setBrokerPort(int port){ this.port = port; return this; } public MessagePublisher setTopic(String topic){ this.topic = topic; return this; } public void publish(String msg){ try { String broker_url = "tcp://" + broker + ":" + port; MqttClient client = new MqttClient(broker_url, CLIENT_ID, persistence); MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setCleanSession(true); logger.info("Connecting to broker: "+broker); client.connect(mqttConnectOptions); logger.info("Connected"); logger.info("Publishing message: " + msg + " on topic: " + topic); MqttMessage message = new MqttMessage(msg.getBytes()); message.setQos(QOS); client.publish(topic, message); logger.info("Message published"); client.disconnect(); logger.info("Disconnected"); } catch(Exception e) { logger.info(e.getLocalizedMessage()); } } }
Shell
UTF-8
628
3.75
4
[]
no_license
#!/bin/bash YELLOW=`tput setaf 3` RESET=`tput sgr0` echo "${YELLOW}All files in current working dir:${RESET}" echo * # echoes all files in current working dir echo echo "${YELLOW}MD files in current working dir:${RESET}" echo *.md # echoes all files matching the predicate (anything.md) in the working dir echo echo "${YELLOW}PDF files in ~/Documents:${RESET}" echo ${HOME}/Documents/*.pdf # echoes all pdfs in the specified directory (~/Documents) echo echo "${YELLOW}No \"for\":${RESET}" for file in *.bash; do grep -L 'for' "$file" # echoes the names of bash files which do not contain the word 'for' done
TypeScript
UTF-8
2,000
2.65625
3
[]
no_license
/** * # 「SEOを意識したHTMLを書いてみよう!」 - SEO Basics * * ## 概要 * `<meta>`タグでOGPの設定をする. */ import { isLeft, isRight } from "fp-ts/lib/Either" import { OgpVisitor } from "../utils/ogpValidator" const cardTypes = [ 'summary', 'summary_large_image', 'app', 'player', ] describe('Station6', function () { beforeEach(() => { // functionの前に必ず実行される // baseUrlのrootへ cy.visit('/station6.html') }) it('有効な`<meta>`OGPタグが存在する', function () { cy.get('meta[property]').should('exist').then(metaTags => { const visitor = new OgpVisitor() metaTags.each(function () { const property = this.getAttribute('property') ?? '' const content = this.getAttribute('content') ?? '' visitor.visitProperty(property, content) }) const res = visitor.finalize() if (isLeft(res)) { const [errors, warnings, _] = res.left cy.on('fail', (error, _) => { error.name = 'ParseError' error.message = 'parse failed due to error(s):\n' + errors.map(err => `(${err.type}) ${err.description ?? ''}`).join('\n') throw error // throw error to have test still fail }) } expect(isRight(res)).to.be.true }) }) it('Twitter用の有効な`<meta>`タグが存在する', function () { cy.get('meta[name="twitter:card"]').should('exist').then(cardMeta => { const cardType = cardMeta.last().attr('content') expect(cardTypes.indexOf(cardType) !== -1, `Twitter card type should be one of : "${cardTypes.join('", "')}"`).to.be.true }) cy.get('meta[name="twitter:site"],meta[name="twitter:creator"]').then(cardMeta => { cardMeta.each((_, el) => { const twitterId = el.getAttribute('content') expect(twitterId).satisfy((v) => /^@(\w){1,15}$/.test(v), 'the values of twitter:site and twitter:creator should be valid Twitter ID') }) }) }) })
C++
UTF-8
3,365
3.15625
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include <string.h> #include "headers/Cartridge.hpp" using namespace std; Cartridge::Cartridge(string path) { if (!path.empty()) { rom.open(path, ios::in | ios::binary); if (!rom.is_open()) { cerr << "Could not open: " << path << endl; exit(1); } std::vector<uint8_t> bytes(HEADER_LENGTH); rom.read((char *)&(bytes.at(0)), HEADER_LENGTH); header = new Header(bytes); load_trainer(); load_prg_rom(); load_chr_rom(); load_prg_ram(); load_playchoice(); } else { cerr << "No file path" << endl; exit(1); } } Cartridge::~Cartridge() { delete header; if (rom.is_open()) { rom.close(); } } /* * Retrieve the cartridge's header. * * @return header The header */ Header Cartridge::get_header() { return *header; } /* * Retrieve all the trainer data for the cartridge. * * @return The trainer data */ std::vector<uint8_t> Cartridge::get_trainer() { return trainer_data; // if (header != NULL && header->is_trainer_present()) { // } else { // return NULL; // } } /* * Retrive the program rom from the cartridge. * * @return prg_rom_data The program rom */ std::vector<uint8_t> Cartridge::get_prg_rom() { return prg_rom_data; } /* * Retrives the character rom from the cartridge. * * @return chr_rom_data The cahracter data */ std::vector<uint8_t> Cartridge::get_chr_rom() { return chr_rom_data; } /* * Retrive the program ram from the cartridge. * * @return Program ram */ std::vector<uint8_t> Cartridge::get_prg_ram() { return prg_ram_data; } /* * Retrieve the Playchoice data from the cartridge. * * @return playchoice_data */ std::vector<uint8_t> Cartridge::get_playchoice() { return playchoice_data; } /* * Check if the cartridge has character ROM. * * @return True if character ROM is present */ bool Cartridge::has_chr_rom() { if (header->get_chr_size_8KB() == 0) { return false; } else { return true; } } /* * Reads the trainer from the file and stores it in memory. */ void Cartridge::load_trainer() { if (header->is_trainer_present()) { trainer_data.resize(TRAINER_SIZE); rom.read((char *)&(trainer_data[0]), TRAINER_SIZE); // rom.read((char *)trainer_data, TRAINER_SIZE); } } /* * Reads the program data from the cartridge and stores it in memory. */ void Cartridge::load_prg_rom() { int size = header->get_prg_rom_size_16KB() * PRG_ROM_UNITS; if (header != NULL && size > 0) { prg_rom_data.resize(size); rom.read((char *)&(prg_rom_data[0]), size); } } /* * Reads the character ROM from the cartrdige and stores it in memory. */ void Cartridge::load_chr_rom() { int size = header->get_chr_size_8KB() * CHR_ROM_UNITS; if (header != NULL && size > 0) { chr_rom_data.resize(size); rom.read((char *)&(chr_rom_data[0]), size); } } /* * Reads teh program RAM from the cartridge and stores it in memory. */ void Cartridge::load_prg_ram() { int size = header->get_prg_ram_size_8KB() * PRG_RAM_UNITS; if (header != NULL && size > 0) { prg_ram_data.resize(size); rom.read((char *)&(prg_ram_data[0]), size); } } /* * Reads the Playchoice from the cartridge and stores it in memmory. */ void Cartridge::load_playchoice() { if (header != NULL && header->is_playchoice()) { playchoice_data.resize(PLAYCHOICE_SIZE); rom.read((char *)&(playchoice_data[0]), PLAYCHOICE_SIZE); } }
Java
UTF-8
985
3.015625
3
[]
no_license
package jianzhioffer; import java.util.ArrayList; /** * \* Created with IntelliJ IDEA. * \* User: TTT * \* Date: 2018/6/3 * \* Time: 21:34 */ /*输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。 * */ public class Solution25 { private ArrayList<ArrayList<Integer>> listAll=new ArrayList<ArrayList<Integer>>(); private ArrayList<Integer> list=new ArrayList<Integer>(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) { if (root==null) return listAll; list.add(root.val); target-=root.val; if (target==0&&root.left==null&&root.right==null) listAll.add(new ArrayList<Integer>(list)); FindPath(root.left,target); FindPath(root.right,target); list.remove(list.size()-1); return listAll; } }
Java
UHC
1,347
2.203125
2
[]
no_license
package com.model2.mvc.view.user; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.model2.mvc.framework.Action; import com.model2.mvc.service.domain.User; import com.model2.mvc.service.user.UserService; import com.model2.mvc.service.user.impl.UserServiceImpl; public class GetUserAction extends Action{ @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String userId=request.getParameter("userId"); UserService userService=new UserServiceImpl(); User user=userService.getUser(userId); List<String> userDetailList = new ArrayList<String>(); userDetailList.add("ȸ ȸ"); userDetailList.add("̵,"+user.getUserId()); userDetailList.add("̸,"+user.getUserName()); userDetailList.add("ּ,"+(user.getAddr() != null?user.getAddr():"")); userDetailList.add("޴ȭȣ,"+(user.getPhone() != null?user.getPhone():"")); userDetailList.add("̸,"+(user.getEmail() != null?user.getEmail():"")); userDetailList.add(","+(user.getRegDate() != null?user.getRegDate():"")); request.setAttribute("list", userDetailList); return "forward:/user/getUser.jsp"; } }
C#
UTF-8
2,221
2.65625
3
[]
no_license
using MvvmHelpers; using SeedShare.Services; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xamarin.CommunityToolkit.ObjectModel; using Xamarin.Forms; namespace SeedShare.ViewModels { [QueryProperty(nameof(Name), nameof(Name))] public class AddLibraryViewModel : BaseViewModel { string name, street, city, state, zip, phone, hours, url; public string Name { get => name; set => SetProperty(ref name, value, propertyName:"Library Name");} public string Street { get => street; set => SetProperty(ref street, value, propertyName:"Address");} public string City { get => city; set => SetProperty(ref city, value, propertyName: "Address"); } public string State { get => state; set => SetProperty(ref state, value, propertyName: "Address"); } public string Zip { get => zip; set => SetProperty(ref zip, value, propertyName: "Address"); } public string Phone { get => phone; set => SetProperty(ref phone, value, propertyName:"Phone, enter 000-000-0000 if not a public library");} public string Hours { get => hours; set => SetProperty(ref hours, value, propertyName:"Hours");} public string URL { get => url; set => SetProperty(ref url, value, propertyName:"Website, enter NA if not a public library");} public AsyncCommand SaveCommand { get; } public AddLibraryViewModel() { Title = "Add Library"; SaveCommand = new AsyncCommand(Save); } public async Task Save() { if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(street) || string.IsNullOrWhiteSpace(city) || string.IsNullOrWhiteSpace(state) || string.IsNullOrWhiteSpace(zip) || string.IsNullOrWhiteSpace(phone) || string.IsNullOrWhiteSpace(hours) || string.IsNullOrWhiteSpace(url)) { return; } await DBService.AddLibrary(name, street, city, state, zip, phone, hours, url); //saves data to database await Shell.Current.GoToAsync(".."); //pop current page off the stack and returns to previous view } } }
C
UTF-8
907
4
4
[]
no_license
/* * Program to count frequency of particular digit in number */ #include<stdio.h> int CountFreq(long, int); int main() { long lNum = 0; int iDig = 0, iRet = 0; printf("Enter the number:\t"); scanf("%ld", &lNum); printf("Enter the digit:\t"); scanf("%d", &iDig); iRet = CountFreq(lNum, iDig); printf("Number of %d in %ld is %d\n", iDig, lNum, iRet ); return 0; } ///////////////////////////////////////////////////////////// // // Name :CountFreq // Input :long, int // Returns :int // Description :count frequency of particular digit in number // Author :Pranav Choudhary // Date :5 August 2020 // ///////////////////////////////////////////////////////////// int CountFreq( long lNum, int iDig ) { int iCnt = 0; if(lNum < 0) { lNum = -lNum; } if(iDig < 0) { iDig = -iDig; } while(lNum > 0) { if(lNum % 10 == iDig) { iCnt++; } lNum = lNum / 10; } return iCnt; }
Markdown
UTF-8
2,784
3.015625
3
[]
no_license
# VPAT-HTML VPAT-HTML is a tool for generating Voluntary Product Accessibility Template html tables from json 🏗ℹ ![preview vpat html](./screenshot.png "preview vpat html") # Usage ``` const VPAT = require('vpat-html'); const support = { // ... } const html = new VPAT(support); ``` # Features ``` // define support for a given guideline: '1194.21-a': true, '1194.21-a': { supported: true, }, '1194.21-a': {}, '1194.21-a': VPAT.SUPPORTED, ``` ``` // define lack of support for a given guideline: '1194.21-a': null, '1194.21-a': undefined, '1194.21-a': false, '1194.21-a': { supported: false, }, '1194.21-a': VPAT.NOT_SUPPORTED, ``` ``` // define n/a for a given guideline: '1194.21-a': NaN, '1194.21-a': { supported: -1, }, '1194.21-': { supported: NaN, }, '1194.21-a': VPAT.NOT_APPLICABLE, ``` ``` // define partial support for a given guideline: '1194.21-a': '', '1194.21-a': { supported: '', }, '1194.21-a': 'partial', '1194.21-a': { supported: 'partial', }, '1194.21-a': 'exceptions', '1194.21-a': { supported: 'exceptions', }, '1194.21-a': VPAT.SUPPORTED_WITH_EXCEPTIONS, ``` ``` // define your own text for a given guideline: '1194.21-a': { supported: VPAT.SUPPORTED_WITH_EXCEPTIONS, text: 'Supports with exceptions: some additional text' }, ``` ``` // define remarks or explanations for a given feature: '1194.21-a': { notes: '<ul><li>Drag-and-drop operations are not accessible to keyboard-only users</li></ul>', }, ``` ``` // define support for a section '1194.21': { supports: true, }, ``` ``` // define support for a sub-section '1194.21-a': { supports: true, }, ``` ``` // define support for a sub-sub-section '1194.23-j-1': { supports: true, }, } ``` # Additional Configuration ``` const support = { '1194.21': { supported: 'n/a', }, } const options = { colors: { supported: '#27ae60', notSupported: '#e74c3c', exceptions: '#d35400', notApplicable: '#7f8c8d', zebra1: '#fff', zebra2: '#ecf0f1', border: '#7f8c8d', }, } ``` # Default Support By default, `vpat-html` assumes "Not Applicable" for non-defined features. If you want to change this default, ``` const support = { '1194.21': { supported: 'n/a', }, } const options: { defaultSupport: VPAT.SUPPORTED, } const html = new VPAT(support, options); ``` # Custom HTML Templates can be modifed. Templates are implemented with [handlebars](https://www.npmjs.com/package/handlebars). ``` # custom row template const options = { templates: { row: '<tr><td>Section</td><td>{{description}}</td><td>{{support}}</td><td>{{notes}}</td></tr>', }, }; const html = new VPAT(support, options); ```
C#
UTF-8
2,806
2.609375
3
[]
no_license
using AppCore.Data; using AppCore.Interfaces; using AppCore.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebAPI.Controllers { [Route("api/wooliesx/[controller]")] [ApiController] public class SortController : ControllerBase { private readonly IWooliesDataService _wooliesDataService; private string strToken = "e3b5361b-e85c-4c62-85fd-4c9e2af2c053"; public SortController(IWooliesDataService wooliesDataService) { _wooliesDataService = wooliesDataService; } // POST: api/wooliesx/Sort [HttpPost] public async Task<ActionResult<IEnumerable<Product>>> Post(string token, string sortOption) { List<CartItem> list = null; if (string.IsNullOrEmpty(token)) { ModelState.AddModelError("token", "token is required"); return BadRequest(ModelState); } if (token != strToken) { ModelState.AddModelError("token", "invalid token"); return BadRequest(ModelState); } if (string.IsNullOrEmpty(sortOption)) { ModelState.AddModelError("sortoption", "sort option required"); return BadRequest(ModelState); } sortOption = sortOption.ToLower(); switch (sortOption) { case "low": // price low to high list = await _wooliesDataService.ProductPriceLowToHigh(); return Ok(list); case "high": // price high to low list = await _wooliesDataService.ProductPriceHighToLow(); return Ok(list); case "ascending": // name ascending list = await _wooliesDataService.ProductNameAscending(); return Ok(list); case "descending": // name descending list = await _wooliesDataService.ProductNameDescending(); return Ok(list); case "recommended": // recommended var Rescommended = await _wooliesDataService.ProductRescommended(); return Ok(Rescommended); default: ModelState.AddModelError("expected", "low, high, ascending, descending and recommended"); ModelState.AddModelError("sortoption", "invalid sort option"); return BadRequest(ModelState); } } } }
Java
UTF-8
1,234
3.625
4
[]
no_license
package knowledge.currenttestexample; import java.util.concurrent.TimeUnit; /** * 6-13 */ public class Join { public static void main(String[] args) throws Exception { Thread previous = Thread.currentThread(); for (int i = 0; i < 10; i++) { Thread thread = new Thread(new Domino(previous,String.valueOf(i)), String.valueOf(i)); thread.start(); previous = thread; } TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + " terminate."); } static class Domino implements Runnable { private Thread thread; private String name; public Domino(Thread thread,String name) { this.thread = thread; this.name = name; } public void run() { System.out.println(this.name +" begine"); try { System.out.println(thread.getName() +" join()."); thread.join(); System.out.println(thread.getName() +" join() over"); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + " terminate." + this.name +" value"); } } }
Python
UTF-8
15,045
2.828125
3
[]
no_license
from __future__ import division import re import sys import StringIO class Procedure(object): """A user-defined Scheme procedure.""" def __init__(self, params, exp, env, runtime): self.params = params self.exp = exp self.env = env self.runtime = runtime def __call__(self, *args): return self.runtime.eval(self.exp, Env(self.params, args, self.env)) class InPort(object): """An input port. Retains a line of chars.""" tokenizer = r"""\s*(,@|[('`,)]|"(?:[\\].|[^\\"])*"|;.*|[^\s('"`,;)]*)(.*)""" def __init__(self, file_handle): self.file = file_handle self.line = '' def next_token(self): """Return the next token, reading new text into line buffer if needed.""" while True: if self.line == '': self.line = self.file.readline() if self.line == '': return eof_object token, self.line = re.match(InPort.tokenizer, self.line).groups() if token != '' and not token.startswith(';'): return token class Env(dict): """An environment: a dict of {'var':val} pairs, with an outer Env.""" def __init__(self, params=(), args=(), outer=None): super(Env, self).__init__() # Bind parm list to corresponding args, or single parm to list of args self.outer = outer if isinstance(params, Symbol): self.update({params: list(args)}) else: if len(args) != len(params): raise TypeError('expected %s, given %s, ' % (to_string(params), to_string(args))) self.update(zip(params, args)) def find(self, var): """Find the innermost Env where var appears.""" if var in self: return self elif self.outer is None: raise LookupError(var) else: return self.outer.find(var) class Symbol(str): pass class SymbolTable(object): def __init__(self): self.symbols = {} def __getitem__(self, key): """Find or create unique Symbol entry for str s in symbol table.""" if key not in self.symbols: self.symbols[key] = Symbol(key) return self.symbols[key] class Continuation(RuntimeWarning): def __init__(self, message): self.return_val = None super(Continuation, self).__init__(message) eof_object = Symbol('#:<eof-object>') # Note: not interned; can't be read sym = SymbolTable() _append = sym["append"] _begin = sym["begin"] _cons = sym["cons"] _define = sym["define"] _define_macro = sym["define-macro"] _if = sym["if"] _lambda = sym["lambda"] _let = sym["let"] _quasiquote = sym["quasiquote"] _quote = sym["quote"] _set = sym["set!"] _unquote = sym["unquote"] _unquote_splicing = sym["unquote-splicing"] # Reader Macros quotes = { "'": _quote, "`": _quasiquote, ",": _unquote, ",@": _unquote_splicing } def require(x, predicate, msg="wrong length"): """Signal a syntax error if predicate is false.""" if not predicate: raise SyntaxError(to_string(x) + ': ' + msg) def read(in_port): """Read a Scheme expression from an input port.""" def atom(token): """ Numbers become numbers; #t and #f are booleans; "..." string; otherwise Symbol. """ if token == '#t': return True elif token == '#f': return False elif token[0] == '"': return token[1:-1].decode('string_escape') try: return int(token) except ValueError: try: return float(token) except ValueError: try: return complex(token.replace('i', 'j', 1)) except ValueError: return sym[token] def read_ahead(token): if '(' == token: l = [] while True: token = in_port.next_token() if token == ')': return l else: l.append(read_ahead(token)) elif ')' == token: raise SyntaxError('unexpected )') elif token in quotes: return [quotes[token], read(in_port)] elif token is eof_object: raise SyntaxError('unexpected EOF in list') else: return atom(token) # body of read: token1 = in_port.next_token() return eof_object if token1 is eof_object else read_ahead(token1) def callcc(procedure): """ Call procedure with current continuation; escape only """ ball = Continuation("Sorry, can't continue this continuation any longer.") def throw(return_val): ball.return_val = return_val raise ball try: return procedure(throw) except Continuation as w: if w is ball: return ball.return_val else: raise w def read_char(in_port): """ Read the next character from an input port. """ if in_port.line != '': ch, in_port.line = in_port.line[0], in_port.line[1:] return ch else: return in_port.file.read(1) or eof_object def cons(x, y): """ Cons """ return [x] + y def is_pair(x): """ Returns whether the given object a pair """ return x != [] and isinstance(x, list) def to_string(x): """ Convert a Python object back into a Lisp-readable string. """ if x is True: return "#t" elif x is False: return "#f" elif isinstance(x, Symbol): return x elif isinstance(x, str): return '"%s"' % x.encode('string_escape').replace('"', r'\"') elif isinstance(x, list): return '({0})'.format(' '.join(map(to_string, x))) elif isinstance(x, complex): return str(x).replace('j', 'i') return str(x) class Runtime(object): def __init__(self): self.global_env = self._create_global_scope() self.macro_table = {_let: self._make_let()} # prelude self.run(""" (begin (define-macro and (lambda args (if (null? args) #t (if (= (length args) 1) (car args) `(if ,(car args) (and ,@(cdr args)) #f))))) ;; More macros can also go here ) """) def _create_global_scope(self): """ Creates a scope and adds the standard symbols. """ env = Env() import math import cmath import operator as op env.update(vars(math)) env.update(vars(cmath)) env.update({ '*': op.mul, '+': op.add, '-': op.sub, '/': op.div, '=': op.eq, 'eq?': op.is_, 'equal?': op.eq, '<': op.lt, '<=': op.le, '>': op.gt, '>=': op.ge, 'not': op.not_, 'boolean?': lambda x: isinstance(x, bool), 'eof-object?': lambda x: x is eof_object, 'list?': lambda x: isinstance(x, list), 'null?': lambda x: x == [], 'pair?': is_pair, 'port?': lambda x: isinstance(x, file), 'symbol?': lambda x: isinstance(x, Symbol), 'call/cc': callcc, 'read': read, 'read-char': read_char, 'append': op.add, 'cons': cons, 'car': lambda x: x[0], 'cdr': lambda x: x[1:], 'length': len, 'list': lambda *x: list(x), 'apply': lambda proc, l: proc(*l), 'close-input-port': lambda p: p.file.close(), 'close-output-port': lambda p: p.close(), 'display': lambda x, port=sys.stdout: port.write(x if isinstance(x, str) else to_string(x)), 'eval': lambda x: self.eval(self.expand(x)), 'load': lambda fn: self.load(fn), 'open-input-file': open, 'open-output-file': lambda f: open(f, 'w'), 'write': lambda x, port=sys.stdout: port.write(to_string(x)), }) return env def run(self, code): """ :param code: Code to evaluate in this runtime :return: The result of evaluating that code """ return self.eval(self.parse(InPort(StringIO.StringIO(code)))) def eval(self, x, env=None): """ Evaluate an expression in an environment. """ if env is None: env = self.global_env while True: if isinstance(x, Symbol): # variable reference return env.find(x)[x] elif not isinstance(x, list): # constant literal return x elif x[0] is _quote: # (quote exp) (_, exp) = x return exp elif x[0] is _if: # (if test conseq alt) (_, test, conseq, alt) = x x = (conseq if self.eval(test, env) else alt) elif x[0] is _set: # (set! var exp) (_, var, exp) = x env.find(var)[var] = self.eval(exp, env) return None elif x[0] is _define: # (define var exp) (_, var, exp) = x env[var] = self.eval(exp, env) return None elif x[0] is _lambda: # (lambda (var*) exp) (_, params, exp) = x return Procedure(params, exp, env, self) elif x[0] is _begin: # (begin exp+) for exp in x[1:-1]: self.eval(exp, env) x = x[-1] else: # (proc exp*) expressions = [self.eval(exp, env) for exp in x] procedure = expressions.pop(0) if isinstance(procedure, Procedure): x = procedure.exp env = Env(procedure.params, expressions, procedure.env) else: return procedure(*expressions) def expand(self, x, top_level=False): """ Walk tree of x, making optimizations/fixes, and signaling SyntaxError. """ def expand_quasiquote(expr): """ Expand `x => 'x; `,x => x; `(,@x y) => (append x y) """ if not is_pair(expr): return [_quote, expr] require(expr, expr[0] is not _unquote_splicing, "can't splice here") if expr[0] is _unquote: require(expr, len(expr) == 2) return expr[1] elif is_pair(expr[0]) and expr[0][0] is _unquote_splicing: require(expr[0], len(expr[0]) == 2) return [_append, expr[0][1], expand_quasiquote(expr[1:])] else: return [_cons, expand_quasiquote(expr[0]), expand_quasiquote(expr[1:])] require(x, x != []) # () => Error if not isinstance(x, list): # constant => unchanged return x elif x[0] is _quote: # (quote exp) require(x, len(x) == 2) return x elif x[0] is _if: if len(x) == 3: x = x + [None] # (if t c) => (if t c None) require(x, len(x) == 4) return map(self.expand, x) elif x[0] is _set: require(x, len(x) == 3) var = x[1] # (set! non-var exp) => Error require(x, isinstance(var, Symbol), "can set! only a symbol") return [_set, var, self.expand(x[2])] elif x[0] is _define or x[0] is _define_macro: require(x, len(x) >= 3) _def, v, body = x[0], x[1], x[2:] if isinstance(v, list) and v: # (define (f args) body) f, args = v[0], v[1:] # => (define f (lambda (args) body)) return self.expand([_def, f, [_lambda, args] + body]) else: require(x, len(x) == 3) # (define non-var/list exp) => Error require(x, isinstance(v, Symbol), "can define only a symbol") exp = self.expand(x[2]) if _def is _define_macro: require(x, top_level, "define-macro only allowed at top level") proc = self.eval(exp) require(x, callable(proc), "macro must be a procedure") self.macro_table[v] = proc # (define-macro v proc) return None # => None; add v:proc to macro_table return [_define, v, exp] elif x[0] is _begin: if len(x) == 1: return None # (begin) => None else: return [self.expand(xi, top_level) for xi in x] elif x[0] is _lambda: # (lambda (x) e1 e2) require(x, len(x) >= 3) # => (lambda (x) (begin e1 e2)) params, body = x[1], x[2:] require(x, (isinstance(params, list) and all(isinstance(v, Symbol) for v in params)) or isinstance(params, Symbol), "illegal lambda argument list") exp = body[0] if len(body) == 1 else [_begin] + body return [_lambda, params, self.expand(exp)] elif x[0] is _quasiquote: # `x => expand_quasiquote(x) require(x, len(x) == 2) return expand_quasiquote(x[1]) elif isinstance(x[0], Symbol) and x[0] in self.macro_table: return self.expand(self.macro_table[x[0]](*x[1:]), top_level) # (m arg...) else: # => macro expand if m isa macro return map(self.expand, x) # (f arg...) => expand each def parse(self, in_port): """ Parse a program: read and expand/error-check it. """ return self.expand(read(in_port), top_level=True) def load(self, filename): """ Eval every expression from a file. """ self.repl(InPort(open(filename))) def repl(self, prompt=None, in_port=InPort(sys.stdin), out=sys.stdout): """ Read-eval-print loop. """ while True: try: if prompt: sys.stderr.write(prompt) x = self.parse(in_port) if x is eof_object: return val = self.eval(x) if val is not None and out: print >> out, to_string(val) sys.stdout.flush() except Exception as e: print '{}: {}'.format(type(e).__name__, e) def _make_let(self): def let(*args): """ Let macro """ args = list(args) x = cons(_let, args) require(x, len(args) > 1) bindings, body = args[0], args[1:] require(x, all(isinstance(b, list) and len(b) == 2 and isinstance(b[0], Symbol) for b in bindings), "illegal binding list") names, values = zip(*bindings) return [[_lambda, list(names)] + map(self.expand, body)] + map(self.expand, values) return let if __name__ == '__main__': sys.stderr.write("Lispy version 2.0\n") r = Runtime() r.repl(prompt='lispy> ')
PHP
UTF-8
3,598
2.765625
3
[ "MIT" ]
permissive
<?php namespace Helpers; use Hyper\Functions\Str; use Hyper\Reflection\Annotation; use ReflectionClass; use ReflectionClassConstant; use ReflectionMethod; use ReflectionProperty; use Reflector; abstract class ReflectionHelper { #region Public public static function getClass(ReflectionClass $ref): object { $optimisedDoc = self::getOptimisedDoc($ref->getDocComment()); $name = $ref->getName(); $prop = function ($prop) { return self::getProperty($prop); }; $filPrivate = function ($prop) { return $prop->access !== 'private'; }; $func = function ($prop) use ($name) { $prop = new ReflectionMethod($name, $prop); return self::getMethod($prop); }; return (object)[ 'name' => $name, 'description' => $optimisedDoc, 'deprecated' => Str::contains($optimisedDoc, '@deprecated'), 'properties' => array_filter(array_map($prop, $ref->getProperties()), $filPrivate), 'constants' => array_map(function ($const) use ($name) { return self::getConstant($const); }, $ref->getReflectionConstants()), 'methods' => array_map($func, get_class_methods($name)) ]; } private static function getOptimisedDoc(string $doc): string { $doc = str_replace("/*", '', $doc); $doc = str_replace("*/", '', $doc); $doc = str_replace("*", '', $doc); $doc = preg_replace( "/@(.*?)[\n]/s", '', $doc ); return Str::trimLine($doc, '<br>') . '<br>'; } public static function getProperty(ReflectionProperty $ref): object { $optimisedDoc = self::getOptimisedDoc($ref->getDocComment()); $name = $ref->getName(); return (object)[ 'name' => $name, 'description' => $optimisedDoc, 'deprecated' => Str::contains($optimisedDoc, '@deprecated'), 'access' => self::getAccessModifier($ref) ]; } private static function getAccessModifier(Reflector $ref): string { $access = 'default'; $access = $ref->isPrivate() ? 'private' : $access; $access = $ref->isProtected() ? 'protected' : $access; $access = $ref->isPublic() ? 'public' : $access; return $ref->isStatic() ? $access . ' static' : $access; } #endregion #region Private public static function getMethod(ReflectionMethod $ref): object { $optimisedDoc = self::getOptimisedDoc($ref->getDocComment()); $name = $ref->getName(); return (object)[ 'name' => $name, 'description' => $optimisedDoc, 'deprecated' => Str::contains($optimisedDoc, '@deprecated'), 'access' => self::getAccessModifier($ref), 'return' => str_replace('|', ' | ', $ref->getReturnType() ?? Annotation::getMethodAnnotation( $ref->class, $name, 'return') ?? 'void|mixed'), 'params' => $ref->getParameters() ]; } public static function getConstant(ReflectionClassConstant $ref): object { $optimisedDoc = self::getOptimisedDoc($ref->getDocComment()); return (object)[ 'name' => $ref->getName(), 'value' => $ref->getValue(), 'description' => $optimisedDoc, 'deprecated' => Str::contains($optimisedDoc, '@deprecated'), ]; } #endregion }
C#
UTF-8
855
2.59375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GlobalFade : MonoBehaviour { public static GlobalFade instance; public Animator animator; #region[Awake] public void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); return; } } #endregion public void FadeAni(float fadeStart,float fadeEnd) { StartCoroutine(Fade(fadeStart, fadeEnd)); } private IEnumerator Fade(float fadeStart, float fadeEnd) { yield return new WaitForSeconds(fadeStart); animator.SetBool("Fade", true); yield return new WaitForSeconds(fadeEnd); animator.SetBool("Fade", false); } }
C++
UTF-8
1,020
3.6875
4
[]
no_license
#include <iostream> #include <vector> using namespace std; string stringCompressor(string A){ string result = ""; vector<pair<char, int>> currentTuples; int Reps = 1; for(int i = 0; i < A.length(); i++){ while(A[i] == A[i+1]){ Reps++; i++; } currentTuples.push_back(make_pair(A[i], Reps)); Reps = 1; } for(auto x:currentTuples) result += (x.first + to_string(x.second)); return result.length() < A.length() ? result:A; } int main(){ /* String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). */ string A = "aabcccccaaa"; string B = "abcdefghi"; cout << stringCompressor(A) << endl; }
JavaScript
UTF-8
966
2.828125
3
[ "Apache-2.0" ]
permissive
'use strict'; const fs = require('fs'); const github_events = 'jsonexamples/github_events.json'; var file = fs.readFileSync(github_events, 'utf-8'); var JSONObj = JSON.parse(file); // Display object content //console.log(JSONObj); // Display Object Keys //console.log(Object.keys(JSONObj)); // Display Object length //console.log(JSONObj.length); // Display strignified Object //console.log(JSON.stringify(JSONObj)); // Display Own Property Names console.log(Object.getOwnPropertyNames(JSONObj)); // Display Own Property Descriptors console.log(Object.getOwnPropertyDescriptors(JSONObj)); // Loop through JSON Array /*try { var i = 1; for (let item of JSONObj) { console.log(item); i++; } } catch(error) { console.error(error); }*/ // Display nested elements /*try { var i = 1; for (let item of simdjsonOBJ) { console.log(item.actor.login); i++; } } catch(error) { console.error(error); }*/
Ruby
UTF-8
1,685
2.890625
3
[]
no_license
require 'spec_helper' module ToySimulator describe Bearing do describe '.new' do it 'is private and cannot be called from outside the class' do expect {Bearing.new(facing: :south, forward: nil)}.to raise_error end end describe '.for' do let(:direction) {:south} let(:bearing) { described_class.for(direction) } context 'with valid direction' do it 'returns a valid bearing' do expect(bearing).to eq Bearing.south end context 'as symbol' do let(:direction) {:north} it 'returns a valid bearing' do expect(bearing).to eq Bearing.north end end end context 'with invalid direction' do let(:direction) {:invalid} let(:bearing) { described_class.for(direction) } it 'returns nil' do expect(bearing).to eq nil end end end describe '#left' do context 'north' do it 'returns west' do expect(Bearing.north.left).to eq Bearing.west end end context 'south' do it 'returns east' do expect(Bearing.south.left).to eq Bearing.east end end end describe '#right' do context 'east' do it 'returns south' do expect(Bearing.east.right).to eq Bearing.south end end context 'west' do it 'returns north' do expect(Bearing.west.right).to eq Bearing.north end end end describe '#to_h' do it 'returns a hash describing the bearing' do expect(Bearing.east.to_h).to eq({facing: :east}) end end end end
TypeScript
UTF-8
1,960
2.765625
3
[]
no_license
import { SimulatedPeripheral } from "../simulated-peripheral"; import { SimulatedBleError, BleErrorCode } from "../ble-error"; import { Base64 } from "../types"; let id = 0 export const IdGenerator = { nextId() { return id++ } } export function delay(delay: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, delay)) } export function findPeripheralWithDescriptor(peripherals: Array<SimulatedPeripheral>, descriptorId: number): SimulatedPeripheral | null { for (let i = 0; i < peripherals.length; i++) { if (peripherals[i].getDescriptor(descriptorId) != null) { return peripherals[i] } } return null } export function findPeripheralWithCharacteristic(peripherals: Array<SimulatedPeripheral>, characteristicIdentifier: number): SimulatedPeripheral | null { for (let i = 0; i < peripherals.length; i++) { if (peripherals[i].getCharacteristic(characteristicIdentifier) != null) { return peripherals[i] } } return null } export function findPeripheralWithService(peripherals: Array<SimulatedPeripheral>, serviceIdentifier: number): SimulatedPeripheral | null { for (let i = 0; i < peripherals.length; i++) { if (peripherals[i].getService(serviceIdentifier) != null) { return peripherals[i] } } return null } export function mapErrorToSimulatedBleError(error: any): SimulatedBleError { if (error instanceof SimulatedBleError) { return error } else { return new SimulatedBleError({ errorCode: BleErrorCode.UnknownError, message: error }) } } export function trimValueToMtu(value: Base64, size: number): Base64 { //3 bytes are reserved by the header of notification/indication const roundedMtu: number = Math.ceil(size / 3) * 3 const maxLength = (roundedMtu / 3) * 4 if (value.length < maxLength) return value return value.slice(0, maxLength) }
Shell
UTF-8
1,076
3.34375
3
[]
no_license
#!/bin/bash # From https://github.com/sunyal/gradle-profiler if [ -z "$ANDROID_HOME" ] then echo "ANDROID_HOME needs to be set" exit; fi if ! [ -x "$(command -v bazel)" ]; then echo 'Error: bazel is not installed.' >&2 exit 1 fi targets="cleanWithColdLocalCache cleanWithColdLocalCacheWithDaemon abiChangeWithLeafLocalCache abiChangeWithRootLocalCache nonAbiChangeWithLeafLocalCache nonAbiChangeWithRootLocalCache androidManifestChangeWithLeafLocalCache androidManifestChangeWithRootLocalCache androidResourceChangeWithLeafLocalCache androidResourceChangeWithRootLocalCache" timestampDir=$(date +"%Y%m%d_%H%M%S") outputDir=output/$timestampDir iterations=10 warmups=6 echo "Exporting benchmark data to $outputDir" echo "Snapshotting performance.scenarios to $outputDir" mkdir -p $outputDir/ cp performance.scenarios $outputDir/ ./gradle-profiler --benchmark $targets --iterations=$iterations --warmups=$warmups --output-dir=$outputDir/gradle ./gradle-profiler --benchmark --bazel $targets --iterations=$iterations --warmups=$warmups --output-dir=$outputDir/bazel
C#
UTF-8
1,135
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace SuperHeroAcademy { class Melee : Hero { int maxStamina; int stamina; string weapon; public Melee(int _stamina, string _weapon, int _hp, int _def, int _dmg, string _name) : base(_hp, _def, _dmg, _name) { stamina = _stamina; maxStamina = _stamina; weapon = _weapon; } public override void Practice() { base.Practice(); stamina++; } public override int GetDmg() { stamina--; if (stamina > 0) return base.GetDmg(); else return 0; } public override void Heal() { base.Heal(); stamina = maxStamina; } public override void PrintStats() { base.PrintStats(); Console.WriteLine("Type: Melee"); Console.WriteLine("Stamina: " + stamina + "/" + maxStamina); Console.WriteLine("Weapon: " + weapon); } } }
Shell
UTF-8
186
2.8125
3
[]
no_license
#!/usr/bin/env bash base=`dirname "$0"` root="$base/.." if [ "$1" = "--dev" ]; then export NODE_ENV="development" echo "activating development mode" fi "$root/src/server/index.mjs"
Markdown
UTF-8
2,660
3.390625
3
[]
no_license
#### SignUp User This week you will create an authentication system from stratch; that measn SignUp, SignIn, SignOut & a way to check if the user is signedIn. Today you only need to create a signUp page; Very important is that you set the validations for the email and password's. 1. The password should be at least 8 characters 2. The email should look like an email 3. Both email & password must be required 4. The email mush be unique and not shared with any other user Once the user has been registerd, redirect him to the home page where you will show his email, password, and sessionID. You can follow the example in [http://elium-athentication-complete.herokuapp.com/]. Moreover you should allert the usser with a message if password and/or email are incorrect. Finally add a route ```/clean``` to remove all user's records from the collection. This will be called at each time we start the test to reset the initial conditions. **API:** Method | URL | Action - | --------| --------- GET | /signUp | show Sign Up form POST | /signUp | Resiter User and redirect to "/" OR show singUp form with error messages. GET | / | Display User Info GET | /clean | Remove all user's records from your collection *GET - /signUp* 1. Expected to have: A form to add new sentences. Look at the example for the full list of errors. ```html <form action="/signUp" method="POST"> <input type="text" name="email"> <input type="password" name="password"> <input type="submit" value="submit"> </form> ``` *POST - /signUp* In case of failure expected to have: A form to add new sentences and the errors. Look at the example for the full list of errors. ```html <!-- if any errors then show --> <p class = "error" for="email"> </p> <p class = "error" for="password"> </p> <form action="/signUp" method="POST"> <input type="text" name="email"> <input type="password" name="password"> <input type="submit" value="submit"> </form> ``` 2. In case of success redirect home. *GET - /* Show user info. sessionID should be also stored in a cookie ```html YOu Made It <div> <div id = "email">email: <%= user.email %></div> <div id = "password">password: <%= user.password %></div> <div id = "sessionID">sessionID: <%= session.id %></div> </div> <form action ="/signOut" method = "post"> <input type = "submit" value = "LogOut"> </form> ``` **Notes:** try to fix the validation's yourself, however, if it takes to long, ask for the solution. The goal of this exercise is not to check that you can find the right settings, but that you can build the functionality.
Java
UTF-8
689
2.265625
2
[]
no_license
package com.android.promosee.core; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; /** * Created by imam on 26/09/16. */ public class Alert { public static void dialog(Context context, String error) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(error); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }
Java
UTF-8
1,709
2.5625
3
[]
no_license
import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import static org.testng.AssertJUnit.fail; /** * Created by fd on 03.07.2016. */ public class TestNegativeEmail { private String userFrom; private String password; private String message; private String topic; private String wrongEmail; /** * Read parameters from testng.xml * @param userFrom theskortabeast@tut.by * @param password * @param message text for a message * @param topic topic for a message * @param wrongEmail dasdagmail.com * */ @BeforeTest @Parameters({"userFrom", "password", "wrongEmail", "message", "topic"}) private void readParam(String userFrom, String password, String wrongEmail, String message, String topic) { this.userFrom = userFrom; this.password = password; this.wrongEmail = wrongEmail; this.message = message; this.topic = topic; } /** * Read param from xml and send * message from 1 acc theskortabeast@tut.by * to dasdagmail.com * */ @Test public void testSendTextMessage() { System.out.println("From acc 1 theskortabeast@tut.by to wrong email "); SendEmailMessages sender = new SendEmailMessages(userFrom, password); String[] users = { wrongEmail }; try { sender.sendMessage(message, topic, userFrom, users ); } catch (AddressException e) { fail(); } catch (MessagingException e) { fail(); } } }
Java
UTF-8
1,166
1.921875
2
[ "Apache-2.0" ]
permissive
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.editor.language.json.converter; import org.activiti.editor.language.bpmn.model.ScriptTask; import org.codehaus.jackson.node.ObjectNode; /** * @author Tijs Rademakers */ public class ScriptTaskConverter extends BaseBpmnElementToJsonConverter { protected String getActivityType() { return STENCIL_TASK_SCRIPT; } protected void convertElement(ObjectNode propertiesNode) { ScriptTask scriptTask = (ScriptTask) flowElement; propertiesNode.put(PROPERTY_SCRIPT_FORMAT, scriptTask.getScriptFormat()); propertiesNode.put(PROPERTY_SCRIPT_TEXT, scriptTask.getScript()); } }
Python
UTF-8
6,251
2.78125
3
[]
no_license
# semantic.py # author: Christophe VG # unit tests for the foo-lang semantic model import unittest from foo_lang.semantic.model import * from foo_lang.semantic.domains.nodes import Nodes, AllNodes, OwnNode from foo_lang.semantic.dumper import Dumper dumper = Dumper() def dump(model): return model.accept(dumper) class TestModel(unittest.TestCase): def setUp(self): self.model = Model() def tearDown(self): self.model = None def assertModelEquals(self, string): self.assertEqual(dump(self.model), string) # OBJECTS AND PROPERTIES def test_property(self): prop = Property(Identifier("name"), value=IntegerLiteralExp("123"), \ type=ObjectType(Identifier("type"))) self.assertEqual(dump(prop), "name : type = 123") def test_empty_object(self): obj = ObjectLiteralExp() self.assertEqual(dump(obj), "{}") def create_object_with_properties(self, amount=2): obj = ObjectLiteralExp() for index in range(amount): obj.properties.append(\ Property(Identifier("name" + str(index)), \ type=ObjectType(Identifier("type" + str(index))), \ value=IntegerLiteralExp(str(index)))) return obj def test_object_with_properties(self): obj = self.create_object_with_properties() self.assertEqual(dump(obj), "{\n name0 : type0 = 0\n" + \ " name1 : type1 = 1\n}") # CONST SUPPORT def test_const(self): const = Constant(Identifier("name"), value=IntegerLiteralExp("123"), \ type=ObjectType(Identifier("type"))) self.assertEqual(dump(const), "const name : type = 123") def test_const_with_unknown_type(self): const = Constant(Identifier("name"), value=IntegerLiteralExp("123")) self.assertEqual(dump(const), "const name = 123") # EXTENSIONS def test_extension_with_object_extension(self): obj = self.create_object_with_properties() ext = Extension(Nodes(), obj) self.assertEqual(dump(ext), "extend nodes with " + dump(obj)) # MODULE SUPPORT def test_empty_module(self): module = Module(Identifier("name")) self.assertEqual(dump(module), "module name\n") def create_module_with_constants(self, name, amount=2): module = Module(Identifier(name)) for index in range(amount): module.constants.append(\ Constant(Identifier("name" + str(index)), \ type=ObjectType(Identifier("type" + str(index))), \ value=IntegerLiteralExp(str(index)))) return module def test_module_with_constants(self): module = self.create_module_with_constants("moduleName") self.assertEqual(dump(module), "module moduleName\n" + \ "const name0 : type0 = 0\n" + \ "const name1 : type1 = 1\n") def create_module_with_extension(self, name, domain, obj): ext = Extension(domain, obj) module = Module(Identifier(name)) module.domains.append(domain) module.domains[domain.name].extend(ext) return module def test_module_with_extensions(self): obj = self.create_object_with_properties() module = self.create_module_with_extension("moduleName", Nodes(), obj) self.assertEqual(dump(module), "module moduleName\n" + \ "extend nodes with " + dump(obj) + "\n") def test_module_with_imports(self): module = Module(Identifier("moduleName")) module.externals["function1"] = "module1" module.externals["function2"] = "module2" module.externals["function1"] = "module3" # simple overriding principle self.assertEqual(dump(module), "module moduleName\n" + \ "from module3 import function1\n" + \ "from module2 import function2\n") # FUNCTIONS def create_function(self, name=None): if not name == None: name = Identifier(name) return FunctionDecl(BlockStmt([IncStmt(VariableExp(Identifier("x"))), IncStmt(VariableExp(Identifier("y")))]), identifier=name, \ parameters=[Parameter(Identifier("x")), Parameter(Identifier("y"))]) def test_function(self): function = self.create_function("name") self.assertEqual(dump(function), "function name(x, y) {\n x++\n y++\n}") def test_anon_function(self): function = self.create_function() self.assertEqual(dump(function), "function(x, y) {\n x++\n y++\n}") # SCOPING def test_domain_scope(self): scope = Nodes().get_scope() self.assertEqual(dump(scope), "nodes") def test_domain_specific_scope(self): scope = Nodes().get_scope("self") self.assertEqual(dump(scope), "nodes.self") # EXECUTION STRATEGIES def test_every_strategy(self): function = self.create_function("name") strategy = Every(AllNodes(Nodes()), function, \ VariableExp(Identifier("interval"))) self.assertEqual(dump(strategy), "@every(interval)\n" + \ "with nodes do " + dump(function)) # MODEL def test_empty_model(self): self.assertModelEquals("") def test_model_with_modules(self): module1 = self.create_module_with_constants("module1") obj = self.create_object_with_properties() module2 = self.create_module_with_extension("module2", Nodes(), obj) self.model.modules['mod1'] = module1 self.model.modules['mod2'] = module2 self.assertModelEquals("module module1\n" + \ "const name0 : type0 = 0\n" + \ "const name1 : type1 = 1\n" + \ "module module2\n" + \ "extend nodes with " + dump(obj) + "\n") # OBJECTS & co def test_methodcall_on_propertyexp(self): obj = ObjectExp(Identifier("obj")) prop = PropertyExp(obj, Identifier("prop")) methodcall = MethodCallExp(prop, Identifier("method")) self.assertEqual(dump(methodcall), "obj.prop.method()") if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestModel) unittest.TextTestRunner(verbosity=2).run(suite)
PHP
UTF-8
318
2.53125
3
[]
no_license
<?php namespace Migrations; use Codeframe\Schema; class CreateRoles { public function run() { Schema::dropIfExists('roles'); Schema::create('roles', function($table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } }
Python
UTF-8
616
2.515625
3
[]
no_license
#!/usr/bin/python3 """ Uses SQLAlchemy to print state objects """ from sys import argv from model_state import Base, State from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine if __name__ == "__main__": Session = sessionmaker() engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format (argv[1], argv[2], argv[3]), pool_pre_ping=True) session = Session(bind=engine) Base.metadata.create_all(engine) result = session.query(State).filter(State.name.like("%a%")).all() for x in result: session.delete(x) session.commit()
Swift
UTF-8
1,582
2.9375
3
[]
no_license
// // CatalogVC+TableViewDataSource.swift // Testflix // // Created by Victor Valfre on 14/04/19. // Copyright © 2019 Victor Valfre. All rights reserved. // import Foundation import UIKit //Extensao responsavel pela Tabela da tela Inicial extension CatalogViewController { override func numberOfSections(in tableView: UITableView) -> Int { return generos.values.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return generos.values[section].name } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let width: CGFloat = tableView.frame.width * 0.4 // 60% do tamanho da tela return width * (3/4) // aspectio ratio } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! TableViewCell cell.backgroundColor = .none var moviesFromGender = [Filme]() if( indexPath.section < generos.values.count){ moviesFromGender = generos.values[indexPath.section].movies! } cell.movies = moviesFromGender return cell } }
Java
UTF-8
14,184
1.648438
2
[]
no_license
package hami.mainapp.train.Services.Fragment; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.hami.common.BaseController.PaymentPresenter; import com.hami.common.BaseNetwork.BaseConfig; import com.hami.common.Util.CustomeChrome.CustomTabsPackages; import com.hami.common.Util.Hashing; import com.hami.common.Util.UtilFonts; import hami.mainapp.R; import hami.mainapp.train.Services.Adapter.PassengerInfoLisTrainAdapter; import hami.mainapp.train.Services.Controller.Model.RegisterTrainResponse; import hami.mainapp.train.Services.Controller.Model.TrainRequest; import hami.mainapp.train.Services.Controller.Model.TrainResponse; import hami.mainapp.train.Services.Controller.Presenter.TrainApi; import com.squareup.picasso.Picasso; import java.text.NumberFormat; import java.util.Locale; public class FragmentFinalBookingTrain extends Fragment { //----------------------------------------------- private View view; private AppCompatButton btnGetTicket, btnBuy, btnEdit, btnExit; private Boolean hasReserve = false, hasPayment = false; private RecyclerView rvResult; private PassengerInfoLisTrainAdapter mAdapter; private TextView txtTitleFinalTicket, txtFinalPrice, txtWarningCheckInfo; private LinearLayout layoutButtonPayment, layoutButtonGetTicket; private RegisterTrainResponse registerTrainResponse; private TrainResponse trainResponse; private TrainRequest trainRequest; //----------------------------------------------- @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { registerTrainResponse = savedInstanceState.getParcelable(RegisterTrainResponse.class.getName()); trainResponse = savedInstanceState.getParcelable(TrainResponse.class.getName()); hasReserve = savedInstanceState.getBoolean("hasReserve"); hasPayment = savedInstanceState.getBoolean("hasPayment"); } } //----------------------------------------------- @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); if (getArguments() != null) { registerTrainResponse = getArguments().getParcelable(RegisterTrainResponse.class.getName()); trainResponse = getArguments().getParcelable(TrainResponse.class.getName()); trainRequest = (TrainRequest) getArguments().getSerializable(TrainRequest.class.getName()); } } //----------------------------------------------- @Override public void onSaveInstanceState(Bundle outState) { if (outState != null) { outState.putParcelable(RegisterTrainResponse.class.getName(), registerTrainResponse); outState.putParcelable(TrainResponse.class.getName(), trainResponse); outState.putSerializable(TrainRequest.class.getName(), trainRequest); outState.putBoolean("hasReserve", hasReserve); outState.putBoolean("hasPayment", hasPayment); } super.onSaveInstanceState(outState); } //----------------------------------------------- public static FragmentFinalBookingTrain newInstance(RegisterTrainResponse registerTrainResponse, TrainResponse trainResponse, TrainRequest trainRequest) { Bundle args = new Bundle(); FragmentFinalBookingTrain fragment = new FragmentFinalBookingTrain(); args.putParcelable(RegisterTrainResponse.class.getName(), registerTrainResponse); args.putParcelable(TrainResponse.class.getName(), trainResponse); args.putSerializable(TrainRequest.class.getName(), trainRequest); fragment.setArguments(args); return fragment; } //----------------------------------------------- @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(R.layout.fragment_service_train_factor, container, false); initialComponentFragment(); } return view; } //----------------------------------------------- @Override public void onResume() { super.onResume(); if (hasReserve) { new TrainApi(getActivity()).hasBuyTicket(registerTrainResponse.getTicketId(), new PaymentPresenter() { @Override public void onStart() { } @Override public void onErrorServer() { } @Override public void onErrorInternetConnection() { } @Override public void onSuccessBuy() { if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { txtWarningCheckInfo.setVisibility(View.GONE); hasPayment = true; setupGetTicket(); txtTitleFinalTicket.setText(R.string.successGetTicket); ViewCompat.setBackgroundTintList(btnGetTicket, ColorStateList.valueOf(getResources().getColor(R.color.greenSelectedChair))); btnGetTicket.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getTicket(); } }); } }); } } @Override public void onErrorBuy() { } @Override public void onReTryGetPayment() { if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setupPayment(); btnGetTicket.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getTicket(); } }); } }); } } @Override public void onReTryGetTicket() { if (getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setupGetTicket(); txtTitleFinalTicket.setText(getString(R.string.msgErrorRunningGetTicket)); ViewCompat.setBackgroundTintList(btnGetTicket, ColorStateList.valueOf(Color.RED)); btnGetTicket.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPayment(); } }); } }); } } @Override public void onError(String msg) { } @Override public void onFinish() { } }); } } //----------------------------------------------- private void initialComponentFragment() { UtilFonts.overrideFonts(getActivity(), view, UtilFonts.IRAN_SANS_BOLD); layoutButtonGetTicket = view.findViewById(R.id.layoutButtonGetTicket); layoutButtonPayment = view.findViewById(R.id.layoutButtonPayment); txtTitleFinalTicket = view.findViewById(R.id.titleFinalTicket); txtWarningCheckInfo = view.findViewById(R.id.txtWarningCheckInfo); txtFinalPrice = view.findViewById(R.id.txtFinalPrice); btnBuy = view.findViewById(R.id.btnBuy); btnEdit = view.findViewById(R.id.btnEditBuy); btnGetTicket = view.findViewById(R.id.btnGetTicket); btnExit = view.findViewById(R.id.btnExit); btnGetTicket.setOnClickListener(onClickListener); btnBuy.setOnClickListener(onClickListener); btnExit.setOnClickListener(onClickListener); btnEdit.setOnClickListener(onClickListener); setupPlace(); setupRecyclerView(); } //----------------------------------------------- private void setupRecyclerView() { rvResult = view.findViewById(R.id.rvResult); rvResult.setHasFixedSize(true); LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity()); rvResult.setLayoutManager(mLayoutManager); rvResult.setItemAnimator(new DefaultItemAnimator()); mAdapter = new PassengerInfoLisTrainAdapter(getActivity(), registerTrainResponse); rvResult.setAdapter(mAdapter); } //----------------------------------------------- View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.btnEditBuy) { getActivity().onBackPressed(); } else if (i == R.id.btnBuy) { showPayment(); } else if (i == R.id.btnGetTicket) { getTicket(); } else if (i == R.id.btnExit) { getActivity().finish(); } } }; //----------------------------------------------- private void setupPlace() { txtFinalPrice.setText(getFinalPrice()); TextView txtWentFlightCity = view.findViewById(R.id.txtWentFlightCity); TextView txtWentFlightDateTime = view.findViewById(R.id.txtWentFlightDateTime); ImageView imgLogoAirLine = view.findViewById(R.id.imgLogoAirLine); TextView txtAirLineAndTypeClass = view.findViewById(R.id.txtAirLineAndTypeClass); txtWentFlightCity.setText("سفر به " + trainRequest.getDestinationTrain()); txtWentFlightDateTime.setText(trainRequest.getDepartureGoTrainPersian() + " , " + trainResponse.getExitTime()); String type = ""; if (trainResponse.getIsCompartment().contentEquals("1")) { type = (getText(R.string.cope) + " " + trainResponse.getCompartmentCapicity() + " " + getText(R.string.unitCountTrain)); } else { type = (getText(R.string.hall) + " " + trainResponse.getCompartmentCapicity() + " " + getText(R.string.unitCountTrain)); } txtAirLineAndTypeClass.setText(trainResponse.getWagonName() + "(" + type + ")"); Picasso.with(getActivity()) .load(BaseConfig.FOLDER_IMAGE_TRAIN_URL + trainResponse.getOwner().toLowerCase() + ".png") .into(imgLogoAirLine); } //----------------------------------------------- private String getFinalPrice() { String finalPrice = ""; try { finalPrice = registerTrainResponse.getViewParamsTrain().getFinalPrice(); finalPrice = NumberFormat.getNumberInstance(Locale.US).format(Long.valueOf(finalPrice) / 10); finalPrice = getString(R.string.finalPriceWithDiscount) + finalPrice + " تومان"; return finalPrice; } catch (Exception e) { finalPrice = getString(R.string.finalPriceWithDiscount) + registerTrainResponse.getViewParamsTrain().getFinalPrice(); return finalPrice + " ریال"; } } //----------------------------------------------- private void setupPayment() { layoutButtonPayment.setVisibility(View.VISIBLE); layoutButtonGetTicket.setVisibility(View.GONE); txtTitleFinalTicket.setVisibility(View.GONE); } //----------------------------------------------- private void setupGetTicket() { layoutButtonPayment.setVisibility(View.GONE); layoutButtonGetTicket.setVisibility(View.VISIBLE); txtTitleFinalTicket.setVisibility(View.VISIBLE); txtWarningCheckInfo.setVisibility(View.GONE); getActivity().findViewById(R.id.btnBack).setVisibility(View.INVISIBLE); } //----------------------------------------------- public void showPayment() { hasReserve = true; String ticketId = registerTrainResponse.getTicketId(); String hash = Hashing.getHash(ticketId); String url = BaseConfig.MELLAT_BANK_TRAIN + ticketId + "/" + hash; new CustomTabsPackages(getActivity()).showUrl(url); } //----------------------------------------------- public void getTicket() { String ticketId = registerTrainResponse.getTicketId(); String hash = Hashing.getHash(ticketId); String url = BaseConfig.BASE_URL_MASTER + "train/pdfticket/" + ticketId + "/" + hash; new CustomTabsPackages(getActivity()).showUrl(url); } //----------------------------------------------- public Boolean hasBuyTicket() { return hasPayment; } }
JavaScript
UTF-8
1,423
2.96875
3
[]
no_license
"use strict"; function loadDoc(){ console.log("loadDoc"); console.log(this); let text_client = new XMLHttpRequest(); text_client.onreadystatechange = () => { if(text_client.readyState == 4 && text_client.status == 200){ document.getElementById("textarea").innerHTML = text_client.responseText; } }; text_client.open("GET","text.txt",true); text_client.send(); } function loadDoc2(){ console.log("loadDoc2"); console.log("loadDoc2\n"+this); let text_client = new XMLHttpRequest(); text_client.onreadystatechange = () => { if(text_client.readyState == 4 && text_client.status == 200){ let colors = ["red","green","blue"]; // document.getElementById("textarea2"); // console.log(text_client.responseText); let lines = text_client.responseText.split('\n'); // console.log(lines); let all_p = ""; for (let i in lines) { let p = "\n<p style=\"color:"+colors[i%3]+";\">"+lines[i]+"</p>\n"; // document.createElement("p"); all_p += p; } document.getElementById("textarea2").innerHTML = all_p; } }; text_client.open("GET","text.txt",true); text_client.send(); }
Markdown
UTF-8
4,447
3.59375
4
[]
no_license
# AndroidLaunchMode > 我们都知道,开启一个Activity,系统会在任务栈中创建实例,而任务栈是一种“后进先出”的栈结构。默认情况下,开启一个Activity,系统会创建实例,如果多次创建同一个实例,难道还要栈中创建多个相同的实例 ? 当然 是不可以的。由此,Android在设计的时候提供了启动模式来修改系统的默认行为。 * **standard** ``` 标准模式,也是系统的默认模式。每次启动一个Act的时候都会创建一个新的实例,系统不管这个实例是否已经存在。 例如:Activity A 启动了Activity B (标准模式),此时在Act A的栈中 就会新建一个Act B 的实例,此时栈中 Act A 在栈底 Act B在栈顶。 ``` * **singleTop** ``` 栈顶复用模式。设置这种启动模式的Act,如果此时已经在任务栈的栈顶,那么此Act不会被重新创建,而是会走此Act的onNewIntent,此Act的onCreate、onStart不会被创建。如果此Act在任务栈中已经有实例但是不是在任务栈的栈顶,那此Act仍会重新创建。 例如:当前任务栈中有 ABCD 4个Act,A在栈底,D在栈顶,其中BD的启动模式为singleTop,此时如果在开启Activity D,那么任务栈中情况为:ABCD,如果此时开启Activity B,任务栈中情况为:ABCDB。 ``` * **singleTask** ``` 栈内复用模式。这是一种单实例模式。设置此启动模式的Act,只要在所在的栈中出现,再多次启动的时候不会重新创建,而是重走onNewIntent方法。 例如(考虑在同一栈中):此时任务栈中有ABC三个Act,A为栈底,B为singleTask,C为栈顶,此时要开启一个ssingleTask的Act D,那么此时就会创建新的Act D。此时任务栈内情况为:ABCD。如果此时再次开启Act B,因为Act B为singleTask,那么此时任务栈内情况为:AB。Act B会重走onNewIntet方法。这里说一下:singleTask默认具有clearTop效果。所以再次开启singleTask的Act B的时候会把Act B上的 C D 销毁。 ``` * **singleInstance** ``` 单实例模式。一种加强的singleTask模式,这种模式具有了singleTask模式的所有特性,还加强了一点,就是具有此启动模式的Act创建的时候只能单独地位于一个任务栈中。 例如:Act A的启动模式是singleInstance,此时如果开始Act A,那么系统会创建一个新的任务栈,然后把Act A单独存放在这个新建的任务栈中,又因为singleInstance具有singleTask的所有特性,也就是说也有栈内复用的特性,如果当前的Act A不会销毁,那么以后再次启动Act A均不会创建新的Act。 例如:此时任务栈中有默认的Act A,此时开启一个singleInstance 模式的Act B,在Act B中开启一个非singleInstance的Act C,此时 Act C在Act A所在的栈中,在Act C中如果按返回键 此时返回看到的是Act A。 ``` *** ## Activity Flags > Activity Flags有很多,这里主要分析一些比较常用的标记位。而标记位作用有很多。 > 比如:设定Activity 启动模式的 FLAG_ACTIVITY_NEW_TASK 和 FLAG_ACTIVITY_SINGLE_TOP等;影响Activity的运行状态的:FLAG_ACTIVITY_CLEAR_TOP 和 FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS等。 * **FLAG_ACTIVITY_NEW_TASK** ``` 此标记位的作用是为Activity指定"singleTask"启动模式,作用效果和在XML中指定该启动模式相同。 ``` * **FLAG_ACTIVITY_SINGLE_TOP** ``` 此标记位的作用是为Activity指定"singleTop"启动模式,作用效果和在XML中指定该启动模式相同。 ``` * **FLAG_ACTIVITY_CLEAR_TOP** ``` 具有此标记位的Act,启动的时候,在同一任务栈中所有位于它上面的Act都要销毁。一般此标记位会和singleTask一起出现,在这种情况下,如果被启动的Act实例已经存在于当前任务栈中,那么系统会调用它的onNewIntent方法。如果此时配合默认的启动方式开启,那么此时会当任务栈中已经存在的实例连同它之上的Act都会销毁,清除出栈。系统会创建新的Act实例对象在栈顶。 ``` * **FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS** ``` 具有此标记位的Act,不会出现在历史Act列表中,当某些情况下我们不希望用户通过历史列表回到我们Act的时候,此标记会很好用。它等同于在XML文件中指定Act的属性"android:excludeFromRecents = "true" "。 ```
PHP
UTF-8
2,469
3.0625
3
[ "MIT" ]
permissive
<?php namespace MyProject\Models\Articles; use MyProject\Exceptions\InvalidArgumentException; use MyProject\Models\ActiveRecordEntity; use MyProject\Models\Users\User; class Article extends ActiveRecordEntity { protected $name; protected $text; protected $authorId; protected $createdAt; public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $name; } public function getText(): string { $parser = new \Parsedown(); return $parser->text($this->text); } public function getShortText(): string { $parser = new \Parsedown(); return $parser->text(mb_substr($this->text, 0, 200)); } public function setText(string $text): void { $this->text = $text; } public function getAuthor(): User { return User::getById($this->authorId); } public function setAuthorId($authorId): void { $this->authorId = $authorId; } public function setAuthor(User $author): void { $this->authorId = $author->getId(); } public function getCreatedAt(): string { return $this->getCorrectDateTime()->createdAt; } protected static function getTableName(): string { return 'articles'; } public static function createArticle(array $fields, User $author): Article { if (empty($fields['name'])) { throw new InvalidArgumentException('Не передано название статьи'); } if (empty($fields['text'])) { throw new InvalidArgumentException('Не передан текст статьи'); } $article = new Article(); $article->setAuthor($author); $article->setName($fields['name']); $article->setText($fields['text']); $article->save(); return $article; } public function editArticle(array $article): Article { if (empty($article['name'])) { throw new InvalidArgumentException('Отсутствует заголовок статьи'); } if (empty($article['text'])) { throw new InvalidArgumentException('Отсутствует текст статьи'); } $this->setName($article['name']); $this->setText($article['text']); $this->save(); return $this; } }
Python
UTF-8
344
2.75
3
[]
no_license
from django.http import HttpResponse def home_page(request): return HttpResponse("Hello, django!") def html_response(request): html = \ """ <html> <head> </head> <body> <h1>Hello, django!</h1> <p>HTML 문서를 응답으로 보내줍니다.</p> </body> </html> """ return HttpResponse(html)
Java
UTF-8
3,385
1.726563
2
[]
no_license
package outdoorapp.utils; /** * Interfaccia che contiene tutte le chiavi-valore per far visualizzare le view * * @author Andrea Zito * @author Francesco Ventura * */ public interface Views { public static final String VIEW_LOGIN = "VIEW_LOGIN"; public static final String VIEW_DASHBOARD_WELCOME = "VIEW_DASHBOARD_WELCOME"; public static final String VIEW_MANAGER_DI_SISTEMA_CONFIG = "VIEW_MANAGER_DI_SISTEMA_CONFIG"; public static final String VIEW_DASHBOARD_MANAGER_DI_SISTEMA = "VIEW_DASHBOARD_MANAGER_DI_SISTEMA"; public static final String VIEW_DASHBOARD_MANAGER_DI_ESCURSIONE = "VIEW_DASHBOARD_MANAGER_DI_ESCURSIONE"; public static final String VIEW_DASHBOARD_PARTECIPANTE = "VIEW_DASHBOARD_PARTECIPANTE"; public static final String VIEW_PASSWORD_DIMENTICATA = "VIEW_PASSWORD_DIMENTICATA"; public static final String VIEW_REGISTRAZIONE_PARTECIPANTE = "VIEW_REGISTRAZIONE_PARTECIPANTE"; public static final String VIEW_GESTIONE_MANAGER_ESCURSIONE = "VIEW_GESTIONE_MANAGER_ESCURSIONE"; public static final String VIEW_VISUALIZZA_ESCURSIONI_SISTEMA = "VIEW_VISUALIZZA_ESCURSIONI_SISTEMA"; public static final String VIEW_REGISTRAZIONE_MANAGER_ESCURSIONE = "VIEW_REGISTRAZIONE_MANAGER_ESCURSIONE"; public static final String VIEW_GESTIONE_ESCURSIONI = "VIEW_GESTIONE_ESCURSIONI"; public static final String VIEW_INSERISCI_ESCURSIONE = "VIEW_INSERISCI_ESCURSIONE"; public static final String VIEW_LE_MIE_ESCURSIONI = "VIEW_LE_MIE_ESCURSIONI"; public static final String VIEW_VISUALIZZA_ESCURSIONI_APERTE = "VIEW_VISUALIZZA_ESCURSIONI_APERTE"; public static final String VIEW_IL_MIO_PROFILO = "VIEW_IL_MIO_PROFILO"; public static final String VIEW_DETTAGLI_MANAGER_DI_ESCURSIONE = "VIEW_DETTAGLI_MANAGER_DI_ESCURSIONE"; public static final String VIEW_MODIFICA_MANAGER_DI_ESCURSIONE = "VIEW_MODIFICA_MANAGER_DI_ESCURSIONE"; public static final String VIEW_DETTAGLI_ESCURSIONI_SISTEMA = "VIEW_DETTAGLI_ESCURSIONI_SISTEMA"; public static final String VIEW_DETTAGLI_PARTECIPANTE = "VIEW_DETTAGLI_PARTECIPANTE"; public static final String VIEW_DETTAGLI_ESCURSIONI_FROM_MDE = "VIEW_DETTAGLI_ESCURSIONI_FROM_MDE"; public static final String VIEW_MODIFICA_ESCURSIONE = "VIEW_MODIFICA_ESCURSIONE"; public static final String VIEW_AGGIORNA_SRC_PARTECIPANTE = "VIEW_AGGIORNA_SRC_PARTECIPANTE"; public static final String VIEW_MODIFICA_DATI_PARTECIPANTE = "VIEW_MODIFICA_DATI_PARTECIPANTE"; public static final String VIEW_ISCRITTI_ESCURSIONE = "VIEW_ISCRITTI_ESCURSIONE"; public static final String VIEW_ISCRIZIONE_ESCURSIONE = "VIEW_ISCRIZIONE_ESCURSIONE"; public static final String VIEW_MODIFICA_ISCRIZIONE_ESCURSIONE = "VIEW_MODIFICA_ISCRIZIONE_ESCURSIONE"; public static final String VIEW_SELEZIONA_OPTIONAL_ISCRIZIONE = "VIEW_SELEZIONA_OPTIONAL_ISCRIZIONE"; public static final String VIEW_ISCRITTI_ESCURSIONE_SISTEMA = "VIEW_ISCRITTI_ESCURSIONE_SISTEMA"; public static final String VIEW_DETTAGLI_PARTECIPANTE_SISTEMA = "VIEW_DETTAGLI_PARTECIPANTE_SISTEMA"; public static final String VIEW_SELEZIONA_OPTIONAL_ISCRIZIONE_PARTECIPANTE = "VIEW_SELEZIONA_OPTIONAL_ISCRIZIONE_PARTECIPANTE"; public static final String VIEW_MODIFICA_ISCRIZIONE_ESCURSIONE_PARTECIPANTE = "VIEW_MODIFICA_ISCRIZIONE_ESCURSIONE_PARTECIPANTE"; public static final String VIEW_SELEZIONA_MODIFICA_OPTIONAL_ISCRIZIONE_PARTECIPANTE = "VIEW_SELEZIONA_MODIFICA_OPTIONAL_ISCRIZIONE_PARTECIPANTE"; }
Java
UTF-8
1,261
2.484375
2
[]
no_license
package usu.cs.Sensys.Messages; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SignatureException; import usu.cs.Sensys.util.PublicKeyManager; public class MessageRequest extends Request { private boolean isEmmergency = false; private String message; private byte[] signature; @Override public String getMessageType() { // TODO Auto-generated method stub return this.getClass().getName(); } public MessageRequest(boolean emmergency, String msg) { // TODO Auto-generated constructor stub isEmmergency = emmergency; message = msg; try { signature = PublicKeyManager.getInstance().generateSignature(msg); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public byte[] getSignature() { return signature; } public String getMessage() { return message; } public boolean isEmmergency() { return isEmmergency; } public MessageRequest() { // TODO Auto-generated constructor stub } }
Markdown
UTF-8
16,987
3.5625
4
[]
no_license
## synchronized概述 Synchronized是Java中解决并发问题的一种最常用的方法,也是最简单的一种方法。 Synchronized主要有三个作用: (1)确保线程互斥的访问同步代码。 (2)保证共享变量的修改能够及时可见。 (3)有效解决重排序问题。 ## synchronized使用场景 ### 普通同步方法,锁是当前实例对象 ```java public class SynchronizedTest { public synchronized void method1() { System.out.println("Method 1 start"); try { System.out.println("Method 1 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); } public synchronized void method2() { System.out.println("Method 2 start"); try { System.out.println("Method 2 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } } ``` Client: ```java public static void main(String[] args) { SynchronizedTest test = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { test.method1(); } }).start(); new Thread(new Runnable() { @Override public void run() { test.method2(); } }).start(); } ``` 打印结果: ```java Method 1 start Method 1 execute Method 1 end Method 2 start Method 2 execute Method 2 end ``` 从打印结果上看,test.method1();方法执行完之后,才能轮到test.method2();执行。 Client: ```java public static void main(String[] args) { SynchronizedTest test01 = new SynchronizedTest(); SynchronizedTest test02 = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { test01.method1(); } }).start(); new Thread(new Runnable() { @Override public void run() { test02.method2(); } }).start(); } ``` 打印结果: ```java Method 1 start Method 1 execute Method 2 start Method 2 execute Method 2 end Method 1 end ``` 从打印结果上看,test01.method1();方法在执行过程中test02.method2();同时也在执行。 ### 静态同步方法,锁是当前类的class对象 ```java public class SynchronizedTest { public static synchronized void method1() { System.out.println("Method 1 start"); try { System.out.println("Method 1 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); } public static synchronized void method2() { System.out.println("Method 2 start"); try { System.out.println("Method 2 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } } ``` Client: ```java public static void main(String[] args) { SynchronizedTest test01 = new SynchronizedTest(); SynchronizedTest test02 = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { test01.method1(); } }).start(); new Thread(new Runnable() { @Override public void run() { test02.method2(); } }).start(); } ``` 打印结果: ```java Method 1 start Method 1 execute Method 1 end Method 2 start Method 2 execute Method 2 end ``` 从打印结果上看,test01.method1();方法执行完之后,才能轮到test02.method2();执行。 ### 同步方法块,锁是括号里面的对象 ```java public class SynchronizedTest { public void method1() { System.out.println("Method 1 start"); try { synchronized (this) { System.out.println("Method 1 execute"); Thread.sleep(3000); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); } public void method2() { System.out.println("Method 2 start"); try { synchronized (this) { System.out.println("Method 2 execute"); Thread.sleep(3000); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } } ``` Client: ```java public static void main(String[] args) { SynchronizedTest test01 = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { test01.method1(); } }).start(); new Thread(new Runnable() { @Override public void run() { test01.method2(); } }).start(); } ``` 打印结果: ```java Method 1 start Method 1 execute Method 2 start Method 1 end Method 2 execute Method 2 end ``` 从打印结果上看,test.method1();方法执行完之后,才能轮到test.method2();执行。 Client: ```java public static void main(String[] args) { SynchronizedTest test01 = new SynchronizedTest(); SynchronizedTest test02 = new SynchronizedTest(); new Thread(new Runnable() { @Override public void run() { test01.method1(); } }).start(); new Thread(new Runnable() { @Override public void run() { test02.method2(); } }).start(); } ``` 打印结果: ```java Method 1 start Method 1 execute Method 2 start Method 2 execute Method 2 end Method 1 end ``` 从打印结果上看,test.method1();方法执行完之后,才能轮到test.method2();执行。 ## synchronize底层原理 Java 虚拟机中的同步(Synchronization)基于进入和退出Monitor对象实现, 无论是显式同步(有明确的 monitorenter 和 monitorexit 指令,即同步代码块)还是隐式同步都是如此。在 Java 语言中,同步用的最多的地方可能是被 synchronized 修饰的同步方法。同步方法 并不是由 monitorenter 和 monitorexit 指令来实现同步的,而是由方法调用指令读取运行时常量池中方法表结构的 ACC_SYNCHRONIZED 标志来隐式实现的。 同步代码块:monitorenter指令插入到同步代码块的开始位置,monitorexit指令插入到同步代码块的结束位置,JVM需要保证每一个monitorenter都有一个monitorexit与之相对应。任何对象都有一个monitor与之相关联,当且一个monitor被持有之后,他将处于锁定状态。线程执行到monitorenter指令时,将会尝试获取对象所对应的monitor所有权,即尝试获取对象的锁。 在JVM中,对象在内存中的布局分为三块区域:对象头、实例变量和填充数据。如下: ![](https://images2017.cnblogs.com/blog/918656/201708/918656-20170824180707777-1312147323.png) 实例变量:存放类的属性数据信息,包括父类的属性信息,如果是数组的实例部分还包括数组的长度,这部分内存按4字节对齐。 填充数据:由于虚拟机要求对象起始地址必须是8字节的整数倍。填充数据不是必须存在的,仅仅是为了字节对齐,这点了解即可。 对象头:Hotspot虚拟机的对象头主要包括两部分数据:Mark Word(标记字段)、Klass Pointer(类型指针)。其中Klass Point是是对象指向它的类元数据的指针,虚拟机通过这个指针来确定这个对象是哪个类的实例,Mark Word用于存储对象自身的运行时数据,它是实现轻量级锁和偏向锁的关键。 Mark Word:用于存储对象自身的运行时数据,如哈希码(HashCode)、GC分代年龄、锁状态标志、线程持有的锁、偏向线程 ID、偏向时间戳等等。Java对象头一般占有两个机器码(在32位虚拟机中,1个机器码等于4字节,也就是32bit),但是如果对象是数组类型,则需要三个机器码,因为JVM虚拟机可以通过Java对象的元数据信息确定Java对象的大小,但是无法从数组的元数据来确认数组的大小,所以用一块来记录数组长度。 Monior:我们可以把它理解为一个同步工具,也可以描述为一种同步机制,它通常被描述为一个对象。与一切皆对象一样,所有的Java对象是天生的Monitor,每一个Java对象都有成为Monitor的潜质,因为在Java的设计中 ,每一个Java对象自打娘胎里出来就带了一把看不见的锁,它叫做内部锁或者Monitor锁。Monitor 是线程私有的数据结构,每一个线程都有一个可用monitor record列表,同时还有一个全局的可用列表。每一个被锁住的对象都会和一个monitor关联(对象头的MarkWord中的LockWord指向monitor的起始地址),同时monitor中有一个Owner字段存放拥有该锁的线程的唯一标识,表示该锁被这个线程占用。其结构如下: ![](https://images2017.cnblogs.com/blog/918656/201708/918656-20170824181742996-1450027779.png) Owner:初始时为NULL表示当前没有任何线程拥有该monitor record,当线程成功拥有该锁后保存线程唯一标识,当锁被释放时又设置为NULL; EntryQ:关联一个系统互斥锁(semaphore),阻塞所有试图锁住monitor record失败的线程。 RcThis:表示blocked或waiting在该monitor record上的所有线程的个数。 Nest:用来实现重入锁的计数。 HashCode:保存从对象头拷贝过来的HashCode值(可能还包含GC age)。 Candidate:用来避免不必要的阻塞或等待线程唤醒,因为每一次只有一个线程能够成功拥有锁,如果每次前一个释放锁的线程唤醒所有正在阻塞或等待的线程,会引起不必要的上下文切换(从阻塞到就绪然后因为竞争锁失败又被阻塞)从而导致性能严重下降。Candidate只有两种可能的值0表示没有需要唤醒的线程1表示要唤醒一个继任线程来竞争锁。 ## Java虚拟机对synchronize的优化 锁的状态总共有四种,无锁状态、偏向锁、轻量级锁和重量级锁。随着锁的竞争,锁可以从偏向锁升级到轻量级锁,再升级的重量级锁,但是锁的升级是单向的,也就是说只能从低到高升级,不会出现锁的降级,关于重量级锁,前面我们已详细分析过,下面我们将介绍偏向锁和轻量级锁以及JVM的其他优化手段。 ### 偏向锁 偏向锁是Java 6之后加入的新锁,它是一种针对加锁操作的优化手段,经过研究发现,在大多数情况下,锁不仅不存在多线程竞争,而且总是由同一线程多次获得,因此为了减少同一线程获取锁(会涉及到一些CAS操作,耗时)的代价而引入偏向锁。偏向锁的核心思想是,如果一个线程获得了锁,那么锁就进入偏向模式,此时Mark Word 的结构也变为偏向锁结构,当这个线程再次请求锁时,无需再做任何同步操作,即获取锁的过程,这样就省去了大量有关锁申请的操作,从而也就提供程序的性能。所以,对于没有锁竞争的场合,偏向锁有很好的优化效果,毕竟极有可能连续多次是同一个线程申请相同的锁。但是对于锁竞争比较激烈的场合,偏向锁就失效了,因为这样场合极有可能每次申请锁的线程都是不相同的,因此这种场合下不应该使用偏向锁,否则会得不偿失,需要注意的是,偏向锁失败后,并不会立即膨胀为重量级锁,而是先升级为轻量级锁。 ### 轻量级锁 倘若偏向锁失败,虚拟机并不会立即升级为重量级锁,它还会尝试使用一种称为轻量级锁的优化手段(1.6之后加入的),此时Mark Word 的结构也变为轻量级锁的结构。轻量级锁能够提升程序性能的依据是“对绝大部分的锁,在整个同步周期内都不存在竞争”,注意这是经验数据。需要了解的是,轻量级锁所适应的场景是线程交替执行同步块的场合,如果存在同一时间访问同一锁的场合,就会导致轻量级锁膨胀为重量级锁。 ### 自旋锁 轻量级锁失败后,虚拟机为了避免线程真实地在操作系统层面挂起,还会进行一项称为自旋锁的优化手段。这是基于在大多数情况下,线程持有锁的时间都不会太长,如果直接挂起操作系统层面的线程可能会得不偿失,毕竟操作系统实现线程之间的切换时需要从用户态转换到核心态,这个状态之间的转换需要相对比较长的时间,时间成本相对较高,因此自旋锁会假设在不久将来,当前的线程可以获得锁,因此虚拟机会让当前想要获取锁的线程做几个空循环(这也是称为自旋的原因),一般不会太久,可能是50个循环或100循环,在经过若干次循环后,如果得到锁,就顺利进入临界区。如果还不能获得锁,那就会将线程在操作系统层面挂起,这就是自旋锁的优化方式,这种方式确实也是可以提升效率的。最后没办法也就只能升级为重量级锁了。 ### 锁消除 消除锁是虚拟机另外一种锁的优化,这种优化更彻底,Java虚拟机在JIT编译时(可以简单理解为当某段代码即将第一次被执行时进行编译,又称即时编译),通过对运行上下文的扫描,去除不可能存在共享资源竞争的锁,通过这种方式消除没有必要的锁,可以节省毫无意义的请求锁时间,如下StringBuffer的append是一个同步方法,但是在add方法中的StringBuffer属于一个局部变量,并且不会被其他线程所使用,因此StringBuffer不可能存在共享资源竞争的情景,JVM会自动将其锁消除。 ## synchronize的可重入性 从互斥锁的设计上来说,当一个线程试图操作一个由其他线程持有的对象锁的临界资源时,将会处于阻塞状态,但当一个线程再次请求自己持有对象锁的临界资源时,这种情况属于重入锁,请求将会成功。在java中,synchronized是基于原子性的内部锁机制,是可重入的,因此在一个线程调用synchronized方法的同时在其方法体内部调用该对象另一个synchronized方法,也就是说一个线程得到一个对象锁后再次请求该对象锁,是允许的,这就是synchronized的可重入性。 ```java public class SynchronizedTest4 { public synchronized void method1() { System.out.println("Method 1 start"); try { System.out.println("Method 1 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 1 end"); // 在method1中调用method3 method3(); } public synchronized void method2() { System.out.println("Method 2 start"); try { System.out.println("Method 2 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 2 end"); } public synchronized void method3() { System.out.println("Method 3 start"); try { System.out.println("Method 3 execute"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Method 3 end"); } } ``` Client: ```java public static void main(String[] args) { SynchronizedTest4 test01 = new SynchronizedTest4(); new Thread(new Runnable() { @Override public void run() { test01.method1(); } }).start(); new Thread(new Runnable() { @Override public void run() { test01.method2(); } }).start(); } ``` 打印结果: ```java Method 1 start Method 1 execute Method 1 end Method 3 start Method 3 execute Method 3 end Method 2 start Method 2 execute Method 2 end ``` 从打印结果中可以看出,method1()执行完之后,接着执行method3(),最后才执行method2()。 注:当子类继承父类时,子类也是可以通过可重入锁调用父类的同步方法。注意由于synchronized是基于monitor实现的,因此每次重入,monitor中的计数器仍会加1。 ## 等待唤醒机制与synchronize 所谓等待唤醒机制本篇主要指的是notify/notifyAll和wait方法,在使用这3个方法时,必须处于synchronized代码块或者synchronized方法中,否则就会抛出IllegalMonitorStateException异常,这是因为调用这几个方法前必须拿到当前对象的监视器monitor对象,也就是说notify/notifyAll和wait方法依赖于monitor对象,在前面的分析中,我们知道monitor 存在于对象头的Mark Word 中(存储monitor引用指针),而synchronized关键字可以获取 monitor ,这也就是为什么notify/notifyAll和wait方法必须在synchronized代码块或者synchronized方法调用的原因。
Ruby
UTF-8
213
2.71875
3
[]
no_license
#Looked at your solution(ashamedly). result = {} letters = ('A'..'Z').to_a.concat( ('a'..'z').to_a ) letters.each do |letter| count = statement.scan(letter.to_s).count result[letter] = count if count > 0 end
TypeScript
UTF-8
1,511
3.09375
3
[]
no_license
import { AxiosError, AxiosResponse } from 'axios'; export function handleResponse(response: { text: () => Promise<any>; ok: boolean; statusText: string; }) { // The `response` object has `text()` method which is also a Promise. return response.text().then(text => { const data = text && JSON.parse(text); if (!response.ok) { // If the fulfilled promise response.text() `ok` property is false, // We will return the relevant error data. const error = data && data.message ? data : response.statusText; return Promise.reject(error); } return data; }); } // Axios helper function for the resolve promise export function handleResolvePromise(response: AxiosResponse) { return response.data; } // Axios helper function for the reject promise // Basically, It will return a reject promise. export function handleRejectPromise(error: AxiosError) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx return Promise.reject(error.response.data); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js return Promise.reject({ message: error.message }); } else { // Something happened in setting up the request that triggered an Error return Promise.reject({ message: error.message }); } }
Markdown
UTF-8
4,452
2.921875
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post date: 2020-07-03 13:43:35 -0600 title: Independence Day Fun With JavaScript permalink: independence_day_fun_with_javascript --- If you live in the USA, Happy Independence Day! I've been busy this week doing family stuff, so I honestly haven't touched the COVIDiary project. We'll hopefully get back into that in the next week or so. Instead, I thought we'd have a little fun with JavaScript today. We are going to use HTML, CSS, and JavaScript to create the American Flag! ## Starter Code This tutorial is focusing on JavaScript, so I have provided the HTML and CSS for you. When you finish the tutorial, feel free to play with the CSS properties to see how they work. I added comments to the code so you know what each line does. Here's the starter code. If you want to code along, I suggest clicking the **Edit on CODEPEN** button and putting that tab in a new window. <p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="html,result" data-user="audthecodewitch" data-slug-hash="RwrxOxZ" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="US Flag (Starter Template)"> <span>See the Pen <a href="https://codepen.io/audthecodewitch/pen/RwrxOxZ"> US Flag (Starter Template)</a> by Audrea Cook (<a href="https://codepen.io/audthecodewitch">@audthecodewitch</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> <script async src="https://static.codepen.io/assets/embed/ei.js"></script> I provided a blank flag template via HTML and CSS. You are going to add the JavaScript to create the field of stripes and the union (the blue square with stars) using two separate functions. I've separated the functions into the two embedded CodePens below, but you'll add the code for both to your JavaScript tab in your CodePen! ## The `stripes()` Function This function will create our 13 red and white stripes. Read the comments for each line to see what it's doing. <p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="js,result" data-user="audthecodewitch" data-slug-hash="jOWYRXR" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="US Flag (Stripes)"> <span>See the Pen <a href="https://codepen.io/audthecodewitch/pen/jOWYRXR"> US Flag (Stripes)</a> by Audrea Cook (<a href="https://codepen.io/audthecodewitch">@audthecodewitch</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> <script async src="https://static.codepen.io/assets/embed/ei.js"></script> ## The `stars()` Function This function will create our blue union with the 9 rows of white stars. The stars are FontAwesome icons.Please note the location of union within our flag container is determined by the CSS `#union` id. <p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="js,result" data-user="audthecodewitch" data-slug-hash="bGEaJXz" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="US Flag (Stars)"> <span>See the Pen <a href="https://codepen.io/audthecodewitch/pen/bGEaJXz"> US Flag (Stars)</a> by Audrea Cook (<a href="https://codepen.io/audthecodewitch">@audthecodewitch</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> <script async src="https://static.codepen.io/assets/embed/ei.js"></script> ## Bippity-Boppity Boo! (Put it Together) If you've been coding along, you should have a beautiful US flag! If not, here's what it looks like when the two functions are put together. <p class="codepen" data-height="500" data-theme-id="dark" data-default-tab="js,result" data-user="audthecodewitch" data-slug-hash="ExPbPQZ" style="height: 500px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="US Flag (Complete)"> <span>See the Pen <a href="https://codepen.io/audthecodewitch/pen/ExPbPQZ"> US Flag (Complete)</a> by Audrea Cook (<a href="https://codepen.io/audthecodewitch">@audthecodewitch</a>) on <a href="https://codepen.io">CodePen</a>.</span> </p> <script async src="https://static.codepen.io/assets/embed/ei.js"></script> I hope you had as much fun with this as I did! Have a safe and wonderful 4th of July!
Python
UTF-8
2,491
2.6875
3
[]
no_license
# coding:utf-8 import torch import shutil import numpy as np class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def adjust_learning_rate_epoch_poly(optimizer, args, burn_in, power, batch_num, max_batches): if batch_num < burn_in: lr = args.lr * pow(float(batch_num) / burn_in, power) else: lr = args.lr * pow(1 - float(batch_num) / max_batches, power) for param_group in optimizer.param_groups: param_group['lr'] = lr return str(batch_num) + " LR: " + str(lr) + "\n" def read_imagenet_labels_list(label_list_path): with open(label_list_path, 'r') as fl: cls_index = 0 darknet_cls_index = {} for c_line in fl: if c_line != "": darknet_cls_index[c_line.strip('\n')] = cls_index cls_index += 1 return darknet_cls_index def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: shutil.copyfile(filename, 'model_best.pth.tar') def accuracy(output, target, topk=(1,), darknet_class_list=None): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() if darknet_class_list is not None: pred_np = pred.cpu().numpy() pred_np_reshape = pred_np.reshape(pred_np.size) pred_np_torch = np.array([darknet_class_list[ci] for ci in pred_np_reshape]) pred_np_torch = pred_np_torch.reshape(pred.shape) pred_np_torch = torch.from_numpy(pred_np_torch) target_cpu = target.cpu() correct = pred_np_torch.eq(target_cpu.view(1, -1).expand_as(pred_np_torch)) else: correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res
C++
UTF-8
2,855
2.9375
3
[]
no_license
// Print Anagrams Together.... // Using A trie.. #include<iostream> #include<cstdio> #include<ctime> #include<cstring> #include<unistd.h> #include<algorithm> #include<stack> #include<deque> #include<vector> using namespace std; void swap(int &a,int &b) { int temp; temp=a; a=b; b=temp; return ; } typedef struct Trie { bool isLeaf; Trie *childs[27]; vector<int> mylist; }; Trie* createTrieNode() { Trie *temp; int i; temp=(Trie*)malloc(sizeof(Trie)); temp->isLeaf=false; for(i=0;i<26;i++) temp->childs[i]=NULL; //(temp->mylist).resize(10); return temp; } int search(Trie *root,char key[]) { int i,len; int index; Trie *move; move=root; len=strlen(key); for(i=0;i<len;i++) { index=key[i]-'a'; if(move->childs[index]==NULL) return 0; move=move->childs[index]; } if(move->isLeaf==true) return 1; return 0; } void insert(Trie *root,char key[],int in) { int i; int len; int index; len=strlen(key); Trie *move=root,*temp=NULL; for(i=0;i<len;i++) { index=key[i]-'a'; // cout<<"Index is "<<index<<endl; if(move->childs[index]==NULL) { temp=createTrieNode(); if(temp==NULL) { cout<<"No Memory..\n"; return ; } move->childs[index]=temp; //move=move->childs[index]; } move=move->childs[index]; } move->isLeaf=true; (move->mylist).push_front(in); // cout<<"Index is "<<in<<endl; // cout<<"Bug..\n"; return ; } void dfsTrie(Trie *root,char* wordArr[]) { if(root==NULL) return ; int i; // then print All Anagrams Together.... if((root->isLeaf)==true) { int size; int index; size=(root->mylist).size(); for(i=0;i<size;i++) { index=root->mylist[i]; cout<<wordArr[index]<<" "; } cout<<endl; } // continue DS.. for(i=0;i<26;i++) dfsTrie(root->childs[i],wordArr); return ; } void printAnagramsTogether(char* wordArr[], int size) { int i,j; int len; char buffer[100]; Trie *root=NULL; root=createTrieNode(); for(i=0;i<size;i++) { strcpy(buffer, wordArr[i]); len=strlen(buffer); sort(buffer,buffer+len); // cout<<"sorted anagram is "<<buffer<<endl; insert(root,buffer,i); } // now time for DFS.... dfsTrie(root,wordArr); } int main() { int a[100]; int b[100]; int t,i,n; int iter,k; char buf[100]; int number; int ans; char* wordArr[] = {"cat", "dog", "tac", "god", "act","abc","xyz","avinash"}; int size = sizeof(wordArr) / sizeof(wordArr[0]); //cout<<size<<endl; printAnagramsTogether(wordArr, size); cin>>ans; return 0; }
PHP
UTF-8
2,432
3.078125
3
[ "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-or-later", "LGPL-2.0-or-later", "LGPL-2.1-or-later", "GPL-3.0-only", "GPL-1.0-or-later", "MIT" ]
permissive
<?php /** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\DataTable\Filter; use Piwik\DataTable; use Piwik\DataTable\BaseFilter; /** * Deletes all rows for which a callback returns true. * * **Basic usage example** * * $labelsToRemove = array('label1', 'label2', 'label2'); * $dataTable->filter('ColumnCallbackDeleteRow', array('label', function ($label) use ($labelsToRemove) { * return in_array($label, $labelsToRemove); * })); * * @api */ class ColumnCallbackDeleteRow extends BaseFilter { private $function; private $functionParams; /** * Constructor. * * @param DataTable $table The DataTable that will be filtered eventually. * @param array|string $columnsToFilter The column or array of columns that should be * passed to the callback. * @param callback $function The callback that determines whether a row should be deleted * or not. Should return `true` if the row should be deleted. * @param array $functionParams deprecated - use an [anonymous function](http://php.net/manual/en/functions.anonymous.php) * instead. */ public function __construct($table, $columnsToFilter, $function, $functionParams = array()) { parent::__construct($table); if (!is_array($functionParams)) { $functionParams = array($functionParams); } if (!is_array($columnsToFilter)) { $columnsToFilter = array($columnsToFilter); } $this->function = $function; $this->columnsToFilter = $columnsToFilter; $this->functionParams = $functionParams; } /** * Filters the given data table * * @param DataTable $table */ public function filter($table) { foreach ($table->getRows() as $key => $row) { $params = array(); foreach ($this->columnsToFilter as $column) { $params[] = $row->getColumn($column); } $params = array_merge($params, $this->functionParams); if (call_user_func_array($this->function, $params) === true) { $table->deleteRow($key); } $this->filterSubTable($row); } } }
Python
UTF-8
444
2.640625
3
[]
no_license
from functions import gapCount import numpy as np def test_sequence(): data = np.zeros((526,1)) i = 0 with open('fastaOutput.txt') as file: for line in file.readlines(): for num in line.split(): data[i] = int(num) i += 1 outputRef = np.zeros((526, 1)) lH, rH = gapCount(data.astype(dtype="int")) rH = rH.astype(dtype="int") assert np.array_equal(rH, outputRef)
Java
UTF-8
1,727
2.25
2
[]
no_license
package com.xc.service.InitServiceFactory; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; import org.springframework.boot.CommandLineRunner; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Component public class InitServiceFactory implements CommandLineRunner { @Autowired private ConfigurableListableBeanFactory beanFactory; @Autowired private ApplicationContext applicationContext; @Autowired private SFactory sFactory; @Override public void run(String... args) throws Exception { Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(MyService.class); System.out.println(beansWithAnnotation); beansWithAnnotation.forEach((a, b) -> { if (b != null) { Class<?> aClass = b.getClass(); MyService annotation = aClass.getAnnotation(MyService.class); // System.out.println(annotation.serviceType()); AppService bean = beanFactory.getBean(a, AppService.class); ServiceType serviceType = annotation.serviceType(); System.out.println(serviceType); HashMap<ServiceType, AppService> map = new HashMap<>(); sFactory.getMap().put(serviceType, bean); } }); } }
Java
UTF-8
13,291
2.25
2
[]
no_license
package com.libra.cloud.poetry.webmagic; import com.libra.cloud.poetry.entity.Detail; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.List; public class PoetryDetailProcessor { private static final String www = "https://www.gushiwen.org"; private static final String so = "https://so.gushiwen.org"; private String urlPath; public PoetryDetailProcessor() { urlPath = so; } public Detail parse(String title, String author, int page) { if (page == 0) { page = 1; } Detail detail = new Detail(); long startTime = System.currentTimeMillis(); try { Document document = Jsoup.connect("https://so.gushiwen.org/search.aspx?value=" + title + "&page=" + page).ignoreContentType(true).get(); Elements ids = document.select("img[id~=btnBeisong+]"); Elements sources = document.select("p[class=source]"); String pid = null; for (int i = 0; i < ids.size(); i++) { Element id = ids.get(i); Element source = sources.get(i); List<String> sourceList = source.children().eachText(); if (sourceList.contains(author)) { pid = id.attr("id").replace("btnBeisong", ""); break; } } if (pid != null && !pid.isEmpty()) { String url = "https://so.gushiwen.org/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=yizhushang"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String yi = ""; String zhu = ""; String shang = ""; Elements yizhushangs = doc.getElementsByTag("p"); if (yizhushangs.size() > 0) { for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { for (int i = 0; i < yizhus.size(); i++) { Element yizhu = yizhus.get(i); Elements children = yizhu.getElementsByAttributeValue("style", "color:#76621c;"); for (Element child : children) { yi += child.text() + "\n"; } children = yizhu.getElementsByAttributeValue("style", "color:#286345;"); for (Element child : children) { if (child.text().startsWith("(") && child.text().endsWith(")")) { continue; } zhu += child.text() + "\n"; } } } else if (yizhushang.hasAttr("style")) { continue; } else { shang += yizhushang.text() + "\n"; } } detail.setTranslation(yi); detail.setRemark(zhu); detail.setAppreciate(shang); System.out.println(detail.getTranslation()); System.out.println(detail.getRemark()); System.out.println(detail.getAppreciate()); } else { parseOther(pid, detail); if (StringUtils.isEmpty(detail.getTranslation()) || StringUtils.isEmpty(detail.getRemark()) || StringUtils.isEmpty(detail.getAppreciate())) { urlPath = www; parseOther(pid, detail); } } } else { //去下一页找 Integer temppage = Integer.valueOf(document.select("label[id=temppage]").text()); Integer sumPage = Integer.valueOf(document.select("label[id=sumPage]").text()); if (sumPage > temppage) { detail = parse(title, author, temppage + 1); } } } catch (Exception e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println(endTime - startTime); return detail; } private void parseOther(String pid, Detail detail) { parseYiZhu(pid, detail); if (StringUtils.isEmpty(detail.getTranslation())) { parseYi(pid, detail); } if (StringUtils.isEmpty(detail.getRemark())) { parseZhu(pid, detail); } parseShang(pid, detail); if (StringUtils.isEmpty(detail.getTranslation())) { parseYiShang(pid, detail); } if (StringUtils.isEmpty(detail.getRemark())) { parseZhuShang(pid, detail); } System.out.println(detail.toString()); } private void parseYi(String pid, Detail detail) { try { String url = urlPath + "/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=yi"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String yi = ""; Elements yizhushangs = doc.getElementsByTag("p"); for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { for (int i = 0; i < yizhus.size(); i++) { Element yizhu = yizhus.get(i); Elements children = yizhu.getElementsByAttributeValue("style", "color:#76621c;"); for (Element child : children) { yi += child.text() + "\n"; } } } } if (!StringUtils.isEmpty(yi)) { detail.setTranslation(yi); } } catch (Exception e) { e.printStackTrace(); } } private void parseZhu(String pid, Detail detail) { try { String url = urlPath + "/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=zhu"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String zhu = ""; Elements yizhushangs = doc.getElementsByTag("p"); for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { for (int i = 0; i < yizhus.size(); i++) { Element yizhu = yizhus.get(i); Elements children = yizhu.getElementsByAttributeValue("style", "color:#286345;"); for (Element child : children) { if (child.text().startsWith("(") && child.text().endsWith(")")) { continue; } zhu += child.text() + "\n"; } } } } if (!StringUtils.isEmpty(zhu)) { detail.setRemark(zhu); } } catch (Exception e) { e.printStackTrace(); } } private void parseShang(String pid, Detail detail) { try { String url = urlPath + "/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=shang"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String shang = ""; Elements yizhushangs = doc.getElementsByTag("p"); for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { continue; } else if (yizhushang.hasAttr("style")) { continue; } else { shang += yizhushang.text() + "\n"; } } detail.setAppreciate(shang); if (!StringUtils.isEmpty(shang)) { detail.setAppreciate(shang); } } catch (Exception e) { e.printStackTrace(); } } private void parseYiZhu(String pid, Detail detail) { try { String url = urlPath + "/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=yizhu"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String yi = ""; String zhu = ""; Elements yizhushangs = doc.getElementsByTag("p"); for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { for (int i = 0; i < yizhus.size(); i++) { Element yizhu = yizhus.get(i); Elements children = yizhu.getElementsByAttributeValue("style", "color:#76621c;"); for (Element child : children) { yi += child.text() + "\n"; } children = yizhu.getElementsByAttributeValue("style", "color:#286345;"); for (Element child : children) { if (child.text().startsWith("(") && child.text().endsWith(")")) { continue; } zhu += child.text() + "\n"; } } } } if (!StringUtils.isEmpty(yi)) { detail.setTranslation(yi); } if (!StringUtils.isEmpty(zhu)) { detail.setRemark(zhu); } } catch (Exception e) { e.printStackTrace(); } } private void parseYiShang(String pid, Detail detail) { try { String url = urlPath + "/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=yishang"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String yi = ""; String shang = ""; Elements yizhushangs = doc.getElementsByTag("p"); for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { for (int i = 0; i < yizhus.size(); i++) { Element yizhu = yizhus.get(i); Elements children = yizhu.getElementsByAttributeValue("style", "color:#76621c;"); for (Element child : children) { yi += child.text() + "\n"; } } } else if (yizhushang.hasAttr("style")) { continue; } else { shang += yizhushang.text() + "\n"; } } if (!StringUtils.isEmpty(yi)) { detail.setTranslation(yi); } if (!StringUtils.isEmpty(shang)) { detail.setAppreciate(shang); } } catch (Exception e) { e.printStackTrace(); } } private void parseZhuShang(String pid, Detail detail) { try { String url = urlPath + "/shiwen2017/ajaxshiwencont.aspx?id=" + pid + "&value=zhushang"; System.out.println(url); Document doc = Jsoup.connect(url).ignoreContentType(true).get(); String zhu = ""; String shang = ""; Elements yizhushangs = doc.getElementsByTag("p"); for (Element yizhushang : yizhushangs) { Elements yizhus = yizhushang.children(); if (yizhus.size() > 0) { for (int i = 0; i < yizhus.size(); i++) { Element yizhu = yizhus.get(i); Elements children = yizhu.getElementsByAttributeValue("style", "color:#286345;"); for (Element child : children) { if (child.text().startsWith("(") && child.text().endsWith(")")) { continue; } zhu += child.text() + "\n"; } } } else if (yizhushang.hasAttr("style")) { continue; } else { shang += yizhushang.text() + "\n"; } } if (!StringUtils.isEmpty(zhu)) { detail.setRemark(zhu); } if (!StringUtils.isEmpty(shang)) { detail.setAppreciate(shang); } } catch (Exception e) { e.printStackTrace(); } } }
Java
UTF-8
579
2.953125
3
[]
no_license
/** * Simulates the effect of executing the given basic block. This modifies the passed-in frame to represent the end result. * @param bb {@code non-null;} the basic block * @param frame {@code non-null;} frame to operate on */ public void simulate(ByteBlock bb,Frame frame){ int end=bb.getEnd(); visitor.setFrame(frame); try { for (int off=bb.getStart(); off < end; ) { int length=code.parseInstruction(off,visitor); visitor.setPreviousOffset(off); off+=length; } } catch ( SimException ex) { frame.annotate(ex); throw ex; } }
Java
UTF-8
813
2.96875
3
[]
no_license
package hackerrank.mkh.samsung; import java.util.ArrayDeque; import java.util.Deque; import java.util.Scanner; public class Cryptogenerator { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while(true) { String num = scan.nextLine(); if(num == null) break; String str = scan.nextLine(); String[] arr = str.split(" "); int len = arr.length; Deque<Integer> queue = new ArrayDeque<>(); int j = 1; for(int i=0; i<len; i++) { queue.add(Integer.parseInt(arr[i])); } int val = -1; while(true) { if(j == 6) j=1; if(val > 0) queue.addLast(val); val = queue.pop() - (j++); if(val <= 0) { queue.addFirst(0); break; } // queue.addLast(val); } System.out.println(queue); } } }
Python
UTF-8
463
3.578125
4
[]
no_license
def main(): corrida = int(input('Quantas corridas voce fez hoje:')) qto = 0 for i in range(0, corrida): valor = int(input('qual o valor da corrida?:')) qto += valor valor_aplicativo = qto / 4 valor_motorista = qto - valor_aplicativo print('valor total é igual {}'.format(qto)) print('o aplicativo tem {} reais'.format(valor_aplicativo)) print('o motorista tem {} reais' .format(valor_motorista)) main()
Rust
UTF-8
11,394
3.140625
3
[ "MIT" ]
permissive
#![allow(dead_code)] //! A 3dsMax / Blender style camera that orbits about a target position use vecmath::{ Vector3, vec3_add, vec3_scale }; use vecmath::traits::Float; use quaternion; use quaternion::Quaternion; use input::{ GenericEvent, Key, MouseButton }; use input::Button::{ Keyboard, Mouse }; use Camera; bitflags!( pub struct Mode: u8 { const ORBIT_BUTTON = 0b00000001; const ZOOM_BUTTON = 0b00000010; const PAN_BUTTON = 0b00000100; const ORBIT_MOD = 0b00001000; const ZOOM_MOD = 0b00010000; const PAN_MOD = 0b00100000; } ); /// Specifies key bindings and speed modifiers for OrbitZoomCamera pub struct OrbitZoomCameraSettings<T=f32> { /// Which mouse button to press to orbit with mouse pub orbit_button: MouseButton, /// Which mouse button to press to zoom with mouse pub zoom_button: MouseButton, /// Which mouse button to press to pan with mouse pub pan_button: MouseButton, /// Which key to press to orbit with mouse (if any) pub orbit_mod: Option<Key>, /// Which key to press to zoom with mouse (if any) pub zoom_mod: Option<Key>, /// Which key to press to pan with mouse (if any) pub pan_mod: Option<Key>, /// What does scrolling control (the given bits are automatically set when scrolling) pub scroll_mode: Mode, /// Modifier for orbiting speed (arbitrary unit) pub orbit_speed: T, /// Modifier for pitch speed relative to orbiting speed (arbitrary unit). /// To reverse pitch direction, set this to -1. pub pitch_speed: T, /// Modifier for panning speed (arbitrary unit) pub pan_speed: T, /// Modifier for zoom speed (arbitrary unit) pub zoom_speed: T, } impl<T: Float> OrbitZoomCameraSettings<T> { /// Clicking and dragging OR two-finger scrolling will orbit camera, /// with LShift as pan modifer and LCtrl as zoom modifier pub fn default() -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { orbit_button : MouseButton::Left, zoom_button : MouseButton::Right, pan_button : MouseButton::Left, orbit_mod : None, zoom_mod : None, pan_mod : Some(Key::LShift), scroll_mode: ZOOM_BUTTON, orbit_speed: T::from_f32(0.05), pitch_speed: T::from_f32(0.1), pan_speed: T::from_f32(0.1), zoom_speed: T::from_f32(0.1), } } /// Set the button for orbiting pub fn orbit_button(self, button: MouseButton) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { orbit_button: button, .. self } } /// Set the button for zooming pub fn zoom_button(self, button: MouseButton) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { zoom_button: button, .. self } } /// Set the button for panning pub fn pan_button(self, button: MouseButton) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { pan_button: button, .. self } } /// Set what scrolling does by default pub fn scroll_mode(self, mode: Mode) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { scroll_mode: mode, .. self } } /// Set the orbit speed modifier pub fn orbit_speed(self, s: T) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { orbit_speed: s, .. self } } /// Set the pitch speed modifier pub fn pitch_speed(self, s: T) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { pitch_speed: s, .. self } } /// Set the pan speed modifier pub fn pan_speed(self, s: T) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { pan_speed: s, .. self } } /// Set the zoom speed modifier pub fn zoom_speed(self, s: T) -> OrbitZoomCameraSettings<T> { OrbitZoomCameraSettings { zoom_speed: s, .. self } } } /// A 3dsMax / Blender-style camera that orbits around a target point pub struct OrbitZoomCamera<T=f32> { /// origin of camera rotation pub target: Vector3<T>, /// Rotation of camera pub rotation: Quaternion<T>, /// Pitch up/down from target pub pitch: T, /// Yaw left/right from target pub yaw: T, /// Camera distance from target pub distance: T, /// Lower distance limit /// Set this to near clipping distance pub distance_near_limit: T, /// Upper distance limit /// Set this to far clipping distance pub distance_far_limit: T, /// Settings for the camera pub settings: OrbitZoomCameraSettings<T>, /// Current camera control mode activated mode: Mode, } impl<T: Float> OrbitZoomCamera<T> { /// Create a new OrbitZoomCamera targeting the given coordinates pub fn new(target: [T; 3], settings: OrbitZoomCameraSettings<T>) -> OrbitZoomCamera<T> { // If there is no modifier button, assume it's as if the button is always pressed let mut mode = Mode::empty(); if settings.orbit_mod == None { mode |= ORBIT_MOD; } if settings.zoom_mod == None { mode |= ZOOM_MOD; } if settings.pan_mod == None { mode |= PAN_MOD; } OrbitZoomCamera { target: target, rotation: quaternion::id(), distance: T::from_f32(10.0), distance_near_limit: T::from_f32(0.1), distance_far_limit: T::from_f32(1000.0), pitch: T::zero(), yaw: T::zero(), mode, settings, } } /// Return a Camera for the current OrbitZoomCamera configuration pub fn camera(&self, _dt: f64) -> Camera<T> { let target_to_camera = quaternion::rotate_vector( self.rotation, [T::zero(), T::zero(), self.distance] ); let mut camera = Camera::new(vec3_add(self.target, target_to_camera)); camera.set_rotation(self.rotation); camera } fn rotation_from_yaw_and_pitch(yaw: T, pitch: T) -> Quaternion<T> { let _1 = T::one(); let _0 = T::zero(); quaternion::mul( quaternion::axis_angle([_0, _1, _0], yaw), quaternion::axis_angle([_1, _0, _0], pitch) ) } /// Initialize the camera configuration, such that next call to camera() gives the correct /// camera rotation pub fn init(&mut self) { self.rotation = Self::rotation_from_yaw_and_pitch(self.yaw, self.pitch); } fn is_orbit(&self) -> bool { self.mode.contains(ORBIT_BUTTON | ORBIT_MOD) } fn is_zoom(&self) -> bool { self.mode.contains(ZOOM_BUTTON | ZOOM_MOD) } fn is_pan(&self) -> bool { self.mode.contains(PAN_BUTTON | PAN_MOD) } /// Orbit the camera using the given horizontal and vertical params, /// or zoom or pan if the appropriate modifier keys are pressed pub fn control_camera(&mut self, dx: T, dy: T) { let _1 = T::one(); let _0 = T::zero(); if self.is_pan() { // Pan target position along plane normal to camera direction let dx = dx * self.settings.pan_speed*self.distance; let dy = dy * self.settings.pan_speed*self.distance; let right = quaternion::rotate_vector(self.rotation, [_1, _0, _0]); let up = quaternion::rotate_vector(self.rotation, [_0, _1, _0]); self.target = vec3_add( vec3_add(self.target, vec3_scale(up, dy)), vec3_scale(right,dx) ); } else if self.is_zoom() { // Zoom to / from target let new_dist = self.distance + dy * self.settings.zoom_speed*self.distance; self.distance = if new_dist > self.distance_far_limit { self.distance_far_limit } else if new_dist < self.distance_near_limit { self.distance_near_limit } else { new_dist } } else if self.is_orbit() { // Orbit around target let dx = dx * self.settings.orbit_speed; let dy = dy * self.settings.orbit_speed; self.yaw = self.yaw + dx; self.pitch = self.pitch + dy*self.settings.pitch_speed; self.rotation = Self::rotation_from_yaw_and_pitch(self.yaw, self.pitch); } } fn mod_key_pressed(&self) -> bool { let mut is_pressed = false; if let Some(_) = self.settings.orbit_mod { if self.mode.contains(ORBIT_MOD) { is_pressed = true; } } else if let Some(_) = self.settings.zoom_mod { if self.mode.contains(ZOOM_MOD) { is_pressed = true; } } else if let Some(_) = self.settings.pan_mod { if self.mode.contains(PAN_MOD) { is_pressed = true; } } is_pressed } /// Respond to scroll and key press/release events pub fn event<E: GenericEvent>(&mut self, e: &E) { //e.touch(|args| { // println!("args = {:?}", args); //}); e.mouse_scroll(|dx, dy| { let dx = T::from_f64(dx); let dy = T::from_f64(dy); // if a mod key is pressed, override the default scroll mode let mut restore = false; if !self.mod_key_pressed() { restore = !self.mode.contains(self.settings.scroll_mode); self.mode.insert(self.settings.scroll_mode); } self.control_camera(dx, dy); if restore { self.mode.remove(self.settings.scroll_mode); } }); e.mouse_relative(|dx, dy| { let dx = T::from_f64(dx); let dy = T::from_f64(dy); self.control_camera(-dx, dy); }); e.press(|x| { if x == Mouse(self.settings.orbit_button) { self.mode.insert(ORBIT_BUTTON); } if x == Mouse(self.settings.pan_button) { self.mode.insert(PAN_BUTTON); } if x == Mouse(self.settings.zoom_button) { self.mode.insert(ZOOM_BUTTON); } if Some(x) == self.settings.orbit_mod.map(|a| Keyboard(a)) { self.mode.insert(ORBIT_MOD); } if Some(x) == self.settings.pan_mod.map(|a| Keyboard(a)) { self.mode.insert(PAN_MOD); } if Some(x) == self.settings.zoom_mod.map(|a| Keyboard(a)) { self.mode.insert(ZOOM_MOD); } }); e.release(|x| { if x == Mouse(self.settings.orbit_button) { self.mode.remove(ORBIT_BUTTON); } if x == Mouse(self.settings.pan_button) { self.mode.remove(PAN_BUTTON); } if x == Mouse(self.settings.zoom_button) { self.mode.remove(ZOOM_BUTTON); } if Some(x) == self.settings.orbit_mod.map(|a| Keyboard(a)) { self.mode.remove(ORBIT_MOD); } if Some(x) == self.settings.pan_mod.map(|a| Keyboard(a)) { self.mode.remove(PAN_MOD); } if Some(x) == self.settings.zoom_mod.map(|a| Keyboard(a)) { self.mode.remove(ZOOM_MOD); } }); } }
Markdown
UTF-8
4,882
3.96875
4
[]
no_license
--- layout: post categories: Java title: 教你 Java 编程中五个奇技淫巧 tagline: by 子悠 tags: - 子悠 --- 枯燥的编程中总得有些乐趣,今天我们不谈论那些高深的技能,教你几个在编程中的奇技淫巧,说不定在某些时候还能炫耀一番呢。 <!--more--> ### 1、找到最大值和最小值 不使用 `if` `else` `switch` 和三元运算符,在给定的三元组中找到最大值和最小值:比如给定 3,14,8,在不使用 `if` `else` `switch` 和三元运算符的情况下找到最大值和最小值。 话不多说,我们先看代码 ```java public static int findMax(int a, int b, int c) { int max = a; boolean b1 = (max < b) && ((max = b) > 0); b1 = (max < c) && ((max = c) > 0); return max; } public static int findMin(int a, int b, int c) { int min = a; boolean b1 = (min > b) && ((min = b) > 0); b1 = (min > c) && ((min = c) > 0); return min; } ``` 这里我们主要使用了`&&` 运算符的短路特性,短路特性是指当 `&&` 前一个表达式为 `true` 的时候才会继续执行下一个表达式,当前一个表达式为 `false` 则不会执行下一个表达式。所以在这里只有当前一个表达式为 `true` 的时候,后面的赋值语句才会被执行到。 我们运行一下结果如下 ![](https://tva1.sinaimg.cn/large/e6c9d24egy1h1bkk16lv8j20wa0eiabk.jpg) 上面的这种方式入参适合正数和负数,如果当我们的入参能确定为正数的时候,我们还可以使用下面的这种方式来实现 ```java public static int findPositiveMax(int a, int b, int c) { int max = 0; while (a > 0 || b > 0 || c > 0) { a--; b--; c--; max++; } return max; } public static int findPositiveMin(int a, int b, int c) { int min = 0; while (a > 0 && b > 0 && c > 0) { a--; b--; c--; min++; } return min; } ``` 上面的这种写法相信大家都能看懂,阿粉就不过的解释了,同样的这里也利用了`&& `和 `||` 运算的短路特性,不过要注意这种形式只能在都是正数的情况下才可以。 ### 2、不使用临时变量交换变量 `swap(x, y)` 操作大家都知道,就是交互 x 和 y 的值,比如 x = 3, y = 4; 在经过 swap 操作过后,x = 4,y = 3;我们这里的问题时如何在不使用临时变量的情况下,只有一行代码来实现这个方法。 首先大家肯定知道这里我们要使用异或运算`^`,没错,话不多说我们看代码 ```java public static void swapByXor(int x, int y) { System.out.println(x + ":" + y); x = x ^ y ^ (y = x); System.out.println(x + ":" + y); } ``` ![](https://tva1.sinaimg.cn/large/e6c9d24egy1h1bkk6c3noj20y20gwt9z.jpg) 运行过后,可以看到,`x` 和 `y` 的值已经被交换了, 这里我们要知道两个知识点,那就是 `n ^ n = 0;` `n ^ 0 = n`,另外`a ^ b` 和 `b ^ a` 是等价的。 ![](https://tva1.sinaimg.cn/large/e6c9d24egy1h1bkka5fp2j20w80fqabg.jpg) 当然除了上面的异或之外,我们还可以通过下面这种方法来实现 ```java public static void swapByAddAndSub(int x, int y) { System.out.println(x + ":" + y); x = x + y - (y = x); System.out.println(x + ":" + y); } public static void swapByMulAndDiv(int x, int y) { System.out.println(x + ":" + y); x = (x * y) / (y = x); System.out.println(x + ":" + y); } ``` 这两种方式都是同样的逻辑,先求和在减去其中一个值和先求积再除以一个值,就可以得到两个替换后的值。 ### 3、两个数相乘 接下来我们再看一个,求两个数的积,但是不能用乘号`*`。在看代码之前,我们先分析一下,比如说我们要求积 `3 * 5` 可以将 `3 * 5` 看成 `3 * 4 + 3`,也就是 `(3 * 3 + 3) + 3`,看到这个可能有的小伙伴已经知道我们要怎么计算了,没错,那就是我们可以用递归。 ```java public static int mulWithoutMul(int x, int y) { if (y == 0) return 0; if (y > 0) return (x + mulWithoutMul(x, y - 1)); return -mulWithoutMul(x, -y); } ``` 通过上面的递归,我们就可以实现两个数相乘但是没有使用乘号了。 ![](https://tva1.sinaimg.cn/large/e6c9d24egy1h1bkkes5b8j20y20h4jsu.jpg) ### 4、不使用乘号计算乘以 15 如果我们要计算一个数乘以 15 的时候,我们可以通过下面这种方式来计算,`(n << 4) - n`, 因 `n * 15 = n * 16 - n = (n << 4) - n`;同样的如果我们某些时候要计算乘以 2 或者除以 2 的时候,我们也可以换成移位操作,`n * 2 = n << 1;n / 2 = n >> 1`,如果是 4 的话就可以左移 2 位或者右移 2 位,即 `n * 4 = n << 2;n / 4 = n >> 2`;一次类推。 使用移位的方式,在某些极端的场景可以提升性能。
C++
ISO-8859-1
1,416
2.828125
3
[]
no_license
#include <stdio.h> #include "C:\Projetos\MyClassTeste\MyClassTeste\stdafx.h" #include "C:\Projetos\MyClassTeste\MyClassTeste\header.h" #include "C:\Projetos\MyClassTeste\MyClassTeste\body.cpp" #include "dll_function.h" extern "C" { _declspec(dllexport) void DisplayHelloFromDLL() { printf("Hello from DLL !\n"); int result, num =4, num2 =4; result = num * num2; printf("Resultado do Calculo %d ", result); myClass MC(20, 30); printf("Resultado da soma externa %lf ", MC.sumX_Y()); } _declspec(dllexport) void showMessageFromOut() { double resu, num01 = 3, num02 = 4; resu = num01 * num02; printf("Esse e mais um teste de impresso de dll!\n"); printf("Resultado da conta: %lf ", resu); printf("Encerrando a conta na DLL! \n"); } _declspec(dllexport) void ChamaFuncStringDesc(int(__stdcall *funcDesconhecida)()) { printf("\nEntrou na DLL para func Desconhecida\n"); funcDesconhecida(); printf("\nDepois da chamada func Desconhecida dentro da DLL\n"); } _declspec(dllexport) void ChamaFuncIntDesc(int x, int(__stdcall *funcDesconhecida)(int valor)) { printf("\n Dentro da DLL fazendo o Calculo Complexo para mostrar o resultado\n"); int numero = x, num = 0; //for (num = 0; num <= numero; num++) { // numero = (numero + num + ((num + numero) / 3)) * 3; //} numero++; printf("\n fim do Calculo Complexo dentro da DLL\n"); funcDesconhecida(numero); } }
SQL
UTF-8
2,788
3.640625
4
[]
no_license
CREATE TABLE winds ( id_wind int(11) NOT NULL AUTO_INCREMENT, speed int(11) DEFAULT NULL, direction int(11) DEFAULT NULL, PRIMARY KEY (id_wind) ) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8; CREATE TABLE atmospheres ( id_atmosphere int(11) NOT NULL AUTO_INCREMENT, humidity int(11) DEFAULT NULL, pressure decimal(10,1) DEFAULT NULL, rising int(11) DEFAULT NULL, visibility decimal(10,1) DEFAULT NULL, PRIMARY KEY (id_atmosphere) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE week_days ( id_week_day int(11) NOT NULL AUTO_INCREMENT, description varchar(10) DEFAULT NULL, alpha3_code varchar(3) DEFAULT NULL, PRIMARY KEY (id_week_day) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; CREATE TABLE countries ( id_country int(11) NOT NULL AUTO_INCREMENT, full_name varchar(30) DEFAULT NULL, alpha2_code varchar(2) DEFAULT NULL, alpha3_code varchar(3) DEFAULT NULL, PRIMARY KEY (id_country) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; CREATE TABLE states ( id_state int(11) NOT NULL AUTO_INCREMENT, id_country int(11) NOT NULL, full_name varchar(60) DEFAULT NULL, alpha2_code varchar(2) DEFAULT NULL, area varchar(30) DEFAULT NULL, largest_city varchar(60) DEFAULT NULL, capital_city varchar(60) DEFAULT NULL, PRIMARY KEY (id_state), FOREIGN KEY (id_country) REFERENCES countries (id_country) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; CREATE TABLE towns ( id_town int(11) NOT NULL AUTO_INCREMENT, id_state int(11) NOT NULL, full_name varchar(60) DEFAULT NULL, PRIMARY KEY (id_town), FOREIGN KEY (id_state) REFERENCES states (id_state) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; CREATE TABLE weather_descriptions ( id_description int(11) NOT NULL AUTO_INCREMENT, text varchar(30) DEFAULT NULL, PRIMARY KEY (id_description) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; CREATE TABLE weathers ( id_weather int(11) NOT NULL AUTO_INCREMENT, id_town int(11) NOT NULL, id_atmosphere int(11) DEFAULT NULL, id_wind int(11) DEFAULT NULL, temp_now int(11) DEFAULT NULL, temp_max int(11) DEFAULT NULL, temp_min int(11) DEFAULT NULL, date_day datetime NOT NULL, id_week_day int(11) DEFAULT NULL, id_description int(11) DEFAULT NULL, PRIMARY KEY (id_weather), FOREIGN KEY (id_town) REFERENCES towns (id_town), FOREIGN KEY (id_atmosphere) REFERENCES atmospheres (id_atmosphere), FOREIGN KEY (id_wind) REFERENCES winds (id_wind), FOREIGN KEY (id_week_day) REFERENCES week_days (id_week_day), FOREIGN KEY (id_description) REFERENCES weather_descriptions (id_description) ) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;
PHP
UTF-8
4,121
2.734375
3
[]
no_license
<?php use Ackintosh\Higher\Table\Record; use Ackintosh\Higher\Table; class RecordTest extends PHPUnit_Framework_TestCase { /** * @test */ public function constructorSetsProperty() { $table = new Table(); $record = new Record($table); $this->assertSame($table, TestHelper::getPrivateProperty($record, 'table'), '-> sets the Talbe object.'); } /** * @test */ public function setColumns() { $table = new Table(); $schema = [ 'id' => ['int', 'sequence'], 'name' => ['varchar'], 'created' => ['datetime'], ]; $record = new Record($table); $record->setColumns($schema); $columns = TestHelper::getPrivateProperty($record, 'columns'); $this->assertSame(count($schema), count($columns), '-> sets number of columns the same as the schema information.'); $this->assertSame(array_keys($schema), $record->getColumnNames(), '-> sets the column that has been defined in schema information.'); } /** * @test */ public function set() { $table = new Table(); $schema = [ 'id' => ['int', 'sequence'], 'name' => ['varchar'], 'created' => ['datetime'], ]; $record = new Record($table); $record->setColumns($schema); $name = 'testname'; $record->name = $name; $this->assertSame($name, $record->name, '-> __set() sets value of column object.'); } /** * @test * @expectedException \Ackintosh\Higher\Exceptions\TableException */ public function setThrowsException() { $table = new Table(); $record = new Record($table); $record->foo = 'foo'; } /** * @test * @expectedException \Ackintosh\Higher\Exceptions\TableException */ public function getThrowsException() { $table = new Table(); $schema = [ 'id' => ['int', 'sequence'], 'name' => ['varchar'], 'created' => ['datetime'], ]; $record = new Record($table); $record->setColumns($schema); $record->foo = 123; } /** * @test */ public function getTable() { $table = new Table(); $record = new Record($table); $this->assertSame($table, $record->getTable(), '-> returns the Table object.'); } /** * @test */ public function getColumnNames() { $table = new Table(); $schema = [ 'id' => ['int', 'sequence'], 'name' => ['varchar'], 'created' => ['datetime'], ]; $record = new Record($table); $record->setColumns($schema); $this->assertSame(array_keys($schema), $record->getColumnNames(), '-> returns the column names'); } /** * @test */ public function getValues() { $table = new Table(); $schema = [ 'id' => ['int', 'sequence'], 'name' => ['varchar'], 'created' => ['datetime'], ]; $record = new Record($table); $record->setColumns($schema); $values = [99, 'foo', '2000-01-01 00:00:00']; $record->id = $values[0]; $record->name = $values[1]; $record->created = $values[2]; $this->assertSame($values, $record->getValues(), '-> returns the values that the record has.'); } /** * @test */ public function setSequenceValue() { $table = new Table(); $schema = [ 'id' => ['int', 'sequence'], 'name' => ['varchar'], 'created' => ['datetime'], ]; $record = new Record($table); $record->setColumns($schema); $value = 999; $record->setSequenceValue($value); $this->assertSame($value, $record->id, '-> sets the passed value to the column that has "sequence" option.'); } }
C
UTF-8
2,602
2.6875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* color_fun.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abarriel <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/20 01:13:21 by abarriel #+# #+# */ /* Updated: 2017/04/20 01:13:22 by abarriel ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void put_color(int fd, char color_nfun) { if (color_nfun == 1) ft_putstr_fd(RED, fd); if (color_nfun == 2) ft_putstr_fd(GREEN, fd); if (color_nfun == 3) ft_putstr_fd(BLUE, fd); if (color_nfun == 4) ft_putstr_fd(PURPLE, fd); if (color_nfun == 5) ft_putstr_fd(YELLOW, fd); if (color_nfun == 6) ft_putstr_fd(AZUR, fd); if (color_nfun == 7) ft_putstr_fd(PEACH, fd); if (color_nfun == 8) ft_putstr_fd(APPLE, fd); if (color_nfun == 9) ft_putstr_fd(OR, fd); } void color_fun__(t_stock *s) { if (ft_strncmp(s->str, "{6}", 3) == 0) s->color_nfun = 6; else if (ft_strncmp(s->str, "{7}", 3) == 0) s->color_nfun = 7; else if (ft_strncmp(s->str, "{8}", 3) == 0) s->color_nfun = 8; else if (ft_strncmp(s->str, "{9}", 3) == 0) s->color_nfun = 9; } void color_fun_(t_stock *s) { if (ft_strncmp(s->str, "{1}", 3) == 0) s->color_nfun = 1; else if (ft_strncmp(s->str, "{2}", 3) == 0) s->color_nfun = 2; else if (ft_strncmp(s->str, "{3}", 3) == 0) s->color_nfun = 5; else if (ft_strncmp(s->str, "{4}", 3) == 0) s->color_nfun = 3; else if (ft_strncmp(s->str, "{5}", 3) == 0) s->color_nfun = 4; else { color_fun__(s); return ; } } void color_fun(t_stock *s) { char *tmp; if (ft_strncmp(s->str, "{RED}", 5) == 0) s->color_nfun = 1; else if (ft_strncmp(s->str, "{GRE}", 5) == 0) s->color_nfun = 2; else if (ft_strncmp(s->str, "{BLU}", 5) == 0) s->color_nfun = 3; else if (ft_strncmp(s->str, "{PUR}", 5) == 0) s->color_nfun = 4; else if (ft_strncmp(s->str, "{YEL}", 5) == 0) s->color_nfun = 5; else { color_fun_(s); return ; } if (s->color_nfun > 0) { tmp = s->str; s->str = ft_strsub(tmp, 5, ft_strlen(s->str) - 5); } }
Java
UTF-8
533
1.71875
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.android.gms.games.leaderboard; import android.os.Bundle; public final class b { private final Bundle nw; public b(Bundle bundle) { Bundle bundle1 = bundle; if (bundle == null) { bundle1 = new Bundle(); } nw = bundle1; } public Bundle cc() { return nw; } }
C++
UTF-8
1,792
4.125
4
[]
no_license
/* 给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8)中, 按结点数值大小顺序第三小结点的值为4。 */ #include <iostream> #include <stack> using namespace std; struct TreeNode{ int val; struct TreeNode* left; struct TreeNode* right; TreeNode(int x=0) : val(x), left(NULL), right(NULL){} }; int count = 0; TreeNode* KthNode(TreeNode* pRoot, int k){ if(pRoot == NULL){ return NULL; } TreeNode* node = pRoot; stack<TreeNode*> nStack; while(node != NULL || !nStack.empty()){ while(node != NULL){//找到二叉搜索树的最左结点 nStack.push(node); node = node->left; } if(!nStack.empty()){ node = nStack.top(); count++; if(count == k){ return node; } nStack.pop(); node = node->right; } } return NULL; } int main() { TreeNode tree[7]; tree[0].val = 5; tree[0].left = &tree[1]; tree[0].right = &tree[2]; tree[1].val = 3; tree[1].left = &tree[3]; tree[1].right = &tree[4]; tree[2].val = 7; tree[2].left = &tree[5]; tree[2].right = &tree[6]; tree[3].val = 2; tree[3].left = NULL; tree[3].right = NULL; tree[4].val = 4; tree[4].left = NULL; tree[4].right = NULL; tree[5].val = 6; tree[5].left = NULL; tree[5].right = NULL; tree[6].val = 8; tree[6].left = NULL; tree[6].right = NULL; TreeNode* res = KthNode(tree, 3); if(res != NULL){ cout << res->val << endl; }else{ cout << "Null node" << endl; } return 0; }
Go
UTF-8
1,160
3.15625
3
[ "MIT" ]
permissive
package config import ( "fmt" "net" "strconv" ) type TypeHostPort struct { Value string Host string Port uint } func (t *TypeHostPort) Set(value string) error { host, port, err := net.SplitHostPort(value) if err != nil { return fmt.Errorf("incorrect host:port value (%v): %w", value, err) } portValue, err := strconv.ParseUint(port, 10, 16) // nolint: gomnd if err != nil { return fmt.Errorf("incorrect port number (%v): %w", value, err) } if portValue == 0 { return fmt.Errorf("incorrect port number (%s)", value) } if host == "" { return fmt.Errorf("empty host: %s", value) } if net.ParseIP(host) == nil { return fmt.Errorf("host is not an IP address: %s", value) } t.Value = net.JoinHostPort(host, port) t.Port = uint(portValue) t.Host = host return nil } func (t TypeHostPort) Get(defaultValue string) string { if t.Value == "" { return defaultValue } return t.Value } func (t *TypeHostPort) UnmarshalText(data []byte) error { return t.Set(string(data)) } func (t TypeHostPort) MarshalText() ([]byte, error) { return []byte(t.String()), nil } func (t TypeHostPort) String() string { return t.Value }
Markdown
UTF-8
1,902
3.359375
3
[ "Apache-2.0" ]
permissive
## print_to_logging [![asciicast](https://asciinema.org/a/mSw4uEVJrvxoKW6so3b5RPjAj.png)](https://asciinema.org/a/mSw4uEVJrvxoKW6so3b5RPjAj) This is an interactive tool for refactoring Python code. The mission is to replace `print` statements with calls to `logging` instead. `print_to_logging` features: - it will ask you to accept or modify any proposed change - support for multiline strings and multiline print statements - preservation of comments - automatic f-string generation - preservation of custom print separators - interactive choice of logging level (info, warning, error, etc.) - showing a diff for before and after change To try it out, clone the repo: `git clone https://github.com/tsoernes/print_to_logging.git && cd print_to_logging` Then run the program on the test file: `python print_to_logging.py -f testfile.py` or on a directory of python files: `python print_to_logging.py -d ~/code/my-python-project` See `python print_to_logging.py --help`: ``` python usage: print_to_logging.py [-h] (-f FILE | -d DIRECTORY | -m MODULE) [-l {info,warning,error,critical,exception}] [--accept_all] [--context_lines CONTEXT_LINES] Refactoring tool to replace print with logging optional arguments: -h, --help show this help message and exit -f FILE, --file FILE -d DIRECTORY, --directory DIRECTORY Find all .py paths in the directory and its subdirectories -m MODULE, --module MODULE Find all .py paths in the directory of the module and its subdirectories -l {info,warning,error,critical,exception}, --level {info,warning,error,critical,exception} Default logging level (info). --accept_all Auto accept all changes. --context_lines CONTEXT_LINES Number of lines before and after change in diff ``` Requires Python version 3.8 or greater to run.
TypeScript
UTF-8
918
2.65625
3
[ "MIT" ]
permissive
import { REQUEST_DRIVER_TYPE } from './request-driver-type'; import { RequestDriver } from './request-driver'; import { NodeRequestDriver } from './node-request-driver'; import { buildMockRequestDriver } from './mock-request-driver'; import { BrowserRequestDriver } from './browser-request-driver'; import { RequestError } from './request-error'; declare var window: any; /** * Obtain the request driver for the given type */ export function getRequestDriver (type?: REQUEST_DRIVER_TYPE, mockData?: any): RequestDriver { if(type === undefined) { return getRequestDriver(typeof window !== 'undefined' ? 'BROWSER' : 'NODE'); } switch(type) { case 'BROWSER': return BrowserRequestDriver; case 'NODE': return NodeRequestDriver; case 'MOCK': return buildMockRequestDriver(mockData); } throw new RequestError('Unknown request driver type: ' + type); }
Python
UTF-8
1,541
2.765625
3
[]
no_license
from bs4 import BeautifulSoup import logging logging.basicConfig() logger = logging.getLogger('pageparser') class Parser: def __init__(self, resource_config, page): self.config = resource_config self.page = page def parse(self): soup = BeautifulSoup(self.page, "lxml") elements = self.config.get('elements', None) element_answers = [] for element in elements: element_type = element['element']['type'] element_class = element['element']['class'] element_attribute = element['element'].get('attribute', None) if element_attribute is not None: answers = map(lambda x: {element['name']: x[element_attribute]}, soup.findAll(element_type, class_=element_class)) else: answers = map(lambda x: {element['name']: x.get_text()}, soup.findAll(element_type, class_=element_class)) element_answers.append(answers) data = Parser.__make_collections(element_answers) return {"name": self.config.get('name'), "data": data} @staticmethod def __make_collections(element_answers): final = [] items = 2 while items > 1: collection = [] for group in element_answers: items = len(group) collection.append(group.pop()) final.append({k: v for d in collection for k, v in d.items()}) return final
C++
UTF-8
2,797
2.75
3
[ "MIT" ]
permissive
/////////////////////////////////////////////////////////////////// // // // Copyright (c) 2006-2009, Universidad de Alcala // // // // See accompanying LICENSE.TXT // // // /////////////////////////////////////////////////////////////////// /* detail/helper_fun_node.hpp -------------------------- Private helper methods for the relationship container-nodes dummy(): get the sentinel/end node of this container (O(1)) dummy_ownwer(): get the container of a dummy node (O(1)) owner(): get the container of a node (O(log N)) */ #ifndef _AVL_ARRAY_HELPER_FUN_NODE_HPP_ #define _AVL_ARRAY_HELPER_FUN_NODE_HPP_ #ifndef _AVL_ARRAY_HPP_ #error "Don't include this file. Include avl_array.hpp instead." #endif namespace mkr // Public namespace { ////////////////////////////////////////////////////////////////// // Most data stored inside the avl_array object come from the base // class: a node. This node is the root of the whole tree and the // end element at the same time. It is the only node whose parent // pointer is NULL. Its right child pointer will allways be NULL. // Last, but not least, it has no T data. The method dummy() // returns a pointer to this sentinel/end node // // Complexity: O(1) template<class T,class A,bool bW,class W,bool bP,class P> inline typename avl_array<T,A,bW,W,bP,P>::node_t * avl_array<T,A,bW,W,bP,P>::dummy () const { return static_cast<node_t*> ( const_cast<my_class*> (this) ); } // The static method dummy_owner() calculates the // address of an avl_array from its dummy's address // // Complexity: O(1) template<class T,class A,bool bW,class W,bool bP,class P> inline //static typename avl_array<T,A,bW,W,bP,P>::my_class * avl_array<T,A,bW,W,bP,P>::dummy_owner (const typename avl_array<T,A,bW,W,bP,P>::node_t * pdummy) { AA_ASSERT (!pdummy->m_parent); return static_cast<my_class*> ( const_cast<node_t*> (pdummy) ); } // Finally, the static method owner() returns the address // of the avl_array to which a node belongs. This takes // some time // // Complexity: O(log N) template<class T,class A,bool bW,class W,bool bP,class P> inline //static typename avl_array<T,A,bW,W,bP,P>::my_class * avl_array<T,A,bW,W,bP,P>::owner (const typename avl_array<T,A,bW,W,bP,P>::node_t * node) { while (node->m_parent) node = node->m_parent; return dummy_owner (node); } ////////////////////////////////////////////////////////////////// } // namespace mkr #endif
Java
ISO-8859-1
10,899
2.90625
3
[]
no_license
/** * Auteurs : Franois Mathieu et Soti * Fichier : PrincipalTp5.java * Cours : 420-165-MO (TP5, Bibliothque) * Date : 6 mai 2015 */ // Packages du systme. import java.io.*; import java.nio.file.*; import java.util.*; // Package du programmeur. import outilsjava.*; /** * La classe PrincipalTp5 permet de grer un menu principal pour pour le TP5. * Programme de gestion des prts de documents d'une bibliothque. Cette classe * implmente l'interface OutilsConstantes. */ public class PrincipalTp5 implements OutilsConstantes { /** * Le constructeur PrincipalTp5() permet de crer l'objet pour la * bibliothque et de prparer la gestion de la bibliothque. */ public PrincipalTp5() { // Constantes. final String MESS_BIENVENUE = "\nBienvenue au programme de gestion de" + " la bibliothque Montmoblitech."; final String QUEST_FIC_BIBLIOTHEQUE = "\nEntrez le nom du " + "fichier qui contient les donnes de la bibliothque : "; final String ERREUR_FIC_BIBLIOTHEQUE = "\nUne erreur est survenue " + "avec le fichier de la bibliothque."; System.out.println(MESS_BIENVENUE); /** * TODO ( COMPLTER). Voir page 8 de l'nonc du TP5. * * Lorsque vous aurez termin et test la premire partie (pages 8 33 * de l'nonc du TP5), n'oubliez pas de faire et de tester la deuxime * partie (pages 33 34 de l'nonc du TP5). */ Bibliotheque bibliotheque = new Bibliotheque(); // Nom Physique du fichier String nomFichier; // Nom logique du fichier binaire en lecture ObjectInputStream ficLecture; nomFichier = OutilsFichier.lireNomFichier(QUEST_FIC_BIBLIOTHEQUE); ficLecture = preparerOuvertureFichier(nomFichier, bibliotheque); if (ficLecture == null) { System.out.println(ERREUR_FIC_BIBLIOTHEQUE); } else { bibliotheque = Bibliotheque.lireFicBin(ficLecture); OutilsFichier.fermerFicBinLecture(ficLecture, nomFichier); gererMenuPrincipal(bibliotheque); sauvegarderFichier(nomFichier, bibliotheque); } System.out.println(MESS_FIN_PROG); } /** * La mthode prive gererMenuPrincipal() permet de traiter le menu * principal pour la gestion de la bibliothque. * * @param bibliotheque * L'objet qui gre la bibliothque. */ private void gererMenuPrincipal(Bibliotheque bibliotheque) { // Constante pour les noms de mois. final String[] tabMois = { "Janvier", "Fvrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aot", "Septembre", "Octobre", "Novembre", "Dcembre" }; // Obtenir la date d'aujourd'hui. GregorianCalendar aujourdhui = new GregorianCalendar(); int annee = aujourdhui.get(GregorianCalendar.YEAR); int mois = aujourdhui.get(GregorianCalendar.MONTH); int jour = aujourdhui.get(GregorianCalendar.DAY_OF_MONTH); // Constante pour le texte du menu principal. final String MENU_PRINCIPAL = "\nMenu principal pour la gestion de la" + " bibliothque Montmoblitech.\n" + "Date : " + jour + " " + tabMois[mois] + " " + annee + "\n\n" + "1. Grer les documents\n" + "2. Grer les abonns\n" + "3. Grer les prts\n" + "4. Quitter le programme"; // Constantes pour les choix du menu principal. final char GERER_DOCUMENTS = '1'; final char GERER_ABONNES = '2'; final char GERER_PRETS = '3'; final char QUITTER = '4'; char choix; do { choix = OutilsAffichage.afficherChoisirMenu(MENU_PRINCIPAL, GERER_DOCUMENTS, QUITTER); switch (choix) { case GERER_DOCUMENTS: this.gererDocuments(bibliotheque); break; case GERER_ABONNES: this.gererAbonnes(bibliotheque); break; case GERER_PRETS: this.gererPrets(bibliotheque); break; } } while (choix != QUITTER); } /** * La mthode prive gererDocuments() permet de grer les documents de la * bibliothque. * * @param bibliotheque * L'objet qui gre la bibliothque. */ private void gererDocuments(Bibliotheque bibliotheque) { // Constante pour le texte du sous-menu pour grer les documents. final String MENU_DOCUMENTS = "\nSous-menu pour la gestion " + "des documents\n\n" + "1. Ajouter un document\n" + "2. Supprimer un document\n" + "3. Consulter un document\n" + "4. Consulter tous les documents\n" + "5. Quitter ce sous-menu"; // Constantes pour les choix du sous-menu pour grer les documents. final char AJOUTER_DOCUMENT = '1'; final char SUPPRIMER_DOCUMENT = '2'; final char CONSULTER_DOCUMENT = '3'; final char CONSULTER_TOUS_DOCUMENTS = '4'; final char QUITTER_SOUS_MENU = '5'; char choix; do { choix = OutilsAffichage.afficherChoisirMenu(MENU_DOCUMENTS, AJOUTER_DOCUMENT, QUITTER_SOUS_MENU); switch (choix) { case AJOUTER_DOCUMENT: new AjouterDocument(bibliotheque); break; case SUPPRIMER_DOCUMENT: new SupprimerDocument(bibliotheque); break; case CONSULTER_DOCUMENT: new ConsulterDocument(bibliotheque); break; case CONSULTER_TOUS_DOCUMENTS: new ConsulterTousDocuments(bibliotheque); break; case QUITTER_SOUS_MENU: System.out.println("\nFin du sous-menu pour la gestion " + "des documents."); break; } } while (choix != QUITTER_SOUS_MENU); } /** * La mthode prive gererAbonnes() permet de grer les abonns de la * bibliothque. * * @param bibliotheque * L'objet qui gre la bibliothque. */ private void gererAbonnes(Bibliotheque bibliotheque) { // Constante pour le texte du sous-menu pour grer les abonns. final String MENU_ABONNES = "\nSous-menu pour la gestion" + " des abonns\n\n" + "1. Ajouter un abonn\n" + "2. Supprimer un abonn\n" + "3. Consulter un abonn\n" + "4. Consulter tous les abonns\n" + "5. Quitter ce sous-menu"; // Constantes pour les choix du sous-menu pour grer les abonns. final char AJOUTER_ABONNE = '1'; final char SUPPRIMER_ABONNE = '2'; final char CONSULTER_ABONNE = '3'; final char CONSULTER_TOUS_ABONNES = '4'; final char QUITTER_SOUS_MENU = '5'; char choix; do { choix = OutilsAffichage.afficherChoisirMenu(MENU_ABONNES, AJOUTER_ABONNE, QUITTER_SOUS_MENU); switch (choix) { case AJOUTER_ABONNE: new AjouterAbonne(bibliotheque); break; case SUPPRIMER_ABONNE: new SupprimerAbonne(bibliotheque); break; case CONSULTER_ABONNE: new ConsulterAbonne(bibliotheque); break; case CONSULTER_TOUS_ABONNES: new ConsulterTousAbonnes(bibliotheque); break; case QUITTER_SOUS_MENU: System.out.println("\nFin du sous-menu pour la gestion " + "des abonns."); break; } } while (choix != QUITTER_SOUS_MENU); } /** * La mthode prive gererPrets() permet de grer les prts de la * bibliothque. * * @param bibliotheque * L'objet qui gre la bibliothque. */ private void gererPrets(Bibliotheque bibliotheque) { // Constante pour le texte du sous-menu pour grer les prts. final String MENU_PRETS = "\nSous-menu pour la gestion des prts\n\n" + "1. Emprunter un document\n" + "2. Retourner un document\n" + "3. Consulter un prt\n" + "4. Consulter tous les prts\n" + "5. Quitter ce sous-menu"; // Constantes pour les choix du sous-menu pour grer les prts. final char EMPRUNTER = '1'; final char RETOURNER = '2'; final char CONSULTER_PRET = '3'; final char CONSULTER_TOUS_PRETS = '4'; final char QUITTER_SOUS_MENU = '5'; char choix; do { choix = OutilsAffichage.afficherChoisirMenu(MENU_PRETS, EMPRUNTER, QUITTER_SOUS_MENU); switch (choix) { case EMPRUNTER: new EmprunterDocument(bibliotheque); break; case RETOURNER: new RetournerDocument(bibliotheque); break; case CONSULTER_PRET: new ConsulterPret(bibliotheque); break; case CONSULTER_TOUS_PRETS: new ConsulterTousPrets(bibliotheque); break; case QUITTER_SOUS_MENU: System.out.println("\nFin du sous-menu pour la gestion " + "des prts."); break; } } while (choix != QUITTER_SOUS_MENU); } /** * La mthode prive preparerOuvertureFichier() permet d'ouvrir le fichier * de la bibliothque en lecture. Si le fichier n'existe pas, on le cre * sans aucune donne et on ouvre ce fichier par la suite en lecture. * * @param nomFichier * Le nom physique du fichier. * @param bibliotheque * L'objet qui gre la bibliothque. * @return le nom logique du fichier si l'opration est un succs ou null * dans le cas contraire. */ private ObjectInputStream preparerOuvertureFichier(String nomFichier, Bibliotheque bibliotheque) { ObjectInputStream ficLecture = null; /** * TODO ( COMPLTER). Voir page 33 de l'nonc du TP5. * * Cette mthode est utilise dans la deuxime partie (pages 33 34 de * l'nonc du TP5). */ ObjectOutputStream ficEcriture = null; Path chemin = null; boolean peutContinuer = true; // Cration du chemin try { chemin = Paths.get(nomFichier); } catch (InvalidPathException errNomFichier) { System.out.println("\nErreur, le fichier " + nomFichier + " contient des caractres illgaux."); peutContinuer = false; } // Si la cration du chemin est valide, on peut poursuivre if (peutContinuer) { // Si le fichier n'existe pas, on le cre avec l'objet de base if (Files.notExists(chemin)) { ficEcriture = OutilsFichier.ouvrirFicBinEcriture(nomFichier); if (ficEcriture == null) { peutContinuer = false; } else { // Le fichier n'existe pas // Cration de ce fichier avec l'objet de base bibliotheque.ecrireFicBin(ficEcriture); OutilsFichier.fermerFicBinEcriture(ficEcriture, nomFichier); } } } // Si on peut continuer, on ouvre le fichier en lecture if (peutContinuer) { ficLecture = OutilsFichier.ouvrirFicBinLecture(nomFichier); } return ficLecture; } /** * La mthode prive sauvegarderFichier() permet de sauvegarder l'objet qui * gre la bibliothque reu en paramtre dans le fichier reu en paramtre. * * @param nomFichier * Le nom physique du fichier. * @param bibliotheque * L'objet qui gre la bibliothque. */ private void sauvegarderFichier(String nomFichier, Bibliotheque bibliotheque) { /** * TODO ( COMPLTER). Voir page 33 de l'nonc du TP5. * * Cette mthode est utilise dans la deuxime partie (pages 33 34 de * l'nonc du TP5). */ ObjectOutputStream ficEcriture = null; System.out.println("\nSauvegarde du fichier " + nomFichier + "."); ficEcriture = OutilsFichier.ouvrirFicBinEcriture(nomFichier); if (ficEcriture != null) { bibliotheque.ecrireFicBin(ficEcriture); OutilsFichier.fermerFicBinEcriture(ficEcriture, nomFichier); } } }
C++
UTF-8
8,208
3.734375
4
[]
no_license
/*==========================================================*\ | 伸展树(splay tree) | 区间操作: | (1)对一段区间都增加一个值value | (2)翻转一个区间 | (3)对一个区间向右移动k步(转化成交换两个相邻的区间) | (4)插入一段区间 | (5)删除一段区间 | (6)返回一段区间的最小值 \*==========================================================*/ #include <iostream> #include <stdio.h> #include <string.h> #include <algorithm> #include <math.h> using namespace std; #define type int #define MAXN 2000005 #define MAXL 100005 #define INF (1<<30) struct Splay_Tree { struct Node//节点 { Node *c[2],*p; //c[0]表示左结点指针,c[1]表示右结点指针 int value,size,Min,lazy; //value表示结点上的值,size表示区间的大小,Min表示这个区间的最小值,lazy标记 bool rev; //是否旋转 }*root,*null,*lb,*rb,S[MAXN]; //root表示根节点,null表示空节点,lb表示左节点,rb表示右节点,S表示Splay Tree int scnt; //表示Splay Tree上结点的个数 inline Node * NewNode(int value,Node *p)//插入新节点 { Node *e=&S[++scnt]; //取数组最后一个元素的地址 e->value=value; e->size=1; e->p=p; e->Min=value; e->lazy=0; e->rev=false; e->c[0]=e->c[1]=null; return e; } inline void Update(Node *p)//更新节点信息 { if (p==null) return; p->size=p->c[0]->size+p->c[1]->size+1; //更新区间大小 p->Min=min(p->value,min(p->c[0]->Min,p->c[1]->Min)); //更新最小值 } inline void PushDown(Node *x)//更新标记 { if(x==null) return; if(x->rev) { x->rev=false; Node *t=x->c[0]; x->c[0]=x->c[1]; x->c[1]=t; x->c[0]->rev=!x->c[0]->rev; x->c[1]->rev=!x->c[1]->rev; } if(x->lazy) //加法更新标记 { int w=x->lazy; x->value+=w; x->Min+=w; x->c[0]->lazy+=w; x->c[1]->lazy+=w; x->lazy=0; } } inline void Rotate(Node *x,int k)//左旋 k=0;右旋 k=1; { Node *y=x->p; //Node 为结点类型,其中c[0]表示左结点指针,c[1]表示右结点指针,p表示指向父节点的指针 PushDown(x->c[0]); PushDown(x->c[1]); PushDown(y->c[!k]); //先将y结点的标记向下传递(因为y在上面),再把x的标记向下传递 y->c[k]=x->c[!k]; y->c[k]->p=y; x->p=y->p; if(y->p->c[0]==y) y->p->c[0]=x; else y->p->c[1]=x; y->p=x; x->c[!k]=y; //维护y结点 Update(y); Update(x); if(root==y) root=x; //root表示整棵树的根节点 } inline void Splay(Node *x,Node *y)//伸展 ,Splay操作,表示把结点x转到结点y的下面 { PushDown(x); while(x->p!=y) { if(x->p->p==y) //父节点的父亲是y,执行单旋转 { if(x->p->c[0]==x) Rotate(x,0); else Rotate(x,1); } else if(x->p->p->c[0]==x->p) { if(x->p->c[0]==x) Rotate(x->p,0),Rotate(x,0); //一字形旋转 else Rotate(x,1),Rotate(x,0); //之字形旋转 } else { if(x->p->c[1]==x) Rotate(x->p,1),Rotate(x,1); //一字形旋转 else Rotate(x,0),Rotate(x,1); //之字形旋转 } } Update(x); //最后再维护x结点 } inline void Select(int k,Node *y) //找到处在中序遍历第k个结点,并将其旋转到结点y的下面 { Node *x=root; PushDown(x); while(k!=x->c[0]->size+1) { if(k<=x->c[0]->size) x=x->c[0]; else { k-=x->c[0]->size+1; x=x->c[1]; } PushDown(x); } Splay(x,y); //执行旋转 } inline void MakeTree(int l,int r,type C[],Node *p,int side) { if(l>r) return; int mid=(l+r)>>1; Node *x; x=NewNode(C[mid],p); p->c[side]=x; MakeTree(l,mid-1,C,x,0); MakeTree(mid+1,r,C,x,1); Update(x); } inline void Insert(int pos,int cnt,type C[])//在pos后插入长度为cnt的区间 { Select(pos+1,null); Select(pos+2,root); MakeTree(1,cnt,C,root->c[1],0); Splay(root->c[1]->c[0],null); } inline void Add(int pos,int cnt,type value)//对pos后长度为cnt的区间中的每个值都增加value { Select(pos,null); Select(pos+cnt+1,root); root->c[1]->c[0]->lazy+=value; Splay(root->c[1]->c[0],null); } inline void Delete(int pos,int cnt)//删除pos后长度为cnt的区间 { Select(pos,null); Select(pos+cnt+1,root); root->c[1]->c[0]=null; Splay(root->c[1],null); } inline void Reverse(int pos,int cnt)//旋转pos后长度为cnt的区间 { Select(pos,null); Select(pos+cnt+1,root); root->c[1]->c[0]->rev=!root->c[1]->c[0]->rev; Splay(root->c[1]->c[0],null); } inline void Revolve(int a,int b,int k)//将[a,b]区间向右旋转k步 { int len=(b-a+1),A,B,C; k=((k%len)+len)%len; if(k==0) return; A=a;B=b-k;C=b; //转化成交换区间[A,B],[B+1,C]; Node *p1,*p2,*p3,*p4; Select(A,null); p1=root; //A-1; Select(C+2,null); p2=root; //C+1; Select(A+1,null); p3=root; //A; Select(B+1,null); p4=root; //B; Select(A,null); //将A-1伸展成root Select(C+2,p1); //将C+1伸展到A-1的右边 Select(B+1,p2); //将B伸展到C+1的左边 Node *x,*y; x=p4->c[1]; //把b的右子树切断,挂在a的左边 p4->c[1]=null; p3->c[0]=x; Splay(p3,null); //把a伸展为root,一路更新即可 } inline type GetMin(int pos,int cnt) //获得pos后长度为cnt的区间的最小值 { Select(pos,null); Select(pos+cnt+1,root); PushDown(root->c[1]->c[0]); return root->c[1]->c[0]->Min; } void Index(int pos) { Select(pos+1,null); printf("*%d\n",root->value); } inline void Print()//打印区间 { int i; for(i=1;i<scnt-1;i++) Index(i); } inline void Init() { scnt=-1; null=0; null=NewNode(INF,0); null->size=0; lb=root=NewNode(INF,null); rb=root->c[1]=NewNode(INF,root); Update(root); } }Splay; int N,M,pos; type C[MAXL],ans; char s[20]; int main() { int i,j,a,b,c,k; Splay.Init(); scanf("%d",&N); for(i=1;i<=N;i++) scanf("%d",&C[i]); //printf("*\n"); //Stop; Splay.Insert(0,N,C); //Splay.Print(); scanf("%d",&M); while(M--) { scanf("%s",s); if(s[0]=='A') { scanf("%d%d%d",&a,&b,&c); Splay.Add(a,b-a+1,c); } else if(s[0]=='R') { scanf("%d%d",&a,&b); if(s[3]=='E') Splay.Reverse(a,b-a+1); else { scanf("%d",&k); Splay.Revolve(a,b,k); //Splay.Print(); } } else if(s[0]=='I') { scanf("%d%d",&a,&C[1]); Splay.Insert(a,1,C); } else if(s[0]=='D') { scanf("%d",&a); Splay.Delete(a,1); } else { scanf("%d%d",&a,&b); ans=Splay.GetMin(a,b-a+1); printf("%d\n",ans); } } return 0; }
Python
UTF-8
2,860
3.4375
3
[]
no_license
import pygame import random pygame.init() width = 1000 height = 500 screen = pygame.display.set_mode((width,height)) white = 255,255,255 red = 255,0,0 black = 0,0,0 img = pygame.image.load("0.png") imgWidth = img.get_width() imgHeight = img.get_height() imgX = random.randint(0, width - imgWidth) imgY = random.randint(0, height - imgHeight) x = 0 y = 0 moveX = 0 moveY = 0 snakeLength = 1 snakeList = [] coinSound = pygame.mixer.Sound('point.wav') bgMusic = pygame.mixer.Sound('bg_music.wav') bgMusic.play(-1) def snake(snakeList): for i in range(len(snakeList)): pygame.draw.rect(screen,red,[snakeList[i][0], snakeList[i][1],50,50]) FPS = 100 CLOCK = pygame.time.Clock() def score(count): font = pygame.font.SysFont(None, 20) text = font.render("Score: {}".format(count),True,black) screen.blit(text, (10,10)) def gameOver(count): font = pygame.font.SysFont(None, 80) text = font.render("Game Over", True, black) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() screen.blit(text, (200,200)) pygame.display.update() count = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: moveX = 5 moveY = 0 elif event.key == pygame.K_LEFT: moveX = -5 moveY = 0 elif event.key == pygame.K_DOWN: moveY = 5 moveX = 0 elif event.key == pygame.K_UP: moveY = -5 moveX = 0 screen.fill(white) screen.blit(img, (imgX, imgY)) rect_1 = pygame.draw.rect(screen,red,[x,y,50,50]) img_rect = pygame.Rect(imgX, imgY, imgWidth, imgHeight) x += moveX y += moveY snakeHead = [] snakeHead.append(x) snakeHead.append(y) snakeList.append(snakeHead) # print(snakeList) if len(snakeList) > snakeLength: del snakeList[0] snake(snakeList) if rect_1.colliderect(img_rect): imgX = random.randint(0, width - imgWidth) imgY = random.randint(0, height - imgHeight) snakeLength += 20 FPS += 5 count += 1 coinSound.play() for each in snakeList[:-1]: if each == snakeList[-1]: gameOver(count) score(count) if x >= width: x = -50 elif x < -50: x = width elif y >= height: y = -50 elif y < -50: y = height pygame.display.update() CLOCK.tick(FPS)
PHP
UTF-8
2,679
2.6875
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
<?php require_once("../includes/session.php"); ?> <?php require_once("../includes/db_connection.php"); ?> <?php require_once("../includes/functions.php"); ?> <?php require_once("../includes/validation_functions.php"); ?> <!--doctor access only--> <?php confirm_logged_in(); ?> <?php if (isset($_POST['submit'])) { // Process the form // validations $required_fields = array("username", "password"); validate_presences($required_fields); $fields_with_max_lengths = array("username" => 30); validate_max_lengths($fields_with_max_lengths); if (empty($errors)) { // Perform Create $username = mysql_prep($_POST["username"]); $hashed_password = password_encrypt($_POST["password"]); $first_name = mysql_prep($_POST["first_name"]); $last_name = mysql_prep($_POST["last_name"]); $query = "INSERT INTO doctor_users ("; $query .= " first_name, last_name, username, hashed_password"; $query .= ") VALUES ("; $query .= " '{$first_name}', '{$last_name}', '{$username}', '{$hashed_password}'"; $query .= ")"; $result = mysqli_query($connection, $query); if ($result) { // Success $_SESSION["message"] = "Doctor created."; redirect_to("manage_doctors.php"); } else { // Failure $_SESSION["message"] = "Doctor creation failed."; } } } else { // This is probably a GET request } // end: if (isset($_POST['submit'])) ?> <?php $layout_context = "admin"; ?> <?php include("../includes/layout/admin_header.php"); ?> <?php echo message(); ?> <?php echo form_errors($errors); ?> <div id="navigation"> <br/><br/> <h2>Create Doctor</h2> </div> <form action="new_doctor.php" method="post"> <table> <tr> <td>First Name:</td> <td> <input type="text" name="first_name" value="" /> </td> </tr> <tr> <td>Last Name</td> <td> <input type="text" name="last_name" value="" /> </td> </tr> <tr> <td>Username </td> <td> <input type="text" name="username" value="" /> </td> </tr> <tr> <td>Password</td> <td> <input type="password" name="password" value="" /> </td> </tr> </table> <input class='btn' type="submit" name="submit" value="Create Doctor" /> </form> <br /> <a class='btn last onePage' href="manage_doctors.php">Cancel</a> </div> </div> <?php include("../includes/layout/admin_footer.php"); ?>
C
UTF-8
615
3.46875
3
[]
no_license
#include <stdlib.h> #include "symbol.h" symbol * symbol_new_char(int frequency, char c) { symbol * new_symbol = malloc(sizeof(symbol)); new_symbol->data.c = c; new_symbol->frequency = frequency; new_symbol->is_leaf = true; return new_symbol; } symbol * symbol_new_children(int frequency, symbol * left, symbol * right) { symbol * new_symbol = malloc(sizeof(symbol)); new_symbol->data.children.left = left; new_symbol->data.children.right = right; new_symbol->frequency = frequency; new_symbol->is_leaf = false; return new_symbol; } void symbol_free(symbol * symbol) { free(symbol); }
C#
UTF-8
3,231
2.515625
3
[]
no_license
using CritiquesShelfBLL.RepositoryInterfaces; using CritiquesShelfBLL.Entities; using Microsoft.EntityFrameworkCore; using System.Linq; using CritiquesShelfBLL.Utility; using System; using CritiquesShelfBLL.ViewModels; using CritiquesShelfBLL.Mapper; using System.Collections.Generic; namespace CritiquesShelfBLL.Managers { public class UserManager : RepositoryBase<ApplicationUser>, IUserRepository { private readonly ImageStore _imageStore; private readonly IMapper _mapper; public UserManager(CritiquesShelfDbContext context, ImageStore imageStore, IMapper mapper) : base(context) { _imageStore = imageStore; _mapper = mapper; } public UserModel Find(string id) { var user = _context.Users .Include(x => x.LikeToRead) .Include(x => x.Favourites) .Include(x => x.Read) .Include(x => x.Reviews).ThenInclude(y => y.Book) .Where(x => x.Id == id) .FirstOrDefault(); if (user.PhotoId != null) { user.Photo = _imageStore.GetImage(user.PhotoId); } var reviewCount = user.Reviews.Count; user.Reviews.OrderByDescending(x => x.Date).Take(10); var model = _mapper.MapUserEntityToModel(user); model.ReadingStat.MaxReviewCount = reviewCount; return model; } public List<ReviewModel> GetPagedUserReviews(string userId, int page, int pageSize) { var reviews = _context.Reviews .Where(x => x.UserId == userId) .Include(x => x.Book) .Include(x => x.User) .OrderByDescending(x => x.Date) .Skip(page * pageSize) .Take(pageSize) .ToList(); return reviews.Select(x => _mapper.MapReviewEntityToModel(x)).ToList(); } public CritiquesShelfRoles GetRole(string userId) { var roleName= _context.Roles.First(r => r.Id == _context.UserRoles.First(ur => ur.UserId == userId).RoleId).Name; foreach(CritiquesShelfRoles enumValue in Enum.GetValues(typeof(CritiquesShelfRoles)) ) { if(enumValue.GetName() == roleName) return enumValue; } throw new Exception($"There was no CritiquesShelfRoles enum defined to the roleName in the database: {roleName}"); } public UserModel Save(UserModel user) { var entity = _context.Users.Find(user.Id); entity.FirstName = user.FirstName; entity.LastName = user.LastName; entity.Email = user.Email; entity.UserName = user.UserName; if (user.Photo != null) { var photoId = _imageStore.SaveImage(user.Photo); entity.PhotoId = photoId; } _context.SaveChanges(); return user; } } }