id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 52 7.08k |
|---|---|---|
02e8b05186e35bcbf0b0 | ```cpp
#include <iostream>
// Define the structure pointed to by PTR
struct Host {
const wchar_t* pNameHost;
};
// Define the structure containing the pointer to Host
struct Data {
Host* PTR;
};
// Define the main structure
struct MainStructure {
Data Data;
};
// Function to extract and print specific i... | |
02eb4571e34b57990ccd | ```bash
#!/bin/bash
OUTPUT_FILENAME="pid$1_$(date +%Y_%m_%d-%H_%M_%S)_monitor.csv"
if [ ! -f "$OUTPUT_FILENAME" ]; then
touch $OUTPUT_FILENAME
fi
# Add BOM file header
echo -e -n "\xef\xbb\xbf" > $OUTPUT_FILENAME
# Function to monitor and update CSV file
monitor_processes() {
while true; do
# Get pr... | |
02ecbc29cc1598697cc1 | ```rust
struct ControlPoint {
uv: [f64; 2],
dir: [f64; 3],
}
fn calculate_total_faces(ctl_pts: &Vec<ControlPoint>, faces: &Vec<[u32; 3]>) -> u32 {
faces.len() as u32
}
fn main() {
let ctl_pts = vec![
ControlPoint { uv: [0.0, 0.0], dir: [-1.0, -1.0, 1.0] },
ControlPoint { uv: [0.0, 1.0]... | |
02ee22c2cf0700109b2c | ```python
class Form:
def __init__(self, request, form_data=None):
self.request = request
self.form_data = form_data if form_data else {}
def is_valid(self):
# Placeholder validation logic - replace with actual validation rules
if all(field in self.form_data for field in ['field... | |
02ee6fdc107665a55fce | ```cpp
double calculateVolume() {
if (_frustumDataDirty) {
// Calculate and update frustum data
_frustumDataDirty = false;
}
double height = getHeight(); // Assume getHeight() returns the height of the frustum
double topArea = getTopArea(); // Assume getTopArea() returns the area of the ... | |
02ef7cb6ee74ad8f2e15 | ```bash
#!/bin/bash
# Update package lists
echo "Updating package lists..."
sudo apt update -y
if [ $? -eq 0 ]; then
echo "Package lists updated successfully."
else
echo "Failed to update package lists. Please check your internet connection or repository configuration."
exit 1
fi
# List available updates
echo "... | |
02f10b353c2a46eb68e3 | ```python
def numbering(source_text, numbering_style, output_format, options):
if output_format == 'latex':
prefix, start_number = numbering_style
if isinstance(source_text, list):
numbered_list = [f"{prefix} {start_number + i}. {item}" for i, item in enumerate(source_text)]
... | |
02f19bb911289ee26dee | ```php
class CustomCollection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
// Define resource model logic
}
/**
* Filter the collection by a specif... | |
02f602ec6e2a6cab724e | ```rust
impl Rtc<init_state::Disabled> {
pub fn disabled(mut self, syscon: &mut Syscon) -> Rtc<init_state::Disabled> {
// Enable the RTC module using the provided syscon instance
// Assuming syscon has a method to enable the RTC module
syscon.enable_rtc_module();
// Return the Rtc i... | |
02f624482625e922ef57 | ```rust
use std::collections::HashMap;
use tokio::time::{delay, Duration};
use reqwest::Client;
async fn fetch_exchange_rates(http_port: u16) -> Result<HashMap<String, f64>, String> {
let response = Client::new()
.get(&format!("http://localhost:{}/rates", http_port))
.send()
.await
... | |
02f73a9eefca07456303 | ```python
class Board:
def __init__(self):
self.board = []
def initialize_board(self, rows, cols):
import random
self.board = [[random.choice([0, 1]) for _ in range(cols)] for _ in range(rows)]
def count_live_neighbors(self, row, col):
live_neighbors = 0
for i in ra... | |
02f7932cee2d9ddbe870 | ```java
public List<Book> searchBooks(String query) {
List<Book> results = new ArrayList<>();
String queryLower = query.toLowerCase();
for (Book book : books) {
if (book.getTitle().toLowerCase().contains(queryLower) ||
book.getAuthor().toLowerCase().contains(queryLower) ||
bo... | |
02f87640d30415186f64 | ```typescript
// Define the respondData type to represent the structure of movie data
type respondData = {
id: number;
title: string;
releaseDate: string;
overview: string;
// Add any other relevant properties
}
// Implement the function to load upcoming movies
function loadUpcomingMovies(upcoming: respondDa... | |
02fa53d1f795bb4a8f9a | ```swift
func countUniqueEdges<T: Equatable>(edges: [Edge<T>]) -> Int {
var uniqueEdges: Set<Edge<T>> = []
for edge in edges {
uniqueEdges.insert(edge)
}
return uniqueEdges.count
}
``` | |
02fb889136882b500580 | ```rust
macro_rules! generate_test_modules {
( $( $feature:ident ),* ) => {
$(
#[cfg(feature = stringify!($feature))]
mod $feature_test;
)*
#[cfg(feature = "use_std")]
mod std_test;
};
}
// Test the macro
generate_test_modules!("feature1", "feature2", "us... | |
02fc720322d07cd93884 | ```python
def translate_rna(rna_sequence):
codon_protein = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCG": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"U... | |
02fc87aafff7f4f8313e | ```python
import logging
from contextlib import contextmanager
from typing import Any, Dict, Generator, TypeVar, Union
import time
import torch
from composer.core import Precision
from composer.trainer.devices.device import Device, T_nnModule
logger = logging.getLogger(__name__)
T = TypeVar('T')
@contextmanager
def... | |
02ffa1975607f1dddba6 | `setup.py`:
```python
import setuptools
__name__ == "__main__" and setuptools.setup(
use_scm_version=True, setup_requires=["setuptools-scm"]
)
```
`fibonacci.py`:
```python
def calculate_fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return calculate_fibonacci(n-... | |
03011d1c5df8989aeb6b | ```python
class EquationOfState:
def pressure(self, density, internal_energy):
# Calculate and return the pressure based on the equation of state
# Example equation of state calculation (replace with actual equation):
pressure = density * internal_energy # Example equation, replace with act... | |
03020f8d1817733940cd | ```java
public class Vehicle {
private String intendedVehicle;
public String getIntendedVehicle() {
return intendedVehicle;
}
public void setIntendedVehicle(String intendedVehicle) {
if (intendedVehicle != null && !intendedVehicle.isEmpty()) {
this.intendedVehicle = intende... | |
03028051a7d5348811fa | ```python
import time
def measure_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time_ms = (end_time - start_time) * 1000
print(f"Execution time: {elapsed_time_ms:.1f} ms")
return resul... | |
0302bb43f9ce905991bd | ```python
import click
import os
import shutil
@click.command()
@click.argument('srcs', type=click.Path(exists=True), nargs=-1)
@click.option('--dist', '-d', default='', help='An optional directory to which extract files.')
def uncmprs(srcs, dist):
if dist:
destination_dir = dist
else:
destinat... | |
0306d452b6fa55ad9f86 | ```python
import tensorflow as tf
import caffe
def convert_caffe_to_tf(caffe_model_file: str, output_dir: str) -> None:
# Load the Caffe model
net = caffe.Net(caffe_model_file, caffe.TEST)
# Convert Caffe model to TensorFlow model
# Assuming conversion logic is implemented in a separate function calle... | |
03080769417b20ab24e8 | ```rust
use sign::verify_detached;
fn verify_with_magic<'a>(
magic: &[u8],
data: &'a [u8],
key: &sign::PublicKey,
) -> SimpleResult<&'a [u8]> {
if data.len() < 64 {
return Err("signature too short");
}
let signature = &data[..64]; // Assuming the signature is the first 64 bytes of ... | |
0308b635de3bb58d0633 | ```typescript
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export function processDataFromHttpRequest(http: HttpClient, url: string): Observable<string> {
return http.get<{ data: string, timestamp: number }>(url).pipe(
map(response =>... | |
0308ebb37d73e750cf30 | ```python
def validate_response(resp_data, expected_data):
assert resp_data == expected_data
```
The `validate_response` function compares the `resp_data` with the `expected_data` using the `assert` statement. If the comparison fails, an `AssertionError` is raised. If the comparison passes, the function completes ... | |
03094e310b6cd9a1928d | ```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseLinkedList(head: ListNode) -> ListNode:
prev = None
current = head
while current is not None:
next_node = current.next
current.next = prev
prev = current
... | |
0309ae437f0164f23341 | ```java
public class Solution {
public static float calculateVerticalPosition(RectF rectF, ImageView imageView, YPosition yPosition) {
float f1 = rectF.getHeight();
float f3 = rectF.getWidth();
int i1 = imageView.getHeight();
if (f1 <= i1) {
switch (yPosition) {
... | |
030aa4fcf90b81a00935 | ```python
def process_file(file_name):
try:
with open(file_name, 'r') as file:
for line in file:
print(line.strip())
except FileNotFoundError:
print("File not found")
# Example usage
process_file("words.txt")
```
The `process_file` function opens the specified file ... | |
030cd4c7ba016f8b0e82 | ```python
from django.conf.urls import include, url
from donations.views import DonateAPI, VerifyAPI
app_name = 'donations'
def configure_donation_urls(urlpatterns):
# Add URL patterns for DonateAPI and VerifyAPI
updated_urlpatterns = [
url(r'^donate/$', DonateAPI.as_view(), name='donate'),
u... | |
030ce4fa54c39d930586 | ```python
import requests
from tqdm import tqdm
def download_file(url: str, output_file: str, show_progress_bar: bool) -> None:
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
with open(output_file, 'wb') as file:
if show_progress_bar:
... | |
030e0ac8ab51120283c7 | ```cpp
#include <iostream>
#include <string>
#ifndef _WIN32
inline std::string basename(const std::string& filepath) {
size_t found = filepath.find_last_of("/\\");
if (found != std::string::npos) {
return filepath.substr(found + 1);
}
return filepath;
}
#endif
int main() {
std::string file... | |
030eafe9fcb4adff26e6 | ```python
def process_protein_data(organism, extra_file=None):
if organism == 'yeast_ecoli':
d = read_in('uniprot', 'pdb', organism=organism)
if extra_file:
d_old = read_in('uniprot', 'pdb', filename=extra_file)
flag = 'EXTRA'
else:
d_old = read_in('unipro... | |
030ed9868191d2b579c2 | ```python
import numpy as np
def calculate_drift_velocity(angular_velocity, position_vector):
# Levi-Civita permutation symbol
LeviCivitaSymbol = np.array([[[0, 0, 0], [0, 0, 1], [0, -1, 0]],
[[0, 0, -1], [0, 0, 0], [1, 0, 0]],
[[0, 1, 0], [-1... | |
030ff978a6f04e61dab4 | ```python
import re
def validate_s3_url(url: str) -> bool:
pattern = r"^simpleflow\+s3://([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)/([a-z0-9-]+(?:/[a-z0-9-]+)*)?$"
return bool(re.match(pattern, url))
``` | |
0310016c0d100be742bd | ```jsx
import React from 'react';
import CustomModal from './CustomModal';
const App = () => {
const handleConfirm = () => {
console.log('Confirmed');
// Perform actions on confirmation
};
const handleCancel = () => {
console.log('Cancelled');
// Perform actions on cancellation
};
return (
... | |
0311a960ccf7d90ed4cd | ```python
def countSubstrings(s: str) -> int:
left, right = 0, 0
subStringCount = 0
counter = {c: 0 for c in 'abc'}
while right < len(s):
counter[s[right]] += 1
while all(counter.values()):
counter[s[left]] -= 1
left += 1
subStringCount += 1 # In... | |
03124a6830eae429cb5a | ```python
import re
def parseUserAgent(userAgent):
match = re.search(r'\((.*?)\)', userAgent)
platform_details = match.group(1).split(';')
browser_match = re.search(r'(\w+)/(\d+\.\d+\.\d+\.\d+)', userAgent)
browser_name = browser_match.group(1)
browser_version = browser_match.group(2)
engine_... | |
031366858f928dd2f780 | ```python
from pyPRMS.Cbh import Cbh
from pyPRMS.prms_helpers import dparse
CBH_VARNAMES = ['prcp', 'tmin', 'tmax']
CBH_INDEX_COLS = [0, 1, 2, 3, 4, 5]
def calculate_total_precipitation(start_date, end_date, cbh_file_path):
cbh_data = Cbh(cbh_file_path)
cbh_data.read()
start_index = dparse(start_date... | |
0315d491780b13d1b427 | ```python
class Application:
def __init__(self, name):
self.name = name
class ApplicationManager:
def __init__(self):
self.running_apps = []
def start(self, application_name):
for app in self.running_apps:
if app.name == application_name:
return
... | |
03168fb74c55ce3e35fa | ```python
class KeyBinding:
def __init__(self):
self.bindings = {
"^A": "beginning-of-line",
"^E": "end-of-line",
"^B": "vi-backward-word",
"^F": "vi-forward-word",
"^W": "vi-backward-kill-word",
"^[": "vi-cmd-mode"
}
def p... | |
0316cbbcc111d8c43efc | ```python
from typing import List, Tuple
def parse_server_log(logs: List[str]) -> List[Tuple[int, str]]:
parsed_logs = []
for log in logs:
parts = log.split()
server_id = int(parts[1])
action = parts[2]
parsed_logs.append((server_id, action))
return parsed_logs
```
The `pars... | |
0317301cb6ab3495da4e | ```python
from datetime import datetime
class News:
def __init__(self, id, category, title, url, image_url, description, date):
self.id = id
self.category = category
self.title = title
self.url = url
self.image_url = image_url
self.description = description
s... | |
0317dfaba868add20c27 | ```python
import eel
import time
from dataclasses import dataclass
@dataclass
class InventoryItem:
name: str
quantity: int
price: float
@eel.expose
@eel.apply_factories(inputfactory=InventoryItem)
def return_a_dataclass(datac: InventoryItem):
assert isinstance(datac, InventoryItem)
return datac
@... | |
03185f1d23b629955103 | ```javascript
// Assuming the useRemark hook implementation
import { useEffect, useState } from 'react';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import unified from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeStringify f... | |
031b938867e41ac21e6c | ```swift
func processMentions(in text: String, removeEntireMention: Bool) -> String {
var processedText = text
let mentionRegex = try! NSRegularExpression(pattern: "@\\w+", options: [])
let matches = mentionRegex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for ... | |
031d2c11ebb10d318a84 | ```python
import numpy as np
def top_three_similarity_scores(jac_similarity):
# Flatten the similarity matrix and sort the scores in descending order
sorted_jac = np.sort(jac_similarity.flatten())[::-1]
# Remove NaN values and shift the array to maintain the original order
sorted_jac = np.roll(sor... | |
031d536fa6b624d1b971 | ```python
import importlib
class PluginLoader:
def __init__(self):
self.loaded_modules = {}
def loaddeps(self, modname, force, showerror, loaded):
if modname in loaded:
return loaded
loaded.append(modname)
module = self.getmodule(modname)
if module:
... | |
031ea6e4a3a3ab7006cf | ```rust
fn handle_input(ctx: &GameContext, self: &mut GameState) {
if input::keyboard::is_key_pressed(ctx, KeyCode::Numpad0) {
self.params.max_iter = MandelbrotRenderParams::DEFAULT_ITER;
self.params.offset_x = 0.0;
self.params.offset_y = 0.0;
}
if input::keyboard::is_key_pressed(ctx... | |
03211fcdce3b6dcec15b | ```python
# math_functions.py
def factorial(n):
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
result = 1
for i in range(1, n + 1):
result *= i
return result
# test_factorial.py
import unittest
from math_functions import factorial
class TestFactorial(unitte... | |
0321668098eb4a42b4a7 | To allow the additional origin `'example.com'` to access the web application, the following code should be added to the Django settings file (`settings.py`) in the provided code snippet:
```python
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'127.0.0.1:8000',
'localhost:8080',
'127.0.0.1:8080',
'exa... | |
0322ba4cf111db2111bc | ```php
class View {
private $template;
private $data;
public function __construct($template, $data) {
$this->template = $template;
$this->data = $data;
}
public function fetch() {
// Simulating view rendering by replacing placeholders with actual data
$renderedView ... | |
0324d425472eaa311aad | ```cpp
#include <iostream>
#include <map>
#include <string>
class VendingMachine {
private:
std::map<int, std::pair<std::string, double>> items; // itemID -> (itemName, itemPrice)
double balance;
public:
// Constructor to initialize the available items
VendingMachine(std::map<int, std::pair<std::strin... | |
03257d2908f4c8ae140c | ```csharp
public class RuleRepository
{
private Dictionary<string, Func<bool>> rules;
public RuleRepository()
{
rules = new Dictionary<string, Func<bool>>();
}
public void AddRule(string ruleId, Func<bool> condition)
{
if (!rules.ContainsKey(ruleId))
{
rules... | |
0325f58315bafe682c89 | ```python
def getCostKey(timeInMs: int, costType: str) -> int:
if costType == "connect":
if 10 <= timeInMs < 20:
return 88
elif 20 <= timeInMs < 30:
return 89
elif 30 <= timeInMs < 50:
return 90
elif 50 <= timeInMs < 100:
return 91
... | |
032670421f2c40f1b595 | ```rust
// Define the Parser trait
trait Parser {
type Output;
fn parse(&self, input: &str) -> Result<Self::Output, &str>;
}
// Define the Count struct
struct Count<P> {
parser: P,
count: usize,
}
impl<P> Count<P> {
// Constructor for Count
fn new(parser: P, count: usize) -> Count<P> {
... | |
0328ea73e2d384ac63a0 | ```python
import os
class FileLister:
def __init__(self, directory):
self.directory = directory
def list(self, showhidden=None):
if showhidden is None:
showhidden = False # Default value is False if showhidden is not provided
file_list = []
for filename in os.list... | |
03290d27117a8b753217 | ```python
class Equation:
def __init__(self, name: str, description: str = "", connection_type: str = "source", fast_expr: ExpressionTree = None) -> None:
self.name = name
self.description = description
self.connection_type = connection_type
self.fast_expr = fast_expr
```
In the solu... | |
03293840bd8b2071f4fc | ```python
def fill_disk(state: str, disk_length: int) -> str:
while len(state) < disk_length:
state += state # Double the current state to add more data
return state[:disk_length] # Return the state truncated to the desired length
``` | |
032aad56fcad53ba0b4b | ```python
def count_file_extensions(file_paths):
file_extension_count = {}
for file_path in file_paths:
file_name = file_path.split('/')[-1] # Extract the file name from the path
file_extension = file_name.split('.')[-1] # Extract the file extension
if file_extension in file_extension_... | |
032b296eb88bf6a9b3b8 | ```python
def calculate_matching_sum(captcha: str) -> int:
captcha = captcha + captcha[0] # Append the first digit to the end to consider circular matching
matching_sum = sum(int(captcha[i]) for i in range(1, len(captcha)) if captcha[i] == captcha[i - 1])
return matching_sum
``` | |
032bcf833ed83f1569ab | ```python
def handle_packet_forwarding(controller, dp, msg):
tx_id = controller.transactions()
datapath, port = 1, 1 # Extract datapath and port information from msg
controller.tx_read(tx_id, 'datapath=%x, port=%x, rx-pkts' % (datapath, port))
actions = [ofp_parser.OFPActionOutput(ofp.OFPP_FLOOD)]
... | |
032c6a292efdd10f4e32 | ```python
import pandas as pd
import json
def variable_simplify(variables, stage_var_dict):
# Implement the logic to simplify the sprite and stage variables
# For example:
# Simplify the variables by removing redundant or unnecessary information
simplified_variables = {} # Placeholder for simplified v... | |
032c70e97945ad5ce575 | ```swift
class MockLAContext: LAContext {
var enabled = true
var replySuccess = true
var replyError: Error? = nil
override func evaluatePolicy(_ policy: LAPolicy, localizedReason: String, reply: @escaping (Bool, Error?) -> Void) {
if enabled {
if let error = replyError {
... | |
032d0d0f94eabd701863 | ```java
/**
* Created by 周思成 on 2020/3/24 16:19
*/
public class ElectionException extends Throwable {
private String errMsg;
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg; // Set the error message
}
}
```
In the solut... | |
032e3e521280b226527d | ```python
import random
def rock_paper_scissors(user_choice):
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
if user_choice not in choices:
return "Invalid input"
elif user_choice == computer_choice:
return "Tie!"
elif (user_choice == "rock" and co... | |
032efc25f09d6808f8f0 | ```python
def get_available_roles(user_info):
return user_info.get('self_assigned_roles', [])
```
The `get_available_roles` function takes the `user_info` dictionary as input and uses the `get` method to retrieve the value associated with the key `'self_assigned_roles'`. If the key is not present in the dictionary... | |
032f971a1bcb69c3884d | ```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def visualize_error_surface(err_surface):
fig = plt.figure(figsize=(18, 12))
ax = fig.add_subplot(1, 1, 1, projection='3d')
window_sizes = err_surface.windows
alphabet_sizes = err_surface.alphabets
... | |
0331f0751f5d18b4ada2 | ```swift
public struct InternalSetProperty {
private(set) public var value: Int {
didSet {
if !isSetterAccessibleFromInline() {
print("Cannot modify 'value': setter is not accessible from outside the module.")
value = oldValue
}
}
}
fi... | |
03321d8065d2bfb88c83 | ```python
from typing import List, Dict
class AddressRecord:
def __init__(self, addressline6: str, postcode: str):
self.addressline6 = addressline6
self.postcode = postcode
def extract_postcodes(records: List[AddressRecord]) -> Dict[int, str]:
extracted_postcodes = {}
for index, record in ... | |
0332f11a04331061a34f | ```java
import java.util.HashMap;
import java.util.Map;
public class FailureManager {
private static final Map<String, String> failureDescriptions = new HashMap<>();
static {
failureDescriptions.put("failure_020_Export_zoneRollback_before_delete", "Failure scenario: Export zone rollback before delete"... | |
0335b7eebe84dc274cba | ```csharp
using UnityEngine;
public class bullet_movement : MonoBehaviour {
public GameObject target;
public float speed;
public float damage;
void Start () {
// Initialization code if needed
}
void Update () {
if (target != null) {
Vector3 direction = target... | |
033626dfcf6c038c32e2 | ```python
def polygon_area(vertices):
n = len(vertices)
area = 0.0
for i in range(n):
j = (i + 1) % n
area += vertices[i][0] * vertices[j][1]
area -= vertices[i][1] * vertices[j][0]
area = abs(area) / 2.0
return area
# Test the function
vertices = [(1, 1), (4, 1), (4, 4), (1... | |
0336f55e159a2ee839ff | ```bash
# Define the generateOTP function to generate a one-time password
generateOTP() {
# Implementation of generating OTP goes here
# Example: Using a library or API to generate a secure OTP
# Return the generated OTP
echo "123456" # Replace with actual OTP generation logic
}
# Define the array 'stuff' wit... | |
0337faa74846629f62da | ```java
public class SumOfThousandsAndHundreds {
public static int sumOfThousandsAndHundreds(int n) {
if (n < 100) {
return -1; // Return -1 if n has less than three digits
} else {
int thousand = n / 1000; // Calculate the digit in the thousands place
int hundred... | |
03391e9bd423e13f3580 | ```javascript
function calculateChartRange(minX, maxX, chartWidth, zoomLevel) {
const dataRange = maxX - minX;
const visibleRange = chartWidth / zoomLevel;
const visibleFraction = visibleRange / dataRange;
const visibleXRange = visibleFraction * dataRange;
const centerOffset = (dataRange - visibleX... | |
0339ea11238ba09dc014 | ```python
def convert_to_xml(log_level: str, log_message: str, template: str) -> str:
xml_str = template.replace('<log level="{}">'.format(log_level), '<log level="{}">'.format(log_level.lower()))
xml_str = xml_str.replace('<log>', '<log>{}</log>'.format(log_message))
return xml_str
``` | |
033a24c618e804bdf5c4 | ```python
from setuptools import setup
setup(
name='webapp',
version='1.0',
packages=['webapp'],
package_data={'webapp': ['templates/*.j2']}, # Updated package name to 'webapp'
install_requires=[
'jinja2',
'lxml',
],
)
```
Explanation:
In the `package_data` dictionary, the key... | |
033aa3d7148c3dec257d | ```python
from typing import List
def calculateAverage(scores: List[int]) -> int:
if len(scores) <= 2:
return round(sum(scores) / len(scores))
scores.sort()
return round(sum(scores[1:-1]) / (len(scores) - 2))
```
The `calculateAverage` function first checks if the list has 2 or fewer elements,... | |
033acd928a2aec2388af | ```python
from recordtype import recordtype
# Define the movie recordtype
Movie = recordtype("Movie", ["id", "title", "director", "year"])
# Initialize a list of movie titles
movie_titles = ["The Shawshank Redemption", "The Godfather", "The Dark Knight", "Pulp Fiction"]
# Movie database to store movie records
movie_... | |
033b9901f558438fe11a | ```python
# Complete the checkAppealGuild function
async def checkAppealGuild(bot, os):
appealguild = bot.get_guild(int(os.getenv('appealguild')))
appealchannel = None
for channel in appealguild.channels:
if channel.name == "appeal-here":
appealchannel = channel
break
ret... | |
033bc3022a3b536c3be5 | ```python
def sum_of_digits(n: int) -> int:
total_sum = 0
while n > 0:
temp = n % 10
n = n // 10
total_sum += temp
return total_sum
``` | |
033c3f3b46f9fd7661be | ```python
def count_substring(string: str, sub_string: str) -> int:
k = len(sub_string)
count = 0
for i in range(len(string) - k + 1):
if string[i:i+k] == sub_string:
count += 1
return count
```
The solution defines the `count_substring` function that iterates through the `string` u... | |
033da4980bbe06f3e7eb | ```java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AsciiDocDocumentAttributeScanner {
public Map<String, String> extractAttributes(String input) {
Map<String, String> attributes = new HashMap<>();
Pattern pattern = P... | |
0341593c68b9d64ef045 | ```javascript
function parseCookie(cookieString) {
const parts = cookieString.split(';');
const cookieData = {};
parts.forEach(part => {
const [key, value] = part.trim().split('=');
if (key.toLowerCase() === 'expires') {
cookieData.options = { ...cookieData.options, expires: new Date(value) };
}... | |
03415aa6c6c0ac85747c | ```python
import re
class UserRegistrationSystem:
def __init__(self):
self.registered_users = {}
def register_user(self, user_name, user_email, user_password, confirm_password):
if user_password != confirm_password:
raise exceptions.PasswordsNotMatchingException()
if not r... | |
0341a284ca72906653fb | ```python
from typing import Generic, TypeVar, List, Union
D = TypeVar('D')
class Gen(Generic[D]):
def __init__(self):
self.elements: List[D] = []
def add_element(self, element: D) -> None:
self.elements.append(element)
def get_elements(self) -> List[D]:
return self.elements
... | |
0342ef02ee493d3bdd3d | ```csharp
using System;
using System.Collections.Generic;
using System.Linq;
public class Transaction
{
public string SenderAddress { get; set; }
public List<To> Tos { get; set; }
}
public class To
{
public string Address { get; set; }
public decimal Value { get; set; }
}
public class TransactionProc... | |
03435796714b7f3408e5 | ```swift
import UIKit
// Enum to represent different types of gestures
enum GestureType {
case tap
case swipe(direction: UISwipeGestureRecognizer.Direction)
case pinch
}
// Class to represent a gesture recognizer
class GestureRecognizer {
var tapCallback: (() -> Void)?
var swipeCallback: ((UISwipe... | |
0343879fa41821b9dac5 | ```python
def extract_metadata(meta):
author = meta.get("authors", [None])[0]
license = meta.get("license", None)
copyright = meta.get("copyright", None)
return author, license, copyright
```
The `extract_metadata` function uses the `get` method to retrieve the values from the metadata dictionary. If a... | |
0343ab29d841f947ad2b | ```csharp
public class TimeInterval
{
private uint _minUs;
public uint MinUs
{
get => _minUs;
}
public void SetMinUs(uint value)
{
_minUs = value;
}
}
```
In the solution, the `TimeInterval` class is implemented with a private field `_minUs` to store the minimum value of t... | |
0347df1f9574745c47ca | ```python
from pdf2image import convert_from_path
import os
def convert_pdf_to_images(pdf_path: str) -> None:
# Convert pages into images
pages = convert_from_path(pdf_path)
# Save the pages in JPEG format
for i, page in enumerate(pages):
image_path = f'page_{i+1}.jpg'
page.save(image_... | |
03486c59180dcd747bbc | ```python
class BuildConfig:
def __init__(self, f77, cc, pplist, usr_lflags, ifmpi, source_root, examples_root, log_root, verbose, parallel_procs):
self.f77 = f77
self.cc = cc
self.pplist = pplist
self.usr_lflags = usr_lflags
self.ifmpi = ifmpi
self.source_root = sour... | |
034afb0d533097e3bda8 | ```python
import ast
def is_magic_name(name: str) -> bool:
return name.startswith('__') and name.endswith('__')
def is_function(node: ast.AST) -> bool:
return isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
def is_assign(node: ast.AST) -> bool:
return isinstance(node, ast.Assign)
```
The `is_ma... | |
034b496693a37dfb98f7 | ```python
import re
def extract_url_and_text(html_snippet):
# Regular expression pattern to match the URL and anchor text
pattern = r'<a\s+href="([^"]+)">([^<]+)</a>'
# Search for the pattern in the HTML snippet
match = re.search(pattern, html_snippet)
if match:
url = match.group(... | |
034b7568caaada508742 | ```csharp
// Add the following code inside the try block to parse the JSON response and display the to-do items
JArray todoItems = JArray.Parse(response);
Console.WriteLine("To-Do Items:");
foreach (JObject item in todoItems)
{
Console.WriteLine($"- {item["id"]}: {item["title"]} (Completed: {item["completed"]})")... | |
034bb81e596cfcff095e | ```python
def generate_ui(layout, meshes_selected, use_selection, use_apply_modifiers, use_armature_pose, use_armature):
col = layout.column(align=True)
col.prop(self, "use_selection", "Selection only (%i meshes)" % meshes_selected)
col.enabled = bool(meshes_selected)
col = layout.column(align=True)
... | |
034c6da5f0998d364618 | ```python
def simulate_setup(install_params):
print(f"Simulating setup for {install_params['name']} module:")
print(f"- Package name: {install_params['name']}")
print(f"- Version: {install_params['version']}")
print(f"- Author: {install_params['author']}")
print(f"- Author email: {install_params['au... | |
034e171a01d459a5ad1f | ```python
import numpy as np
class TwoAdditiveFactorModel:
def __init__(self, phi_func):
self.phi_func = phi_func
def calculate_interest_rate_change(self, t, x, y):
try:
dr_t = self.phi_func(t) + x + y
return dr_t
except Exception as e:
print(f"Error... | |
034e63c154c72d5488ad | ```python
def process_config(config: dict) -> dict:
# Modify 'JSON_AS_ASCII' key if present
if 'JSON_AS_ASCII' in config:
config['JSON_AS_ASCII'] = True
# Add 'debug' key if not present
if 'debug' not in config:
config['debug'] = False
return config
```
The `process_config` functi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.