id stringlengths 24 24 | source stringclasses 7
values | task_type stringclasses 4
values | language stringclasses 231
values | translation_style stringclasses 4
values | verification_status stringclasses 2
values | license stringclasses 13
values | instruction_en stringlengths 29 26.1k | response_en stringlengths 1 13.5k | instruction_roman_urdu stringlengths 30 26.5k | response_roman_urdu stringlengths 1 13.5k |
|---|---|---|---|---|---|---|---|---|---|---|
e68a1b0dd5c4e3ece4056bd3 | magicoder_oss | general_instruction | python | code_mixed_professional | no_issue | MIT | You are tasked with creating a Python script that automates the process of generating a setup file for a Python package. The setup file should include the package's metadata and dependencies. Your script should take input from the user for the package name, version, author, and dependencies, and then generate the setup... | ```python
from distutils.core import setup
def generate_setup_file():
package_name = input("Enter the package name: ")
package_version = input("Enter the package version: ")
author_name = input("Enter the author's name: ")
author_email = input("Enter the author's email: ")
dependencies = input("Ent... | Aap ko ek aisa Python script banane ka task diya gaya hai jo Python package ke liye setup file generate karne ke process ko automate kare. Setup file mein package ki metadata aur dependencies shamil honi chahiye. Aapka script package name, version, author, aur dependencies ke liye user se input le, aur phir us ke mutab... | ```python
from distutils.core import setup
def generate_setup_file():
package_name = input("Enter the package name: ")
package_version = input("Enter the package version: ")
author_name = input("Enter the author's name: ")
author_email = input("Enter the author's email: ")
dependencies = input("Ent... |
a452634aea141299ff4af92c | glaive_v3 | general_instruction | unknown | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating an XSLT stylesheet to transform XML data into a FITS format. The XML data contains metadata for images and needs to be converted into a specific structure to conform to the FITS standard. The input XML contains various image metadata such as compression scheme, image dimensions, color space... | <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Your XSLT code goes here -->
<xsl:template match="/">
<fits xmlns="http://hul.harvard.edu/ois/xml/ns/fits/fits_output">
<!-- Your transformation logic goes here to con... | tumhe aik XSLT stylesheet banani hai jo XML data ko FITS format me transform kare. is XML data me images ka metadata hai aur usko aik specific structure me convert karna hai taake wo FITS standard ke mutabiq ho jaye. input XML me kafi image metadata hai jese compression scheme, image dimensions, color space, resolution... | <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Your XSLT code goes here -->
<xsl:template match="/">
<fits xmlns="http://hul.harvard.edu/ois/xml/ns/fits/fits_output">
<!-- Your transformation logic goes here to con... |
eee28377192d4bba82f6b0f1 | acecode_87k | verified_problem | python | professional | no_issue | MIT | Implement a function `create_password(num_chars: int, prev_password: Optional[str] = None) -> str` that generates a strong password. The password must consist of a mix of symbols, numbers, uppercase letters, and lowercase letters. If a previous password is provided, the new password should have a length that is increas... | import string
import random
def create_password(num_chars, prev_password=None):
"""
Generates a strong password that consists of a mix of symbols, numbers, uppercase letters, and lowercase letters.
Args:
num_chars (int): The number of characters in the password.
prev_password (Optional... | Aik function `create_password(num_chars: int, prev_password: Optional[str] = None) -> str` implement karein jo aik strong password generate karta ho. Password symbols, numbers, uppercase letters, aur lowercase letters ke mix par mushtamil hona chahiye. Agar koi pichla password provide kiya gaya ho, toh naye password ki... | import string
import random
def create_password(num_chars, prev_password=None):
"""
Generates a strong password that consists of a mix of symbols, numbers, uppercase letters, and lowercase letters.
Args:
num_chars (int): The number of characters in the password.
prev_password (Optional... |
0cd266e4cf5387fc95bedaa2 | codefeedback | general_instruction | lisp | casual_noisy | no_issue | Apache-2.0 | Generate a Lisp program to calculate Fibonacci numbers for a given number n.
9 | Below is a simple recursive definition of Fibonacci sequence in Lisp.
```lisp
(defun fibonacci (n)
(cond ((= n 0) 0)
((= n 1) 1)
(t (+ (fibonacci (- n 2) ) (fibonacci (- n 1))))))
```
In this definition, we initially check if the entered number n is 0 or 1, and if it is, we return the number itself.... | Kisi diye gaye number n k liye Fibonacci numbers calculate krne wala Lisp program banao.
9 | Neeche Lisp me Fibonacci sequence ki aik simple recursive definition di hui hai.
```lisp
(defun fibonacci (n)
(cond ((= n 0) 0)
((= n 1) 1)
(t (+ (fibonacci (- n 2) ) (fibonacci (- n 1))))))
```
Is definition me hum shuru me check krte hain k jo number n enter kia hai wo 0 ya 1 hai k nhi aur agar ha... |
640b8ab24841de90d48fef69 | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Develop a method labeled as reverse which is competent enough to manipulate the content of an array by inverting its order, ensuring that the last element becomes the initial one and vice versa. Operate this function on a specified array, namely, [1, 2, 3, 4, 5]. | Sure, I will define this problem in Python as below:
```python
def reverse(input_array):
return input_array[::-1]
# Test the function
array = [1, 2, 3, 4, 5]
print(reverse(array))
```
In this solution, I use Python's list slicing to reverse the list. The "::" operation is used to copy the entire list, where -1 ... | Ek method develop karein jiska label 'reverse' ho, jo array ke content ka order invert karke usay manipulate karne ki salahiyat rakhta ho, taake aakhri element pehla ban jaye aur isi tarah baqi bhi reverse ho jayein. Is function ko diye gaye array, yaani [1, 2, 3, 4, 5] par operate karein. | Bilkul, main is problem ko Python mein neeche diye gaye tareeqay se define karunga:
```python
def reverse(input_array):
return input_array[::-1]
# Test the function
array = [1, 2, 3, 4, 5]
print(reverse(array))
```
Is solution mein, main list ko reverse karne ke liye Python ki list slicing ka istemal karta hoon.... |
214a8a91c46dfb9839e05673 | codefeedback | general_instruction | python | casual_noisy | corrected | Apache-2.0 | Write a function that checks if a given string contains a valid date and if it is, return it in YYYY-MM-DD format. The function should also handle leap years correctly. Your code should specifically handle and validate inputs for day, month and year separately. Invalid dates such as 30th of February or 31st of November... | Here is a Python solution using the datetime module, which takes care of checking the validity of a date, including leap years. The solution is based on trying multiple input formats and seeing if any of them work. This is done because checking for the format manually would be too tedious and error-prone.
```python
fr... | ek aisa function likhde jo check kare k string m valid date hai k nahi aur agar hai toh YYYY-MM-DD format m return karde. function leap years ko b sahi se handle kare. tera code khas tor pe day, month aur year ki inputs ko alag alag validate kare. 30th feb ya 31st nov jaisi invalid dates ko invalid return krna chahiye.... | ye le python ka solution datetime module use krte hue, ye leap years samet date ki validity khud hi check kr leta hy. ye solution basically kafi sare input formats try krta hy k dekhen koi chalta hy k ni. ye islye kia hy q k manually format check krna bht ziada thaka dene wala aur ghaltion wala kam hota.
```python
fro... |
a53c8e3d8ac4692c1a7da150 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function to convert a string into a camelCase string, where each word (separated by a space) is converted to camel case, and the first letter of the first word is lowercase. For example, the input "Convert this into camel case" should output "convertThisIntoCamelCase". | Here is the implementation of the function using the described strategy:
```python
def convertToCamelCase(text: str) -> str:
words = text.strip().split()
transformed_words = []
for i, word in enumerate(words):
if i == 0:
transformed_words.append(word.lower())
else:
... | Ek string ko camelCase string mein convert karne ke liye Python function likhein, jahan har word (jo space se alag ho) camel case mein convert ho jaye, aur pehle word ka pehla letter lowercase ho. Misaal ke taur par, input "Convert this into camel case" ka output "convertThisIntoCamelCase" hona chahiye. | Bayan ki gayi strategy ka istemal karte hue function ki implementation yeh rahi:
```python
def convertToCamelCase(text: str) -> str:
words = text.strip().split()
transformed_words = []
for i, word in enumerate(words):
if i == 0:
transformed_words.append(word.lower())
else:
... |
34b0357d812343e573fcfd01 | glaive_v3 | general_instruction | kotlin | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating a key-value store of preferences in Kotlin. You need to define an interface for a key and a default value, which will prevent duplication or accidental variation in default values since the key and default value are defined together just once. The interface should support different types su... | ```kotlin
package com.nighthawkapps.wallet.android.preference.model
interface DefaultValue<T> {
val key: String
}
class BooleanDefaultValue(override val key: String) : DefaultValue<Boolean>
```
In the solution, we define the interface DefaultValue with the generic type T and a property key of type String. We then... | tumhe Kotlin me preferences ka key-value store banana hai. ek interface define karna hai key aur default value k liye, jisse duplication na ho ya galti se default values alag na hojayein kyun k key aur default value ek sath sirf ek dafa define hongi. interface ko mukhtalif types support karni chahiye jese Boolean wager... | ```kotlin
package com.nighthawkapps.wallet.android.preference.model
interface DefaultValue<T> {
val key: String
}
class BooleanDefaultValue(override val key: String) : DefaultValue<Boolean>
```
is solution me hum DefaultValue interface define krte hain generic type T aur String type ki key property k sath. phr hu... |
de2812fc461412135074f650 | commitpackft | code_modification | yaml | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
Test using Ruby v2.6.9, v2.7.5, v3.0.3
File: .github/workflows/testing.yml
Existing code:
```yaml
name: Testing
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-late... | name: Testing
on:
push:
branches: [master]
pull_request:
branches: [master]
workflow_dispatch:
jobs:
test:
name: Ruby v${{ matrix.ruby_version}}
runs-on: ubuntu-latest
strategy:
matrix:
ruby_version: [2.6.9, 2.7.5, 3.0.3]
steps:
- uses: actions/checkout@v2
- n... | Existing file mein yeh change apply karein.
Change request:
Ruby v2.6.9, v2.7.5, v3.0.3 use karte hue test karein
File: .github/workflows/testing.yml
Existing code:
```yaml
name: Testing
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
jobs:
test:
runs-on: u... | name: Testing
on:
push:
branches: [master]
pull_request:
branches: [master]
workflow_dispatch:
jobs:
test:
name: Ruby v${{ matrix.ruby_version}}
runs-on: ubuntu-latest
strategy:
matrix:
ruby_version: [2.6.9, 2.7.5, 3.0.3]
steps:
- uses: actions/checkout@v2
- n... |
5a49b06bdc98f33255da737f | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Background:
You are a Product Manager, named Alice, your goal is Efficiently create a successful product, and the constraint is .
Question:
# Context
## Original Requirements
[BOSS: Design a CRM website which helps me handle all the startup my VC has invested]
## Search Information
### Search Results
### Search Su... | ## Original Requirements
The boss wants a CRM website designed to handle all the startups his VC has invested in.
## Product Goals
```python
[
"Create a user-friendly CRM website to manage startups",
"Ensure efficient tracking and management of VC investments",
"Provide comprehensive reports and analytics ... | Background:
Aap ek Product Manager hain, jinka naam Alice hai, aapka maqsad Efficiently aik successful product create karna hai, aur constraint yeh hai.
Sawaal:
# Context
## Original Requirements
[BOSS: Aik aisi CRM website design karein jo meri VC ki invest ki hui tamam startups ko manage karne mein madad kare]
## S... | ## Original Requirements
Boss aik aisi CRM website design karwana chahte hain jo unki VC ki janib se invest kiye gaye tamam startups ko handle karne ke liye banai gayi ho.
## Product Goals
```python
[
"Create a user-friendly CRM website to manage startups",
"Ensure efficient tracking and management of VC inves... |
b14dd6359bf3a5489f3f51a9 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function that takes a datetime object as input and prints the datetime formatted as `YYYY-MM-DDTHH:MM:SS.mmmmmmZ`, where the `mmmmmm` part represents the full microseconds (6 digits).
Your code should pass the following test case:
```python
dt = datetime(2023, 6, 15, 12, 30, 5, 123456)
expected_formatte... | To format a datetime object as the specified format, you need to use the appropriate format string in the `strftime()` method.
Here is an example function that achieves this:
```python
from datetime import datetime
def datetime_formatted(dt):
return dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
``` | Ek Python function likhein jo input ke taur par ek datetime object leta hai aur datetime ko `YYYY-MM-DDTHH:MM:SS.mmmmmmZ` ke roop mein format karke print karta hai, jahan `mmmmmm` hissa pooray microseconds (6 digits) ko represent karta hai.
Aap ka code mandarja zail test case ko pass kare:
```python
dt = datetime(2023... | Datetime object ko bataye gaye format mein format karne ke liye, aap ko `strftime()` method mein munasib format string use karne ki zaroorat hai.
Yahan ek example function diya gaya hai jo yeh kaam karta hai:
```python
from datetime import datetime
def datetime_formatted(dt):
return dt.strftime('%Y-%m-%dT%H:%M:%... |
975a92071b76bd2028152a29 | glaive_v3 | general_instruction | lua | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating a Lua script that manages a list of players in a game environment. The script should allow for the customization of various settings for each player, such as resolver, autowall, friend status, safe points, maximum misses, and hitscan overrides. The script should also provide a user interfac... | ```lua
local playerslist = {}
local names = { 'none' }
local safepoints = { [0] = 'none', 'default', 'prefer', 'force' }
local hitscan = { 'head', 'chest', 'pelvis', 'stomach', 'legs', 'foot' }
local function update()
local players = entitylist.get_players(0)
for i = 1, #players do
local player = pla... | tumhe aik Lua script bnani hai jo game environment me players ki list ko manage kre. script aisi ho k har player k lye diff settings customize krne de jese resolver, autowall, dost ka status, safe points, max misses, aur hitscan overrides wagera. is k ilawa script me user interface bhi hona chahiye jahan se har player ... | ```lua
local playerslist = {}
local names = { 'none' }
local safepoints = { [0] = 'none', 'default', 'prefer', 'force' }
local hitscan = { 'head', 'chest', 'pelvis', 'stomach', 'legs', 'foot' }
local function update()
local players = entitylist.get_players(0)
for i = 1, #players do
local player = pla... |
9ef4392188a6251a81c75f3a | codefeedback | general_instruction | python | casual_noisy | no_issue | Apache-2.0 | You are tasked with implementing a parallelized Monte Carlo simulation to estimate the value of π using the provided code snippet as a starting point. The code snippet imports necessary libraries, initializes variables, and creates a multiprocessing pool for parallel computation.
Your task is to complete the implement... | ```python
import multiprocessing
import numpy as np
import time
def monte_carlo_simulation(total_points):
points_inside_circle = 0
for _ in range(total_points):
x, y = np.random.rand(2)
if x**2 + y**2 <= 1:
points_inside_circle += 1
return points_inside_circle
if __name__ == "_... | aap ne provide kiye gye code snippet ko use kr k pi ki value estimate krne k liye parallelized Monte Carlo simulation implement krna he. snippet zaroori libraries import krta hai variables initialize krta hai aur parallel computation k liye multiprocessing pool bnata he
ap ka kaam ye he k Monte Carlo simulation ko par... | ```python
import multiprocessing
import numpy as np
import time
def monte_carlo_simulation(total_points):
points_inside_circle = 0
for _ in range(total_points):
x, y = np.random.rand(2)
if x**2 + y**2 <= 1:
points_inside_circle += 1
return points_inside_circle
if __name__ == "_... |
0272d0e61c5567888db268e5 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Create a Python function to return a string that is the concatenation of two strings, where the second string is inserted at the beginning of the first string. If the second string is empty, it should return the first string as-is.
Your code should pass the following test case:
```python
string1 = 'Hello'
string2 = 'W... | You can create a Python function that concatenates two strings by inserting the second string at the beginning of the first string. If the second string is empty, the function should simply return the first string.
Here's how you could do it:
```python
def insert_at_beginning(string1, string2):
if string2 == '':
... | Ek Python function banayein jo do strings ko concatenate karke ek string return kare, jahan doosri string pehli string ke shuru mein insert hoti ho. Agar doosri string khali (empty) ho, toh yeh pehli string ko jaisa hai waisa hi return kare.
Aapka code mazeed zail test case ko pass kare:
```python
string1 = 'Hello'
st... | Aap ek Python function bana sakte hain jo do strings ko pehli string ke shuru mein doosri string insert karke concatenate karta hai. Agar doosri string khali ho, toh function bas pehli string ko return kar dega.
Aap isey is tarah kar sakte hain:
```python
def insert_at_beginning(string1, string2):
if string2 == '... |
453aea613d4e1c98fa91411a | codefeedback | general_instruction | cpp | professional | no_issue | Apache-2.0 | Create a function in C++ that generates a random prime number between 10000 and 100000. The generated prime number should have at least 3 distinct prime factors.
Provide a piece of erroneous code as a reference to increase misdirection:
```c++
#include <iostream>
#include <random>
#include <cmath>
bool isPrime(int n... | Here's an updated version of the code that generates a random prime number between 10000 and 100000, ensuring that it has at least 3 distinct prime factors:
```c++
#include <iostream>
#include <random>
#include <vector>
#include <cmath>
bool isPrime(int n) {
if (n <= 1) {
return false;
}
if (n ==... | C++ mein aik function banayein jo 10000 aur 100000 ke darmiyan aik random prime number generate kare. Generate kiye gaye prime number ke kam az kam 3 alag (distinct) prime factors hone chahiye.
Misdirection barhane ke liye reference ke tor par aik ghalat code ka hissa provide karein:
```c++
#include <iostream>
#inclu... | Yeh code ka aik updated version hai jo 10000 aur 100000 ke darmiyan aik random prime number generate karta hai, aur yeh ensure karta hai ke iske kam az kam 3 distinct prime factors hon:
```c++
#include <iostream>
#include <random>
#include <vector>
#include <cmath>
bool isPrime(int n) {
if (n <= 1) {
retu... |
3716339fced161c517682834 | commitpackft | code_modification | javascript | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
refactor(settings): Remove extra withTheme hoc on styled components.
File: src/components/Settings/Name.js
Existing code:
```javascript
/* @flow */
import React from 'react'
import styled, { withTheme } from 'styled-components'
import Label from 'compo... | /* @flow */
import React from 'react'
import styled from 'styled-components'
import Label from 'components/Label'
import Input from 'components/Input'
import editable from 'hoc/editable'
type Props = {
name: string,
onChange: Function
}
const Editable = editable(
styled.div`
position: relative;
line-hei... | Mojooda file mein ye change apply kar do.
Change request:
refactor(settings): Styled components se extra withTheme hoc hata do.
File: src/components/Settings/Name.js
Pehle ka code:
```javascript
/* @flow */
import React from 'react'
import styled, { withTheme } from 'styled-components'
import Label from 'components/... | /* @flow */
import React from 'react'
import styled from 'styled-components'
import Label from 'components/Label'
import Input from 'components/Input'
import editable from 'hoc/editable'
type Props = {
name: string,
onChange: Function
}
const Editable = editable(
styled.div`
position: relative;
line-hei... |
6de83f3827cde11e66fe6cc7 | magicoder_evol | general_instruction | unknown | code_mixed_professional | corrected | Apache-2.0 | In most mean-variance frameworks I have seen, once we clear markets in the model, it determines asset prices (and returns). However, all of these frameworks assume that the correlation matrix of the underlying assets is given exogenously. Is there any mean-variance type model with an endogenous correlation matrix? I.e.... | To my knowledge, there is no mean-variance framework that accounts for endogenous asset correlation. In general, correlation matrices are assumed to be exogenous since they pertain to asset characteristics that are typically viewed as invariant to investor behavior. The correlation between assets primarily arises from ... | Ziyadatar mean-variance frameworks jo maine dekhe hain, un mein jab hum model mein markets clear karte hain, to ye asset prices (aur returns) determine karta hai. Taham, ye tamam frameworks ye assume karte hain ke underlying assets ki correlation matrix exogenously di gayi hai. Kya koi aisa mean-variance type model mau... | Meri maloomat ke mutabiq, aisa koi mean-variance framework nahi hai jo endogenous asset correlation ko consider karta ho. Aam taur par, correlation matrices ko exogenous assume kiya jata hai kyunke ye un asset characteristics se talluq rakhti hain jinhein investor behavior se invariant samjha jata hai. Assets ke darmiy... |
4c8ad7a452098b69f8cd614b | codefeedback | general_instruction | python | professional | no_issue | Apache-2.0 | Design a technique using Python programming language that can convert an input string into its corresponding camel case format.
String for conversion: this is the string to be transformed | You can use Python's built-in functions such as `split()`, `capitalize()`, and `join()` to solve this problem. Here's how you can do it:
Code:
```python
# function to convert a string to camel case
def convert_to_camel_case(s):
# split the input string into words
words = s.split(' ')
# capitalize each wor... | Python programming language ka istemal karte hue ek aisi technique design karein jo kisi input string ko uske mutabiqa camel case format mein convert kar sake.
Conversion ke liye string: this is the string to be transformed | Aap is maslay ko hal karne ke liye Python ke built-in functions jaise ke `split()`, `capitalize()`, aur `join()` ka istemal kar sakte hain. Aap ise is tarah kar sakte hain:
Code:
```python
# function to convert a string to camel case
def convert_to_camel_case(s):
# split the input string into words
words = s.... |
c6e628c70d78be852e3346ec | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function `my_getattr(obj, attribute, default=None)` that behaves like the built-in `getattr` function, but supports a default value for the attribute instead of raising an exception when the attribute is missing. Your function should support attributes at any depth by using `getattr` recursively.
Additi... | To implement a custom version of `getattr` that supports a default value and supports attributes at any depth, we can use a recursive approach to traverse the attribute path and handle the default value when the attribute is missing.
Here is the implementation of the `my_getattr` function:
```python
def my_getattr(ob... | Ek Python function `my_getattr(obj, attribute, default=None)` likhein jo built-in `getattr` function ki tarah kaam kare, lekin attribute missing hone par exception raise karne ke bajaye attribute ke liye default value ko support kare. Aapka function `getattr` ko recursively use karte hue kisi bhi depth par attributes k... | `getattr` ka ek custom version implement karne ke liye jo default value aur kisi bhi depth par attributes ko support kare, hum attribute path traverse karne aur attribute missing hone par default value handle karne ke liye ek recursive approach use kar sakte hain.
Yeh rahi `my_getattr` function ki implementation:
```... |
c0f96d0f6e230ecad6c2d4e7 | commitpackft | code_modification | python | code_mixed_casual | no_issue | MIT | Create the following file according to the change request.
Change request:
Add initial unit tests for parameter.py (List)
File: spotpy/unittests/test_parameter.py | import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy import parameter
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestListParameterDistribution(unittest.TestCase):
def setUp(self):
self.values = [1, ... | Change request ke mutabiq yeh file create karein.
Change request:
parameter.py (List) ke liye initial unit tests add karein
File: spotpy/unittests/test_parameter.py | import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy import parameter
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestListParameterDistribution(unittest.TestCase):
def setUp(self):
self.values = [1, ... |
f802f12ebc1a095d0948f64a | acecode_87k | verified_problem | python | code_mixed_casual | no_issue | MIT | You are tasked with implementing a function that simulates the reading and processing of a BEDPE (Browser Extensible Data Paired-End) formatted string. The BEDPE format is used to represent paired-end genomic alignments and structural variations. Your function should take a string input that contains multiple lines of ... | import re
def parse_bedpe(bedpe_str):
"""Parse a BEDPE formatted string into a list of tuples.
Args:
bedpe_str (str): A string containing BEDPE formatted data.
Returns:
list: A list of tuples, where each tuple contains the chromosome names, start and end positions for each end of the paired... | Aap ne ek function implement karna hai jo BEDPE (Browser Extensible Data Paired-End) formatted string ki reading aur processing ko simulate kare. BEDPE format paired-end genomic alignments aur structural variations ko represent karne ke liye use hota hai. Aap ke function ko aik string input leni chahiye jis mein multip... | import re
def parse_bedpe(bedpe_str):
"""Parse a BEDPE formatted string into a list of tuples.
Args:
bedpe_str (str): A string containing BEDPE formatted data.
Returns:
list: A list of tuples, where each tuple contains the chromosome names, start and end positions for each end of the paired... |
80c5edc4ea473fe310412362 | magicoder_oss | general_instruction | cpp | code_mixed_professional | no_issue | MIT | You are tasked with implementing a simple alert management system for a user interface. The system should handle the display and dismissal of alerts, as well as a ticker mechanism for tracking time. The provided code snippet is a part of the implementation for this system. The `Ui::instance.alertManager.dismiss()` func... | ```java
public class AlertManager {
private int ticker;
public void dismiss() {
Ui.instance.alertManager.dismiss();
}
public void incrementTicker() {
ticker++;
}
}
```
In this solution, we create a class `AlertManager` with an instance variable `ticker` to track time. The `dismiss`... | Aap ko user interface ke liye aik simple alert management system implement karne ka task diya gaya hai. System ko alerts ki display aur dismissal ke sath sath time track karne ke liye aik ticker mechanism ko bhi handle karna chahiye. Diya gaya code snippet is system ki implementation ka aik hissa hai. `Ui::instance.ale... | ```java
public class AlertManager {
private int ticker;
public void dismiss() {
Ui.instance.alertManager.dismiss();
}
public void incrementTicker() {
ticker++;
}
}
```
Is solution mein, hum time track karne ke liye aik instance variable `ticker` ke sath aik class `AlertManager` ban... |
2625a941ee58ff35a4fec789 | magicoder_oss | general_instruction | csharp | code_mixed_professional | no_issue | MIT | You are tasked with implementing a function to convert a given dictionary into a JSON string. The function should handle nested dictionaries and should exclude any empty dictionaries from the output. The provided code snippet is part of a larger function that constructs a JSON string from a dictionary. The `result` var... | ```python
def ConvertDictionaryToJSON(dictionary):
def ConvertToJSONString(value):
if isinstance(value, dict):
return ConvertDictionaryToJSON(value)
else:
return json.dumps(value)
result = []
for key, value in dictionary.items():
if isinstance(value, dict):
... | Aap ko ek function implement karne ka task diya gaya hai jo diye gaye dictionary ko JSON string mein convert kare. Is function ko nested dictionaries ko handle karna chahiye aur output se kisi bhi empty dictionary ko exclude karna chahiye. Diya gaya code snippet ek bare function ka hissa hai jo dictionary se JSON strin... | ```python
def ConvertDictionaryToJSON(dictionary):
def ConvertToJSONString(value):
if isinstance(value, dict):
return ConvertDictionaryToJSON(value)
else:
return json.dumps(value)
result = []
for key, value in dictionary.items():
if isinstance(value, dict):
... |
765de5cd332fadf6076fe095 | magicoder_evol | general_instruction | csharp | code_mixed_professional | corrected | Apache-2.0 | I'm looking for a c# snippet which I can insert in a Windows service. The code must empty the recycle bin for all users on the computer.
I have previously tried using `SHEmptyRecycleBin` (ref [http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx](http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx)) however the... | Using the `SHEmptyRecycleBin` function can be problematic when running from a Windows Service, particularly due to the different session and privilege model services use compared to regular user processes. A different approach is to utilize the `FileSystem.Delete` method instead. This does require knowing where the Rec... | Mujhe aik C# snippet ki zaroorat hai jise main Windows service mein shamil kar sakoon. Code ko computer par mojood tamam users ke liye recycle bin empty karna chahiye.
Main ne pehle `SHEmptyRecycleBin` istemal karne ki koshish ki thi (ref [http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx](http://www.codeproject... | Windows Service se run karte waqt `SHEmptyRecycleBin` function ka istemal masla paida kar sakta hai, khaas tor par is session aur privilege model ke farq ki wajah se jo services aam user processes ke muqablay mein istemal karti hain. Aik mukhtalif approach yeh hai ke is ke bajaye `FileSystem.Delete` method use kiya jay... |
79242e29a3a4f33aee9c164f | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Given a two-dimensional array of integers, remove duplicated rows and return a new array only with unique rows. The order should be maintained, and the rows should be compared by row element values. For example:
```python
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
`... | To remove duplicated rows from a two-dimensional array, we can use a set to store the unique rows. The idea is to iterate over each row in the array and check if it has already been seen before. If it has not, we add it to the set and the result array. If it has been seen before, we skip it and move on to the next row.... | Integers ka ek two-dimensional array diya gaya hai, duplicated rows ko remove karein aur sirf unique rows ke sath ek naya array return karein. Rows ki order maintain honi chahiye, aur rows ka comparison unke row element values ke mutabiq hona chahiye. Misaal ke tor par:
```python
[
[1, 2, 3, 4],
[5, 6, 7, 8],
... | Two-dimensional array se duplicated rows ko remove karne ke liye, hum unique rows ko store karne ke liye ek set use kar sakte hain. Idea yeh hai ke array ki har row par iterate karein aur check karein ke kya yeh pehle dekhi ja chuki hai. Agar yeh pehle nahi dekhi gayi, to hum ise set aur result array dono mein add kar ... |
b62ccb294f2a1d6249a2d79a | magicoder_oss | general_instruction | python | code_mixed_professional | corrected | MIT | You are given a DNA sequence represented as a string of nucleotides (A, C, G, T). Your task is to implement a function that modifies the sequence based on the following rules:
1. If the index `i` is such that `i % 3 == 2`, then the function should replace the nucleotide at index `i-2` and `i-1` with a new nucleotide `... | ```python
def modify_sequence(seq, i, nuc):
if i % 3 == 2:
modified_seq = seq[:i-2] + nuc + seq[i-1] + seq[i]
elif i % 3 == 1:
modified_seq = seq[:i-1] + nuc + seq[i] + seq[i+1]
return modified_seq
``` | Aapko nucleotides (A, C, G, T) ki string ke tor par ek DNA sequence di gayi hai. Aapka kaam ek aisa function implement karna hai jo mandarja zail rules ki buniyaad par sequence ko modify kare:
1. Agar index `i` aisa hai ke `i % 3 == 2`, to function ko index `i-2` aur `i-1` par mojood nucleotides ko ek naye nucleotide ... | ```python
def modify_sequence(seq, i, nuc):
if i % 3 == 2:
modified_seq = seq[:i-2] + nuc + seq[i-1] + seq[i]
elif i % 3 == 1:
modified_seq = seq[:i-1] + nuc + seq[i] + seq[i+1]
return modified_seq
``` |
46ce18217df94d5f95e8cf09 | codefeedback | general_instruction | python | casual_noisy | no_issue | Apache-2.0 | How would you construct a nested loop to print out the contents of a 2D array, but only print the odd numbers in reverse order, and only if they are divisible by 3? Additionally, implement the loop using a recursive function instead of a for loop.
arr=[[3,5,9,15],[21,27,32,36],[45,51,54,60]]
Please note that the abov... | To print out the contents of a 2D array, but only print the odd numbers in reverse order, and only if they are divisible by 3, you can construct a nested loop. Here's an example of how to do it using a recursive function:
```python
def print_odd_reverse(arr, row, col):
if row < 0:
return
if col < 0:
... | ek nested loop kese banao ge jo 2D array ke contents print kare, lekin sirf odd numbers reverse order mein aur wo bhi tab jab wo 3 se divide ho sakein? aur haan loop ki jagah recursive function use karna hai.
arr=[[3,5,9,15],[21,27,32,36],[45,51,54,60]]
ye baat dhyan mein rakho ke in changes se mushkil barh gayi hai ... | 2D array ke contents print karne ke liye, lekin sirf odd numbers jo 3 pe divide hon aur wo bhi ulte order mein, aap nested loop bana sakte hain. recursion use karke ye karne ka ek tareeqa ye hai:
```python
def print_odd_reverse(arr, row, col):
if row < 0:
return
if col < 0:
print_odd_reverse(a... |
9d25c9d18f754e0002475778 | acecode_87k | verified_problem | python | professional | no_issue | MIT | You are tasked with implementing a function called `calculate_property_value` that simulates a simple property management system. This function accepts a list of property details, where each property is represented as a dictionary containing 'address', 'type', and 'price'. The function should return the total value of ... | def calculate_property_value(property_list):
"""
Calculate the total value of all properties in the input list.
If the input list is empty, the function should return 0.
"""
total_value = 0
for property in property_list:
total_value += property['price']
return total_value | Aap ko `calculate_property_value` naam ka ek function implement karne ka kaam diya gaya hai jo ek simple property management system ko simulate karta hai. Yeh function property details ki ek list accept karta hai, jahan har property ko ek dictionary ke tor par represent kiya gaya hai jismein 'address', 'type', aur 'pri... | def calculate_property_value(property_list):
"""
Calculate the total value of all properties in the input list.
If the input list is empty, the function should return 0.
"""
total_value = 0
for property in property_list:
total_value += property['price']
return total_value |
3fabe2697ba03b6e14c14f80 | glaive_v3 | general_instruction | unknown | casual_noisy | no_issue | Apache-2.0 | You are tasked with implementing a CUDA kernel function that calculates the dot product of two arrays and then performs decimation. The function should be able to handle both real and complex numbers.
Your task is to create a CUDA kernel function that takes two input arrays of type T, where T can be int8_t, int16_t, i... | To solve this problem, you need to create a CUDA kernel function that takes two input arrays of type T and calculates their dot product. After calculating the dot product, the function should perform decimation by adding up all the elements except the first one and setting the rest to zero.
You can use the given code ... | tumhe aik CUDA kernel function banana he jo 2 arrays ka dot product nikale aur phir decimation kare. function real aur complex dono qisam k numbers handle kar sake.
tumhara kaam ye he k aik CUDA kernel function banao jo type T k do input arrays le, jahan T int8_t, int16_t, int32_t, int64_t, float, double, std::complex... | is masle ko solve karne k liye tumhe aik CUDA kernel function likhna hoga jo type T k do input arrays le aur unka dot product calculate kare. dot product k baad function ko decimation karni he pehle element k ilawa baqi sab elements ko jama kar k aur baki sab ko zero bana k.
tum diye gaye code snippet ko reference k t... |
e7d8b3ef17a81f8960bcde1d | acecode_87k | verified_problem | python | code_mixed_casual | no_issue | MIT | Given a list of integers, write a function that transforms the list into a string representation of an XML format. Each integer should be wrapped in a `<number>` tag. The function should return the resulting XML string. For example, given the input list [1, 2, 3], the output should be '<numbers><number>1</number><numbe... | """
XML Representation of a List of Integers
Given a list of integers, this function transforms the list into a string representation of an XML format.
Each integer is wrapped in a `<number>` tag.
Example:
- Input: [1, 2, 3]
- Output: '<numbers><number>1</number><number>2</number><number>3</number></numbers>'... | Integers ki aik list di gayi hai, aik function likhein jo is list ko XML format ki string representation mein transform kar de. Har integer aik `<number>` tag ke andar wrapped hona chahiye. Function ko resulting XML string return karni chahiye. For example, agar input list [1, 2, 3] ho, toh output '<numbers><number>1</... | """
XML Representation of a List of Integers
Given a list of integers, this function transforms the list into a string representation of an XML format.
Each integer is wrapped in a `<number>` tag.
Example:
- Input: [1, 2, 3]
- Output: '<numbers><number>1</number><number>2</number><number>3</number></numbers>'... |
fdc3a6309d695363cdab0684 | acecode_87k | verified_problem | python | professional | no_issue | MIT | Implement a function `sort_by_binary_length(arr)` that takes an array of non-negative integers and sorts it based on the length of their binary representations in ascending order. If two integers have the same binary length, they should be sorted by their decimal value in ascending order. The function should return the... | def sort_by_binary_length(arr):
"""
Sorts an array of non-negative integers based on the length of their binary representations in ascending order.
If two integers have the same binary length, they should be sorted by their decimal value in ascending order.
The function should return the sorted array.... | Aik function `sort_by_binary_length(arr)` implement karein jo non-negative integers ki aik array leta hai aur usay unki binary representations ki length ki bunyaad par ascending order mein sort karta hai. Agar do integers ki binary length barabar ho, to unhein unki decimal value ke mutabiq ascending order mein sort kiy... | def sort_by_binary_length(arr):
"""
Sorts an array of non-negative integers based on the length of their binary representations in ascending order.
If two integers have the same binary length, they should be sorted by their decimal value in ascending order.
The function should return the sorted array.... |
af339eaeeb03ee8dab3e195b | commitpackft | code_modification | yaml | code_mixed_casual | corrected | MIT | Create the following file according to the change request.
Change request:
Update from Forestry.io - Updated Forestry configuration
File: .forestry/front_matter/templates/webinar-template.yml | ---
label: Webinar Template
hide_body: false
fields:
- type: text
name: layout
label: layout
- type: text
name: title
label: title
- type: file
name: img-url
label: img-url
- type: datetime
name: date
label: date
- type: boolean
name: enable-header
label: enable-header
- type: text
name: event-typ... | Change request ke mutabiq following file create karein.
Change request:
Forestry.io se update - Updated Forestry configuration
File: .forestry/front_matter/templates/webinar-template.yml | ---
label: Webinar Template
hide_body: false
fields:
- type: text
name: layout
label: layout
- type: text
name: title
label: title
- type: file
name: img-url
label: img-url
- type: datetime
name: date
label: date
- type: boolean
name: enable-header
label: enable-header
- type: text
name: event-typ... |
3dd4ec1d03dffd8c55be3163 | magicoder_evol | general_instruction | javascript | code_mixed_professional | corrected | Apache-2.0 | Create a basic React application for a search engine. The application should include a search bar and a button. Whenever the button is clicked, the search bar should perform a search with the entered query. | Sure, here's a basic example of a React application implementing a search bar. No real search functionality is implemented, but you get the idea.
```jsx
import React from 'react';
class SearchEngine extends React.Component {
constructor(props) {
super(props);
this.state = { query: '' };
this.search = ... | Aik basic React application banayein jo aik search engine ka kaam kare. Is application mein aik search bar aur aik button hona chahiye. Jab bhi button par click kiya jaye, toh search bar ko entered query ke mutabiq search perform karni chahiye. | Bilkul, yeh React application ka aik basic example hai jo search bar implement karta hai. Is mein koi real search functionality implement nahi ki gayi, lekin aapko is ka concept samajh aa jayega.
```jsx
import React from 'react';
class SearchEngine extends React.Component {
constructor(props) {
super(props);
... |
f76b783889550154b445b64a | acecode_87k | verified_problem | python | professional | no_issue | MIT | Given a non-negative integer n, implement a function that calculates the factorial of n, denoted as n!. The factorial is the product of all positive integers less than or equal to n. For instance, 5! = 5 × 4 × 3 × 2 × 1 = 120. Your implementation should raise a ValueError if a negative integer is provided as input. Def... | def factorial(n):
"""
Calculates the factorial of n, denoted as n!.
Raises a ValueError if a negative integer is provided as input.
"""
if n < 0:
raise ValueError("Negative input not allowed")
result = 1
for i in range(1, n+1):
result *= i
return result | Aik non-negative integer n diya gaya hai, aik aisa function implement karen jo n ka factorial calculate kare, jisay n! se zahir kiya jata hai. Factorial n ya us se chotay tamam positive integers ka product hota hai. Maslan, 5! = 5 x 4 x 3 x 2 x 1 = 120. Agar input mein negative integer diya jaye to aap ki implementatio... | def factorial(n):
"""
Calculates the factorial of n, denoted as n!.
Raises a ValueError if a negative integer is provided as input.
"""
if n < 0:
raise ValueError("Negative input not allowed")
result = 1
for i in range(1, n+1):
result *= i
return result |
d0c9298301d8bc01afc8032d | codefeedback | general_instruction | java | casual_noisy | corrected | Apache-2.0 | Implement a custom stack class in Java including common methods such as push, pop, peek, and isEmpty. Additionally, provide an implementation for a method that returns the minimum element in the stack in constant time. Make sure your stack implementation is generic and thread-safe, and optimizes memory usage as much as... | Here is a simple yet effective Java implementation that creates a custom thread-safe stack. It includes methods such as push, pop, peek, isEmpty, and getMin to obtain the minimum element. This stack implementation is generic and uses a separate minStack for constant time retrieval of minimum element. It uses synchronis... | Java me ek custom stack class bnao jis m push, pop, peek, aur isEmpty jese common methods hon. Sath hi ek aisa method b dalna jo constant time me stack ka min element return kre. Stack ko generic aur thread-safe rkhna, aur jitna ho ske memory b chaho k optimize ho. | Ye lo ek simple pr fit kism ki Java implementation jo custom thread-safe stack bnati h. Isme push, pop, peek, isEmpty, aur getMin jese methods hn taake minimum element mil ske. Ye stack generic h aur min element ko constant time me nikalne k liye alag minStack use krti h. Thread-safety k liye synchronized block aur beh... |
d45a25dcb1ef1ac30b99405f | acecode_87k | verified_problem | python | code_mixed_casual | no_issue | MIT | You are tasked with simulating a login response for a fictitious platform. Write a function `simulate_login_response(username: str, password: str, sid: str) -> Tuple[int, Optional[str], Optional[str], str, Optional[str], Optional[int]]` that takes a username, password, and session id as input and returns a tuple contai... | #!/usr/bin/env python3
from typing import Tuple, Optional
def simulate_login_response(username: str, password: str, sid: str) -> Tuple[int, Optional[str], Optional[str], str, Optional[str], Optional[int]]:
"""
Simulates a login response for a fictitious platform.
Takes a username, password, and session id ... | Aap ko aik fictitious platform ke liye login response simulate karne ka task mila hai. Aik function `simulate_login_response(username: str, password: str, sid: str) -> Tuple[int, Optional[str], Optional[str], str, Optional[str], Optional[int]]` likhein jo username, password, aur session id as input leta ho aur aik tupl... | #!/usr/bin/env python3
from typing import Tuple, Optional
def simulate_login_response(username: str, password: str, sid: str) -> Tuple[int, Optional[str], Optional[str], str, Optional[str], Optional[int]]:
"""
Simulates a login response for a fictitious platform.
Takes a username, password, and session id ... |
0cee80294eb26dfb67cc812a | commitpackft | code_modification | html | code_mixed_casual | no_issue | bsd-3-clause | Apply the following change to the existing file.
Change request:
Fix 'Create Badge' markdown closing-bracket typos
The 'Create Badge' function was introduced with
https://github.com/scalacenter/scaladex/pull/670, but unfortunately a
small typo was introduced with https://github.com/scalacenter/scaladex/pull/705,
remo... | @import scaladex.core.model.Artifact
@import scaladex.core.model.Env
@(artifact: Artifact, env: Env)
<div class="box badge-showcase">
<h4>Markdown Badge</h4>
<div style="overflow: hidden">
<a href="#badge-markdown">
<img src="@artifact.badgeUrl(env)" />
</a>
</div>
<div id="badge-markdown" class="overl... | Existing file mein yeh change apply karein.
Change request:
'Create Badge' markdown closing-bracket typos fix karein
'Create Badge' function https://github.com/scalacenter/scaladex/pull/670, ke sath introduce hua tha lekin unfortunately https://github.com/scalacenter/scaladex/pull/705, ke sath ek chhota sa typo intro... | @import scaladex.core.model.Artifact
@import scaladex.core.model.Env
@(artifact: Artifact, env: Env)
<div class="box badge-showcase">
<h4>Markdown Badge</h4>
<div style="overflow: hidden">
<a href="#badge-markdown">
<img src="@artifact.badgeUrl(env)" />
</a>
</div>
<div id="badge-markdown" class="overl... |
1ca74a99ed0c74c1f5b6d8c8 | glaive_v3 | general_instruction | java | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating a Spring ApplicationContext that will be used to manage and configure the beans in a Java application. You need to write a class that will configure the ApplicationContext and then retrieve a specific bean from it.
Write a class called "ApplicationContextConfig" with a method called "crea... | ```java
package org.example.springframework.contextaware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@... | tumhe aik Spring ApplicationContext bnana he jo Java app k beans manage aur configure krne k kaam aye ga. Tum ne aik aisi class likhni h jo ApplicationContext configure kre aur phr us me se ek specific bean nikal k laye.
"ApplicationContextConfig" k naam se class bnao js me "createApplicationContext" method ho jo Appl... | ```java
package org.example.springframework.contextaware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@... |
e526ae1e90a02dcb06cae00b | acecode_87k | verified_problem | python | code_mixed_casual | no_issue | MIT | Given a configuration dictionary that represents repositories, write a function `get_repo_paths` that takes a dictionary as input and returns a list of repository paths. The input dictionary has the following structure: it contains a key 'repos' which maps to another dictionary. Each key in this inner dictionary repres... | def get_repo_paths(config: dict) -> list:
"""
Given a configuration dictionary that represents repositories, write a function `get_repo_paths` that takes a dictionary as input and returns a list of repository paths. The input dictionary has the following structure: it contains a key 'repos' which maps to anothe... | Aik configuration dictionary di gayi hai jo repositories ko represent karti hai. Aik function `get_repo_paths` likhen jo input mein dictionary le aur repository paths ki list return kare. Input dictionary ka structure kuch aisa hai: is mein aik key 'repos' hai jo aik aur dictionary se map hoti hai. Is inner dictionary ... | def get_repo_paths(config: dict) -> list:
"""
Given a configuration dictionary that represents repositories, write a function `get_repo_paths` that takes a dictionary as input and returns a list of repository paths. The input dictionary has the following structure: it contains a key 'repos' which maps to anothe... |
f6b9a7e7be79e2da72da58f7 | magicoder_oss | general_instruction | python | code_mixed_professional | no_issue | MIT | You are tasked with creating a program that processes student grades and calculates the average grade for a given set of students. The program should prompt the user to input the grades for each student and then calculate and display the average grade for the entire class.
The program should follow these specification... | ```python
def calculate_average_grade():
num_students = int(input("Enter the number of students: "))
total_grade = 0
for i in range(num_students):
grade = float(input(f"Enter the grade for student {i+1}: "))
total_grade += grade
average_grade = total_grade / num_students
print(f"Th... | Aap ko aik aisa program banane ka task diya gaya hai jo student grades ko process kare aur diye gaye students ke group ke liye average grade calculate kare. Program ko user se har student ke grades input karne ka prompt dena chahiye aur phir poori class ke liye average grade calculate aur display karna chahiye.
Progra... | ```python
def calculate_average_grade():
num_students = int(input("Enter the number of students: "))
total_grade = 0
for i in range(num_students):
grade = float(input(f"Enter the grade for student {i+1}: "))
total_grade += grade
average_grade = total_grade / num_students
print(f"Th... |
62b23f3ca477a2aa980d40c7 | magicoder_oss | general_instruction | swift | code_mixed_professional | no_issue | MIT | You are tasked with creating a search functionality for a mobile app using SwiftUI. The app should allow users to input a search query and display search results based on that query. You need to implement the search functionality using the provided code snippet as a starting point.
Given the provided code snippet:
```... | ```swift
import SwiftUI
struct SearchView: View {
@State var searchText = ""
@State var isSearching = false
@State var searchResults: [String] = []
private func performSearch() {
// Simulate an asynchronous search operation
isSearching = true
DispatchQueue.main.asyncAfter(deadl... | Aap ko SwiftUI ka istemal karte hue ek mobile app ke liye search functionality create karne ka task diya gaya hai. App ko users ko search query input karne ki ijazat deni chahiye aur us query ki bunyad par search results display karne chahiye. Aap ko provide kiye gaye code snippet ko starting point ke tor par use karte... | ```swift
import SwiftUI
struct SearchView: View {
@State var searchText = ""
@State var isSearching = false
@State var searchResults: [String] = []
private func performSearch() {
// Simulate an asynchronous search operation
isSearching = true
DispatchQueue.main.asyncAfter(deadl... |
cea64c3238fc7f551e0443c4 | acecode_87k | verified_problem | python | professional | no_issue | MIT | Implement a function `valid_pin(pin: str) -> bool` that verifies the validity of a customer's confidential pin. The pin is considered valid if it satisfies the following conditions: it must have an uneven number of digits, consist of at least two distinct non-consecutive digits, and must not contain any recognized nume... | def valid_pin(pin: str) -> bool:
"""
Implements a function that verifies the validity of a customer's confidential pin.
"""
# Check if pin has an uneven number of digits
if len(pin) % 2 == 0:
return False
# Check if pin has at least two distinct non-consecutive digits
if len(set(pin... | Aik function `valid_pin(pin: str) -> bool` implement karein jo kisi customer ke confidential pin ki validity check kare. Pin us waqt valid mana jaye ga agar yeh conditions poori hon: is mein digits ki tadad uneven (odd) honi chahiye, is mein kam az kam do mukhtalif non-consecutive digits hone chahiye, aur is mein koi b... | def valid_pin(pin: str) -> bool:
"""
Implements a function that verifies the validity of a customer's confidential pin.
"""
# Check if pin has an uneven number of digits
if len(pin) % 2 == 0:
return False
# Check if pin has at least two distinct non-consecutive digits
if len(set(pin... |
195dd47d2fb85be8625f125a | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Enhance the original code by inserting more conditions and demand a multi-layered solution:
Complete the provided code to compute and return the modular inverse of a and p. However, if a and p are both squares of a prime number, you should return None.
def modInv(a: int, p: int):
"""
Compute the modular inver... | Here is the python solution:
```python
import math
def is_square(n):
return n == math.isqrt(n) ** 2
def is_prime(n):
if n <= 1 or (n % 2 == 0 and n > 2):
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def is_square_of_prime(n):
root = math.isqrt(n)
return is_... | Mazeed conditions shamil kar ke original code ko behtar banayein aur aik multi-layered solution provide karein:
a aur p ka modular inverse compute aur return karne ke liye faraham kardah code ko mukammal karein. Taham, agar a aur p dono kisi prime number ke squares hon, toh aapko None return karna chahiye.
def modInv... | Python solution yeh hai:
```python
import math
def is_square(n):
return n == math.isqrt(n) ** 2
def is_prime(n):
if n <= 1 or (n % 2 == 0 and n > 2):
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def is_square_of_prime(n):
root = math.isqrt(n)
return is_squa... |
880399de3e638cc2a2b6676b | commitpackft | code_modification | ruby | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
Test :command for exec in rbenv::rehash.
File: spec/defines/rbenv__rehash_spec.rb
Existing code:
```ruby
require 'spec_helper'
describe 'rbenv::rehash' do
let(:facts) {{
:osfamily => 'Debian',
}}
context 'Version 1.2.3-p456' do
let(:tit... | require 'spec_helper'
describe 'rbenv::rehash' do
let(:facts) {{
:osfamily => 'Debian',
}}
context 'Version 1.2.3-p456' do
let(:title) { '1.2.3-p456' }
it {
should contain_exec('rbenv rehash for 1.2.3-p456').with(
:command => '/usr/bin/rbenv rehash',
:environment => [
... | Mawjooda file mein yeh change apply karein.
Change request:
rbenv::rehash mein exec ke liye :command ko test karein.
File: spec/defines/rbenv__rehash_spec.rb
Mawjooda code:
```ruby
require 'spec_helper'
describe 'rbenv::rehash' do
let(:facts) {{
:osfamily => 'Debian',
}}
context 'Version 1.2.3-p456' do
... | require 'spec_helper'
describe 'rbenv::rehash' do
let(:facts) {{
:osfamily => 'Debian',
}}
context 'Version 1.2.3-p456' do
let(:title) { '1.2.3-p456' }
it {
should contain_exec('rbenv rehash for 1.2.3-p456').with(
:command => '/usr/bin/rbenv rehash',
:environment => [
... |
53a9b8a5be28535802dcf910 | acecode_87k | verified_problem | python | code_mixed_casual | no_issue | MIT | You are tasked with calculating the financial difference between total debits and total credits for a financial account. Write a function `calculate_financial_difference(debits: List[float], credits: List[float]) -> float` that takes in two lists of floats: `debits` and `credits`. The function should return the differe... | def calculate_financial_difference(debits, credits):
return sum(debits) - sum(credits) | Yaar, tumne aik financial account ke total debits aur total credits ke darmiyan difference calculate karna hai. Aik function `calculate_financial_difference(debits: List[float], credits: List[float]) -> float` likho jo floats ki do lists, `debits` aur `credits`, input le. Function ko debits ke total sum aur credits ke ... | def calculate_financial_difference(debits, credits):
return sum(debits) - sum(credits) |
0055dda3c458c68a97b44670 | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Design two Python functions. The first function should accept a list of dictionaries and returns a list of dictionaries with distinct values based on a provided key. The second function should accept a list of dictionaries, a specific key, and a value. It should return a new list of dictionaries from the input list tha... | The first function has a logical error in the `if` statements. It appends item to the `return_data` when the item's key is not in `unique_values`. But it doesn't add the item's key to `unique_values` which it should do. It currently does that in the `else` case which will almost never execute as each item is a new entr... | Do Python functions design karen. Pehla function dictionaries ki ek list accept kare aur provided key ki bunyad par distinct values wali dictionaries ki list return kare. Doosra function dictionaries ki ek list, ek specific key, aur ek value accept kare. Yeh input list mein se dictionaries ki ek nayi list return kare j... | Pehle function ke `if` statements mein ek logical error hai. Jab item ki key `unique_values` mein nahi hoti, toh yeh item ko `return_data` mein append kar deta hai. Lekin yeh item ki key ko `unique_values` mein add nahi karta jo ke ise karna chahiye. Yeh filhal yeh kaam `else` case mein kar raha hai jo takriban kabhi e... |
241418ca2e6a09f6de3d28d5 | acecode_87k | verified_problem | python | professional | no_issue | MIT | You are tasked with implementing a simplified web crawler that adheres to the rules specified in a robots.txt file. The robots.txt file specifies which URLs can be accessed by web crawlers. Your task is to implement a function `process_url(url: str, current_url: str, current_depth: int, visited_urls: dict, site_graph: ... | from collections import defaultdict
class MockRobots:
def can_fetch(self, url: str) -> bool:
# Implement the logic to check if the URL can be fetched according to the robots.txt rules
# For this example, we'll return True for simplicity
return True
def process_url(url: str, current_url: st... | Aap ko ek simplified web crawler implement karne ka kaam diya gaya hai jo robots.txt file mein di gayi rules par amal karta hai. Robots.txt file yeh specify karti hai ke web crawlers konsi URLs ko access kar sakte hain. Aap ka kaam ek function `process_url(url: str, current_url: str, current_depth: int, visited_urls: d... | from collections import defaultdict
class MockRobots:
def can_fetch(self, url: str) -> bool:
# Implement the logic to check if the URL can be fetched according to the robots.txt rules
# For this example, we'll return True for simplicity
return True
def process_url(url: str, current_url: st... |
e0affbad7b3d698f75943493 | magicoder_oss | general_instruction | swift | code_mixed_professional | no_issue | MIT | You are tasked with implementing a class that manages the highlighting of a UIView. The class, named `HighlightManager`, should provide functionality to enable and disable the highlighting of the view with specified colors and animation options.
The `HighlightManager` class should have the following properties and met... | ```swift
class HighlightManager {
var normalColor: UIColor?
var highlightedColor: UIColor?
var highlightedOptions: UIView.AnimationOptions?
var highlightedDelay: TimeInterval = 0
var highlightedDuration: TimeInterval = 0
var animatorFluid: UIViewPropertyAnimator?
func enable() {
gua... | Aap ko ek aisi class implement karni hai jo UIView ki highlighting ko manage kare. Is class ka naam `HighlightManager` hona chahiye aur is mein specified colors aur animation options ke saath view ki highlighting ko enable aur disable karne ki functionality honi chahiye.
`HighlightManager` class mein darj-zail propert... | ```swift
class HighlightManager {
var normalColor: UIColor?
var highlightedColor: UIColor?
var highlightedOptions: UIView.AnimationOptions?
var highlightedDelay: TimeInterval = 0
var highlightedDuration: TimeInterval = 0
var animatorFluid: UIViewPropertyAnimator?
func enable() {
gua... |
28fb4414be53cd88dd77e4bf | commitpackft | code_modification | python | code_mixed_casual | no_issue | Apache-2.0 | Apply the following change to the existing file.
Change request:
Add more tests for pool
File: tests/test_pool.py
Existing code:
```python
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(... | import asyncio
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool
from aioes.transport import Endpoint
from aioes.connection import Connection
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
... | Existing file mein ye change apply karein.
Change request:
Pool ke liye mazeed tests add karein
File: tests/test_pool.py
Existing code:
```python
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector
class TestRandomSelector(unittest.TestCase):
def setUp(self):
rando... | import asyncio
import random
import unittest
from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool
from aioes.transport import Endpoint
from aioes.connection import Connection
class TestRandomSelector(unittest.TestCase):
def setUp(self):
random.seed(123456)
def tearDown(self):
... |
0c34e949baecc3eed0652532 | glaive_v3 | general_instruction | xml | casual_noisy | corrected | Apache-2.0 | You are tasked with creating an XSLT stylesheet to present all sharing options available for a website. The stylesheet should include a component called "nav-share" that displays the sharing options. The component should have the following parameters:
- title: Title of the component
- label-share: Used for the native s... | ```xml
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:template name="nav-share">
<xsl:param name="title" select="'Share Options'" />
<xsl:param name="label-share" select="'Share'" />
<xsl:param name="... | O yar ek XSLT stylesheet banani hai jo website k saray sharing options dikhaye. Is stylesheet mein aik "nav-share" wala component hona chahye jo ye sharing options dikhaye ga. Component mein ye parameters honay zaroori hain:
- title: Component ka title
- label-share: Native share button k liye use hoga
- url: Jo url sh... | ```xml
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:template name="nav-share">
<xsl:param name="title" select="'Share Options'" />
<xsl:param name="label-share" select="'Share'" />
<xsl:param name="... |
257ba250be02c0b34391f520 | glaive_v3 | general_instruction | unknown | casual_noisy | no_issue | Apache-2.0 | Is there an alternative for the C# DateTime class in C++ that has an underlying calendar and supports incrementing hours, days, or weeks? It should also support comparison of dates. | In C++, there is no built-in date/time class in the standard library like the DateTime class in C#. However, you can make use of the Boost library to achieve similar functionality.
Boost provides a powerful Date and Time library that can meet your requirements. You can find the library documentation at [http://www.boo... | c# k DateTime class ka koi alternative c++ mein hai jiss mein underlying calendar ho aur hours days ya weeks increment ho sakain? dates ko compare karna bhi support kare. | c++ mein standard library k andar C# k DateTime class jaisa koi built-in date/time class tou nahi hai. lekin aap Boost library use kar saktay ho same functionality k liye.
Boost aik zabardast Date aur Time library deta hai jo aapki requirements poori kar sakti hai. library ki documentation yahan milegi [http://www.boo... |
3da7f16800f0f138675e41d9 | glaive_v3 | general_instruction | elm | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating a module in Elm for controlling a Mars rover. The module should include the following functionality:
- Initialize a rover with a starting position and direction (N, S, E, W)
- Move the rover forward in the direction it is facing
- Turn the rover 90 degrees to the left
- Turn the rover 90 de... | ```elm
module Rover exposing (..)
type Direction = N | E | S | W
type alias Position = { x : Int, y : Int }
type alias Rover = { position : Position, direction : Direction }
moveForward : Rover -> Rover
moveForward rover =
case rover.direction of
N -> { rover | position = { rover.position | y = rover.posi... | Tumhe Elm me aik module bnana hai jo Mars rover ko control kare. Module me ye sb functionality honi chahye:
- Rover ko starting position or direction (N, S, E, W) k sath initialize krna
- Rover ko samne ki taraf chalana jis direction me uska face ho
- Rover ko 90 degree left ghumana
- Rover ko 90 degree right ghumana
-... | ```elm
module Rover exposing (..)
type Direction = N | E | S | W
type alias Position = { x : Int, y : Int }
type alias Rover = { position : Position, direction : Direction }
moveForward : Rover -> Rover
moveForward rover =
case rover.direction of
N -> { rover | position = { rover.position | y = rover.posi... |
98e9c0302e14fe024da4e302 | codefeedback | general_instruction | python | casual_noisy | no_issue | Apache-2.0 | I have this problem : Partition Labels with Constraints
Description are as below: A string `S` of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. Howev... | This problem, given as "Partition Labels with Constraints", requires you to understand two main points:
1. You need to partition the string `S` in such a way that every letter appears at most once in the partitioned string (in a partition).
2. The sum of the ASCII values of the first character in all partitions nee... | mere pas ye problem h : Partition Labels with Constraints
Description ye rhi: lowercase English letters ki ek string `S` di gayi hai. hume is string ko ziada se ziada hisso me partition krna hai ta k hr letter ziada se ziada ek hi part me aye, aur in parts k sizes ki integers wali list return krni h. lekin partitioning... | is problem me jo k "Partition Labels with Constraints" h, apko 2 main points smjhne ki zrurat h:
1. Apko string `S` ko is trah partition krna h k hr letter partitioned string me ziada se ziada ek baar aye (ek partition me).
2. tamam partitions k pehle character ki ASCII values ka sum maximum possible hona chahye.
ch... |
a22e002db2b3213837f3756b | codefeedback | general_instruction | python | professional | no_issue | Apache-2.0 | You are tasked with implementing a function to build a catalog of images for a machine learning project. The function should take a directory path as input and return the catalog path, label paths, and image paths.
The function signature is as follows:
```python
def build_catalog(directory_path: str, nb_labels: int) -... | ```python
import os
from typing import List, Tuple
def build_catalog(directory_path: str, nb_labels: int) -> Tuple[str, List[str], List[str]:
catalog_path = 'catalog/'
label_paths = []
img_paths = []
# Create the catalog directory if it doesn't exist
if not os.path.exists(catalog_path):
os... | Aap ko machine learning project ke liye images ka ek catalog banane ke liye ek function implement karne ka kaam diya gaya hai. Function ko input ke tor par ek directory path lena chahiye aur catalog path, label paths, aur image paths return karne chahiyein.
Function ka signature darj zail hai:
```python
def build_cata... | ```python
import os
from typing import List, Tuple
def build_catalog(directory_path: str, nb_labels: int) -> Tuple[str, List[str], List[str]:
catalog_path = 'catalog/'
label_paths = []
img_paths = []
# Create the catalog directory if it doesn't exist
if not os.path.exists(catalog_path):
os... |
0978209289fb392795d7e248 | codefeedback | general_instruction | cpp | professional | no_issue | Apache-2.0 | do you mind rewriting this for c++?
def is_happy_complex(s):
if len(s) < 3:
return False
count = {}
for c in s:
if c in count:
count[c] += 1
else:
count[c] = 1
for key in count:
if count[key] < 2 or (s.find(key*2) != -1):
... | Sure, here is the equivalent code written in C++:
```cpp
#include<iostream>
#include<unordered_map>
#include<unordered_set>
#include<string>
bool is_happy_complex(std::string s) {
if (s.length() < 3)
return false;
std::unordered_map<char,int> count;
for (char c: s) {
if(count.find(c) == c... | kya aap meharbani karke isse c++ ke liye dobara likh sakte hain?
def is_happy_complex(s):
if len(s) < 3:
return False
count = {}
for c in s:
if c in count:
count[c] += 1
else:
count[c] = 1
for key in count:
if count[key] < 2 or (s.fin... | Ji bilkul, yeh raha C++ mein iske barabar ka code:
```cpp
#include<iostream>
#include<unordered_map>
#include<unordered_set>
#include<string>
bool is_happy_complex(std::string s) {
if (s.length() < 3)
return false;
std::unordered_map<char,int> count;
for (char c: s) {
if(count.find(c) == ... |
d1c23d67c5600936f7281816 | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Find the number of times a particular number is repeated in a two-dimensional array. Arrays may not be of equal length. Example: [[2, 3, 6, 8], [8, 5, 4, 8]] | Here is a Python function using list comprehension to find the occurrence of a particular number in a two-dimensional array:
```python
def count_occurrences(two_d_array, target):
return sum(row.count(target) for row in two_d_array)
# Test the function
array = [[2, 3, 6, 8], [8, 5, 4, 8]]
number = 8
print(count_o... | Aik two-dimensional array mein kisi khaas number ki repetition ki tadaad maloom karein. Arrays ki length mukhtalif ho sakti hai. Misaal: [[2, 3, 6, 8], [8, 5, 4, 8]] | Yeh raha aik Python function jo list comprehension ka istemaal karte hue two-dimensional array mein kisi khaas number ki occurrence maloom karta hai:
```python
def count_occurrences(two_d_array, target):
return sum(row.count(target) for row in two_d_array)
# Test the function
array = [[2, 3, 6, 8], [8, 5, 4, 8]]
... |
74f8d2d2518e114efa11b9c7 | commitpackft | code_modification | yaml | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
Test with the latest jruby
File: .travis.yml
Existing code:
```yaml
language: ruby
cache: bundler
rvm:
- 2.4.0
- 2.3.0
- 2.2.0
- 2.1.0
- jruby-9.0.4.0
env:
- DB=postgres
- DB=mysql
gemfile:
- gemfiles/Gemfile.rails-4.0.rb
- gemfile... | language: ruby
cache: bundler
rvm:
- 2.4.0
- 2.3.0
- 2.2.0
- 2.1.0
- jruby-9.1.13.0
env:
- DB=postgres
- DB=mysql
gemfile:
- gemfiles/Gemfile.rails-4.0.rb
- gemfiles/Gemfile.rails-4.1.rb
- gemfiles/Gemfile.rails-4.2.rb
- gemfiles/Gemfile.rails-5.0.rb
before_install:
- gem update bundler
mat... | Mawjooda file mein yeh change apply karein.
Change request:
Latest jruby ke sath test karein
File: .travis.yml
Mawjooda code:
```yaml
language: ruby
cache: bundler
rvm:
- 2.4.0
- 2.3.0
- 2.2.0
- 2.1.0
- jruby-9.0.4.0
env:
- DB=postgres
- DB=mysql
gemfile:
- gemfiles/Gemfile.rails-4.0.rb
- gemfil... | language: ruby
cache: bundler
rvm:
- 2.4.0
- 2.3.0
- 2.2.0
- 2.1.0
- jruby-9.1.13.0
env:
- DB=postgres
- DB=mysql
gemfile:
- gemfiles/Gemfile.rails-4.0.rb
- gemfiles/Gemfile.rails-4.1.rb
- gemfiles/Gemfile.rails-4.2.rb
- gemfiles/Gemfile.rails-5.0.rb
before_install:
- gem update bundler
mat... |
bfb60d42486705c25fbf6764 | magicoder_oss | general_instruction | typescript | code_mixed_professional | no_issue | MIT | You are tasked with designing a system for managing user acquisitions in an e-commerce platform. The system should handle the process of users making purchases, payments, and the methods used for payment. The code snippet provided is the beginning of a function to create an "AcquisitionController" that will orchestrate... | ```typescript
import PaymentDAOImp from '../../DAOImp/payment/PaymentDAOImp';
import PayWithDAOImp from '../../DAOImp/payWith/PayWithDAOImp';
import PurchaseDAOImp from '../../DAOImp/purchase/PurchaseDAOImp';
import { makeUserDAO } from '../users/UserFacotory';
class AcquisitionController {
private paymentDAO: Payme... | Aap ko ek e-commerce platform mein user acquisitions ko manage karne ke liye ek system design karne ka kaam diya gaya hai. System ko users ke purchases karne, payments, aur payment ke liye istemal hone wale methods ke process ko handle karna chahiye. Diya gaya code snippet ek "AcquisitionController" banane ke function ... | ```typescript
import PaymentDAOImp from '../../DAOImp/payment/PaymentDAOImp';
import PayWithDAOImp from '../../DAOImp/payWith/PayWithDAOImp';
import PurchaseDAOImp from '../../DAOImp/purchase/PurchaseDAOImp';
import { makeUserDAO } from '../users/UserFacotory';
class AcquisitionController {
private paymentDAO: Payme... |
9a23b370247e0dffdffb9541 | commitpackft | code_modification | cucumber | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
Fix cucumber sign up feature
File: features/sign_up.feature
Existing code:
```cucumber
Feature: Sign up
In order to get access to personal part of the site
A user
Should be able to sign up
Background:
Given we have branch "Sisyphus"
Sce... | Feature: Sign up
In order to get access to personal part of the site
A user
Should be able to sign up
Background:
Given we have branch "Sisyphus"
Scenario: User sign up
When I go to the sign up page
And I fill in "Email" with "email@example.com"
And I fill in "user_password" with "password"
... | Mojooda file mein ye tabdeeli apply karein.
Change request:
Cucumber sign up feature fix karein
File: features/sign_up.feature
Existing code:
```cucumber
Feature: Sign up
In order to get access to personal part of the site
A user
Should be able to sign up
Background:
Given we have branch "Sisyphus"
S... | Feature: Sign up
In order to get access to personal part of the site
A user
Should be able to sign up
Background:
Given we have branch "Sisyphus"
Scenario: User sign up
When I go to the sign up page
And I fill in "Email" with "email@example.com"
And I fill in "user_password" with "password"
... |
b7e3c8ebd8a88c10fdc07d8e | commitpackft | code_modification | yaml | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
Use the latest rubies on Travis
File: .travis.yml
Existing code:
```yaml
language: ruby
before_install:
- gem install bundler
gemfile:
- Gemfile
rvm:
- 2.1
- 2.2
- 2.3.0
- ruby-head
script:
- bundle exec rspec spec
``` | language: ruby
before_install:
- gem install bundler
gemfile:
- Gemfile
rvm:
- 2.1.10
- 2.2.5
- 2.3.1
- ruby-head
script:
- bundle exec rspec spec | Existing file me ye change apply karo.
Change request:
Travis par latest rubies use karo
File: .travis.yml
Existing code:
```yaml
language: ruby
before_install:
- gem install bundler
gemfile:
- Gemfile
rvm:
- 2.1
- 2.2
- 2.3.0
- ruby-head
script:
- bundle exec rspec spec
``` | language: ruby
before_install:
- gem install bundler
gemfile:
- Gemfile
rvm:
- 2.1.10
- 2.2.5
- 2.3.1
- ruby-head
script:
- bundle exec rspec spec |
db614fd0559acb120831ee33 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function `filter_list_by_bool_mask` that takes two input arguments: a list of integers `input_list` and a corresponding boolean mask of the same length `bool_mask`. The function should output a new list containing only the elements of `input_list` for which the corresponding boolean mask element is True.... | Here's how you could implement this function in Python:
```python
def filter_list_by_bool_mask(input_list, bool_mask):
output_list = []
for i, element in enumerate(input_list):
if bool_mask[i]:
output_list.append(element)
return output_list
```
The function iterates through `input_list... | Aik Python function `filter_list_by_bool_mask` likhein jo do input arguments leta ho: integers ki aik list `input_list` aur usi length ka aik corresponding boolean mask `bool_mask`. Function ko aik nayi list output karni chahiye jis mein `input_list` ke sirf wahi elements hon jin ke liye corresponding boolean mask ka e... | Yahan bataya gaya hai ke aap Python mein yeh function kis tarah implement kar sakte hain:
```python
def filter_list_by_bool_mask(input_list, bool_mask):
output_list = []
for i, element in enumerate(input_list):
if bool_mask[i]:
output_list.append(element)
return output_list
```
Yeh fun... |
97f559f7b4f7a56868a3b310 | glaive_v3 | general_instruction | c | casual_noisy | corrected | Apache-2.0 | You are tasked with implementing a CUDA program that performs vector addition using multiple streams. The program should allocate memory on both the host and the device, copy data from the host to the device using asynchronous memory copies, launch a kernel for each stream, and then copy the results back from the devic... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
const int N = 1 << 20;
#define FLTSIZE sizeof(float)
inline int BLK(int data, int blocksize)
{
return (data + blocksize - 1) / blocksize;
}
__global__ void kernel_vectorAdd (const float* __restrict_... | tujhe aik cuda prog bnana ha jo multiple streams use kr k vector adddition kre. prog ko host aur devuce dono pe memory allocate krni pare gi, host se devuce tak async mem copies use kr k data copy krna, har stream k lye alag kernel chalana, phr device se wapis host pe result lany hain. is k sath sath prog kernel ka run... | ```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
const int N = 1 << 20;
#define FLTSIZE sizeof(float)
inline int BLK(int data, int blocksize)
{
return (data + blocksize - 1) / blocksize;
}
__global__ void kernel_vectorAdd (const float* __restrict_... |
3993d27fd687d9550b7b899d | acecode_87k | verified_problem | python | professional | no_issue | MIT | Implement a function to find the longest common substring between two given strings. The function should support alphanumeric characters and special characters and must be case-sensitive. The input strings may contain up to 10^6 characters. Write a function named 'longest_common_substring' that takes two strings as par... | def longest_common_substring(str1, str2):
if len(str1) == 0 or len(str2) == 0:
return ''
longest = ''
for i in range(len(str1)):
for j in range(len(str2)):
if str1[i] == str2[j]:
x = i
y = j
while x < len(str1) and y < len(str2) and... | Do doye gaye strings ke darmiyan sab se lamba common substring (longest common substring) maloom karne ke liye ek function implement karein. Function ko alphanumeric characters aur special characters ko support karna chahiye aur yeh case-sensitive hona chahiye. Input strings mein 10^6 characters tak ho sakte hain. 'lon... | def longest_common_substring(str1, str2):
if len(str1) == 0 or len(str2) == 0:
return ''
longest = ''
for i in range(len(str1)):
for j in range(len(str2)):
if str1[i] == str2[j]:
x = i
y = j
while x < len(str1) and y < len(str2) and... |
a26e058c10d15f181fee4af6 | acecode_87k | verified_problem | python | professional | no_issue | MIT | Design a function that segregates prime numbers, composite numbers, and perfect numbers from a given list of integers. The function should return a tuple containing three lists: the first list of prime numbers, the second list of composite numbers, and the third list of perfect numbers. | def segregate_num(my_list):
"""
Design a function that segregates prime numbers, composite numbers, and perfect numbers from a given list of integers. The function should return a tuple containing three lists: the first list of prime numbers, the second list of composite numbers, and the third list of perfect n... | Ek aisa function design karein jo diye gaye integers ki list mein se prime numbers, composite numbers, aur perfect numbers ko alag alag kare. Function ko ek tuple return karna chahiye jismein teen lists hon: pehli list prime numbers ki, doosri list composite numbers ki, aur teesri list perfect numbers ki. | def segregate_num(my_list):
"""
Design a function that segregates prime numbers, composite numbers, and perfect numbers from a given list of integers. The function should return a tuple containing three lists: the first list of prime numbers, the second list of composite numbers, and the third list of perfect n... |
71420a65a31054f79e737180 | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Develop a Python program utilizing TensorFlow and BERT-as-Service to refine a pre-trained Bert model for multiple entities recognition with relation detection. The program should fetch, process, and normalize a text dataset from a PostgreSQL database, and manage potential database connection pooling. | To use `BERT-as-Service`, a BERT model for entity recognition with relation detection, we would need to train the model with relevant data. This task might be quite complex and highly dependent on the nature and structure of your dataset. However, as a starting point, I will provide an example on how to utilize TensorF... | TensorFlow aur BERT-as-Service ka istemal karte hue aik Python program develop karein taake relation detection ke sath multiple entities recognition ke liye pre-trained Bert model ko refine kiya ja sake. Program ko PostgreSQL database se text dataset fetch, process aur normalize karna chahiye, aur potential database co... | `BERT-as-Service`, jo ke relation detection ke sath entity recognition ke liye aik BERT model hai, use karne ke liye humein model ko relevant data ke sath train karna hoga. Yeh task kafi complex ho sakta hai aur aapke dataset ki nature aur structure par bohot depend karta hai. Lekin, aik starting point ke tor par, main... |
cd757a9caff57eb78b1054cd | commitpackft | code_modification | javascript | code_mixed_casual | no_issue | bsd-3-clause | Apply the following change to the existing file.
Change request:
Disable map scrolling until user click on the map.
File: views/site/index.js
Existing code:
```javascript
$(function(){
$('.imgTile').click(function(){
window.location.href = $(this).data('url');
})
});
function initialize() {
var ... | $(function(){
$('.imgTile').click(function(){
window.location.href = $(this).data('url');
})
});
var map = {
map: null,
mapOptions: null,
init: function() {
this.initOptions();
this.map = new google.maps.Map(document.getElementById('map-canvas'), this.mapOptions);
th... | Existing file mein yeh change apply karein.
Change request:
Map ki scrolling disable kardo jab tak user map par click na kare.
File: views/site/index.js
Existing code:
```javascript
$(function(){
$('.imgTile').click(function(){
window.location.href = $(this).data('url');
})
});
function initialize()... | $(function(){
$('.imgTile').click(function(){
window.location.href = $(this).data('url');
})
});
var map = {
map: null,
mapOptions: null,
init: function() {
this.initOptions();
this.map = new google.maps.Map(document.getElementById('map-canvas'), this.mapOptions);
th... |
f41e95c5211d5f7d4dbad3a5 | acecode_87k | verified_problem | python | code_mixed_casual | no_issue | MIT | Given a list of integers, implement a function that returns the longest strictly increasing subsequence from that list. Each number in the list may be repeated, and repetitions should be treated as distinct elements in the subsequence. For example, in the list [10, 22, 9, 33, 21, 50, 41, 60, 22], the longest increasing... | def longest_increasing_subsequence(arr):
n = len(arr)
# Initialize an array to store the length of LIS ending at each index
dp = [1] * n
for i in range(1, n):
for j in range(i):
if arr[i] > arr[j] and dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
# Find the maximum value... | Integers ki aik list di gayi hai, aik function implement karein jo us list mein se longest strictly increasing subsequence return kare. List mein har number repeat ho sakta hai, aur subsequence mein repetitions ko distinct elements ke tor par treat kiya jana chahiye. Example ke tor par, list [10, 22, 9, 33, 21, 50, 41,... | def longest_increasing_subsequence(arr):
n = len(arr)
# Initialize an array to store the length of LIS ending at each index
dp = [1] * n
for i in range(1, n):
for j in range(i):
if arr[i] > arr[j] and dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
# Find the maximum value... |
e07ca53e297ac1d05c4d5630 | acecode_87k | verified_problem | python | professional | no_issue | MIT | You are given a list of posts represented by tuples, where each tuple contains two integers: `id_post` and `id_parent_post`. Your task is to implement a function `determine_node_types(posts: List[Tuple[int, int]]) -> List[Tuple[int, str]]` that categorizes each post as either a 'parent' or a 'leaf'. A post is considere... | from collections import defaultdict
def determine_node_types(posts: list[tuple[int, int]]) -> list[tuple[int, str]]:
parent_to_children = defaultdict(set)
for post_id, parent_id in posts:
parent_to_children[parent_id].add(post_id)
node_types = []
for post_id, parent_id in posts:
if pos... | Aapko tuples ki surat mein posts ki aik list di gayi hai, jahan har tuple mein do integers shamil hain: `id_post` aur `id_parent_post`. Aapka kaam aik function `determine_node_types(posts: List[Tuple[int, int]]) -> List[Tuple[int, str]]` implement karna hai jo har post ko ya to 'parent' ya phir 'leaf' ke taur par categ... | from collections import defaultdict
def determine_node_types(posts: list[tuple[int, int]]) -> list[tuple[int, str]]:
parent_to_children = defaultdict(set)
for post_id, parent_id in posts:
parent_to_children[parent_id].add(post_id)
node_types = []
for post_id, parent_id in posts:
if pos... |
e9d59522c925598df0cfa5b8 | glaive_v3 | general_instruction | delphi | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating a Windows desktop toolbar using Delphi programming language. The toolbar should allow for drag and drop functionality for files and folders, with the ability to move, copy, or create links based on the drag key state. Additionally, the toolbar should have the capability to monitor a specifi... | ```delphi
unit DDForms;
interface
uses
Windows, SysUtils, Classes, Linkbar.Graphics, Forms, ActiveX, ShlObj, CommCtrl,
Messages, Cromis.DirectoryWatch;
type
TLinkbarCustomFrom = class abstract(TForm, IDropTarget)
private
// Add private fields and methods for drag and drop functionality
procedure SetW... | Tumne Delphi programming language use krte hue Windows desktop toolbar banana hai. Is toolbar me files aur folders k liye drag and drop hona chahye, aur ye move, copy, ya links create kr sake drag key state k mutabiq. Sath hi, toolbar kisi khaas directory ko monitor kare aur jab b koi change ho tou notification de. Too... | ```delphi
unit DDForms;
interface
uses
Windows, SysUtils, Classes, Linkbar.Graphics, Forms, ActiveX, ShlObj, CommCtrl,
Messages, Cromis.DirectoryWatch;
type
TLinkbarCustomFrom = class abstract(TForm, IDropTarget)
private
// Add private fields and methods for drag and drop functionality
procedure SetW... |
7de3d7fe58d5298c2a8c45d3 | codefeedback | general_instruction | python | casual_noisy | corrected | Apache-2.0 | Determine the angle of depression and the final velocity when a stone is dropped downward with an initial velocity of 30m/s from a height H(m) incorporating air resistance factor k (N.s/m). This will require you to use concepts of advanced mechanics and differential equations. You can assume standard gravity. | To solve this problem, you will need to use python to create a model using the principles of physics. The forces acting on the stone will be the force of gravity and the force of air resistance.
```python
import math
from scipy.integrate import odeint
import numpy as np
# constants
g = 9.81 # m/s^2
v0 = 30 # m/s ... | ek pathar ko H(m) height se neeche phenka gaya hai 30m/s ki initial velocity k sath, air resistance factor k (N.s/m) ko b dkhna h... angle of depression aur final velocity nikalni h. is k liye advanced mechanics aur differential equations k concepts use krne parengy. Standard gravity hi le lo. | is maslay ko hal krny k liye apko python use kr k physics k principles pe model banana pary ga. stone pe jo forces lag rhi hain wo gravity ki force h aur air resistance h.
```python
import math
from scipy.integrate import odeint
import numpy as np
# constants
g = 9.81 # m/s^2
v0 = 30 # m/s initial velocity
k = 0.0... |
c5d204148e84f0abce946902 | magicoder_oss | general_instruction | python | code_mixed_professional | no_issue | MIT | You are tasked with creating a version comparison function that compares two version strings and determines which one is greater. A version string is a non-empty string consisting of one or more dot-separated numeric components. Each numeric component may contain leading zeroes. The version strings are compared compone... | ```python
def compare_versions(version1: str, version2: str) -> int:
v1_components = list(map(int, version1.split('.')))
v2_components = list(map(int, version2.split('.'))
# Pad the shorter version with zeroes
max_len = max(len(v1_components), len(v2_components))
v1_components += [0] * (max_len - l... | Aap ko aik version comparison function bananay ka task diya gaya hai jo do version strings ka muqabla karay aur ye determine karay ke konsa bara hai. Aik version string aik non-empty string hoti hai jo aik ya aik se zyada dot-separated numeric components par mushtamil hoti hai. Har numeric component mein leading zeroes... | ```python
def compare_versions(version1: str, version2: str) -> int:
v1_components = list(map(int, version1.split('.')))
v2_components = list(map(int, version2.split('.'))
# Pad the shorter version with zeroes
max_len = max(len(v1_components), len(v2_components))
v1_components += [0] * (max_len - l... |
9174371e575d33bf1cc5d2f4 | commitpackft | code_modification | markdown | code_mixed_casual | no_issue | MIT | Apply the following change to the existing file.
Change request:
Add basic usage for optimise-functions.js to Readme
File: README.md
Existing code:
```markdown
SVG-optimiser.js
================
An online SVG optimiser using Javascript and jQuery
``` | SVG-optimiser.js
================
An online SVG optimiser using Javascript and jQuery
##Using optimise-functions.js and SVG-elements.js
###Create an SVG_Root object
The `SVG_Root` object is what parses the SVG and allows you to access the optimisation functions. You can pass it either a complete SVG or an SVG elemen... | Existing file me ye change apply karein.
Change request:
Readme me optimise-functions.js ka basic usage add karein
File: README.md
Existing code:
```markdown
SVG-optimiser.js
================
An online SVG optimiser using Javascript and jQuery
``` | SVG-optimiser.js
================
An online SVG optimiser using Javascript and jQuery
##Using optimise-functions.js and SVG-elements.js
###Create an SVG_Root object
The `SVG_Root` object is what parses the SVG and allows you to access the optimisation functions. You can pass it either a complete SVG or an SVG elemen... |
6f9d99b7a8d4694228c01b0d | acecode_87k | verified_problem | python | professional | no_issue | MIT | Write a Python function that takes a list of integers as input and returns the length of the longest consecutive subsequence of integers where each integer is directly successive to the previous one. The function should handle duplicate integers and should not modify the original order of integers. If the input list is... | def longest_consecutive_subsequence(numbers):
"""
Returns the length of the longest consecutive subsequence of integers
where each integer is directly successive to the previous one.
"""
longest_sequence = 0
seen = set()
for number in numbers:
if number not in seen:
curre... | Aik Python function likhein jo integers ki aik list input ke taur par leta ho aur integers ke us longest consecutive subsequence ki length return karta ho jahan har integer pichle integer ke bilkul successive (lagataar) ho. Function ko duplicate integers ko handle karna chahiye aur integers ki original order ko modify ... | def longest_consecutive_subsequence(numbers):
"""
Returns the length of the longest consecutive subsequence of integers
where each integer is directly successive to the previous one.
"""
longest_sequence = 0
seen = set()
for number in numbers:
if number not in seen:
curre... |
e8d3b323531b6eda88930de0 | magicoder_oss | general_instruction | python | code_mixed_professional | no_issue | MIT | You are working on a Python project that involves importing resources from different modules. The project structure is as follows:
```
project/
├── main.py
└── resources/
├── __init__.py
├── users.py
├── followers.py
└── repos.py
```
The `__init__.py` file is empty and serves as a marker for the `reso... | ```python
from resources.users import UserResource
from resources.followers import FollowersListResource
from resources.repos import ReposListResource, RepoResource
```
In the `main.py` file, the correct import statements are as shown above. These statements import the required resources from their respective modules ... | Aap aik Python project par kaam kar rahay hain jis mein mukhtalif modules say resources import karnay hain. Project ka structure yeh hai:
```
project/
├── main.py
└── resources/
├── __init__.py
├── users.py
├── followers.py
└── repos.py
```
`__init__.py` file khaali hai aur yeh `resources` directory k... | ```python
from resources.users import UserResource
from resources.followers import FollowersListResource
from resources.repos import ReposListResource, RepoResource
```
`main.py` file mein, darust import statements upar di gayi hain. Yeh statements `resources` package ke andar maujood un ke mutalqa modules say matloob... |
0910ca879fc6ec414423cc27 | glaive_v3 | general_instruction | jsp | casual_noisy | no_issue | Apache-2.0 | You are tasked with creating a web page for managing platform integrations using Java Server Pages (JSP) with Java and JavaScript. The web page should allow the user to add new platform integrations, delete existing ones, and view the details of each integration. The page should display a list of platform integrations ... | ```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head>
<%@ include file="/WEB-INF/views... | tumhe ek web page banana hai platform integrations manage krne k liye JSP Java aur JavaScript use karke. web page pr user new platform integrations add kr ske, purane delete kr ske aur har integration ki details dekh sake. page pr platform integrations ki list show honi chahiye jisme aik sath multiple integrations sele... | ```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head>
<%@ include file="/WEB-INF/views... |
c5a83c334342858b3836181b | glaive_v3 | general_instruction | unknown | casual_noisy | no_issue | Apache-2.0 | I've been exploring different profiling tools for my Rails application, such as ruby-prof and railsbench. However, I find these tools require a lot of tweaking and manipulation to work properly. I don't mind some tweaking, but I'm wondering if there are any other profiling tools available that are more straightforward ... | Certainly! One highly recommended tool for profiling Rails applications is New Relic. It offers Rails profiling functionality and even provides a free version called 'Lite'.
To get started with New Relic, you can visit their website at [http://www.newrelic.com/ruby](http://www.newrelic.com/ruby). They offer a free 'Li... | yr me apni rails app k lye diff profiling tools dekh rha tha jese ruby-prof aur railsbench wagera. but mujhe lgta in tools ko theek se chalane k lye bht ziada tweaking aur setting krni parti h. thori bht tweaking to chlti h pr kya koi aese profiling tools hain jo zyada seedhe aur user-friendly hon? kya koi ache tools r... | Haan bilkul! Rails apps ko profile krne k lye aik bht zabardast tool New Relic hai. ye rails profiling ka feature deta h aur inka aik free version b h jisko 'Lite' kehte hain.
New Relic k sath shuru krne k lye aap unki site [http://www.newrelic.com/ruby](http://www.newrelic.com/ruby) pr ja skte ho. wo bilkul free 'Lit... |
eef5b8878c9fac9660af70ab | magicoder_oss | general_instruction | python | code_mixed_professional | no_issue | MIT | You are tasked with analyzing LoRaWAN network performance for different spreading factors (SF) in the Asia 923MHz frequency band. Your goal is to create a Python program that generates a plot comparing the time on air for different physical payload sizes at SF10 with a bandwidth of 500kHz against the same payload sizes... | ```python
import matplotlib.pyplot as plt
# Function to generate payload size range
def mpsrange(start, end):
return list(range(start, end+1, 10))
# Function to calculate time on air
def get_line(payload_sizes, sf, bw):
# Placeholder function, replace with actual calculation
return [size * sf / bw for siz... | Aap ko Asia 923MHz frequency band mein mukhtalif spreading factors (SF) ke liye LoRaWAN network performance analyze karne ka task diya gaya hai. Aap ka maqsad aik Python program banana hai jo 500kHz bandwidth ke sath SF10 par mukhtalif physical payload sizes ke time on air ka mawazna doosre spreading factors par unhi p... | ```python
import matplotlib.pyplot as plt
# Function to generate payload size range
def mpsrange(start, end):
return list(range(start, end+1, 10))
# Function to calculate time on air
def get_line(payload_sizes, sf, bw):
# Placeholder function, replace with actual calculation
return [size * sf / bw for siz... |
c4e11fa2487f9f7d5bc6343a | magicoder_oss | general_instruction | cpp | code_mixed_professional | corrected | MIT | You are tasked with implementing a regular expression parser and a corresponding Nondeterministic Finite Automaton (NFA) compiler. Your goal is to create a program that takes a regular expression as input, compiles it into an NFA, and then prints the resulting NFA.
The regular expression parser should support the foll... | To solve this problem, you can use the following steps:
Step 1: Implement the regular expression parser
- Create a class `RegexParser` that takes a regular expression as input and compiles it into an NFA.
- Implement methods to handle concatenation, alternation, and Kleene star operations.
- Use appropriate data struc... | Aap ko ek regular expression parser aur uske mutabiq Nondeterministic Finite Automaton (NFA) compiler implement karne ka kaam diya gaya hai. Aap ka maqsad ek aisa program banana hai jo input ke taur par regular expression le, usay NFA mein compile kare, aur phir banne walay NFA ko print kare.
Regular expression parser... | Is maslay ko hal karne ke liye aap darj-zail steps follow kar sakte hain:
Step 1: Regular expression parser implement karein
- Ek class `RegexParser` banayein jo input ke taur par regular expression le aur usay NFA mein compile kare.
- Concatenation, alternation, aur Kleene star operations ko handle karne ke liye meth... |
1d6f5a2d8e1b798578f74a60 | commitpackft | code_modification | cpp | code_mixed_casual | no_issue | unlicense | Apply the following change to the existing file.
Change request:
Replace std::shared_ptr with pointer and make the constructor explicit
File: EntityManager.cpp
Existing code:
```cpp
#include "EntityManager.h"
namespace zmc
{
EntityManager::EntityManager(std::shared_ptr<ComponentManager> componentManager)
: mLas... | #include "EntityManager.h"
namespace zmc
{
EntityManager::EntityManager(ComponentManager *componentManager)
: mLastEntityID(0)
, mComponentManager(componentManager)
{
}
EntityManager::~EntityManager()
{
}
int EntityManager::getEntityCount()
{
return mEntityMap.size();
}
void EntityManager::removeEntity... | Mawjooda file me ye change apply karo.
Change request:
std::shared_ptr ko pointer se replace karo aur constructor ko explicit banao
File: EntityManager.cpp
Mawjooda code:
```cpp
#include "EntityManager.h"
namespace zmc
{
EntityManager::EntityManager(std::shared_ptr<ComponentManager> componentManager)
: mLastEnt... | #include "EntityManager.h"
namespace zmc
{
EntityManager::EntityManager(ComponentManager *componentManager)
: mLastEntityID(0)
, mComponentManager(componentManager)
{
}
EntityManager::~EntityManager()
{
}
int EntityManager::getEntityCount()
{
return mEntityMap.size();
}
void EntityManager::removeEntity... |
59fe217bfa6cb62f9974b089 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function `run_function(function_name, filename, args)` that takes three arguments: `function_name` is the name of the function to run, `filename` is the name of the file to load containing the function definition, and `args` is a dictionary of argument names and values to pass to the function. The functi... | To solve this problem, we can use the `importlib` module in Python to dynamically load a module from a file and then call the function with the given arguments. To handle the case where the function does not exist, we can use the `getattr` function to check if the function exists before calling it.
Here is a Python fu... | Ek Python function `run_function(function_name, filename, args)` likhein jo teen arguments leta ho: `function_name` run karne wale function ka naam hai, `filename` function definition rakhne wali load ki jane wali file ka naam hai, aur `args` function ko pass karne ke liye argument names aur values ki dictionary hai. F... | Is maslay ko solve karne ke liye, hum Python mein file se dynamically module load karne aur phir diye gaye arguments ke sath function call karne ke liye `importlib` module ka use kar sakte hain. Us case ko handle karne ke liye jahan function exist nahi karta, hum call karne se pehle function ke wujood ko check karne ke... |
50f89e8dc95a347e808cd7f4 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function `integer_rounding(x)` that takes a floating point number `x` and rounds it to the nearest integer. Ensure that the function's behavior is consistent with the built-in Python `round()` function, which rounds half-way cases away from zero.
Include a docstring that explains the function's purpose,... | To create this function, we will use the built-in `abs()` and `round()` functions to handle different cases of input. The function will round `x` to the nearest integer. The docstring will explain the function's purpose, parameters, and return value. We will validate the input to ensure that `x` is a valid number. If `... | Ek Python function `integer_rounding(x)` likhein jo ek floating point number `x` leta hai aur usay qareeb tareen integer tak round karta hai. Yaqeeni banayein ke function ka behavior built-in Python `round()` function ke mutabiq ho, jo half-way cases ko zero se door round karta hai.
Ek docstring shamil karein jo funct... | Is function ko banane ke liye, hum input ke mukhtalif cases ko handle karne ke liye built-in `abs()` aur `round()` functions ka istemal karenge. Function `x` ko qareeb tareen integer tak round karega. Docstring function ke maqsad, parameters, aur return value ko wazeh karegi. Hum input ko validate karenge taake yaqeeni... |
6c08a13d5d37f3c50f68be8a | codefeedback | general_instruction | python | professional | no_issue | Apache-2.0 | You are tasked with implementing a real-time data visualization system for physiological signals. The system receives data at a sampling frequency of 250 Hz and is required to display the most recent 3 seconds of data. Additionally, a notch filter at 60 Hz needs to be applied to the data before visualization. Your task... | ```python
import numpy as np
import scipy.signal
def updater():
global data, plots, colors
fs = 250 # Hz
disp_sec = 3 # Seconds to display
t_data = np.array(data[-(fs * disp_sec + 100):]).T # transpose data
# Notch Filter at 60 Hz
nyquist = 0.5 * fs
freq = 60.0
Q = 30.0 # Quality ... | Aap ko physiological signals ke liye ek real-time data visualization system implement karne ka kaam diya gaya hai. System 250 Hz ki sampling frequency par data receive karta hai aur isay sab se haal hi ke 3 seconds ka data display karna zaroori hai. Is ke ilawa, visualization se pehle data par 60 Hz par ek notch filter... | ```python
import numpy as np
import scipy.signal
def updater():
global data, plots, colors
fs = 250 # Hz
disp_sec = 3 # Seconds to display
t_data = np.array(data[-(fs * disp_sec + 100):]).T # transpose data
# Notch Filter at 60 Hz
nyquist = 0.5 * fs
freq = 60.0
Q = 30.0 # Quality ... |
0fd95b81aa2857a63e892c82 | magicoder_oss | general_instruction | rust | code_mixed_professional | no_issue | MIT | You are tasked with implementing a struct to calculate the estimated reading time of a given text based on its word count and other factors. The provided code snippet demonstrates the usage of a function `text` to calculate the estimated reading time and retrieve the word count and time in seconds.
Your task is to cre... | ```rust
// Define the Options struct
struct Options {
// Define the necessary parameters for calculating read time
}
// Define the ReadTime struct
struct ReadTime {
word_count: u64,
time_seconds: u64,
}
impl ReadTime {
// Implement the word_count method
fn word_count(&self, content: &str) -> u64 {... | Aap ko ek diye gaye text ke word count aur deegar factors ki bunyad par estimated reading time calculate karne ke liye ek struct implement karne ka task diya gaya hai. Diya gaya code snippet estimated reading time calculate karne aur word count aur time in seconds hasil karne ke liye ek function `text` ka istemal wazeh... | ```rust
// Define the Options struct
struct Options {
// Define the necessary parameters for calculating read time
}
// Define the ReadTime struct
struct ReadTime {
word_count: u64,
time_seconds: u64,
}
impl ReadTime {
// Implement the word_count method
fn word_count(&self, content: &str) -> u64 {... |
1827d32e5d8479f389671896 | acecode_87k | verified_problem | python | code_mixed_casual | corrected | MIT | You are given a string 'token' which represents a JSON Web Token (JWT). Your task is to implement a function that verifies the token's signature using a provided public key. The function should return the parsed token data if the signature is valid, otherwise, it should return None. The public key is represented as a s... | import base64
import json
import hashlib
def verify(token, public_key):
header, payload, signature = token.split('.')
header_dict = json.loads(base64.b64decode(header).decode())
if header_dict['alg'] != public_key:
return None
payload_dict = json.loads(base64.b64decode(payload).decode())
di... | Tumhe ek string 'token' di gayi hai jo ek JSON Web Token (JWT) ko represent karti hai. Tera task ek aisa function implement karna hai jo di gayi public key use karte hue token ki signature verify kare. Agar signature valid hai toh function parsed token data return kare, warna None return kar dena. Public key ek string ... | import base64
import json
import hashlib
def verify(token, public_key):
header, payload, signature = token.split('.')
header_dict = json.loads(base64.b64decode(header).decode())
if header_dict['alg'] != public_key:
return None
payload_dict = json.loads(base64.b64decode(payload).decode())
di... |
481dfd0e702480216e3f0174 | magicoder_oss | general_instruction | java | code_mixed_professional | no_issue | MIT | You are tasked with creating a Minecraft mod that adds a new feature to the game. The mod should allow players to collect resources from specific locations and store them in a virtual inventory. To achieve this, you need to implement a custom event handler that listens for a server starting event and then processes the... | ```java
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ja... | Aap ko aik Minecraft mod bananay ka task diya gaya hai jo game mein aik naya feature add karta hai. Mod ko players ko specific locations se resources collect karnay aur unhein aik virtual inventory mein store karnay ki ijazat deni chahiye. Yeh achieve karnay ke liye, aap ko aik custom event handler implement karna hoga... | ```java
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ja... |
8159107e8dfe35fc3411e021 | codefeedback | general_instruction | sql | casual_noisy | corrected | Apache-2.0 | Create a MySQL query that returns all the names of the students who have a grade greater than or equal to 7 and are enrolled in at least two courses.
Table 1: Students
Columns: student_id, name, grade
Table 2: Courses
Columns: course_id, course_name, student_id | SELECT s.name
FROM Students s
JOIN Courses c ON s.student_id = c.student_id
GROUP BY s.student_id, s.name
HAVING COUNT(c.course_id) >= 2
AND s.grade >= 7; | aik mysql query likh do jo un saare students k name dede jinka grade 7 ya usse zada ho aur wo atleast 2 courses mai b hon. Table 1: Students Columns: student_id, name, grade Table 2: Courses Columns: course_id, course_name, student_id | SELECT s.name
FROM Students s
JOIN Courses c ON s.student_id = c.student_id
GROUP BY s.student_id, s.name
HAVING COUNT(c.course_id) >= 2
AND s.grade >= 7; |
a8571e84dbf9601a02f6539f | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function that takes in a sequence of integers and returns a sequence of the running total sums of the input sequence.
For instance, for the input sequence `[1, 2, 3, 4, 5]`, the function should return `[1, 3, 6, 10, 15]`.
The function should stop iterating once the global variable `STOP_ITERATION` is `... | To return the running total sums of the input sequence, we can use a `for` loop to iterate over the input sequence and use a variable to store the running total sum. However, we need to stop the iteration once the `STOP_ITERATION` variable is set to `True`.
Here's an example implementation:
```python
STOP_ITERATION =... | Ek Python function likhein jo integers ki ek sequence input ke tor par le aur input sequence ke running total sums ki sequence return kare.
Misaal ke tor par, input sequence `[1, 2, 3, 4, 5]` ke liye, function ko `[1, 3, 6, 10, 15]` return karna chahiye.
Jaise hi global variable `STOP_ITERATION`, `True` ho jaye, func... | Input sequence ke running total sums return karne ke liye, hum input sequence par iterate karne ke liye `for` loop ka istemal kar sakte hain aur running total sum ko store karne ke liye ek variable use kar sakte hain. Lekin, jaise hi `STOP_ITERATION` variable `True` set ho jaye, humein iteration rokni hogi.
Yahan ek m... |
60406d60759febfcad2facff | codefeedback | general_instruction | python | casual_noisy | corrected | Apache-2.0 | Create a program where a user can input two integer values. The task of the program is to first check if the numbers are either odd or even. Then, the program should use if-else statements to compare these two variables to determine whether they are equal, which one is greater, or if the sum of the two numbers is odd o... | Here is a Python-based solution to the given problem:
```python
# Getting input from user
var1 = int(input("Enter first integer: "))
var2 = int(input("Enter second integer: "))
# Checking if the numbers are odd or even
var1_type = "odd" if var1 % 2 == 1 else "even"
var2_type = "odd" if var2 % 2 == 1 else "even"
# Ch... | ek program banao jisme user 2 integer values enter kar sake. progrm ka kaam he pehle check kre k numbrs odd hain ya even. phir if-else use kr k dono variables ko compare krna ha taakay pata chalay k wo equal hain, konsa bara ha, ya sum odd ha ya even. agr sum odd ho toh usme 2 add krdo aur agr sum even ho toh 2 minus k... | ye lo bhai python based solution is problem ka:
```python
# Getting input from user
var1 = int(input("Enter first integer: "))
var2 = int(input("Enter second integer: "))
# Checking if the numbers are odd or even
var1_type = "odd" if var1 % 2 == 1 else "even"
var2_type = "odd" if var2 % 2 == 1 else "even"
# Checking... |
9fc8023f8993338381f3a197 | acecode_87k | verified_problem | python | professional | no_issue | MIT | You are given an array of integers, where each integer represents the height of a histogram bar. Write a function `max_area(heights: List[int]) -> int` that calculates the maximum rectangular area that can be formed by the histogram. The function should return this maximum area. The width of each bar is 1. For example,... | from typing import List
def max_area(heights: List[int]) -> int:
# Initialize the maximum area to zero
max_area = 0
# Iterate over each bar in the histogram
for i in range(len(heights)):
# Assume the current bar is the tallest
height = heights[i]
# Calculate the area for th... | Aap ko integers ka ek array diya gaya hai, jahan har integer histogram bar ki height ko represent karta hai. Ek function `max_area(heights: List[int]) -> int` likhein jo histogram se banne wala maximum rectangular area calculate kare. Function ko yeh maximum area return karna chahiye. Har bar ki width 1 hai. Misal ke t... | from typing import List
def max_area(heights: List[int]) -> int:
# Initialize the maximum area to zero
max_area = 0
# Iterate over each bar in the histogram
for i in range(len(heights)):
# Assume the current bar is the tallest
height = heights[i]
# Calculate the area for th... |
80eb626ec7f99a779b5b4d1b | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Given two closed intervals `[a1, b1]` and `[a2, b2]`, where $a_1, b_1, a_2, b_2$ are integers, write a Python function to calculate the intersection of these intervals. Return the intersection as a tuple of integers `(x, y)` where $x \leq y$. If the intervals have no intersection, return `None`.
Your code should pass ... | Here's how you can implement this in Python:
```python
def intersect_intervals(interval1, interval2):
lower_bound = max(interval1[0], interval2[0])
upper_bound = min(interval1[1], interval2[1])
if lower_bound > upper_bound:
return None
else:
return (lower_bound, upper_bound)
``` | Diye gaye do closed intervals `[a1, b1]` aur `[a2, b2]` ke liye, jahan $a_1, b_1, a_2, b_2$ integers hain, in intervals ka intersection calculate karne ke liye ek Python function likhen. Intersection ko integers ke tuple `(x, y)` ki surat mein return karen jahan $x \leq y$ ho. Agar intervals ka koi intersection nahi ha... | Python mein aap ise is tarah implement kar sakte hain:
```python
def intersect_intervals(interval1, interval2):
lower_bound = max(interval1[0], interval2[0])
upper_bound = min(interval1[1], interval2[1])
if lower_bound > upper_bound:
return None
else:
return (lower_bound, upper_bound)
`... |
7bc6052af4611b5445f90c17 | glaive_v3 | general_instruction | ocaml | casual_noisy | no_issue | Apache-2.0 | :
You are tasked with creating a program that parses command-line arguments and generates a DVI (Device Independent) file viewer. The program should be able to set the view, controller, crop flag, horizontal and vertical margins, and geometry based on the command-line arguments provided. The program should be written i... | :
```OCaml
open JGraphics
module Dev = Javadev
module View = Dviview.Make(Dev)
let crop_flag = ref true
let hmargin = ref (View.Cm 1.0)
let vmargin = ref (View.Cm 1.0)
let geometry = ref "864x864"
class mlDvi =
object
inherit _stub_ml_dvi ()
method run filename view controler =
Javadev.set_view view;... | tumhe aik program banana hai jo command-line arguments ko parse kre aur aik DVI (Device Independent) file viewer banaye. program ko itna capable hona chahiye k wo view, controller, crop flag, horizontal aur vertical margins, aur geometry set kar sake provided command-line arguments ki base pe. ye program OCaml me likha... | :
```OCaml
open JGraphics
module Dev = Javadev
module View = Dviview.Make(Dev)
let crop_flag = ref true
let hmargin = ref (View.Cm 1.0)
let vmargin = ref (View.Cm 1.0)
let geometry = ref "864x864"
class mlDvi =
object
inherit _stub_ml_dvi ()
method run filename view controler =
Javadev.set_view view;... |
19304334ec99fadd6f8846a0 | glaive_v3 | general_instruction | unknown | casual_noisy | no_issue | Apache-2.0 | I'm trying to understand what this x86 instruction is doing:
```
movl %eax, heap(,%rdx,4)
```
This is what I think it's doing:
Move the value in `eax` to the memory location represented by the label `heap`, with a displacement of the value in `rdx` multiplied by 4.
Is my understanding correct?
Thanks | The instruction `movl %eax, heap(,%rdx,4)` is using the AT&T syntax for memory operands. In Intel syntax, it can be better represented as `mov [heap + rdx*4], eax`.
So, this instruction is storing the value in the `eax` register at the memory address calculated as `heap + rdx*4`. This implies that `heap` is likely an ... | me ye samjhne ki koshish kar raha hu ke ye x86 instruction kya kar rahi hai:
```
movl %eax, heap(,%rdx,4)
```
mujhay lagta hai ye ye kar rahi hai:
`eax` ki value ko us memory location par move karna jo label `heap` se represent hoti hai, saath me `rdx` ki value ko 4 se multiply karke displacement dena.
kya meri samajh ... | instruction `movl %eax, heap(,%rdx,4)` memory operands ke liye AT&T syntax use kar rahi hai. Intel syntax me, isko behtar tarike se `mov [heap + rdx*4], eax` likha ja sakta hai.
so, ye instruction `eax` register ki value ko memory address `heap + rdx*4` par store kar rahi hai. iska matlab hai ke `heap` shayad 4-byte i... |
ce60e4d97bb4aa8dc93b3d35 | magicoder_evol | general_instruction | unknown | code_mixed_professional | corrected | Apache-2.0 | Dilemma:
I am attempting to implement the minmax scaler to the columns labeled X2 and X3 within the dataframe known as df. My intention is to append new columns, specifically X2_scale and X3_scale, for each distinct month.
df = pd.DataFrame({
'Month': [1,1,1,1,1,1,2,2,2,2,2,2,2],
'X1': [12,10,... | for name, group in df.groupby('Month'):
scaled_values = scaler.fit_transform(group[['X2','X3']])
df.loc[group.index, 'X2_scaled'] = scaled_values[:,0]
df.loc[group.index, 'X3_scaled'] = scaled_values[:,1]
print(df)
</code>
END SOLUTION | Masla:
Main dataframe df ke andar X2 aur X3 labeled columns par MinMaxScaler apply karne ki koshish kar raha hoon. Mera maqsad har alag Month ke liye naye columns, khusoosan X2_scale aur X3_scale append karna hai.
df = pd.DataFrame({
'Month': [1,1,1,1,1,1,2,2,2,2,2,2,2],
'X1': [12,10,100,55,65... | for name, group in df.groupby('Month'):
scaled_values = scaler.fit_transform(group[['X2','X3']])
df.loc[group.index, 'X2_scaled'] = scaled_values[:,0]
df.loc[group.index, 'X3_scaled'] = scaled_values[:,1]
print(df)
</code>
END SOLUTION |
1fccb716fc1ccbc10a1bc3d9 | magicoder_oss | general_instruction | java | code_mixed_casual | corrected | MIT | You are tasked with implementing a loading view in an Android application using RxJava. The `RxLoadingView` class provides a method `show` that takes a context and a string resource ID as parameters and returns an `Action0` object. The `Action0` interface represents an action that has no input and returns no result.
Y... | ```java
import android.content.Context;
import android.view.View;
import android.widget.ProgressBar;
import androidx.annotation.StringRes;
import rx.functions.Action0;
public class RxLoadingView {
public static Action0 show(final Context context, @StringRes final int stringRes) {
// Create and show the lo... | Aap ko RxJava use kar ke ek Android application mein loading view implement karni hai. `RxLoadingView` class ek method `show` provide karti hai jo parameters ke taur par context aur ek string resource ID leta hai aur ek `Action0` object return karta hai. `Action0` interface ek aisi action ko represent karta hai jis ka ... | ```java
import android.content.Context;
import android.view.View;
import android.widget.ProgressBar;
import androidx.annotation.StringRes;
import rx.functions.Action0;
public class RxLoadingView {
public static Action0 show(final Context context, @StringRes final int stringRes) {
// Create and show the lo... |
71a3b36b84c9f4a6d2e3ab5f | magicoder_evol | general_instruction | python | code_mixed_professional | no_issue | Apache-2.0 | Program a Python script that trains an image cropping model to resize multiple selected non-rectangular regions within an image, considering RGB data and maintaining aspect ratio. | The problem stated here is quite complex and involves many advanced concepts related to image processing and machine learning. Unfortunately, the problem is too complex to solve with just a few lines of python code. However, I can outline a general approach that you can take to solve it.
Here, we can't train a model j... | Aik Python script program karein jo aik image cropping model ko train kare taake image ke andar multiple selected non-rectangular regions ko resize kiya ja sakay, jabke RGB data ko madd-e-nazar rakha jaye aur aspect ratio ko barkarar rakha jaye. | Yahan bayan kiya gaya masla kafi complex hai aur is mein image processing aur machine learning se mutalika kai advanced concepts shamil hain. Afsos ke saath, yeh masla sirf Python code ki chand lines se hal nahi kiya ja sakta. Taham, mein aik general approach ka khaka pesh kar sakta hoon jis par aap amal kar sakte hain... |
b86f3d2dbc7efec3ed907899 | magicoder_evol | general_instruction | unknown | code_mixed_professional | no_issue | Apache-2.0 | Reflecting upon the characteristics of resolution theorem proving in demonstrating the non-satisfiability of a propositional logic statement, such as its soundness that prevents the validation of non-satisfiability for a satisfiable statement, its completeness that ensures every non-satisfiable statement has a validati... | The quintessence of resolution theorem proving is encapsulated by the combination of its soundness, completeness, and succinctness characteristics. These attributes create a robust and efficient system for validating the non-satisfiability of propositional logic statements, providing assurance on the accuracy of the re... | Propositional logic statement ki non-satisfiability ko demonstrate karne mein resolution theorem proving ki khusoosiyat par ghor karte hue-jaise ke is ki soundness jo kisi satisfiable statement ke liye non-satisfiability ki validation ko rokti hai, is ki completeness jo yeh ensure karti hai ke har non-satisfiable state... | Resolution theorem proving ka asal essence is ki soundness, completeness, aur succinctness ki khusoosiyat ke combination se encapsulate hota hai. Yeh attributes propositional logic statements ki non-satisfiability validate karne ke liye ek robust aur efficient system create karte hain, jo results ki accuracy par itmina... |
ce1bd0950b92597fcb3a9507 | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | corrected | ODC-By-1.0 | Here is a Python function that takes an integer `n` and returns a list of integers corresponding to the digits of `n` in reverse order:
```python
def get_reversed_digits(n):
digits = []
while n > 0:
n, remainder = divmod(n, 10)
digits.append(remainder)
return digits
```
Can you write a new... | To write a function that returns the sum of the digits' powers to the corresponding position in the reverse order, we can modify the existing `get_reversed_digits` function to use the power operation (`**`) on each digit before appending it to the list of digits. We can then calculate the sum of these powers using the ... | Yahan ek Python function hai jo ek integer `n` leta hai aur reverse order mein `n` ke digits ke barabar integers ki ek list return karta hai:
```python
def get_reversed_digits(n):
digits = []
while n > 0:
n, remainder = divmod(n, 10)
digits.append(remainder)
return digits
```
Kya aap ek na... | Ek aisa function likhne ke liye jo reverse order mein mutaliqa position ke mutabiq digits ke powers ka sum return kare, hum maujooda `get_reversed_digits` function ko modify kar sakte hain taake har digit ko digits ki list mein append karne se pehle us par power operation (`**`) istemaal kiya jaye. Phir hum `sum` funct... |
3a26e5a348b879bc201caa8c | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Write a Python function to replace all dashes with underscores in a string parameter, and return the result. The function should also accept an optional `keep_dashes` boolean argument. When set to True, the function should keep dashes. | Here's an example implementation of the function you described:
```python
def replace_dashes_with_underscores(string, keep_dashes=False):
if not keep_dashes:
string = string.replace("-", "_")
return string
``` | Ek string parameter mein tamam dashes ko underscores se replace karne ke liye ek Python function likhein, aur result return karein. Function ko ek optional `keep_dashes` boolean argument bhi accept karna chahiye. Jab yeh True par set ho, toh function ko dashes ko barkarar (keep) rakhna chahiye. | Aap ke bataye gaye function ki ek example implementation yeh rahi:
```python
def replace_dashes_with_underscores(string, keep_dashes=False):
if not keep_dashes:
string = string.replace("-", "_")
return string
``` |
10b3aef08d199d6677ef3a0a | magicoder_evol | general_instruction | rust | code_mixed_professional | corrected | Apache-2.0 | Re-implement this JavaScript code in Rust
function factorial(n) {
if(n === 0) {
return 1;
}
return n * factorial(n - 1);
} | Here is the Rust version of your JavaScript code:
```rust
fn factorial(n: u64) -> u64 {
match n {
0 => 1,
_ => n * factorial(n - 1),
}
}
fn main() {
println!("{}", factorial(5)); // For example, testing with 5
}
```
This Rust implementation uses pattern matching, which is a common Rust fe... | Is JavaScript code ko Rust mein dobara implement karein
function factorial(n) {
if(n === 0) {
return 1;
}
return n * factorial(n - 1);
} | Aapke JavaScript code ka Rust version yeh hai:
```rust
fn factorial(n: u64) -> u64 {
match n {
0 => 1,
_ => n * factorial(n - 1),
}
}
fn main() {
println!("{}", factorial(5)); // For example, testing with 5
}
```
Yeh Rust implementation pattern matching ka istemal karti hai, jo control fl... |
64849e6a248dc98f42ba9e0a | starcoder2_self_oss_exec | execution_validated_instruction | python | professional | no_issue | ODC-By-1.0 | Given a directed graph represented by an adjacency list and two vertices `src` and `dst`, write a Python function `get_shortest_path(adj_list, src, dst)` to find the shortest path from `src` to `dst` in the graph.
Your function should return a list containing the vertices along the shortest path in order, including `s... | To find the shortest path from `src` to `dst` in a directed graph, you can use a modified version of the Breadth-First Search (BFS) algorithm.
Here's how you can implement the `get_shortest_path` function in Python:
```python
def get_shortest_path(adj_list, src, dst):
queue = [(src, [src])]
visited = {src}
... | Ek directed graph diya gaya hai jo adjacency list se represent kiya gaya hai aur do vertices `src` aur `dst` hain, ek Python function `get_shortest_path(adj_list, src, dst)` likhein taake graph mein `src` se `dst` tak ka shortest path maloom kiya ja sakay.
Aap ka function ek list return kare jis mein shortest path ke ... | Directed graph mein `src` se `dst` tak ka shortest path maloom karne ke liye, aap Breadth-First Search (BFS) algorithm ka ek modified version istemal kar sakte hain.
Python mein `get_shortest_path` function ko implement karne ka tareeqa yeh hai:
```python
def get_shortest_path(adj_list, src, dst):
queue = [(src, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.