qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,565,837
|
<p>I have a <strong>React-Typescript</strong> application and had recently configured <strong>i18next</strong> setup for multi-language support. I believe all of the setups have been done correctly by following the guidelines of the official documentation. However, when I run the app, it gives me a bunch of compilation errors, such as;</p>
<pre><code>Property 'changeLanguage' does not exist on type 'typeof import("...some_path_info.../node_modules/i18next/index")'.
</code></pre>
<p>or</p>
<pre><code>Module '"i18next"' has no exported member 'Module'
</code></pre>
<p>I tried a bunch of different <code>tsconfig.json</code> configurations, such as including the type definition file from the <code>node_modules</code> folder of <strong>i18next</strong>, and other things, but none of them solved the issue, here is the current version of my <code>tsconfig.json</code> file;</p>
<pre><code>"include": ["src"],
"compilerOptions": {
"target": "ES2019",
"lib": ["esnext", "dom", "dom.iterable"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"baseUrl": "." /* Specify the base directory to resolve non-relative module names. */,
"paths": {
"libdefs/*": ["src/libdefs/*"]
},
"strict": false,
"noImplicitReturns": false,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"downlevelIteration": true,
"resolveJsonModule": true
}
}
</code></pre>
<p>After spending lots of time searching and testing, I found a way to make it work, and can lead me to the real solution, however, I still couldn't figure it out. The thing is, when I go to the <code>node_modules</code> folder of the <strong>i18next</strong>, the default file structure looks like this;</p>
<p><a href="https://i.stack.imgur.com/LbcFp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LbcFp.png" alt="Default File Structure of i18next package" /></a></p>
<p>Within this package, when I tried to move the <code>index.d.ts</code> type definition file inside the <code>dist</code> folder and then build my project, everything started to work magically without any further configuration or change. However, obviously, it is not a permanent solution.</p>
<p>Finally, I need a permanent solution to this problem, and my last finding about manipulating the package folder of <strong>i18next</strong> can give some hints.</p>
<p>Here are the versions for related packages;</p>
<pre><code>"i18next": "^22.0.6",
"react-i18next": "^12.0.0",
</code></pre>
<p>Thanks.</p>
|
[
{
"answer_id": 74654930,
"author": "e382df99a7950919789725ceeec126",
"author_id": 237209,
"author_profile": "https://Stackoverflow.com/users/237209",
"pm_score": 0,
"selected": false,
"text": "i18next changeLanguage i18next import * as i18n from 'i18next' changeLanguage i18n.changeLanguage i18next tsconfig.json compilerOptions tsconfig.json \"typeRoots\": [\"node_modules/@types\", \"./src/libdefs\"],\n i18next"
},
{
"answer_id": 74670689,
"author": "MaxPrilutskiy",
"author_id": 4446378,
"author_profile": "https://Stackoverflow.com/users/4446378",
"pm_score": 0,
"selected": false,
"text": "i18next @types/i18next package i18next npm install @types/i18next --save-dev\n i18next tsconfig.json \"types\" {\n \"compilerOptions\": {\n // Other compiler options...\n },\n \"types\": [\"i18next\"]\n}\n"
},
{
"answer_id": 74672796,
"author": "Midas",
"author_id": 20678816,
"author_profile": "https://Stackoverflow.com/users/20678816",
"pm_score": 2,
"selected": true,
"text": "import * as i18next from 'i18next/dist/cjs/i18next';\n \"i18next\": [\"node_modules/i18next/dist/cjs/i18next\"]\n"
},
{
"answer_id": 74673151,
"author": "Paiman Rasoli",
"author_id": 17462012,
"author_profile": "https://Stackoverflow.com/users/17462012",
"pm_score": 0,
"selected": false,
"text": "React-intl"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10721563/"
] |
74,565,844
|
<p>all!
I am trying to generate results of this repo</p>
<blockquote>
<p><a href="https://github.com/ArnaudBu/stock-returns-prediction" rel="nofollow noreferrer">https://github.com/ArnaudBu/stock-returns-prediction</a></p>
</blockquote>
<p>for stocks price prediction based on financial analysis. Running the very first step</p>
<blockquote>
<p>1_get_data.py</p>
</blockquote>
<p>I come across an error: <strong>TypeError: Cannot join tz-naive with tz-aware DatetimeIndex</strong></p>
<p>The code is</p>
<pre><code># -*- coding: utf-8 -*-
from yfinance import Ticker
import pandas as pd
from yahoofinancials import YahooFinancials
import requests
from tqdm import tqdm
import time
import pickle
# with open('tmp.pickle', 'rb') as f:
# statements, tickers_done = pickle.load(f)
# Download function
def _download_one(ticker, start=None, end=None,
auto_adjust=False, back_adjust=False,
actions=False, period="max", interval="1d",
prepost=False, proxy=None, rounding=False):
return Ticker(ticker).history(period=period, interval=interval,
start=start, end=end, prepost=prepost,
actions=actions, auto_adjust=auto_adjust,
back_adjust=back_adjust, proxy=proxy,
rounding=rounding, many=True)
# Modify project and reference index according to your needs
tickers_all = []
# for project in ["sp500", "nyse", "nasdaq"]:
for project in ["nasdaq"]:
print(project)
ref_index = ["^GSPC", "^IXIC"]
# Load tickers
companies = pd.read_csv(f"data/{project}/{project}.csv", sep=",")
# companies = companies.drop(companies.index[companies['Symbol'].index[companies['Symbol'].isnull()][0]]) # the row with Nan value
tickers = companies.Symbol.tolist()
tickers = [a for a in tickers if a not in tickers_all and "^" not in a and r"/" not in a]
tickers_all += tickers
# Download prices
full_data = {}
for ticker in tqdm(tickers + ref_index):
tckr = _download_one(ticker,
period="7y",
actions=True)
full_data[ticker] = tckr
ohlc = pd.concat(full_data.values(), axis=1,
keys=full_data.keys())
ohlc.columns = ohlc.columns.swaplevel(0, 1)
ohlc.sort_index(level=0, axis=1, inplace=True)
prices = ohlc["Adj Close"]
dividends = ohlc["Dividends"]
prices.to_csv(f"data/{project}/prices_daily.csv")
dividends.to_csv(f"data/{project}/dividends.csv")
statements = {}
tickers_done = []
for ticker in tqdm(tickers):
# Get statements
if ticker in tickers_done:
continue
yahoo_financials = YahooFinancials(ticker)
stmts_codes = ['income', 'cash', 'balance']
all_statement_data = yahoo_financials.get_financial_stmts('annual',
stmts_codes)
# build statements dictionnary
for a in all_statement_data.keys():
if a not in statements:
statements[a] = list()
for b in all_statement_data[a]:
try:
for result in all_statement_data[a][b]:
extracted_date = list(result)[0]
dataframe_row = list(result.values())[0]
dataframe_row['date'] = extracted_date
dataframe_row['symbol'] = b
statements[a].append(dataframe_row)
except Exception as e:
print("Error on " + ticker + " : " + a)
tickers_done.append(ticker)
with open('tmp.pickle', 'wb') as f:
pickle.dump([statements, tickers_done], f)
# save dataframes
for a in all_statement_data.keys():
df = pd.DataFrame(statements[a]).set_index('date')
df.to_csv(f"data/{project}/{a}.csv")
# Donwload shares
shares = []
tickers_done = []
for ticker in tqdm(tickers):
if ticker in tickers_done:
continue
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
if not d.ok:
time.sleep(300)
d = requests.get(f"https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{ticker}?symbol={ticker}&padTimeSeries=true&type=annualPreferredSharesNumber,annualOrdinarySharesNumber&merge=false&period1=0&period2=2013490868")
ctn = d.json()['timeseries']['result']
dct = dict()
for n in ctn:
type = n['meta']['type'][0]
dct[type] = dict()
if type in n:
for o in n[type]:
if o is not None:
dct[type][o['asOfDate']] = o['reportedValue']['raw']
df = pd.DataFrame.from_dict(dct)
df['symbol'] = ticker
shares.append(df)
tickers_done.append(ticker)
time.sleep(1)
# save dataframe
df = pd.concat(shares)
df['date'] = df.index
df.to_csv(f"data/{project}/shares.csv", index=False)
# https://query1.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/MSFT?symbol=MSFT&padTimeSeries=true&type=annualTreasurySharesNumber,trailingTreasurySharesNumber,annualPreferredSharesNumber,trailingPreferredSharesNumber,annualOrdinarySharesNumber,trailingOrdinarySharesNumber,annualShareIssued,trailingShareIssued,annualNetDebt,trailingNetDebt,annualTotalDebt,trailingTotalDebt,annualTangibleBookValue,trailingTangibleBookValue,annualInvestedCapital,trailingInvestedCapital,annualWorkingCapital,trailingWorkingCapital,annualNetTangibleAssets,trailingNetTangibleAssets,annualCapitalLeaseObligations,trailingCapitalLeaseObligations,annualCommonStockEquity,trailingCommonStockEquity,annualPreferredStockEquity,trailingPreferredStockEquity,annualTotalCapitalization,trailingTotalCapitalization,annualTotalEquityGrossMinorityInterest,trailingTotalEquityGrossMinorityInterest,annualMinorityInterest,trailingMinorityInterest,annualStockholdersEquity,trailingStockholdersEquity,annualOtherEquityInterest,trailingOtherEquityInterest,annualGainsLossesNotAffectingRetainedEarnings,trailingGainsLossesNotAffectingRetainedEarnings,annualOtherEquityAdjustments,trailingOtherEquityAdjustments,annualFixedAssetsRevaluationReserve,trailingFixedAssetsRevaluationReserve,annualForeignCurrencyTranslationAdjustments,trailingForeignCurrencyTranslationAdjustments,annualMinimumPensionLiabilities,trailingMinimumPensionLiabilities,annualUnrealizedGainLoss,trailingUnrealizedGainLoss,annualTreasuryStock,trailingTreasuryStock,annualRetainedEarnings,trailingRetainedEarnings,annualAdditionalPaidInCapital,trailingAdditionalPaidInCapital,annualCapitalStock,trailingCapitalStock,annualOtherCapitalStock,trailingOtherCapitalStock,annualCommonStock,trailingCommonStock,annualPreferredStock,trailingPreferredStock,annualTotalPartnershipCapital,trailingTotalPartnershipCapital,annualGeneralPartnershipCapital,trailingGeneralPartnershipCapital,annualLimitedPartnershipCapital,trailingLimitedPartnershipCapital,annualTotalLiabilitiesNetMinorityInterest,trailingTotalLiabilitiesNetMinorityInterest,annualTotalNonCurrentLiabilitiesNetMinorityInterest,trailingTotalNonCurrentLiabilitiesNetMinorityInterest,annualOtherNonCurrentLiabilities,trailingOtherNonCurrentLiabilities,annualLiabilitiesHeldforSaleNonCurrent,trailingLiabilitiesHeldforSaleNonCurrent,annualRestrictedCommonStock,trailingRestrictedCommonStock,annualPreferredSecuritiesOutsideStockEquity,trailingPreferredSecuritiesOutsideStockEquity,annualDerivativeProductLiabilities,trailingDerivativeProductLiabilities,annualEmployeeBenefits,trailingEmployeeBenefits,annualNonCurrentPensionAndOtherPostretirementBenefitPlans,trailingNonCurrentPensionAndOtherPostretirementBenefitPlans,annualNonCurrentAccruedExpenses,trailingNonCurrentAccruedExpenses,annualDuetoRelatedPartiesNonCurrent,trailingDuetoRelatedPartiesNonCurrent,annualTradeandOtherPayablesNonCurrent,trailingTradeandOtherPayablesNonCurrent,annualNonCurrentDeferredLiabilities,trailingNonCurrentDeferredLiabilities,annualNonCurrentDeferredRevenue,trailingNonCurrentDeferredRevenue,annualNonCurrentDeferredTaxesLiabilities,trailingNonCurrentDeferredTaxesLiabilities,annualLongTermDebtAndCapitalLeaseObligation,trailingLongTermDebtAndCapitalLeaseObligation,annualLongTermCapitalLeaseObligation,trailingLongTermCapitalLeaseObligation,annualLongTermDebt,trailingLongTermDebt,annualLongTermProvisions,trailingLongTermProvisions,annualCurrentLiabilities,trailingCurrentLiabilities,annualOtherCurrentLiabilities,trailingOtherCurrentLiabilities,annualCurrentDeferredLiabilities,trailingCurrentDeferredLiabilities,annualCurrentDeferredRevenue,trailingCurrentDeferredRevenue,annualCurrentDeferredTaxesLiabilities,trailingCurrentDeferredTaxesLiabilities,annualCurrentDebtAndCapitalLeaseObligation,trailingCurrentDebtAndCapitalLeaseObligation,annualCurrentCapitalLeaseObligation,trailingCurrentCapitalLeaseObligation,annualCurrentDebt,trailingCurrentDebt,annualOtherCurrentBorrowings,trailingOtherCurrentBorrowings,annualLineOfCredit,trailingLineOfCredit,annualCommercialPaper,trailingCommercialPaper,annualCurrentNotesPayable,trailingCurrentNotesPayable,annualPensionandOtherPostRetirementBenefitPlansCurrent,trailingPensionandOtherPostRetirementBenefitPlansCurrent,annualCurrentProvisions,trailingCurrentProvisions,annualPayablesAndAccruedExpenses,trailingPayablesAndAccruedExpenses,annualCurrentAccruedExpenses,trailingCurrentAccruedExpenses,annualInterestPayable,trailingInterestPayable,annualPayables,trailingPayables,annualOtherPayable,trailingOtherPayable,annualDuetoRelatedPartiesCurrent,trailingDuetoRelatedPartiesCurrent,annualDividendsPayable,trailingDividendsPayable,annualTotalTaxPayable,trailingTotalTaxPayable,annualIncomeTaxPayable,trailingIncomeTaxPayable,annualAccountsPayable,trailingAccountsPayable,annualTotalAssets,trailingTotalAssets,annualTotalNonCurrentAssets,trailingTotalNonCurrentAssets,annualOtherNonCurrentAssets,trailingOtherNonCurrentAssets,annualDefinedPensionBenefit,trailingDefinedPensionBenefit,annualNonCurrentPrepaidAssets,trailingNonCurrentPrepaidAssets,annualNonCurrentDeferredAssets,trailingNonCurrentDeferredAssets,annualNonCurrentDeferredTaxesAssets,trailingNonCurrentDeferredTaxesAssets,annualDuefromRelatedPartiesNonCurrent,trailingDuefromRelatedPartiesNonCurrent,annualNonCurrentNoteReceivables,trailingNonCurrentNoteReceivables,annualNonCurrentAccountsReceivable,trailingNonCurrentAccountsReceivable,annualFinancialAssets,trailingFinancialAssets,annualInvestmentsAndAdvances,trailingInvestmentsAndAdvances,annualOtherInvestments,trailingOtherInvestments,annualInvestmentinFinancialAssets,trailingInvestmentinFinancialAssets,annualHeldToMaturitySecurities,trailingHeldToMaturitySecurities,annualAvailableForSaleSecurities,trailingAvailableForSaleSecurities,annualFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,trailingFinancialAssetsDesignatedasFairValueThroughProfitorLossTotal,annualTradingSecurities,trailingTradingSecurities,annualLongTermEquityInvestment,trailingLongTermEquityInvestment,annualInvestmentsinJointVenturesatCost,trailingInvestmentsinJointVenturesatCost,annualInvestmentsInOtherVenturesUnderEquityMethod,trailingInvestmentsInOtherVenturesUnderEquityMethod,annualInvestmentsinAssociatesatCost,trailingInvestmentsinAssociatesatCost,annualInvestmentsinSubsidiariesatCost,trailingInvestmentsinSubsidiariesatCost,annualInvestmentProperties,trailingInvestmentProperties,annualGoodwillAndOtherIntangibleAssets,trailingGoodwillAndOtherIntangibleAssets,annualOtherIntangibleAssets,trailingOtherIntangibleAssets,annualGoodwill,trailingGoodwill,annualNetPPE,trailingNetPPE,annualAccumulatedDepreciation,trailingAccumulatedDepreciation,annualGrossPPE,trailingGrossPPE,annualLeases,trailingLeases,annualConstructionInProgress,trailingConstructionInProgress,annualOtherProperties,trailingOtherProperties,annualMachineryFurnitureEquipment,trailingMachineryFurnitureEquipment,annualBuildingsAndImprovements,trailingBuildingsAndImprovements,annualLandAndImprovements,trailingLandAndImprovements,annualProperties,trailingProperties,annualCurrentAssets,trailingCurrentAssets,annualOtherCurrentAssets,trailingOtherCurrentAssets,annualHedgingAssetsCurrent,trailingHedgingAssetsCurrent,annualAssetsHeldForSaleCurrent,trailingAssetsHeldForSaleCurrent,annualCurrentDeferredAssets,trailingCurrentDeferredAssets,annualCurrentDeferredTaxesAssets,trailingCurrentDeferredTaxesAssets,annualRestrictedCash,trailingRestrictedCash,annualPrepaidAssets,trailingPrepaidAssets,annualInventory,trailingInventory,annualInventoriesAdjustmentsAllowances,trailingInventoriesAdjustmentsAllowances,annualOtherInventories,trailingOtherInventories,annualFinishedGoods,trailingFinishedGoods,annualWorkInProcess,trailingWorkInProcess,annualRawMaterials,trailingRawMaterials,annualReceivables,trailingReceivables,annualReceivablesAdjustmentsAllowances,trailingReceivablesAdjustmentsAllowances,annualOtherReceivables,trailingOtherReceivables,annualDuefromRelatedPartiesCurrent,trailingDuefromRelatedPartiesCurrent,annualTaxesReceivable,trailingTaxesReceivable,annualAccruedInterestReceivable,trailingAccruedInterestReceivable,annualNotesReceivable,trailingNotesReceivable,annualLoansReceivable,trailingLoansReceivable,annualAccountsReceivable,trailingAccountsReceivable,annualAllowanceForDoubtfulAccountsReceivable,trailingAllowanceForDoubtfulAccountsReceivable,annualGrossAccountsReceivable,trailingGrossAccountsReceivable,annualCashCashEquivalentsAndShortTermInvestments,trailingCashCashEquivalentsAndShortTermInvestments,annualOtherShortTermInvestments,trailingOtherShortTermInvestments,annualCashAndCashEquivalents,trailingCashAndCashEquivalents,annualCashEquivalents,trailingCashEquivalents,annualCashFinancial,trailingCashFinancial&merge=false&period1=493590046&period2=1613490868
# https://query1.finance.yahoo.com/v8/finance/chart/MSFT?symbol=MSFT&period1=1550725200&period2=1613491890&useYfid=true&interval=1d&events=div
# https://query1.finance.yahoo.com/v10/finance/quoteSummary/MSFT?formatted=true&crumb=2M1BZy1YB7f&lang=en-US&region=US&modules=incomeStatementHistory,cashflowStatementHistory,balanceSheetHistory,incomeStatementHistoryQuarterly,cashflowStatementHistoryQuarterly,balanceSheetHistoryQuarterly&corsDomain=finance.yahoo.com
</code></pre>
<p>The screenshot of the error is:</p>
<p><a href="https://i.stack.imgur.com/PEgjO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PEgjO.png" alt="Error Screenshot" /></a></p>
<p>It refers to the <strong>line 51</strong> of the above code. I have tried multiple times, and check some related questions/answers here as well but have not any satisfied answer. There is another similar question but it has not any proper answer.
Any help in this regard would be highly appreciated.
Thanks in anticipation!</p>
|
[
{
"answer_id": 74654930,
"author": "e382df99a7950919789725ceeec126",
"author_id": 237209,
"author_profile": "https://Stackoverflow.com/users/237209",
"pm_score": 0,
"selected": false,
"text": "i18next changeLanguage i18next import * as i18n from 'i18next' changeLanguage i18n.changeLanguage i18next tsconfig.json compilerOptions tsconfig.json \"typeRoots\": [\"node_modules/@types\", \"./src/libdefs\"],\n i18next"
},
{
"answer_id": 74670689,
"author": "MaxPrilutskiy",
"author_id": 4446378,
"author_profile": "https://Stackoverflow.com/users/4446378",
"pm_score": 0,
"selected": false,
"text": "i18next @types/i18next package i18next npm install @types/i18next --save-dev\n i18next tsconfig.json \"types\" {\n \"compilerOptions\": {\n // Other compiler options...\n },\n \"types\": [\"i18next\"]\n}\n"
},
{
"answer_id": 74672796,
"author": "Midas",
"author_id": 20678816,
"author_profile": "https://Stackoverflow.com/users/20678816",
"pm_score": 2,
"selected": true,
"text": "import * as i18next from 'i18next/dist/cjs/i18next';\n \"i18next\": [\"node_modules/i18next/dist/cjs/i18next\"]\n"
},
{
"answer_id": 74673151,
"author": "Paiman Rasoli",
"author_id": 17462012,
"author_profile": "https://Stackoverflow.com/users/17462012",
"pm_score": 0,
"selected": false,
"text": "React-intl"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12078322/"
] |
74,565,861
|
<p>I want to make sure, that one of the arguments, passed when class creation is of certain type. Here is an example:</p>
<pre class="lang-py prettyprint-override"><code>from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class ListItems:
items: list | str | int | ListItems
class PList:
def __init__(self, name: str, items: ListItems):
self.type = "list"
self.name = name
self.items = items
a = PList('asd', ['asd'])
</code></pre>
<p>The idea was next: <code>items</code> can only be list of <code>string</code>, <code>int</code> data type <strong>or other list</strong> of <code>string</code> and <code>int</code>, and it's nested. For example:</p>
<pre><code>[] OK
[1,2,'asd'] OK
[[1,2,3],'asd',[]] OK
[{}] NOT OK
['test', [{}]] NOT OK
</code></pre>
<p>Is it possible to implement something like this in Python?</p>
<p>I am not really familiar with Python OOP, but from what I have found, there is no native implementation of interfaces and/or abstract class like in other programming languages.</p>
<p>PS:
The code you see, was just my attempt of implementation, it did not work.</p>
|
[
{
"answer_id": 74565929,
"author": "Nate",
"author_id": 19924402,
"author_profile": "https://Stackoverflow.com/users/19924402",
"pm_score": 0,
"selected": false,
"text": " def __init__(self, name: str, items: ListItems): items: ListItems items ListItems ListItems items: list[str|int] list List"
},
{
"answer_id": 74566007,
"author": "Amanda Woods",
"author_id": 19771135,
"author_profile": "https://Stackoverflow.com/users/19771135",
"pm_score": -1,
"selected": false,
"text": "class PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) is str or type(items) is int:\n self.items = items\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16732680/"
] |
74,565,895
|
<p>I have a problem in this recursive function that basically takes two numbers and returns the biggest one of them without using comparison (> || < ) operators, thing is, it returns dicremented values even though I held the starting values in a variable.</p>
<p>Here's my code:</p>
<pre><code>#include <stdio.h>
int WhoBig(int A, int B) {
int TrueA=A, TrueB=B;
if(A==0)
{
return TrueB;
}
else if(B==0)
{
return TrueA;
}
else
{
return WhoBig(A-1,B-1);
}
}
void main() {
printf("%d",WhoBig(9,2));
//Output:7
}
</code></pre>
|
[
{
"answer_id": 74565929,
"author": "Nate",
"author_id": 19924402,
"author_profile": "https://Stackoverflow.com/users/19924402",
"pm_score": 0,
"selected": false,
"text": " def __init__(self, name: str, items: ListItems): items: ListItems items ListItems ListItems items: list[str|int] list List"
},
{
"answer_id": 74566007,
"author": "Amanda Woods",
"author_id": 19771135,
"author_profile": "https://Stackoverflow.com/users/19771135",
"pm_score": -1,
"selected": false,
"text": "class PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) is str or type(items) is int:\n self.items = items\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20361438/"
] |
74,565,896
|
<p>I want to create a simple input component in Vue, <br> which if the <code>IsPassword</code> condition was true, set its <code>type="password"</code> and if it is not, set it to <code>type="text"</code>.<br>
<em>I'm probably making a mistake somewhere in the syntax because I'm getting <code>parsing javascript error</code></em></p>
<p>this is Simplified version of my code
<br>
<strong>App.vue</strong></p>
<pre><code>import InputText from "@/components/InputText.vue";
<template>
Username : <InputText/>
Password : <InputText :isPassword="true">
</template>
</code></pre>
<p><strong>InputText.vue</strong></p>
<pre><code><template>
<input :type="{IsPassword ? 'password':'text'}" value="Im getting error here">
</template>
<script>
export default {
props: {
IsPassword: Boolean
}
}
</script>
</code></pre>
|
[
{
"answer_id": 74565929,
"author": "Nate",
"author_id": 19924402,
"author_profile": "https://Stackoverflow.com/users/19924402",
"pm_score": 0,
"selected": false,
"text": " def __init__(self, name: str, items: ListItems): items: ListItems items ListItems ListItems items: list[str|int] list List"
},
{
"answer_id": 74566007,
"author": "Amanda Woods",
"author_id": 19771135,
"author_profile": "https://Stackoverflow.com/users/19771135",
"pm_score": -1,
"selected": false,
"text": "class PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) is str or type(items) is int:\n self.items = items\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19338216/"
] |
74,565,928
|
<p>I would like to send a post request. But I have to change the key.</p>
<pre><code>function call(obj) {
console.log("Call " + obj.value);
if (obj.value == 1)
{
$.post( "index.htm", { '"webdata".web[1].Taster': '1'} );
}
</code></pre>
<p>I would like to change [1] to a dynamic different number.
To take a car between with + + do not work.</p>
<p>Do you have any idea?
Thank you</p>
<p>Thanks for your help</p>
|
[
{
"answer_id": 74565929,
"author": "Nate",
"author_id": 19924402,
"author_profile": "https://Stackoverflow.com/users/19924402",
"pm_score": 0,
"selected": false,
"text": " def __init__(self, name: str, items: ListItems): items: ListItems items ListItems ListItems items: list[str|int] list List"
},
{
"answer_id": 74566007,
"author": "Amanda Woods",
"author_id": 19771135,
"author_profile": "https://Stackoverflow.com/users/19771135",
"pm_score": -1,
"selected": false,
"text": "class PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) is str or type(items) is int:\n self.items = items\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20593986/"
] |
74,565,931
|
<p>Whenever i add or update an object it goes straight to the local storage and it works fine. However when i refresh a page the data stored in LS is being replaced with an empty array. What am i doing wrong?</p>
<pre><code> const [data, setData] = useState<NoteType[]>([]);
useEffect(() => {
setData(JSON.parse(window.localStorage.getItem("notes") || "[]"));
}, []);
useEffect(() => {
window.localStorage.setItem("notes", JSON.stringify(data));
}, [data]);
const handleNoteSave = (text: string, id: string) => {
const updatedNote = data.map((note) => {
if (note.id === id) {
return { ...note, text };
}
return note;
});
setData(updatedNote);
};
const handleNoteAdd = () => {
setData((prevState) => [...prevState, { text: "", id: nanoid() }]);
};
</code></pre>
|
[
{
"answer_id": 74565929,
"author": "Nate",
"author_id": 19924402,
"author_profile": "https://Stackoverflow.com/users/19924402",
"pm_score": 0,
"selected": false,
"text": " def __init__(self, name: str, items: ListItems): items: ListItems items ListItems ListItems items: list[str|int] list List"
},
{
"answer_id": 74566007,
"author": "Amanda Woods",
"author_id": 19771135,
"author_profile": "https://Stackoverflow.com/users/19771135",
"pm_score": -1,
"selected": false,
"text": "class PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) is str or type(items) is int:\n self.items = items\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18367514/"
] |
74,565,948
|
<p>We would like to filter SKU's List which has <code>verificationData</code> data and <code>differenceInStock</code> difference greater than or Less than 0</p>
<p>Here is an example Data Set.</p>
<pre><code>[
{
"_id": "636e0beaa13ef73324e613f0",
"status": "ACTIVE",
"inventory": 132,
"parentCategory": [
"Salt"
],
"title": "Aashirvaad MRP: 28Rs Salt 27 kg Bopp Bag (Set of 1 kg x 27)",
"createdAt": "2022-11-11T08:46:34.950Z",
"updatedAt": "2022-11-24T17:43:27.361Z",
"__v": 3,
"verificationData": [
{
"_id": "637c57ebbe783a9a138fc2d3",
"verificationDate": "2022-11-22T05:02:35.155Z",
"items": {
"listingId": "636e0beaa13ef73324e613f0",
"phyiscalVerification": [
{
"verifiedBy": "634534e72ef6462fcb681a39",
"closingStock": 178,
"phyiscalStock": 178,
"differenceInStock": 0,
"verifiedAt": "2022-11-22T10:19:38.388Z",
"_id": "637ca23abe783a9a1394f402"
}
],
"_id": "637ca23abe783a9a1394f401"
},
"yearMonthDayUTC": "2022-11-22"
},
{
"_id": "637d9b65be783a9a13998726",
"verificationDate": "2022-11-23T04:02:45.804Z",
"items": {
"listingId": "636e0beaa13ef73324e613f0",
"phyiscalVerification": [
{
"verifiedBy": "634534e72ef6462fcb681a39",
"closingStock": 161,
"phyiscalStock": 167,
"differenceInStock": 6,
"verifiedAt": "2022-11-23T09:52:36.815Z",
"_id": "637ded64be783a9a13a29d55"
}
],
"_id": "637ded64be783a9a13a29d54"
},
"yearMonthDayUTC": "2022-11-23"
},
{
"_id": "637f0254be783a9a13a94354",
"verificationDate": "2022-11-24T05:34:12.995Z",
"items": {
"listingId": "636e0beaa13ef73324e613f0",
"phyiscalVerification": [
{
"verifiedBy": "634534e72ef6462fcb681a39",
"closingStock": 144,
"phyiscalStock": 146,
"differenceInStock": 2,
"verifiedAt": "2022-11-24T12:02:28.123Z",
"_id": "637f5d54be783a9a13b1039a"
}
],
"_id": "637f5d54be783a9a13b10399"
},
"yearMonthDayUTC": "2022-11-24"
},
{
"_id": "2022-11-25",
"yearMonthDayUTC": "2022-11-25",
"items": null
}
]
},
{
"_id": "62b5c39062ddb963fc64c42d",
"status": "ACTIVE",
"inventory": 10,
"parentCategory": [
"Salt"
],
"finalMeasurementUnit": "kg",
"finalMeasure": "1 kg",
"title": "Marvella Citric Acid Lemon Salt 1 kg Pouch (Set of 500 gm x 2)",
"createdAt": "2022-06-24T14:00:49.052Z",
"updatedAt": "2022-11-21T11:04:21.643Z",
"__v": 2,
"verificationData": [
{
"_id": "2022-11-22",
"yearMonthDayUTC": "2022-11-22",
"items": null
},
{
"_id": "2022-11-23",
"yearMonthDayUTC": "2022-11-23",
"items": null
},
{
"_id": "2022-11-24",
"yearMonthDayUTC": "2022-11-24",
"items": null
},
{
"_id": "2022-11-25",
"yearMonthDayUTC": "2022-11-25",
"items": null
}
]
}
]
</code></pre>
<p>This could have array of 100+ SKU's</p>
<p>Our Aggregate Functions is as Follows</p>
<pre><code>let reqData = await userListing.aggregate([
{
$match: {
warehouseId: { $eq: ObjectId(warehouseId) },
parentCategory: { $in: catList },
isWarehouseListing: { $eq: true },
isBlocked: { $ne: true },
isArchived: { $ne: true },
},
},
{ $sort: { whAddedAt: -1 } },
{
$lookup: {
from: "listingstockverifications",
let: { listId: "$_id" },
pipeline: [
{
$match: {
verificationDate: {
$gte: newFromDate,
$lt: newToDate,
},
},
},
{
$project: {
verificationDate: 1,
items: {
$filter: {
input: "$items",
cond: {
$and: [
/* {
"$$this.phyiscalVerification": {
$filter: {
input: "$$this.phyiscalVerification",
as: "psitem",
cond: { $gt: [ "$$psitem.differenceInStock", 0 ] },
},
},
}, */
{
$eq: ["$$this.listingId", "$$listId"],
},
],
},
},
},
yearMonthDayUTC: {
$dateToString: {
format: "%Y-%m-%d",
date: "$verificationDate",
},
},
},
},
{ $unwind: "$items" },
],
as: "stockVerification",
},
},
{
$addFields: {
verificationData: {
$map: {
input: dummyArray,
as: "date",
in: {
$let: {
vars: {
dateIndex: {
$indexOfArray: [
"$stockVerification.yearMonthDayUTC",
"$$date",
],
},
},
in: {
$cond: {
if: { $ne: ["$$dateIndex", -1] },
then: {
$arrayElemAt: ["$stockVerification", "$$dateIndex"],
},
else: {
_id: "$$date",
yearMonthDayUTC: "$$date",
items: null,
},
},
},
},
},
},
},
},
},
{
$project: {
stockVerification: 0,
},
},
]);
</code></pre>
<p>At Last now we would like to filter the SKU List the which has following Data</p>
<p><code>verificationData[].items.phyiscalVerification[].differenceInStock is Greater than or Less than 0 </code></p>
<p>Expected Output in the following Exmaple would be 1st SKUs
as 2nd SKU does not have any Item Data
and even if in 3rd SKU if we got Item Data but should match the following condition</p>
<p><code>verificationData[].items.phyiscalVerification[].differenceInStock is Greater than or Less than 0 </code></p>
<p>Thank you for taking your time to read and support.</p>
|
[
{
"answer_id": 74565929,
"author": "Nate",
"author_id": 19924402,
"author_profile": "https://Stackoverflow.com/users/19924402",
"pm_score": 0,
"selected": false,
"text": " def __init__(self, name: str, items: ListItems): items: ListItems items ListItems ListItems items: list[str|int] list List"
},
{
"answer_id": 74566007,
"author": "Amanda Woods",
"author_id": 19771135,
"author_profile": "https://Stackoverflow.com/users/19771135",
"pm_score": -1,
"selected": false,
"text": "class PList:\n def __init__(self, name, items):\n self.type = 'list'\n self.name = name\n if type(items) is list or type(items) is str or type(items) is int:\n self.items = items\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9919277/"
] |
74,565,953
|
<p>I have a column in my pandas dataframe with the following values that represent hours worked in a week.</p>
<pre><code>0 40
1 40h / week
2 46.25h/week on average
3 11
</code></pre>
<p>I would like to check every row, and if the length of the value is larger than 2 digits - extract the number of hours only from it.
I have tried the following:</p>
<pre><code>df['Hours_per_week'].apply(lambda x: (x.extract('(\d+)') if(len(str(x)) > 2) else x))
</code></pre>
<p>However I am getting the <strong>AttributeError: 'str' object has no attribute 'extract'</strong> error.</p>
|
[
{
"answer_id": 74566027,
"author": "Bill",
"author_id": 1609514,
"author_profile": "https://Stackoverflow.com/users/1609514",
"pm_score": 0,
"selected": false,
"text": "df['Hours_per_week'].str.extract('(\\d+)')\n"
},
{
"answer_id": 74566048,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 0,
"selected": false,
"text": "\\d+\\.?\\d+ >>> s = pd.Series(['40', '40h / week', '46.25h/week on average', '11'])\n>>> s.str.extract(\"(\\d+\\.?\\d+)\")\n 0\n0 40\n1 40\n2 46.25\n3 11\n"
},
{
"answer_id": 74566067,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "h df['Hours_per_week'].str.extract(r'(\\d{2}\\.?\\d*)h', expand=False)\n 0 NaN\n1 40\n2 46.25\n3 NaN\nName: Hours_per_week, dtype: object\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19685776/"
] |
74,565,989
|
<p>I am trying it iterate through an array with the map function. I have the key property on the children. I am still getting the error ```Warning: Each child in a list should have a unique "key" prop.'''.
When I comment out the rating property in the objects, in my array, the error goes away. The rating property is used in the 'rating' function to create a 'star rating' with an svg image. The ratings function is called in the JSX, within the map function.</p>
<pre class="lang-js prettyprint-override"><code>const Reviews = () => {
const reviews = [
{
id: 1,
rating: 3,
image: "/images/reviews/one.jpg",
name: "Adam Jarod",
jobTitle: "Sales manager",
review:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur necessitatibus voluptatem aliquid alias quia beatae non quidem dolore praesentium",
},
{
id: 2,
rating: 4,
image: "/images/reviews/two.jpg",
name: "Emily Rees ",
jobTitle: "Marketing Specialist",
review:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur necessitatibus voluptatem aliquid alias quia beatae non quidem dolore praesentium",
},
{
id: 3,
rating: 5,
image: "/images/reviews/three.jpg",
name: "John Smith",
jobTitle: "Office Assistant",
review:
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur necessitatibus voluptatem aliquid alias quia beatae non quidem dolore praesentium",
},
];
const ratings = (review) => {
let stars = [];
for (let i = 0; i < review.rating; i++) {
stars.push(React.createElement("img", { src: "/images/star.svg" }));
}
return stars;
};
return (
<section className="reviews">
<h2 className="subtitle">What our clients say</h2>
<h1 className="title">Reviews</h1>
<div className="reviews__cards">
{reviews &&
reviews.map((review) => {
return (
<div key={review.id} className="review-card">
<div className="avatar-name">
<div className="avatar">
<img src={review.image} alt="Client" />
</div>
<div className="name">
<h1>{review.name}</h1>
<h2>{review.jobTitle}</h2>
</div>
<div className="quote-icon"></div>
</div>
<div className="review-body">
<div className="review-body__rating">{ratings(review)}</div>
<div className="review-body__text">
<p>{review.review}</p>
</div>
</div>
</div>
);
})}
<div className="reviews__nav-buttons">
<div className="left-arrow">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
className="w-6 h-6"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M19.5 12h-15m0 0l6.75 6.75M4.5 12l6.75-6.75"
/>
</svg>
</div>
<div className="right-arrow">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
className="w-6 h-6"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75"
/>
</svg>
</div>
</div>
</div>
</section>
);
};
</code></pre>
|
[
{
"answer_id": 74566027,
"author": "Bill",
"author_id": 1609514,
"author_profile": "https://Stackoverflow.com/users/1609514",
"pm_score": 0,
"selected": false,
"text": "df['Hours_per_week'].str.extract('(\\d+)')\n"
},
{
"answer_id": 74566048,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 0,
"selected": false,
"text": "\\d+\\.?\\d+ >>> s = pd.Series(['40', '40h / week', '46.25h/week on average', '11'])\n>>> s.str.extract(\"(\\d+\\.?\\d+)\")\n 0\n0 40\n1 40\n2 46.25\n3 11\n"
},
{
"answer_id": 74566067,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "h df['Hours_per_week'].str.extract(r'(\\d{2}\\.?\\d*)h', expand=False)\n 0 NaN\n1 40\n2 46.25\n3 NaN\nName: Hours_per_week, dtype: object\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15611155/"
] |
74,565,992
|
<p>I want to create a dockerfile which contains 2 stages.
The first stage is to set up a MySQL server and the second stage is to start a backend service that accesses the server.
The problem is that the backend service stops when no MySQL server is available. Is there a way to make the stage dependent on the first stage being started?
what is a little strange is that when i create the dockerfile with the database at the top, the log of the backend is displayed. If the backend is on top, the log of the MySQL is displayed when starting.</p>
<p>Actual Dockerfile:</p>
<pre><code>FROM mysql:latest AS BackendDatabase
RUN chown -R mysql:root /var/lib/mysql/
ARG MYSQL_DATABASE="DienstplanverwaltungDatabase"
ARG MYSQL_USER="user"
ARG MYSQL_PASSWORD="password"
ARG MYSQL_ROOT_PASSWORD="password"
ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
EXPOSE 3306
FROM openjdk:10-jre-slim AS Backend
LABEL description="Backend Dienstplanverwaltung"
LABEL maintainer="Martin"
COPY ./SpringDienstplanverwaltung/build/libs/dienstplanverwaltung-0.0.1-SNAPSHOT.jar /usr/local/app.jar
EXPOSE 8080
ENTRYPOINT java -jar /usr/local/app.jar
</code></pre>
|
[
{
"answer_id": 74566027,
"author": "Bill",
"author_id": 1609514,
"author_profile": "https://Stackoverflow.com/users/1609514",
"pm_score": 0,
"selected": false,
"text": "df['Hours_per_week'].str.extract('(\\d+)')\n"
},
{
"answer_id": 74566048,
"author": "Grzegorz Skibinski",
"author_id": 11610186,
"author_profile": "https://Stackoverflow.com/users/11610186",
"pm_score": 0,
"selected": false,
"text": "\\d+\\.?\\d+ >>> s = pd.Series(['40', '40h / week', '46.25h/week on average', '11'])\n>>> s.str.extract(\"(\\d+\\.?\\d+)\")\n 0\n0 40\n1 40\n2 46.25\n3 11\n"
},
{
"answer_id": 74566067,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "h df['Hours_per_week'].str.extract(r'(\\d{2}\\.?\\d*)h', expand=False)\n 0 NaN\n1 40\n2 46.25\n3 NaN\nName: Hours_per_week, dtype: object\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74565992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15783873/"
] |
74,566,024
|
<p>I have an express app with a simple GET with axios (1.2.0):</p>
<pre><code>const result: AxiosResponse = await axios.get('https://jsonplaceholder.typicode.com/posts')
</code></pre>
<p>The result.data ends up a cryptic, badly encoded string:</p>
<pre><code>k�H���>������T��N.���r�H�v �_"9'?1���J��\���LA. ��H���!�b�R� 9�܅��ڹ�K�}��%��A�v�Q*�g�dwf� ..goes long
</code></pre>
<p>I have tried with different configs added to the request but no luck.
Also couldn't find any related posts elsewhere.</p>
<p>Why would this be? How could I fix it?</p>
|
[
{
"answer_id": 74566313,
"author": "Amal",
"author_id": 3520225,
"author_profile": "https://Stackoverflow.com/users/3520225",
"pm_score": 0,
"selected": false,
"text": "resp = await fetch(\"https://jsonplaceholder.typicode.com/posts\").then(res=> res.json())\n axios.default.get(\"https://reddit.com/r/android.json\") \n"
},
{
"answer_id": 74567911,
"author": "Bench Vue",
"author_id": 8054998,
"author_profile": "https://Stackoverflow.com/users/8054998",
"pm_score": 4,
"selected": true,
"text": "Accept-Encoding gzip const axios = require('axios')\n\nconst getTitles = async () => {\n try {\n const resp = await axios.get(\n 'https://jsonplaceholder.typicode.com/posts',\n {\n headers: {\n 'Accept-Encoding': 'application/json',\n }\n }\n );\n console.log(JSON.stringify(resp.data, null, 4));\n } catch (err) {\n // Handle Error Here\n console.error(err);\n }\n};\n\ngetTitles();\n $ node titles.js\n[\n {\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"sunt aut facere repellat provident occaecati excepturi optio r\neprehenderit\",\n \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et\ncum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem\neveniet architecto\"\n },\n {\n \"userId\": 1,\n \"id\": 2,\n \"title\": \"qui est esse\",\n \"body\": \"est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor b\neatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut\n reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla\"\n },\n removed\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/494659/"
] |
74,566,043
|
<p>I have a strange issue with <code>SourceTree</code>. I merged my feature branch with the <code>development</code> branch and it was ok. No problem.</p>
<p>Then I merged the <code>development</code> to the <code>main</code> branch. It says conflicts, but it doesn't show any conflicted files whatsoever. When I do continue the merging, it merged successfully, without any changes detected from my feature branch.</p>
<p>I realized it after a while because when I connect to the production DB (which I usually don't do), it shows a different schema than my local main branch. But when I tried to merge the development branch again, it doesn't pull the feature changes that I worked on. Anyone can explain this?</p>
<p><a href="https://i.stack.imgur.com/bvZJK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bvZJK.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74566313,
"author": "Amal",
"author_id": 3520225,
"author_profile": "https://Stackoverflow.com/users/3520225",
"pm_score": 0,
"selected": false,
"text": "resp = await fetch(\"https://jsonplaceholder.typicode.com/posts\").then(res=> res.json())\n axios.default.get(\"https://reddit.com/r/android.json\") \n"
},
{
"answer_id": 74567911,
"author": "Bench Vue",
"author_id": 8054998,
"author_profile": "https://Stackoverflow.com/users/8054998",
"pm_score": 4,
"selected": true,
"text": "Accept-Encoding gzip const axios = require('axios')\n\nconst getTitles = async () => {\n try {\n const resp = await axios.get(\n 'https://jsonplaceholder.typicode.com/posts',\n {\n headers: {\n 'Accept-Encoding': 'application/json',\n }\n }\n );\n console.log(JSON.stringify(resp.data, null, 4));\n } catch (err) {\n // Handle Error Here\n console.error(err);\n }\n};\n\ngetTitles();\n $ node titles.js\n[\n {\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"sunt aut facere repellat provident occaecati excepturi optio r\neprehenderit\",\n \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et\ncum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem\neveniet architecto\"\n },\n {\n \"userId\": 1,\n \"id\": 2,\n \"title\": \"qui est esse\",\n \"body\": \"est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor b\neatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut\n reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla\"\n },\n removed\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137814/"
] |
74,566,071
|
<p>I am trying to create a recipe handler using arrays and read CSV files, and i am trying from the HMI to create a dialog browser to open a specific folder and then select any <code>.csv</code> file and load it to the array, but I can not find ANY information about it. Does anyone have any info if its possible to do?</p>
<p>I have been searching google a lot and I have been trying to convert code from other languages but I can not get it to work.</p>
<p>I have also tried to make a button to open ANY csv file from the folder as well but I can not get that to work either. As of now I have hardcoded the file to open and that works. But in production the file names will change from every file.</p>
<p>I really hope someone have any solution to this</p>
|
[
{
"answer_id": 74569736,
"author": "Roald",
"author_id": 6329629,
"author_profile": "https://Stackoverflow.com/users/6329629",
"pm_score": 1,
"selected": false,
"text": ".txtrecipe"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15596972/"
] |
74,566,076
|
<p>I've got a load of imported data but the main id keys of the object aren't surrounded in quotation marks and so aren't valid javascript.</p>
<p>Here's a sample of some of the data I have:</p>
<pre><code>
8ae3fcef-d1f5-43e4-9df0-b1861117c2f2: {
id: "8ae3fcef-d1f5-43e4-9df0-b1861117c2f2",
randomNumber: null,
openSearchId: null,
facilityId: "dd4bf527-d395-40df-a079-6ed9c73272d9",
spaceId: "9672350c-8b0e-4a99-a836-16a8f1e11667",
bucket: "ist1-tenant-1af9e2a9-41c8-45c4-9d0d-fe25a1d9b988",
key: "8ae3fcef-d1f5-43e4-9df0-b1861117c2f2/7ae3fcef-d1f5-43e4-9df0-b1861117c2f2_1662040410090952011.jpeg"
},
8dc3d....... etc
</code></pre>
<p>What I figure I need to do is target something that is:</p>
<ul>
<li>36 characters long</li>
<li>contains numbers, letters and hyphens</li>
<li>not starting or ending with quotation marks</li>
<li>has a colon afterwards.</li>
</ul>
<p>I want to use find and replace in vscode to target and replace what i need.</p>
<p>I've tried to check that the first character isn't " and that all 36 characters are letters, numbers or a hyphen. Closest i've come so far is this (it looks like it checks the first letter and then the following ones so I had to put 35 for it to not break completely):</p>
<p><code>[^" ][A-Za-z0-9\-]{35}</code></p>
<p>However that also gives me all of the ones (and other unrelated values) that are surrounded by "". I've also checked various other threads but i can't figure it out, can anyone offer any guidance?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74571036,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 1,
"selected": false,
"text": "(?<!\\S)(?=[a-f0-9-]{36}:)[a-f0-9]+(?:-[a-f0-9]+){2,}\n (?<!\\S) (?=[a-f0-9-]{36}:) [a-f0-9]+(?:-[a-f0-9]+){2,} \"$0\"\n"
},
{
"answer_id": 74578660,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 0,
"selected": false,
"text": "^([A-Za-z0-9\\-]{36}):\n \"$1\":\n $1"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13039295/"
] |
74,566,105
|
<p>I've got stuck with automatical closing of the <code>MessageBox</code> after expiration of the timer. I use <code>static</code> variable of type <code>Timer</code>(not <code>System.Windows.Forms.Timer</code>) which is defined in the special <code>class</code>(definition of the <code>class</code> is not <code>static</code>).</p>
<p>Timer is calling with the help of the reference to name of the class because of <code>static</code> keyword. My <code>class</code> where this timer defined as <code>static</code> called <code>Helper</code>. So the calling I produce using next code</p>
<pre><code>Helper.timer.Interval = 300000;
Helper.timer.Enable = true;
</code></pre>
<p>timer is the name of this variable</p>
<p>The task is to handle time when the <code>MessageBox</code> appeared and after the time expiry, close this <code>MessageBox</code> automatically if none of the buttons inside it weren't clicked. Is it possible to do this operation without using and defining <code>AutoClosingMessageBox</code> class like I've seen in the simular questions?</p>
<p>I've got tried some of methods including checking whether user clicked some of the buttons of <code>MessageBox</code> but it didn't give me a required result.</p>
<p>I would be grateful if someone could show me the realization :) If it's required I can fill up the question with the code template of my whole project. This all I need to create on the C# programming language.</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 74567622,
"author": "eloiz",
"author_id": 16756296,
"author_profile": "https://Stackoverflow.com/users/16756296",
"pm_score": 0,
"selected": false,
"text": "public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n\n private Timer CloseTimer { get; } = new Timer();\n private string Caption { get; set; }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n CloseTimer.Tick += CloseTimerOnTick;\n CloseTimer.Interval = 100;\n }\n\n private void CloseTimerOnTick(object sender, EventArgs e)\n {\n // find window\n var mbWnd = FindWindow(\"#32770\", Caption);\n // check window\n if (mbWnd == IntPtr.Zero)\n {\n // stop timer\n CloseTimer.Enabled = false;\n }\n else\n {\n // check timeout\n if ((DateTime.Now - Time).TotalMilliseconds < Timeout)\n return;\n // close\n SendMessage(mbWnd, 0x0010, IntPtr.Zero, IntPtr.Zero);\n // stop timer\n CloseTimer.Enabled = false;\n }\n }\n\n private void btMessage_Click(object sender, EventArgs e)\n {\n Show(@\"Caption\", @\"Auto close message\", 3000);\n }\n\n private void Show(string caption, string message, int timeout)\n {\n // start\n CloseTimer.Enabled = true;\n // set timeout\n Timeout = timeout;\n // set time\n Time = DateTime.Now;\n // set caption\n Caption = caption;\n // show \n MessageBox.Show(message, Caption);\n }\n\n [DllImport(\"user32.dll\", SetLastError = true)]\n private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n}\n"
},
{
"answer_id": 74603316,
"author": "IVSoftware",
"author_id": 5438626,
"author_profile": "https://Stackoverflow.com/users/5438626",
"pm_score": 1,
"selected": false,
"text": "MessageBox owner Show Form Task.Delay public MainForm()\n{\n InitializeComponent();\n buttonHelp.Click += onHelp;\n}\n\nprivate async void onHelp(object sender, EventArgs e)\n{\n var owner = new Form { Visible = false };\n // Force the creation of the window handle.\n // Otherwise the BeginInvoke will not work.\n var handle = owner.Handle;\n owner.BeginInvoke((MethodInvoker)delegate \n {\n MessageBox.Show(owner, text: \"Help message\", \"Timed Message\");\n });\n await Task.Delay(TimeSpan.FromSeconds(2));\n owner.Dispose();\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19870246/"
] |
74,566,108
|
<p>I'm trying to get the growth (in %) between two values at different period. Here is how my DataFrame looks like:</p>
<pre><code> sessionSource dateRange activeUsers
0 instagram.com current 5
1 instagram.com previous 0
2 l.instagram.com current 83
3 l.instagram.com previous 11
4 snapchat.com current 2
5 snapchat.com previous 1
</code></pre>
<p>What I'm trying to get is:</p>
<pre><code> sessionSource dateRange activeUsers Growth
0 instagram.com current 5 xx%
2 l.instagram.com current 83 xx%
4 snapchat.com current 2 xx%
</code></pre>
<p>I'm not a Pandas expert, I tried few things but nothing came close to what I need.</p>
<p>Thanks a lot for any help.</p>
|
[
{
"answer_id": 74566184,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "(df.sort_values(by=['sessionSource', 'dateRange'],\n ascending=[True, False])\n .groupby('sessionSource', as_index=False)\n .agg({'dateRange': 'first', 'activeUsers': lambda s: s.pct_change().dropna().mul(100)})\n )\n sessionSource dateRange activeUsers\n0 instagram.com previous inf\n1 l.instagram.com previous 654.545455\n2 snapchat.com previous 100.000000\n"
},
{
"answer_id": 74566189,
"author": "Alex.Kh",
"author_id": 10982177,
"author_profile": "https://Stackoverflow.com/users/10982177",
"pm_score": 2,
"selected": true,
"text": "pandas.Series.pct_change() # sort values before to make sure the order is maintained\ndf = df.sort_values(by=[\"sessionSource\", \"dateRange\"], ascending=False)\ndf['Growth']= (df.groupby('sessionSource')['activeUsers'].apply(pd.Series.pct_change))\n#drop na from the unavailable results and convert to %\ndf[\"growth\"] = (df[\"growth\"].dropna()*100).round(2)\n\n s = pd.Series([90, 91, 85])\ns\n0 90\n1 91\n2 85\ndtype: int64\n\ns.pct_change()\n0 NaN\n1 0.011111\n2 -0.065934\ndtype: float64\n group_by pct_change"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4300586/"
] |
74,566,111
|
<p>Currently struggling to center two columns that contain text, specifically two lists.</p>
<p>The idea is to have two columns on the same row with the two lists centered, and their respecitve list items aligned like normal bullet points.</p>
<p>Any advice would be appreciated.</p>
<p>Code here:</p>
<pre><code>
</code></pre>
<pre><code><div class="container d-none d-md-block text-center">
<div class="row">
<div class="col">
<div class="row">
<h4 style="color:#2CA851;"><strong>Premium</strong></h4>
</div>
<div class="row">
<h4 style="color:#2CA851;">Academic Advantage</h4>
</div>
<ul class="row list-group list-unstyled ">
<li class="row p-1 list-group-item border-0">
<span><i class="h5 fa fa-check-circle px-1" style="color:#2CA851;" ></i>Unlimited A+ Exam Focused Revision Notes.</span>
</li>
<li class="row p-1 list-group-item border-0">
<span><i class="h5 fa fa-check-circle px-1" style="color:#2CA851;" ></i>Past Examinations and Questions by Topic.</span>
</li>
<li class="row p-1 list-group-item border-0">
<span><i class="h5 fa fa-check-circle px-1" style="color:#2CA851;" ></i>A+ Sample Essays, Quizzes, and Math Content.</span>
</li>
</ul>
</div>
<div class="col">
<div class="row">
<h4 style="color:#EF6F5E;"><strong>Limited Access</strong></h4>
</div>
<div class="row">
<h4 style="color:#EF6F5E;">Ordinary Outcome</h4>
</div>
<ul class=" row list-group list-unstyled">
<li class="row p-1 list-group-item border-0" style="color: #001847;">
<span><i class="h5 fa fa-times-circle px-1" style="color:#EF6F5E;"></i>Restricted Access. Limited Features.</span>
</li>
<li class="row p-1 list-group-item border-0">
<span><i class="h5 fa fa-times-circle px-1" style="color:#EF6F5E;"></i>Less than 10% of Premium Material.</span>
</li>
<li class="row p-1 list-group-item border-0">
<span><i class="h5 fa fa-times-circle px-1" style="color:#EF6F5E;"></i>Older Content & Legacy Features.</span>
</li>
</ul>
</div>
</div>
</div>
</code></pre>
<pre><code>
</code></pre>
<p><a href="https://i.stack.imgur.com/nrKAs.png" rel="nofollow noreferrer">Current attempt col-6 </a></p>
<p>This uses col-6 for each column and doesn't center properly.
Using text-center on the container for this row yeilds the following.</p>
<p><a href="https://i.stack.imgur.com/0M2RP.png" rel="nofollow noreferrer">Using text-center</a>
However this issue with this is that now the icons for each list item are miss-aligned.</p>
<p><strong>EDITS:</strong>
<a href="https://i.stack.imgur.com/GDOjl.png" rel="nofollow noreferrer">Using justify-content-center recommended by @surya-prima-siregar and @harvir</a>
This is closer to a solution however I'd still like for these lists to be centered based on the buttons below, instead of appearing at the start of each button.</p>
<p>Huge thanks to @alexandra-batrak for the solution
<a href="https://i.stack.imgur.com/2HvRP.png" rel="nofollow noreferrer">See the answer by @alexandra-batrak below</a></p>
|
[
{
"answer_id": 74567627,
"author": "Alexandra Batrak",
"author_id": 8870249,
"author_profile": "https://Stackoverflow.com/users/8870249",
"pm_score": 1,
"selected": true,
"text": "row <div class=\"container d-none d-md-block\" style=\"height: 400px;\">\n <div class=\"row\">\n <div class=\"col\">\n <h4 style=\"color:#2CA851;\"><strong>Premium</strong></h4> \n <h4 style=\"color:#2CA851;\">Academic Advantage</h4>\n <ul class=\"list-group list-unstyled \">\n <li class=\"p-1 list-group-item border-0\">\n <span><i class=\"h5 fa fa-check-circle px-1\" style=\"color:#2CA851;\"></i>Unlimited A+ Exam Focused Revision Notes.</span>\n </li>\n <li class=\"p-1 list-group-item border-0\">\n <span><i class=\"h5 fa fa-check-circle px-1\" style=\"color:#2CA851;\"></i>Past Examinations and Questions by Topic.</span>\n </li>\n <li class=\"p-1 list-group-item border-0\">\n <span><i class=\"h5 fa fa-check-circle px-1\" style=\"color:#2CA851;\"></i>A+ Sample Essays, Quizzes, and Math Content.</span>\n </li>\n </ul>\n </div>\n <div class=\"col\">\n <h4 style=\"color:#EF6F5E;\"><strong>Limited Access</strong</h4> \n <h4 style=\"color:#EF6F5E;\">Ordinary Outcome</h4>\n <ul class=\" list-group list-unstyled\">\n <li class=\" p-1 list-group-item border-0\" style=\"color: #001847;\">\n <span><i class=\"h5 fa fa-times-circle px-1\" style=\"color:#EF6F5E;\"></i>Restricted Access. Limited Features.</span>\n\n </li>\n <li class=\"p-1 list-group-item border-0\">\n <span><i class=\"h5 fa fa-times-circle px-1\" style=\"color:#EF6F5E;\"></i>Less than 10% of Premium Material.</span>\n\n </li>\n <li class=\"p-1 list-group-item border-0\">\n <span><i class=\"h5 fa fa-times-circle px-1\" style=\"color:#EF6F5E;\"></i>Older Content & Legacy Features.</span>\n\n </li>\n </ul>\n </div>\n</div>\n .row { \n display: flex; // it should already be in bootstrap\n justify-content: space-around; \n margin: auto; // helps to get them a bit closer by removing bootstrap margin\n}\n\n.col {\n display: flex;\n flex-direction: column;\n align-content: flex-start;\n align-items: center;\n}\n text-centered"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19001164/"
] |
74,566,125
|
<p>Every time i am geting else condition as true. If i pass input string as "ama" then code should give input string is palindrom. But i am getting string is not palindrom.
Input: ami
output: ami
Expected:string is palindrom</p>
<p>Input: amit
output: tima
Expected:string is n palindrom</p>
<pre><code>def str_rev (input_str):
print("input_str:", input_str)
rev_str = " "
for i in (input_str):
rev_str = i + rev_str
print("inp_str:", input_str)
print("rev_str:", rev_str)
if (input_str == rev_str):
print("string is palindrom")
else:
print("string is not palindrom")
return rev_str
str = input ("Enter the string:")
print("org string:", str)
final_str= str_rev (str)
print("reverse string:", final_str)
</code></pre>
|
[
{
"answer_id": 74566153,
"author": "Trimonu",
"author_id": 15324906,
"author_profile": "https://Stackoverflow.com/users/15324906",
"pm_score": 1,
"selected": false,
"text": "ami"
},
{
"answer_id": 74566173,
"author": "GaryMBloom",
"author_id": 3159059,
"author_profile": "https://Stackoverflow.com/users/3159059",
"pm_score": 1,
"selected": true,
"text": "rev_str = \" \"\n rev_str = \"\"\n .strip() ' hi '.strip() --> 'hi'\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594077/"
] |
74,566,130
|
<pre><code>const obj = {A: 2}
module.exports = obj
</code></pre>
<p>If another module imports from the above module, will it get a deep copy of <code>obj</code> or just a reference?</p>
|
[
{
"answer_id": 74566152,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "obj exports require"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5432156/"
] |
74,566,140
|
<p>I like to reshape a time series data from long to wide format , with columns such as <code>StartTime</code> and <code>StopTime</code>. All variables measured during the same time interval (<code>StartTime</code>, <code>StopTime</code>) to be in the same line.</p>
<p>For example if this is my dataset</p>
<pre><code> Id Time Status Col1
10 2012 4 2
11 2009 2 5
11 2010 2 5
12 2004 2 2
12 2009 2 3
12 2011 2 1
12 2018 2 3
17 2018 2 3
17 2020 2 1
</code></pre>
<p>Expecting a dataset like this</p>
<pre><code> Id From To Status Col1
10 2012 2012 4 2
11 2009 2010 2 5
12 2004 2009 2 2
12 2009 2011 2 3
12 2011 2018 2 1
12 2018 2018 2 3
17 2018 2020 2 3
17 2020 2020 2 1
</code></pre>
<p>Thanks in advance for the help.</p>
|
[
{
"answer_id": 74566152,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "obj exports require"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18795729/"
] |
74,566,143
|
<pre><code>
count = defaultdict(int, sum(map(Counter, board), Counter()))
</code></pre>
<p>board is a 2d array: <code>List[List[str]]</code></p>
<p>I can understand that this one-line code is to count the frequency of the board,
and we can write this way:</p>
<pre><code>count = defaultdict(int)
for i in range(len(board)):
for j in range(len(board[0]):
count[board[i][j]] += 1
</code></pre>
<p>Could you help explain the one-line logic? Thank you!</p>
|
[
{
"answer_id": 74566214,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": false,
"text": "board board = [[\"hello\", \"hello\"], [\"world\", \"hello\"]]\n map >>> list(map(Counter, board))\n[Counter({'hello': 2}), Counter({'world': 1, 'hello': 1})]\n >>> sum(map(Counter, board))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unsupported operand type(s) for +: 'int' and 'Counter'\n 0 >>> sum(map(Counter, board), Counter())\nCounter({'hello': 3, 'world': 1})\n defaultdict"
},
{
"answer_id": 74566363,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
"author_profile": "https://Stackoverflow.com/users/5014455",
"pm_score": 1,
"selected": false,
"text": "sum(map(Counter, board), Counter()) Counter board sum In [5]: rs = [range(i, i+1000) for i in range(1, 10_000, 1000)]\n\nIn [6]: rs\nOut[6]:\n[range(1, 1001),\n range(1001, 2001),\n range(2001, 3001),\n range(3001, 4001),\n range(4001, 5001),\n range(5001, 6001),\n range(6001, 7001),\n range(7001, 8001),\n range(8001, 9001),\n range(9001, 10001)]\n\nIn [7]: %timeit sum(map(Counter, rs), Counter())\n15.2 ms ± 155 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [8]: %%timeit\n ...: counts = Counter()\n ...: for r in rs:\n ...: counts.update(r)\n ...:\n500 µs ± 5.51 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n map In [15]: %timeit sum(map(Counter, rs), Counter())\n60.9 ms ± 1.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\nIn [16]: %%timeit\n ...: counts = Counter()\n ...: for r in rs:\n ...: counts.update(r)\n ...:\n1.01 ms ± 8.37 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n map In [19]: rs = [range(i, i+1000) for i in range(1, 40_000, 1000)]\n\nIn [20]: %timeit sum(map(Counter, rs), Counter())\n244 ms ± 8.96 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nIn [21]: %%timeit\n ...: counts = Counter()\n ...: for r in rs:\n ...: counts.update(r)\n ...:\n2.13 ms ± 34.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11286731/"
] |
74,566,145
|
<p>At the moment my method only prints a random number.</p>
<p>Heres the method.</p>
<pre><code> public void printMultiRandom(int howMany){
Random rand = new Random();
System.out.println(rand.nextInt(howMany));
</code></pre>
|
[
{
"answer_id": 74566222,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 1,
"selected": false,
"text": "\npublic void printMultiRandom(int howMany){\n new Random().ints(howMany)\n .forEach(System.out::println);\n\n}\n"
},
{
"answer_id": 74566289,
"author": "Isaac Dzikum",
"author_id": 18494246,
"author_profile": "https://Stackoverflow.com/users/18494246",
"pm_score": -1,
"selected": false,
"text": "public void printMultiRandom(int num){\n while(num-- > 0){\n double gen= 100 * Math.random();\n System.out.println(gen);\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20555484/"
] |
74,566,157
|
<p>Is there an easier way to do this?
<a href="https://i.stack.imgur.com/RbkKa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RbkKa.png" alt="Example" /></a></p>
|
[
{
"answer_id": 74566222,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 1,
"selected": false,
"text": "\npublic void printMultiRandom(int howMany){\n new Random().ints(howMany)\n .forEach(System.out::println);\n\n}\n"
},
{
"answer_id": 74566289,
"author": "Isaac Dzikum",
"author_id": 18494246,
"author_profile": "https://Stackoverflow.com/users/18494246",
"pm_score": -1,
"selected": false,
"text": "public void printMultiRandom(int num){\n while(num-- > 0){\n double gen= 100 * Math.random();\n System.out.println(gen);\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15547413/"
] |
74,566,172
|
<p>I am trying to use jquery to get a random fact. However I got alot of errors whilst trying to use ajax, after changing the way i defined $ or jquery alot of times it still hasn't solved it. I found another post with a similar problem and told me to use this:</p>
<pre><code>var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = jQuery = require('jquery')(window);
</code></pre>
<p>but this gives the error: Error: Cannot find module 'jsdom'</p>
<p>My package.json (the part with tyhe dependencies) looks like this:</p>
<pre><code>"dependencies": {
"quick.db": "^9.0.6",
"jquery": "^3.6.1",
"jsdom": "^20.0.3",
"jsdom-global": "^3.0.2",
"xmlhttprequest": "^1.8.0"
}
</code></pre>
<p>Why does it keep saying it cannot find the module? Or should I use another way to request the data?</p>
<p>This is what I am trying to request by the way:</p>
<pre><code>var limit = 1;
$.ajax({
method: 'GET',
url: 'https://api.api-ninjas.com/v1/facts?limit=' + limit,
headers: { 'X-Api-Key': 'MY-API-KEY'},
contentType: 'application/json',
success: function(result) {
console.log(result);
interaction.reply({embeds: [
new EmbedBuilder()
.setTitle(`Random fact for @<${interaction.user.id}>`)
.setAuthor({name: 'vixitu', iconURL: 'https://external-preview.redd.it/lqDFDXXvfqMs7kyQ9y1FrGcQzdCE23uMPlcxFqo_oYE.png?width=640&crop=smart&auto=webp&s=1aad996b62437feb367356c6bed434385bda0699'})
.setDescription("Here is your random fact.")
.setThumbnail('https://external-preview.redd.it/lqDFDXXvfqMs7kyQ9y1FrGcQzdCE23uMPlcxFqo_oYE.png?width=640&crop=smart&auto=webp&s=1aad996b62437feb367356c6bed434385bda0699')
.addFields(
{name: 'Random fact #1', value: result}
)
.setTimeStamp()
]})
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
})
},
</code></pre>
|
[
{
"answer_id": 74566222,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 1,
"selected": false,
"text": "\npublic void printMultiRandom(int howMany){\n new Random().ints(howMany)\n .forEach(System.out::println);\n\n}\n"
},
{
"answer_id": 74566289,
"author": "Isaac Dzikum",
"author_id": 18494246,
"author_profile": "https://Stackoverflow.com/users/18494246",
"pm_score": -1,
"selected": false,
"text": "public void printMultiRandom(int num){\n while(num-- > 0){\n double gen= 100 * Math.random();\n System.out.println(gen);\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19617459/"
] |
74,566,181
|
<p>I have an array spread between 2 components using the context api.</p>
<p>Adding objects to the array works fine, however I seem to be having trouble returning the modified array when removing an object from the array. Essentially it doesn't remove in the UI.</p>
<p>Here is my onClickHandler and a link to the <a href="https://codesandbox.io/s/sad-surf-sqgo0q?file=/src/components/Favorites/Favorites.js:337-520" rel="nofollow noreferrer">sandbox</a>.</p>
<pre><code> const onClickHandlerDelete = (user) => {
const itemToBeRemoved = user;
const array = favourites.splice(
favourites.findIndex((favourite) => favourite.id === itemToBeRemoved.id),
1
);
return array;
};
</code></pre>
|
[
{
"answer_id": 74566231,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 2,
"selected": true,
"text": "onClickHandlerDelete filter const onClickHandlerDelete = (user) =>\n favourites.filter((fav) => fav.id !== user.id)\n"
},
{
"answer_id": 74566261,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 0,
"selected": false,
"text": "const arr=[{id:4,name:\"Fred\"},{id:5,name:\"Harry\"},{id:6,name:\"Herminony\"}], user={id:5, name:\"Kate\"};\n\nconst remusr = (u) => arr.filter(e=>e.id!=u.id);\n\nconsole.log(remusr(user));"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19932692/"
] |
74,566,182
|
<p>so I'm trying to make this bot with selenium but when I'm trying to use the send keys func it doesn't work
I'm stuck on it for hours and I cant seem to find to solve the problem please if anyone has any idea I beg you to help me thanks.</p>
<pre><code>print(driver.title)
tos = driver.find_element("xpath", '//*[@id="pop"]/button')
tos.click()
time.sleep(5)
name = driver.find_element("ID", "inpNick")
time.sleep(5)
name.send_keys('baby')
time.sleep(50)
driver.quit()
</code></pre>
<pre><code>Traceback (most recent call last):
File "c:\Users\SexiKiller41\Downloads\a\catchno1se.py", line 17, in <module>
name = driver.find_element("ID", "inpNick")
File "C:\Users\SexiKiller41\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 861, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "C:\Users\SexiKiller41\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
self.error_handler.check_response(response)
File "C:\Users\SexiKiller41\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator
(Session info: chrome=107.0.5304.122)
Stacktrace:
Backtrace:
Ordinal0 [0x0039ACD3+2075859]
Ordinal0 [0x0032EE61+1633889]
Ordinal0 [0x0022B7BD+571325]
Ordinal0 [0x0025A745+763717]
Ordinal0 [0x0025AE1B+765467]
Ordinal0 [0x0028D0F2+970994]
Ordinal0 [0x00277364+881508]
Ordinal0 [0x0028B56A+963946]
Ordinal0 [0x00277136+880950]
Ordinal0 [0x0024FEFD+720637]
Ordinal0 [0x00250F3F+724799]
GetHandleVerifier [0x0064EED2+2769538]
GetHandleVerifier [0x00640D95+2711877]
GetHandleVerifier [0x0042A03A+521194]
GetHandleVerifier [0x00428DA0+516432]
Ordinal0 [0x0033682C+1665068]
Ordinal0 [0x0033B128+1683752]
Ordinal0 [0x0033B215+1683989]
Ordinal0 [0x00346484+1729668]
BaseThreadInitThunk [0x7753FEF9+25]
RtlGetAppContainerNamedObjectPath [0x77D37BBE+286]
RtlGetAppContainerNamedObjectPath [0x77D37B8E+238]
[Done] exited with code=1 in 9.895 seconds
</code></pre>
<p>I was trying to enter text to an input on a website</p>
|
[
{
"answer_id": 74566231,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 2,
"selected": true,
"text": "onClickHandlerDelete filter const onClickHandlerDelete = (user) =>\n favourites.filter((fav) => fav.id !== user.id)\n"
},
{
"answer_id": 74566261,
"author": "Carsten Massmann",
"author_id": 2610061,
"author_profile": "https://Stackoverflow.com/users/2610061",
"pm_score": 0,
"selected": false,
"text": "const arr=[{id:4,name:\"Fred\"},{id:5,name:\"Harry\"},{id:6,name:\"Herminony\"}], user={id:5, name:\"Kate\"};\n\nconst remusr = (u) => arr.filter(e=>e.id!=u.id);\n\nconsole.log(remusr(user));"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19358532/"
] |
74,566,194
|
<p>In this program, I have the user input their username into a login entry. Once they click the login button, the login_user() function is called to verify that their username exists in a .txt file.</p>
<p>I am trying to access the user's username in a later part of the program, more specifically in this line:</p>
<pre><code>welcomeLabel = ttk.Label(F3, text="Welcome, {}".format(usernameEntry), background='#EAE2E2', font=('Inter', '20')).grid()
</code></pre>
<p>More specifically, I am trying to display a string "Welcome, USERNAME" on the home page, but when I reference the usernameEntry it gives the value None.</p>
<p>I have also tried creating a global variable in the login_user() function and referencing that along with reading the loginString String variable, but those have not worked.</p>
<p>I am new to TKinter, so any help would be appreciated - thanks!</p>
<p>More specifically, I am trying to display a string "Welcome, USERNAME" on the home page, but when I reference the usernameEntry it gives the value None.</p>
<p>I have also tried creating a global variable in the login_user() function and referencing that along with reading the loginString String variable, but those have not worked.</p>
<p>I am new to TKinter, so any help would be appreciated - thanks!</p>
<p>I also attached my code below.</p>
<pre><code>from tkinter import *
from tkinter import ttk
def raise_frame(frame):
frame.tkraise()
def login_user():
#Without this if-statement, the blank input is captured and goes to the second frame
uInput = loginString.get()
if uInput == '':
return loginString.get()
with open('username.txt', 'r') as searchUsername:
textFileSearch = searchUsername.readlines()
for row in textFileSearch:
findUserName = row.find(uInput)
if findUserName == 0:
raise_frame(F3)
break
else:
print('Your username does not exist')
root = Tk()
root.title("FLASHCARDS PROGRAM")
root.resizable(width=False,height=False)
style = ttk.Style()
style.theme_use('default')
#Login Screen Frame
F1 = Frame(root, background = '#BACDAF', highlightbackground="black", highlightthickness=1)
F1.grid(padx=410,pady=210)
#Top-Label Frame
login_top_frame = Frame(F1, background='#468D70')
login_top_frame.grid(row=0, column=0, padx=10, pady=5)
#Light-Gray Background Frame
F2 = Frame(root, width=1280, height=720, background='#939393')
F2.grid(row=0, column=0, sticky='news')
#Home Screen Frame
F3 = Frame(root, width=1280, height=720, background='#EAE2E2')
F3.grid(row=0, column=0, sticky='news')
header_frame = Frame(F3, width = 1000, height = 100, background='#E4DDF4', highlightbackground="black", highlightthickness=1)
header_frame.grid(row=0, column=0, padx=10, pady=5, ipadx=475)
#Login Screen Widgets
loginHeader = ttk.Label(login_top_frame, text = "Flashcards For Free", background = '#468D70', font=('Inter','28','bold')).grid(column = 0, row = 0, padx = 90, pady = 20)
loginLabel = ttk.Label(F1, text = "Username:", font=('Inter', '15'), background='#BACDAF').grid(column=0,row=1, padx=20, sticky=W)
loginString = StringVar()
usernameEntry = ttk.Entry(F1, width=10, textvariable=loginString, background='green').grid(column=0, row=2, padx=20, pady=5, ipady = 5, sticky=W)
usernameInput = ttk.Button(F1, text="LOGIN", width = 8, command=login_user).grid(column=0, row=5, padx=21, sticky=W)
createAccount = ttk.Button(F1, text="No Account? Click Here").grid(column=0, row=8, padx=125,pady=25)
#Home Screen Widgets
menuLabel = ttk.Label(header_frame, text="Flashcards for Free", background='#E4DDF4', font=('Inter', '15')).grid(row=0, column=1, padx=10)
homeButton = ttk.Button(header_frame, text='Home').grid(row=0, column=2, padx=5)
createButton = ttk.Button(header_frame, text='Create').grid(row=0, column=3, padx=5)
welcomeLabel = ttk.Label(F3, text="Welcome, {}".format(usernameEntry), background='#EAE2E2', font=('Inter', '20')).grid()
raise_frame(F2)
raise_frame(F1)
root.mainloop()
</code></pre>
|
[
{
"answer_id": 74566299,
"author": "Ahwar Khan",
"author_id": 14231880,
"author_profile": "https://Stackoverflow.com/users/14231880",
"pm_score": 0,
"selected": false,
"text": ".txt"
},
{
"answer_id": 74566430,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 1,
"selected": false,
"text": "get welcomeLabel.configure(text=f\"Welcome {usernameEntry.get()}\")\n welcomeLabel None"
},
{
"answer_id": 74566433,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 0,
"selected": false,
"text": "loginString.get() tkinter"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594104/"
] |
74,566,195
|
<p>I need to get a PIN code through an API but I can't get the Body of an End-Point response.
The process is very simple and requires no authentication.
Just send the email in the MAILTO field and the webservice returns the pin, or says that the email was not found. In my case below, I just want to receive the Json. But I can't do that.</p>
<p>However, when I test the endpoint in Postman, it works perfectly. But I can't when I try in PHP, even getting the CURL generated by Postman itself.</p>
<p>Here's the PHP code I'm using.</p>
<pre><code><?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api-dev.meucliente.app.br/api/Login/sistema/forgot-pin?mailto=teste@verificando.com.br');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
$esposta = curl_exec($curl);
curl_close($curl);
header('Content-Type: application/json');
var_dump($esposta);
?>
</code></pre>
<p>The above script returns the following result:</p>
<pre><code>string(123) "HTTP/1.1 404 Not Found
Date: Thu, 24 Nov 2022 14:28:51 GMT
Content-Length: 0
Connection: keep-alive
Server: Kestrel
</code></pre>
<p>When I test the same end-point in Postman, the return is correct:</p>
<pre><code>[
{
"Mensagem": "Email não foi encontrado!!",
"InnerException": null
}
]
</code></pre>
<p>I will be very grateful to whoever helps me.</p>
|
[
{
"answer_id": 74568579,
"author": "Marcin Orlowski",
"author_id": 1235698,
"author_profile": "https://Stackoverflow.com/users/1235698",
"pm_score": -1,
"selected": false,
"text": "GET POST GET POST curl_setopt($curl, CURLOPT_POST, true);\n <?php\n$curl = curl_init();\ncurl_setopt($curl, CURLOPT_URL, 'https://api-dev.meucliente.app.br/api/Login/sistema/forgot-pin?mailto=teste@verificando.com.br');\n\ncurl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($curl, CURLOPT_HEADER, true);\ncurl_setopt($curl, CURLOPT_POST, true);\n$esposta = curl_exec($curl);\ncurl_close($curl);\nheader('Content-Type: application/json');\nvar_dump($esposta);\n string(167) \"HTTP/2 400\ndate: Fri, 25 Nov 2022 05:11:11 GMT\ncontent-type: application/json\nserver: Kestrel\n\n[{\"Mensagem\":\"Email não foi encontrado!!\",\"InnerException\":null}]\"\n header('Content-Type: application/json');\n var_dump() curl_setopt($curl, CURLOPT_HEADER, true); var_dump() echo header() echo '<pre>';"
},
{
"answer_id": 74572886,
"author": "Jetro Bernardo",
"author_id": 5567784,
"author_profile": "https://Stackoverflow.com/users/5567784",
"pm_score": -1,
"selected": false,
"text": "<?php\n$curl = curl_init();\ncurl_setopt($curl, CURLOPT_URL, 'https://api-dev.meucliente.app.br/api/Login/sistema/forgot-pin?mailto=teste@verificando.com.br');\ncurl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($curl, CURLOPT_POSTFIELDS, \"{}\");\n$esposta = curl_exec($curl);\ncurl_close($curl);\nheader('Content-Type: application/json');\necho $esposta;\n?>\n"
},
{
"answer_id": 74579134,
"author": "Misunderstood",
"author_id": 3813605,
"author_profile": "https://Stackoverflow.com/users/3813605",
"pm_score": 0,
"selected": false,
"text": "curl_setopt($curl, CURLOPT_HEADER, true);\n 404 Not Found https://api-dev.meucliente.app.br/"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5567784/"
] |
74,566,243
|
<p>html</p>
<pre><code><body>
<header>
<div class="indexHeaderWall" id="headerLeftWall">
</div>
<img id="profilePic" src="icons/myPicture.jpg" alt="Picture of Daniel Campos">
<div class="indexHeaderWall" id="headerRightWall">
</div>
</header>
</body>
</code></pre>
<p>css</p>
<pre><code>body {
background-color: aqua;
margin: 0%;
}
header {
background-color: orange;
display: flex;
position: relative;
}
#profilePic {
position: absolute;
left: 26%;
top: 0%;
bottom: 0%;
margin: auto 0%;
}
.indexHeaderWall {
background-color: aliceblue;
height: 300px;
border: solid red 1px;
}
#headerLeftWall {width: 30%;}
#headerRightWall {width: 70%;}
</code></pre>
<p><strong>I tried using percentages with position but I cant seem to keep my image horizontally centered on the split as I reduce my window size.</strong></p>
<p><strong>Left div takes up 30% of the width, while the right div takes the rest.</strong></p>
<p><strong>I'm assuming ill have to manually adjust position percentages to try and center a given image on the split, does anyone know of a method that would work on any given image? Or how I might adjust my current code to do so?</strong></p>
<p><strong>Thank you for your time!</strong></p>
|
[
{
"answer_id": 74566562,
"author": "Morgan Feeney",
"author_id": 1793962,
"author_profile": "https://Stackoverflow.com/users/1793962",
"pm_score": 1,
"selected": false,
"text": "calc() :root {\n --left-wall: 30%;\n}\n\nbody {\n background-color: aqua;\n margin: 0%;\n}\n\nheader {\n background-color: orange;\n display: flex;\n position: relative;\n}\n\n#profilePic {\n position: absolute;\n left: calc(var(--left-wall) - var(--image-width)/2);\n top: 0%;\n bottom: 0%;\n margin: auto 0%;\n opacity: 0.5;\n}\n\n.indexHeaderWall {\n background-color: aliceblue;\n height: 300px;\n border: solid red 1px;\n\n}\n#headerLeftWall {width: var(--left-wall)}\n#headerRightWall {width: 70%;}\n const img = document.querySelector(\"img\");\nimg.style.setProperty('--image-width', `${img.width}px`);\n"
},
{
"answer_id": 74566729,
"author": "Maicon Rodrigues dos Santos",
"author_id": 19234327,
"author_profile": "https://Stackoverflow.com/users/19234327",
"pm_score": 2,
"selected": false,
"text": "<div id= \"container\">\n <div id= \"profilePic\">\n <img />\n </div>\n <div id=\"colorLeft\">\n </div>\n <div id=\"colorRight\">\n </div>\n</div>\n #container {\n display: flex;\n align-items: center;\n justify-content: center;\n heigth: 100%;\n}\n\n#profilePic {\n width: 300px;\n background: yellow;\n position: absolute;\n}\n\n#colorLeft {\n background: green;\n width: 500px;\n height: 500px;\n max-width: 50%;\n}\n\n#colorRight {\n height: 500px;\n background: blue;\n max-width: 50%;\n width: 500px;\n}\n"
},
{
"answer_id": 74567832,
"author": "Alexandra Batrak",
"author_id": 8870249,
"author_profile": "https://Stackoverflow.com/users/8870249",
"pm_score": 3,
"selected": true,
"text": "<body>\n\n<header>\n\n <div class=\"indexHeaderWall\" id=\"headerLeftWall\">\n </div>\n \n <img id=\"profilePic\" src=\"icons/myPicture.jpg\" alt=\"Picture of Daniel Campos\">\n\n <div class=\"indexHeaderWall\" id=\"headerRightWall\">\n </div>\n\n</header>\n body {\n background-color: aqua;\n margin: 0%;\n}\n\nheader {\n background-color: orange;\n display: flex;\n position: relative;\n justify-content: center;\n align-items: center;\n}\n\n\n#profilePic {\n width: fit-content;\n border: 2px solid yellow;\n position: absolute;\n left: 30%;\n right: 70%;\n transform: translateX( -50% );\n display: flex;\n align-self: center;\n}\n\n.indexHeaderWall {\n background-color: aliceblue;\n height: 300px;\n border: solid red 1px;\n}\n#headerLeftWall {width: 30%;}\n#headerRightWall {width: 70%;}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20593466/"
] |
74,566,249
|
<p>I'm building an angular 14 application with a backend using spring cloud gateway. I have configured CORS in the gateway. I run the application on http://localhost:4200.
The first call to the backend is to get user information. I defined a method :</p>
<pre><code>getUserInfo() {
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json'
})
};
return this.http.post<any>("http://localhost:8180/auth/userInfo", {}, httpOptions)
.pipe(map(user => {
// store user details in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}));
}
</code></pre>
<p>And I have 2 Interceptors : 1 for setting the X-Requested-With header and 1 for intercepting errors :</p>
<pre><code>intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', err.error.message);
const error = err.error.message;
return throwError(error);
} else {
console.error(`Error type ${err.name}`);
console.error(err.message);
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
if (err.status === 401) {
console.warn(`Backend returned code 401, login out`);
// auto logout if 401 response returned from api
this.authenticationService.logout();
this.router.navigate(['/login']);
} else {
console.error(`Backend returned code ${err.status}`);
if (err.error) {
console.error(`app error code was: ${err.error.code}`);
}
}
return throwError(err);
}
}))
}
</code></pre>
<p>The problem I get is the call to getUserInfo() always return a TypeError error with the message "headers.get(...) is null"</p>
<p>I can't see any request made to the backend neither in my browser log or in the backend access log.</p>
<p>Do you have any idea?
Thanks</p>
<p><strong>EDIT</strong></p>
<p>The call to the getUserInfo() is in a component :</p>
<pre><code>ngOnInit() {
//this.loading = true;
this.authenticationService.getUserInfo()
.pipe(first())
.subscribe(
data => {
this.router.navigate(['/']);
},
error => {
this.errorMsg = error.message;
});
}
</code></pre>
|
[
{
"answer_id": 74566562,
"author": "Morgan Feeney",
"author_id": 1793962,
"author_profile": "https://Stackoverflow.com/users/1793962",
"pm_score": 1,
"selected": false,
"text": "calc() :root {\n --left-wall: 30%;\n}\n\nbody {\n background-color: aqua;\n margin: 0%;\n}\n\nheader {\n background-color: orange;\n display: flex;\n position: relative;\n}\n\n#profilePic {\n position: absolute;\n left: calc(var(--left-wall) - var(--image-width)/2);\n top: 0%;\n bottom: 0%;\n margin: auto 0%;\n opacity: 0.5;\n}\n\n.indexHeaderWall {\n background-color: aliceblue;\n height: 300px;\n border: solid red 1px;\n\n}\n#headerLeftWall {width: var(--left-wall)}\n#headerRightWall {width: 70%;}\n const img = document.querySelector(\"img\");\nimg.style.setProperty('--image-width', `${img.width}px`);\n"
},
{
"answer_id": 74566729,
"author": "Maicon Rodrigues dos Santos",
"author_id": 19234327,
"author_profile": "https://Stackoverflow.com/users/19234327",
"pm_score": 2,
"selected": false,
"text": "<div id= \"container\">\n <div id= \"profilePic\">\n <img />\n </div>\n <div id=\"colorLeft\">\n </div>\n <div id=\"colorRight\">\n </div>\n</div>\n #container {\n display: flex;\n align-items: center;\n justify-content: center;\n heigth: 100%;\n}\n\n#profilePic {\n width: 300px;\n background: yellow;\n position: absolute;\n}\n\n#colorLeft {\n background: green;\n width: 500px;\n height: 500px;\n max-width: 50%;\n}\n\n#colorRight {\n height: 500px;\n background: blue;\n max-width: 50%;\n width: 500px;\n}\n"
},
{
"answer_id": 74567832,
"author": "Alexandra Batrak",
"author_id": 8870249,
"author_profile": "https://Stackoverflow.com/users/8870249",
"pm_score": 3,
"selected": true,
"text": "<body>\n\n<header>\n\n <div class=\"indexHeaderWall\" id=\"headerLeftWall\">\n </div>\n \n <img id=\"profilePic\" src=\"icons/myPicture.jpg\" alt=\"Picture of Daniel Campos\">\n\n <div class=\"indexHeaderWall\" id=\"headerRightWall\">\n </div>\n\n</header>\n body {\n background-color: aqua;\n margin: 0%;\n}\n\nheader {\n background-color: orange;\n display: flex;\n position: relative;\n justify-content: center;\n align-items: center;\n}\n\n\n#profilePic {\n width: fit-content;\n border: 2px solid yellow;\n position: absolute;\n left: 30%;\n right: 70%;\n transform: translateX( -50% );\n display: flex;\n align-self: center;\n}\n\n.indexHeaderWall {\n background-color: aliceblue;\n height: 300px;\n border: solid red 1px;\n}\n#headerLeftWall {width: 30%;}\n#headerRightWall {width: 70%;}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597444/"
] |
74,566,264
|
<p>I am trying to get a list of SMB shares on a remote file server. Unfortunately because of the type of server I am querying WMI and CIM won't work. The only thing I can get to work is net view (which I believe uses netbios).</p>
<p>I am running the following code which gets the shares:</p>
<pre><code>$shares = net view \\server1 /all | select -Skip 7 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null;"\\server1\$($matches[1])"}
$shares += net view \\server2 /all | select -Skip 7 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null;"\\server2\$($matches[1])"}
foreach ($share in $shares) {
$logdir1 = @("$share\App_Data\","errorlogs")
$logdirs = @($logdir1)
foreach ($log in $logdirs) {
write-host $log[0]
</code></pre>
<p>However, instead of getting a list of paths, I am getting the first character of each path. So basically $log[0] is a character - not a string as I an expecting.</p>
<p>I think this has to do with the net view command returning characters instead of an object.</p>
<p>I tried using <code>ToString()</code> in various places to no avail. Anyone help me figure out how to get this to work?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 74566418,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": true,
"text": "@(...) $logdirs = @($logdir1) # WRONG: same as $logDirs = $logdir1 in this case.\n $logdirs = , $logdir1\n $logDir , foreach [0] [1] @(...) $logdir1 = @(\"$share\\App_Data\\\",\"errorlogs\")\n$logdirs = @($logdir1)\n $logdirs = @(\"$share\\App_Data\\\", \"errorlogs\") foreach ($log in $logdirs) {\n $logDirs write-host $log[0]\n [0] 'abc'[1] 'b' $log $logDir foreach ($logdir in $logdirs) {\n $filesInDir = Get-ChildItem -File -LiteralPath $logdir\n $filesInDir[0]\n}\n"
},
{
"answer_id": 74566850,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": 0,
"selected": false,
"text": "string[] -replace"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535432/"
] |
74,566,265
|
<p>I'm learning 'modern' C++ and I'm having a really hard time discerning the issue with this code.</p>
<p>Ball.h:</p>
<pre><code>#ifndef BALL_H
#define BALL_H
#include <string>
#include <string_view>
namespace ball
{
class Ball
{
std::string _color{};
double _radius{};
public:
Ball() = default;
Ball(double radius);
Ball(std::string_view color = "black", double radius = 10);
void print() const;
};
}
#endif // !BALL_H
</code></pre>
<p>Ball.cpp:</p>
<pre><code>#include "Ball.h"
#include <iostream>
#include <string_view>
namespace ball
{
Ball::Ball(double radius)
{
_color = "black";
_radius = radius;
}
Ball::Ball(std::string_view color, double radius)
{
_color = color;
_radius = radius;
}
void Ball::print() const
{
std::cout << "Ball: " << std::endl;
std::cout << "\tcolor: " << _color << std::endl;
std::cout << "\tradius: " << _radius << std::endl;
}
}
</code></pre>
<p>Why does defining <code>Ball() = default;</code> produce a compiler error (complaining about the constructor that takes two arguments, causing further confusion).</p>
<p>If I omit the default constructor definition entirely the code compiles and functions perfectly fine.</p>
<p>I wish I could be more descriptive, but I'm at a loss here.</p>
|
[
{
"answer_id": 74566290,
"author": "The Dreams Wind",
"author_id": 5690248,
"author_profile": "https://Stackoverflow.com/users/5690248",
"pm_score": 3,
"selected": false,
"text": "Ball(std::string_view, double) Ball() Ball a; // Ball() or Ball(std::string_view, double) with default arguments?\n class Ball\n{\n ...\n\npublic:\n\n Ball(double radius);\n // all good now. This constructor is used to default-construct the class\n Ball(std::string_view color = \"black\", double radius = 10);\n\n ...\n};\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594161/"
] |
74,566,273
|
<p><strong>Context</strong>
I am using: Windows 11, VSCode and node v18.12.1</p>
<p>I am trying to filter a JSON object, using an array variable, as I have more than one value I want to filter against.</p>
<p><strong>Question</strong>
I have the following code working which filters based on a single user's name. What I want to do is filter based on matching one or more of the names.</p>
<p><strong>Here is the code that's working filtering on one owner's name</strong></p>
<pre><code>let carOwners = [{ "name": "Phil", "age": 52, "car": null },
{ "name": "Carl Phil", "age": 25, "car": "Tesla" },
{ "name": "Bob", "age": 65, "car": "Land Rover" },
{ "name": "Megan", "age": 34, "car": "Mercedez" },
{ "name": "Charlene", "age": 67, "car": "Mazda" }]
checkUsers = carOwners.filter(user => !(user.name.includes("Phil")));
console.log(checkUsers);
</code></pre>
<p>which gives the result:</p>
<pre><code>[
{ name: 'Bob', age: 65, car: 'Land Rover' },
{ name: 'Megan', age: 34, car: 'Mercedez' },
{ name: 'Charlene', age: 67, car: 'Mazda' }
]
</code></pre>
<p>What I want to do is filter out any results that contain Phil or Bob.</p>
<p><strong>What I've tried</strong>
I have searched various other solutions, but they don't seem to cater for what I'm after...</p>
<p>This is the first method tried:</p>
<pre><code>filteredNames = ['Phil', 'Bob'];
checkUsers = carOwners.filter(user => !(user.name.includes(filteredNames)));
console.log(checkUsers);
</code></pre>
<p>The result I'm after is:</p>
<pre><code>[
{ name: 'Megan', age: 34, car: 'Mercedez' },
{ name: 'Charlene', age: 67, car: 'Mazda' }
]
</code></pre>
<p>except I get:</p>
<pre><code>[
{ name: 'Phil', age: 52, car: null },
{ name: 'Carl Phil', age: 25, car: 'Tesla' },
{ name: 'Bob', age: 65, car: 'Land Rover' },
{ name: 'Megan', age: 34, car: 'Mercedez' },
{ name: 'Charlene', age: 67, car: 'Mazda' }
]
</code></pre>
<p>I tried numerous others, the closest I got was based on the solution <a href="https://stackoverflow.com/a/74150538/20331138">here</a> I tried the following:</p>
<pre><code>const filteredNames = ['Phil', 'Bob'];
let checkUsers = carOwners.filter(a => !(filteredNames.includes(a.name + '')));
console.log(checkUsers);
</code></pre>
<p>which is closer (as it's filtered out objects with the names Bob and Phil), however I am still returned the object 'Carl Phil', as you can see below... The question I specifically have is how do I filter out any object that contains any appearance of any of the names in the filteredNames array, so that I am left with the objects with the name 'Megan' and 'Charlene'?</p>
<pre><code>[
{ name: 'Carl Phil', age: 25, car: 'Tesla' },
{ name: 'Megan', age: 34, car: 'Mercedez' },
{ name: 'Charlene', age: 67, car: 'Mazda' }
]
</code></pre>
<p>Any advice appreciated. Thanks in advance</p>
|
[
{
"answer_id": 74566290,
"author": "The Dreams Wind",
"author_id": 5690248,
"author_profile": "https://Stackoverflow.com/users/5690248",
"pm_score": 3,
"selected": false,
"text": "Ball(std::string_view, double) Ball() Ball a; // Ball() or Ball(std::string_view, double) with default arguments?\n class Ball\n{\n ...\n\npublic:\n\n Ball(double radius);\n // all good now. This constructor is used to default-construct the class\n Ball(std::string_view color = \"black\", double radius = 10);\n\n ...\n};\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20331138/"
] |
74,566,279
|
<p>I've a middleware to validate a user <code>quota</code> and I need to inject the service that call the database into it to check this quota.</p>
<p>This is the middleware:</p>
<pre class="lang-js prettyprint-override"><code>export class PointMaxStorageMiddleware implements NestMiddleware {
constructor(private readonly points: PointsService) {}
async use(req: Request, res: Response, next: NextFunction) {
const total = await this.points.count('user-id-test');
if (total >= LIMIT) throw new HttpException('error sample', 400);
// ...
}
}
</code></pre>
<p>The service class:</p>
<pre class="lang-js prettyprint-override"><code>@Injectable()
export class PointsService {
private readonly logger = new Logger(PointsService.name);
constructor(
@InjectModel(Point.name)
private readonly collection: Model<PointDocument>,
) {}
async count(userId: string): Promise<number> {
return await this.collection.countDocuments({ userId: userId });
}
}
</code></pre>
<p>My service class has the <code>Injectable</code> annotation and is being used on other parts of the project, but when I inject it into the middleware, I got the error:</p>
<blockquote>
<p>Cannot read properties of undefined (reading 'count')</p>
</blockquote>
<p><strong>The <code>count</code> method exist on the service.</strong></p>
<p>I also tried to use like this:</p>
<pre class="lang-js prettyprint-override"><code>constructor(
@Inject(PointsService) private readonly points: PointsService,
) {}
</code></pre>
<p>And got the erro:</p>
<blockquote>
<p>Nest can't resolve dependencies of the PointsService (?). Please make sure that the argument PointModel at index [0] is available in the AppModule context.
Potential solutions:</p>
<ul>
<li>If PointModel is a provider, is it part of the current AppModule?</li>
<li>If PointModel is exported from a separate @Module, is that > module imported within AppModule? @Module({ imports: [ /* the Module containing PointModel */ ]})
Error: Nest can't resolve dependencies of the PointsService (?). Please make sure that the argument PointModel at index [0] is available in the AppModule context.</li>
</ul>
</blockquote>
<p>Also tried to add a new provider on the <code>AppModule</code> class:</p>
<pre class="lang-js prettyprint-override"><code>providers: [
{
provide: 'POINT_SERVICE',
useClass: PointsService,
},
]
</code></pre>
<pre class="lang-js prettyprint-override"><code>constructor(
@Inject('POINT_SERVICE') private readonly points: PointsService,
) {}
</code></pre>
<p>And got the same error as above.</p>
<p>The injection is not being placed correctly, how can I inject a service into a middleware?</p>
|
[
{
"answer_id": 74566666,
"author": "Micael Levi",
"author_id": 5290447,
"author_profile": "https://Stackoverflow.com/users/5290447",
"pm_score": 1,
"selected": false,
"text": "@Injectable() PointsService PointMaxStorageMiddleware PointMaxStorageMiddleware @Inject(PointsService) private readonly points: PointsService"
},
{
"answer_id": 74568171,
"author": "Manuel Herrera",
"author_id": 1988557,
"author_profile": "https://Stackoverflow.com/users/1988557",
"pm_score": 1,
"selected": false,
"text": "NestMiddleware @injectable() configure() @module @Module({\n providers: [PointsService],\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(PointMaxStorageMiddleware)\n .forRoutes('myroute');\n }\n}\n PointsService providers imports"
},
{
"answer_id": 74636209,
"author": "Farista Latuconsina",
"author_id": 8510684,
"author_profile": "https://Stackoverflow.com/users/8510684",
"pm_score": 0,
"selected": false,
"text": "Manuel Herrera configure() @Module({\n imports: [PointsModule], // this is the module where you provide the PointsService\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(PointMaxStorageMiddleware)\n .forRoutes('myroute');\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2336081/"
] |
74,566,282
|
<p>I am currently editing multiple CSVs to add 2 columns ORIGIN_FILE and WRITE_DATE. The problem is that the string is always added after a new line for some reason.</p>
<p>Here is an example of my input csv:</p>
<pre><code>PRODUCT, QUANTITY, PRICE
ITEM1, 4.8, 380.33
ITEM2, 2.3, 120.50
ITEM3, 1.5, 210.11
</code></pre>
<p>But everytime I run my bash command below:</p>
<pre class="lang-bash prettyprint-override"><code>find $target_dir -type f -name "*.csv" | parallel sed -i '\'1s/$/,ORIGIN_FILE,WRITE_DATE/; 2,$s/$/,myfilename.csv,2022-11-24/\'' {}'
</code></pre>
<p>This is the output I get:</p>
<pre><code>PRODUCT, QUANTITY, PRICE, ORIGIN_FILE, WRITE_DATE
ITEM1, 4.8, 380.33
myfilename.csv, 2022-11-24
ITEM2, 2.3, 120.50
myfilename.csv, 2022-11-24
ITEM3, 1.5, 210.11
myfilename.csv, 2022-11-24
</code></pre>
<p>It always creates a new line after the second row and add my string there.</p>
<p>I'm hoping to get this output:</p>
<pre><code>PRODUCT, QUANTITY, PRICE, ORIGIN_FILE, WRITE_DATE
ITEM1, 4.8, 380.33, myfilename.csv, 2022-11-24
ITEM2, 2.3, 120.50, myfilename.csv, 2022-11-24
ITEM3, 1.5, 210.11, myfilename.csv, 2022-11-24
</code></pre>
<p>Hoping someone can help me spot what I'm doing wrong.</p>
<p>I'll appreciate if someone can just help me with the sed command.</p>
|
[
{
"answer_id": 74566666,
"author": "Micael Levi",
"author_id": 5290447,
"author_profile": "https://Stackoverflow.com/users/5290447",
"pm_score": 1,
"selected": false,
"text": "@Injectable() PointsService PointMaxStorageMiddleware PointMaxStorageMiddleware @Inject(PointsService) private readonly points: PointsService"
},
{
"answer_id": 74568171,
"author": "Manuel Herrera",
"author_id": 1988557,
"author_profile": "https://Stackoverflow.com/users/1988557",
"pm_score": 1,
"selected": false,
"text": "NestMiddleware @injectable() configure() @module @Module({\n providers: [PointsService],\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(PointMaxStorageMiddleware)\n .forRoutes('myroute');\n }\n}\n PointsService providers imports"
},
{
"answer_id": 74636209,
"author": "Farista Latuconsina",
"author_id": 8510684,
"author_profile": "https://Stackoverflow.com/users/8510684",
"pm_score": 0,
"selected": false,
"text": "Manuel Herrera configure() @Module({\n imports: [PointsModule], // this is the module where you provide the PointsService\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(PointMaxStorageMiddleware)\n .forRoutes('myroute');\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11721871/"
] |
74,566,293
|
<p>Limiting to a line would be simple using <code>white-space:nowrap</code> but I have a specific problem where I would like to force my header text to fit in a specific width.</p>
<p>I had success adding individual style on the element to force them to the specific 2 lines I want but it does not seem like a long term solution.</p>
<p>e.g.</p>
<pre><code><table class="table table-hover table-sm text-center">
<thead>
<tr>
<th>Lorem ipsum</th>
<th>Lorem ipsum</th>
<th>Lorem ipsum</th>
<th>Lorem ipsum</th>
<th>Lorem ipsum</th>
<th style="min-width: 90px">Lorem ipsum dolor sit amet</th>
</tr>
</thead>
</table>
</code></pre>
<p>Another way I tried was to include break points in the text itself but I also don't want to go through the multiple files to do so.</p>
<pre><code><th>Lorem ipsum <br /> dolor sit amet</th>
</code></pre>
<p>I have also tried adding a external style sheet to force the min-width of all to a value but this causes huge gaps in-between the table headers.</p>
<p>Would like to know if there's a better method to do this.</p>
|
[
{
"answer_id": 74566666,
"author": "Micael Levi",
"author_id": 5290447,
"author_profile": "https://Stackoverflow.com/users/5290447",
"pm_score": 1,
"selected": false,
"text": "@Injectable() PointsService PointMaxStorageMiddleware PointMaxStorageMiddleware @Inject(PointsService) private readonly points: PointsService"
},
{
"answer_id": 74568171,
"author": "Manuel Herrera",
"author_id": 1988557,
"author_profile": "https://Stackoverflow.com/users/1988557",
"pm_score": 1,
"selected": false,
"text": "NestMiddleware @injectable() configure() @module @Module({\n providers: [PointsService],\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(PointMaxStorageMiddleware)\n .forRoutes('myroute');\n }\n}\n PointsService providers imports"
},
{
"answer_id": 74636209,
"author": "Farista Latuconsina",
"author_id": 8510684,
"author_profile": "https://Stackoverflow.com/users/8510684",
"pm_score": 0,
"selected": false,
"text": "Manuel Herrera configure() @Module({\n imports: [PointsModule], // this is the module where you provide the PointsService\n})\nexport class AppModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(PointMaxStorageMiddleware)\n .forRoutes('myroute');\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10638194/"
] |
74,566,302
|
<p>After using <code>.groupby(['match_id', 'team']).sum()</code> I'm left with this multi-index dataframe:</p>
<pre><code> visionScore
match_id team
EUW1_5671848066 blue 212
red 127
EUW1_5671858853 blue 146
red 170
EUW1_5672206092 blue 82
... ...
</code></pre>
<p>How do I add a new boolean column that will tell whether blue or red team has larger <code>visionScore</code>? If there's a draw, consider both teams to be winning.</p>
|
[
{
"answer_id": 74566708,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 3,
"selected": true,
"text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\"visionScore\": [212, 127, 146, 170, 82, 82]},\n index=pd.MultiIndex.from_product([[\"EUW1_5671848066\", \"EUW1_5671858853\", \"EUW1_5672206092\"], [\"blue\", \"red\"]], names=[\"match_id\", \"team\"]) \n)\n\ndf[\"winner\"] = df.groupby(\"match_id\").transform(lambda x: [x[0] >= x[1], x[1] >= x[0]])\n\n# df:\n# visionScore winner\n# match_id team \n# EUW1_5671848066 blue 212 True\n# red 127 False\n# EUW1_5671858853 blue 146 False\n# red 170 True\n# EUW1_5672206092 blue 82 True\n# red 82 True\n"
},
{
"answer_id": 74566770,
"author": "Meio",
"author_id": 7190595,
"author_profile": "https://Stackoverflow.com/users/7190595",
"pm_score": 0,
"selected": false,
"text": "df = df.reset_index(drop=True)\ndf = df.loc[df['team'] == 'blue'].merge(df.loc[df['team'] == 'red'], on=['match_id'], suffixes=('_blue', '_red'))\ndf['blueWins'] = df['visionScore_blue'] >= df['visionScore_red']\n blueWins visionScore_blue visionScore_red\nFalse 156 189\nFalse 83 90\nTrue 142 102\nTrue 185 161\nTrue 147 94\n...\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7190595/"
] |
74,566,341
|
<p>I've got a Svelte (with Sveltekit) app which I just containerized. It builds correctly and there are no errors when running, but I cannot access it from the browser. I tried accessing <code>http://localhost:5050/</code> and also <code>http://0.0.0.0:5050/</code> but I'm getting:</p>
<pre><code>This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
</code></pre>
<p>This is the <code>Dockerfile</code> I'm using:</p>
<pre><code># Our Node base image
FROM node:19-alpine
# Set the Node environment to development to ensure all packages are installed
ENV NODE_ENV development
# Change our current working directory
WORKDIR /app
# Copy over `package.json` and lock files to optimize the build process
COPY package.json package-lock.json ./
# Install Node modules
RUN npm install
# Copy over rest of the project files
COPY . .
RUN npm run build
# Expose port
ENV PORT 5050
EXPOSE 5050
# Run `yarn dev` and set the host to 0.0.0.0 so we can access the web app from outside
CMD ["npm", "run", "dev"]
</code></pre>
<p>This is how I'm building it:
<code>docker build -t sveltekit:node --network=host .</code></p>
<p>And this is how I'm running it:
<code>docker run -d -p 5050:5050 --name sveltekit-app sveltekit:node</code></p>
<p>And this is the output of running <code>docker ps</code>:</p>
<pre><code>a9e241b09fd3
IMAGE
sveltekit:node
COMMAND
"docker-entrypoint.s…"
CREATED
About a minute ago
STATUS
Up About a minute
PORTS
0.0.0.0:5050->5050/tcp
NAMES
sveltekit-app
</code></pre>
<p>What am I missing?</p>
<p><strong>UPDATE</strong></p>
<p><strong>Container Logs</strong></p>
<pre><code>2022-11-30 19:09:18
2022-11-30 19:09:18 > dundermifflin-ui@0.0.1 start
2022-11-30 19:09:18 > export PORT=8080 && node ./build
2022-11-30 19:09:18
2022-11-30 19:09:18 Listening on 0.0.0.0:8080
</code></pre>
<p>why it is listening to port 8080? I updated my <code>package.json</code> to be:</p>
<p><code>"dev": "vite dev --port=5050"</code></p>
<p>meaning that I'm enforcing port 5050, isn't that right?</p>
|
[
{
"answer_id": 74566534,
"author": "2pha",
"author_id": 1550696,
"author_profile": "https://Stackoverflow.com/users/1550696",
"pm_score": 1,
"selected": false,
"text": "npm install --global http-server && http-server ./app -p 5050"
},
{
"answer_id": 74662242,
"author": "akdev",
"author_id": 2065831,
"author_profile": "https://Stackoverflow.com/users/2065831",
"pm_score": 0,
"selected": false,
"text": "Dockerfile CMD [\"npm\", \"run\", \"dev\"] CMD [\"npm\", \"run\", \"dev\", \"--\", \"-p\", \"5050]"
},
{
"answer_id": 74663157,
"author": "Benjamin Woolston",
"author_id": 20188398,
"author_profile": "https://Stackoverflow.com/users/20188398",
"pm_score": 0,
"selected": false,
"text": "\"scripts\": {\n \"start\": \"export PORT=5050 && node ./build\"\n}\nSet the PORT environment variable when running the container, like this:\nCopy code\ndocker run -d -p 5050:5050 -e PORT=5050 --name sveltekit-app sveltekit:node\n \"scripts\": {\n \"start\": \"export PORT=5050 && node ./build\"\n}\n http://localhost:5050/ or http://0.0.0.0:5050/."
},
{
"answer_id": 74666585,
"author": "Begging",
"author_id": 16606223,
"author_profile": "https://Stackoverflow.com/users/16606223",
"pm_score": 3,
"selected": true,
"text": "docker run -d -p 5050:8080 --name sveltekit-app sveltekit:node\n"
},
{
"answer_id": 74668780,
"author": "colek42",
"author_id": 3226186,
"author_profile": "https://Stackoverflow.com/users/3226186",
"pm_score": 0,
"selected": false,
"text": "# create a new bridge network for the container\ndocker network create my-bridge\n\n# run the container on the my-bridge network and bind to IP address 172.17.0.2\ndocker run -d --name sveltekit-app --network=my-bridge --ip=172.17.0.2 -p 5050:5050 sveltekit:node\n # run the container and publish port 5050 to the host's network interface\ndocker run -d --name sveltekit-app --publish 5050:5050 sveltekit:node\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2882913/"
] |
74,566,348
|
<p>Method in model User</p>
<pre><code>public function news()
{
return $this->hasMany(News::class);
}
</code></pre>
<p>Method in model News</p>
<pre><code>public function user()
{
return $this->belongsTo(User::class);
};
</code></pre>
<p>Work</p>
<pre><code>$user=User::all();
dd($user[0]->news->user->name);
</code></pre>
<p>Not work</p>
<pre><code>$news=News::all();
dd($news[0]->user->name);
</code></pre>
<p>But array objects 'news' i getted</p>
|
[
{
"answer_id": 74566460,
"author": "Alfredo Osorio",
"author_id": 14342247,
"author_profile": "https://Stackoverflow.com/users/14342247",
"pm_score": 0,
"selected": false,
"text": "<div class=\"container\">\n@foreach ($users as $user)\n {{ $user->name }}\n@endforeach\n</div>\n \n{{ $users->links() }}"
},
{
"answer_id": 74566575,
"author": "Valentino",
"author_id": 1168006,
"author_profile": "https://Stackoverflow.com/users/1168006",
"pm_score": 1,
"selected": false,
"text": "@foreach($news as $newsCard)\n @include('includes.news.card', ['newsCard' => $newsCard])\n@endforeach\n{{$news->links()}}\n $news=News::with('user')->all();\n $news[0]->user()->name\n news user_id"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19912943/"
] |
74,566,349
|
<p>This is for WebDriverWait issue</p>
<p><a href="https://i.stack.imgur.com/nQZiL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nQZiL.png" alt="enter image description here" /></a></p>
<p>I am unable to import it despite the dependeny in my pom file.</p>
<p>This is for the error I am seeing my Intellij. it is like there is an issue with maven repo</p>
<p><a href="https://i.stack.imgur.com/CHS8j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CHS8j.png" alt="enter image description here" /></a></p>
<pre><code>package atda;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver();
}
public void open() {
driver.get("suacedemo.com");
}
public boolean isLoaded() {
WebDriverWait
}
}
</code></pre>
<p>I was hoping to be able to add WebDriverWait from Maven dependencies but it is not available despite the dependency has been added to POM</p>
|
[
{
"answer_id": 74566460,
"author": "Alfredo Osorio",
"author_id": 14342247,
"author_profile": "https://Stackoverflow.com/users/14342247",
"pm_score": 0,
"selected": false,
"text": "<div class=\"container\">\n@foreach ($users as $user)\n {{ $user->name }}\n@endforeach\n</div>\n \n{{ $users->links() }}"
},
{
"answer_id": 74566575,
"author": "Valentino",
"author_id": 1168006,
"author_profile": "https://Stackoverflow.com/users/1168006",
"pm_score": 1,
"selected": false,
"text": "@foreach($news as $newsCard)\n @include('includes.news.card', ['newsCard' => $newsCard])\n@endforeach\n{{$news->links()}}\n $news=News::with('user')->all();\n $news[0]->user()->name\n news user_id"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20179124/"
] |
74,566,354
|
<p>I need to sort the hashmap based on value List size and its' not working. I've written my custom comparator. For example hashmap is as follow:</p>
<pre><code>Test1-a,b
Test2-c,d,e
Test3-f
Test4-d,g,h,i
Test5-p,b
</code></pre>
<p>After sorting it should look like this:</p>
<pre><code>Test3-f
Test1-a,b
Test5-p,b
Test2-c,d,e
Test4-d,g,h,i
</code></pre>
<p>Sorting the keys based on value list size in ascending order. I wrote this code and it's not working:</p>
<pre><code>List<Map.Entry<String,List<String>>> list =
new ArrayList<>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<String,List<String>>>() {
public int compare( Map.Entry<String,List<String>> o1,
Map.Entry<String,List<String>> o2) {
return o1.getValue().size().compareTo(o2.getValue().size() );
}
});
</code></pre>
|
[
{
"answer_id": 74566447,
"author": "xerx593",
"author_id": 592355,
"author_profile": "https://Stackoverflow.com/users/592355",
"pm_score": 1,
"selected": false,
"text": "List.size() int Collections.sort( \n list,\n // when java >= 8, we can save all the \"decoration\" (anonymous class), and \"lambda\" instead:\n (o1,o2) -> Integer.compare(o1.getValue().size(), o2.getValue().size())\n);\n Integer.compare(int x, int y) public static int compare(int x, int y) {\n return (x < y) ? -1 : ((x == y) ? 0 : 1);\n}\n"
},
{
"answer_id": 74566755,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": " List<Map.Entry<String,List<String>>> list = \n m.entrySet()\n .stream()\n .sorted((e1, e2) -> Integer.compare(e1.getValue().size(), e2.getValue().size()))\n .collect(Collectors.toList());\n System.out.println(list);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19191974/"
] |
74,566,379
|
<p>When I run from TestNG or Maven test from locally all the test cases are working fine but in pipeline it gives me this "cannot access org.testng.Assert".
I am attaching the error screenshot of Azure Pipeline:
<a href="https://i.stack.imgur.com/k7EI5.png" rel="nofollow noreferrer">enter image description here</a></p>
<p><a href="https://i.stack.imgur.com/DhB5o.png" rel="nofollow noreferrer">enter image description here</a></p>
|
[
{
"answer_id": 74566447,
"author": "xerx593",
"author_id": 592355,
"author_profile": "https://Stackoverflow.com/users/592355",
"pm_score": 1,
"selected": false,
"text": "List.size() int Collections.sort( \n list,\n // when java >= 8, we can save all the \"decoration\" (anonymous class), and \"lambda\" instead:\n (o1,o2) -> Integer.compare(o1.getValue().size(), o2.getValue().size())\n);\n Integer.compare(int x, int y) public static int compare(int x, int y) {\n return (x < y) ? -1 : ((x == y) ? 0 : 1);\n}\n"
},
{
"answer_id": 74566755,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": " List<Map.Entry<String,List<String>>> list = \n m.entrySet()\n .stream()\n .sorted((e1, e2) -> Integer.compare(e1.getValue().size(), e2.getValue().size()))\n .collect(Collectors.toList());\n System.out.println(list);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9855896/"
] |
74,566,388
|
<p>I have a string which is like that "00100101 10010011 01010100". Every 8 bits there is a space and the string might be bigger. I want to convert it to plaintext with python3.</p>
<p>I am new in python and I tried some solutions I found here but without success.</p>
|
[
{
"answer_id": 74566447,
"author": "xerx593",
"author_id": 592355,
"author_profile": "https://Stackoverflow.com/users/592355",
"pm_score": 1,
"selected": false,
"text": "List.size() int Collections.sort( \n list,\n // when java >= 8, we can save all the \"decoration\" (anonymous class), and \"lambda\" instead:\n (o1,o2) -> Integer.compare(o1.getValue().size(), o2.getValue().size())\n);\n Integer.compare(int x, int y) public static int compare(int x, int y) {\n return (x < y) ? -1 : ((x == y) ? 0 : 1);\n}\n"
},
{
"answer_id": 74566755,
"author": "g00se",
"author_id": 16376827,
"author_profile": "https://Stackoverflow.com/users/16376827",
"pm_score": 0,
"selected": false,
"text": " List<Map.Entry<String,List<String>>> list = \n m.entrySet()\n .stream()\n .sorted((e1, e2) -> Integer.compare(e1.getValue().size(), e2.getValue().size()))\n .collect(Collectors.toList());\n System.out.println(list);\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594243/"
] |
74,566,404
|
<p>The Object Lookup method is very popular in JS and used as a better replacement for Switch-case statements e.g.</p>
<pre><code>function phoneticLookup(val) {
var result = "";
switch(val) {
case "alpha":
result = "Adams";
break;
case "bravo":
result = "Boston";
break;
case "charlie":
result = "Chicago";
break;
}
return result;
}
function phoneticLookup(val) {
var result = "";
var lookup = {
"alpha": "Adams",
"bravo": "Boston",
"charlie": "Chicago",
};
result = lookup[val];
return result;
}
</code></pre>
<p>But if the switch case is like the one below, as you can see multiple cases return the same result. How can we write it in a better way using <code>objects</code>, <code>map</code>, or any other way (not using <code>if-else</code>) in JS?</p>
<pre><code>let continent = '';
switch (country) {
case "China":
case "India":
case "Nepal":
continent = 'Asia';
break;
case "UK":
case "France":
case "Poland":
continent = 'Europe';
break;
case "Egypt":
case "Zimbave":
case "Somalia":
continent = 'Africa';
break;
default:
continent = 'Other'
break;
}
</code></pre>
|
[
{
"answer_id": 74566503,
"author": "Zac Anger",
"author_id": 5774952,
"author_profile": "https://Stackoverflow.com/users/5774952",
"pm_score": 1,
"selected": false,
"text": "const continents = {\n \"Africa\": [\"Egypt\", \"Ghana\"], // etc\n \"Asia\": [\"China\", \"Bhutan\"], // etc\n}\n\nconst assignContinent = (country) => {\n const possibleMatch = Object.entries(continents)\n .find((continent) => continent[1].includes(country))\n return possibleMatch ? possibleMatch[0] : \"Other\"\n}\n"
},
{
"answer_id": 74566754,
"author": "Peter Thoeny",
"author_id": 7475450,
"author_profile": "https://Stackoverflow.com/users/7475450",
"pm_score": 1,
"selected": false,
"text": "countryToContinentMap = {\n China: 'Asia',\n India: 'Asia',\n Nepal: 'Asia',\n UK: 'Europe',\n France: 'Europe',\n Poland: 'Europe',\n Egypt: 'Africa',\n Zimbave: 'Africa',\n Somalia: 'Africa'\n}\n\nfunction getContinent(country) {\n return countryToContinentMap[country] || 'Other';\n}\n\nconsole.log('Nepal => ' + getContinent('Nepal'));\nconsole.log('Xomur => ' + getContinent('Xomur')); Nepal => Asia\nXomur => Other\n"
},
{
"answer_id": 74566907,
"author": "Warm Red",
"author_id": 14209943,
"author_profile": "https://Stackoverflow.com/users/14209943",
"pm_score": 1,
"selected": false,
"text": "const continents = {\n \"Asia\": [\"China\", \"India\", \"Nepal\"],\n \"Europe\": [\"UK\", \"France\", \"Poland\"],\n \"Africa\": [\"Egypt\", \"Zimbabwe\", \"Somalia\"],\n};\n\nlet countryContinent = {};\n\nfor(const [continent, countries] of Object.entries(continents)){\n//Merge countryContinent with newly created object with countries as keys and for each key value equal to continent\n countryContinent = Object.assign(countryContinent, Object.fromEntries(countries.map(country =>[country, continent])));\n}\n countryContinent {\n 'China': 'Asia',\n 'India': 'Asia',\n 'Nepal': 'Asia',\n 'UK': 'Europe',\n 'France': 'Europe',\n 'Poland': 'Europe',\n 'Egypt': 'Africa',\n 'Zimbabwe': 'Africa',\n 'Somalia': 'Africa'\n}\n phoneticLookup"
},
{
"answer_id": 74572718,
"author": "Hitmands",
"author_id": 4099454,
"author_profile": "https://Stackoverflow.com/users/4099454",
"pm_score": 3,
"selected": true,
"text": "return const whichContinent = (country) => {\n switch (country) {\n case \"China\":\n case \"India\":\n case \"Nepal\": \n return 'Asia';\n\n case \"UK\":\n case \"France\":\n case \"Poland\": \n return 'Europe';\n\n case \"Egypt\":\n case \"Zimbave\":\n case \"Somalia\": \n return 'Africa';\n\n default: \n return 'Unknown'\n }\n}\n\nconsole.log(\n whichContinent('hogwarts'),\n);"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916855/"
] |
74,566,421
|
<p>I collect Free disk space metrics at regular intervals and would like to predict when the disk will be full.</p>
<p>I thought I could use <a href="https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/series-decompose-forecastfunction" rel="nofollow noreferrer">series_decompose_forecast</a></p>
<p>Here's a sample query:</p>
<pre><code>let DiskSpace =
range Timestamp from ago(60d) to now() step 1d
| order by Timestamp desc
| serialize rn=row_number() + 10
| extend FreeSpace = case
(
rn % 5 == 0, rn + 5
, rn % 3 == 0, rn -4
, rn % 7 == 0, rn +3
, rn
)
| project Timestamp, FreeSpace;
DiskSpace
| make-series
FreeSpace = max(FreeSpace) default= long(null)
on Timestamp from ago(60d) to now() step 12h
| extend FreeSpace = series_fill_backward(FreeSpace)
| extend series_decompose_forecast(FreeSpace, 24)
| render timechart
</code></pre>
<p>And the result</p>
<p><a href="https://i.stack.imgur.com/pcgKJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pcgKJ.png" alt="enter image description here" /></a></p>
<p>The baseline seems like it could show me when it will hit zero (or some other threshold), but if I specify more <code>Points</code>, it excludes more points from the learning process (still unsure if it excludes them from the start or end).</p>
<p>I don't even care for the whole time series, just the date of running out of free space. Is this the correct approach?</p>
|
[
{
"answer_id": 74567466,
"author": "ChrisWue",
"author_id": 220986,
"author_profile": "https://Stackoverflow.com/users/220986",
"pm_score": 1,
"selected": false,
"text": "let DiskSpace = \nrange Timestamp from ago(60d) to now() step 1d\n| order by Timestamp desc\n| serialize rn=row_number() + 10\n| extend FreeSpace = case\n(\n rn % 5 == 0, rn + 5\n , rn % 3 == 0, rn -4\n , rn % 7 == 0, rn +3\n , rn\n)\n| project Timestamp, FreeSpace;\nDiskSpace\n// add 4 weeks of empty slots in the \"future\" - these slots will be forecast\n| make-series FreeSpace = max(FreeSpace) default=long(null) on Timestamp from ago(60d) to now()+24h*7*4 step 12h\n| extend FreeSpace = series_fill_backward(FreeSpace)\n| extend forecast=series_decompose_forecast(FreeSpace, 7*4*2)\n| render timechart \n points N let DiskSpace = \nrange Timestamp from ago(60d) to now() step 1d\n| order by Timestamp desc\n| serialize rn=row_number() + 10\n| extend FreeSpace = case\n(\n rn % 5 == 0, rn + 5\n , rn % 3 == 0, rn -4\n , rn % 7 == 0, rn +3\n , rn\n)\n| project Timestamp, FreeSpace;\nDiskSpace\n| make-series FreeSpace = max(FreeSpace) default=long(null) on Timestamp from ago(60d) to now()+24h*7*4 step 12h\n| extend FreeSpace = series_fill_backward(FreeSpace)\n| extend forecast=series_decompose_forecast(FreeSpace, 7*4*2)\n| mv-apply with_itemindex=idx f=forecast to typeof(double) on (\n where f <= 0.5\n | summarize min(idx)\n)\n| project AlmostOutOfDiskSpace = Timestamp[min_idx], PredictedDiskSpaceAtThatPoint = forecast[min_idx]\n"
},
{
"answer_id": 74571775,
"author": "David דודו Markovitz",
"author_id": 6336479,
"author_profile": "https://Stackoverflow.com/users/6336479",
"pm_score": 3,
"selected": true,
"text": "range Timestamp from now() to ago(60d) step -1d\n| extend rn = row_number() + 10\n| extend FreeSpace = rn + case(rn % 5 == 0, 5, rn % 3 == 0, -4, rn % 7 == 0, 3, 0)\n| make-series FreeSpace = max(FreeSpace) default= long(null) on Timestamp from ago(60d) to now() step 12h\n| extend FreeSpace = series_fill_forward(series_fill_backward(FreeSpace))\n| extend (rsquare, slope, variance, rvariance, interception, line_fit) = series_fit_line(FreeSpace)\n| project slope, interception, Timestamp, FreeSpace, line_fit\n| extend x_intercept = todatetime(Timestamp[0]) - 12h*(1 + interception / slope)\n| project-reorder x_intercept\n| render timechart with (xcolumn=Timestamp, ycolumns=FreeSpace,line_fit)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4609186/"
] |
74,566,472
|
<p>I am using Blazor and I am a beginner.</p>
<p>Currently I have several Blazor components that all need the same JSON data (data fetched from one URL, e.g., http://localhost/todo)</p>
<p>Instead of fetching the same URL inside all my components and duplicating my code, I decided to create a Service that fetchs the URL and share this service's output accross my components.</p>
<p>Here is the service, and all it does fetch a URL and return a JSON object (at least that is what I am trying to do)</p>
<pre><code>using TodoApp.Models.TodoTestModel;
using Newtonsoft.Json;
using System.Net.Http.Headers;
namespace Todo.Services
{
public class Todo
{
public string TodoURL { get; set; }
public object result { get; set; }
async public Task<object> TodoTypes()
{
using (HttpClient client = new HttpClient())
{
// HTTP header stuff
HttpResponseMessage response = client.GetAsync(TodoURL).Result;
response.EnsureSuccessStatusCode();
string responseData = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<TodoTestModel>(responseData);
return result;
}
}
}
}
}
</code></pre>
<p>The idea is call this service and give my components the output as</p>
<pre><code><TodoComponent ToDoResult="@result"> </ToDoComponent>
</code></pre>
<p>But I am having a problem when instanciating the object, e.g,:</p>
<pre><code>@page "/"
@using TodoApp.Services;
@inject TodoApp.Services.Todo Todo;
<h5> List of todos </h5>
@code {
Todo td = new Todo();
td.TodoURL = ".." // does not work
}
</code></pre>
<p>In short I am trying to do the following:</p>
<ul>
<li>Instanciate the class</li>
<li>Provide it a URL</li>
<li>Get the JSON data (result) to pass it into my TodoComponent</li>
</ul>
<p>Thanks for the help</p>
|
[
{
"answer_id": 74576462,
"author": "Vikram Reddy",
"author_id": 20552709,
"author_profile": "https://Stackoverflow.com/users/20552709",
"pm_score": 0,
"selected": false,
"text": "await builder.Build().RunAsync(); ...\nusing Microsoft.AspNetCore.Components.Web;\nusing Microsoft.AspNetCore.Components.WebAssembly.Hosting;\n\nvar builder = WebAssemblyHostBuilder.CreateDefault(args);\nbuilder.RootComponents.Add<App>(\"#app\");\nbuilder.RootComponents.Add<HeadOutlet>(\"head::after\");\n\nbuilder.Services.AddScoped(sp => new HttpClient { BaseAddress = new \nUri(builder.HostEnvironment.BaseAddress) });\n\n// Register services\nbuilder.Services.AddScoped<TodoService>(); // <----- Add this line\n\nawait builder.Build().RunAsync();\n public class TodoService\n{\n public string TodoURL { get; set; }\n \n public async Task<List<TodoTestModel>> GetTodoTypesAsync()\n {\n using (HttpClient client = new HttpClient())\n {\n // HTTP header stuff\n\n HttpResponseMessage response = await client.GetAsync(TodoURL);\n response.EnsureSuccessStatusCode();\n string responseData = await response.Content.ReadAsStringAsync();\n return JsonConvert.DeserializeObject<List<TodoTestModel>>(responseData);\n }\n }\n}\n @page \"/\"\n@using TodoApp.Services; \n@inject TodoService TodoService; \n\n<h5> List of todos </h5>\n@if(todoList is not null && todoList.Any())\n{\n <ul>\n @foreach(var item in todoList)\n {\n <li>@item.Name</li>\n }\n </ul>\n}\n\n@code {\n private List<TodoTestModel> todoList;\n\n protected override async Task OnInitializedAsync()\n {\n TodoServices.TodoURL = \"\"; // TODO: set the API url\n todoList = await TodoService.GetTodoTypesAsync();\n await base.OnInitializedAsync();\n }\n}\n"
},
{
"answer_id": 74613572,
"author": "Ivan Ambla",
"author_id": 11514602,
"author_profile": "https://Stackoverflow.com/users/11514602",
"pm_score": 0,
"selected": false,
"text": "using Microsoft.AspNetCore.Components.Web;\nusing Microsoft.AspNetCore.Components.WebAssembly.Hosting;\nusing BlazorApp1;\n\nvar builder = WebAssemblyHostBuilder.CreateDefault(args);\nbuilder.RootComponents.Add<App>(\"#app\");\nbuilder.RootComponents.Add<HeadOutlet>(\"head::after\");\n\nbuilder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });\nbuilder.Services.AddScoped(sp => new TodoService());\n\nawait builder.Build().RunAsync();\n namespace BlazorApp1;\n\npublic class TodoService\n{\n public TodoService()\n {\n }\n\n public List<string> GetTodos()\n {\n //write your code here that fetches the todos using the TodosUrl\n throw new NotImplementedException();\n }\n \n public string TodosUrl { get; set; } = \"https://google.com\";\n}\n @inject TodoService TodoService\n\n<ul>\n @foreach (var todo in Todos)\n {\n <li>@todo</li>\n }\n</ul>\n\n@code {\n public List<string> Todos { get; set; }\n protected override void OnInitialized()\n {\n TodoService.TodosUrl = \"https://stackoverflow.com\";\n Todos = TodoService.GetTodos();\n base.OnInitialized();\n }\n\n}\n\n"
},
{
"answer_id": 74635529,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 1,
"selected": false,
"text": "new Todo td = new Todo();\n Todo TodoURL td.TodoURL = \"http://localhost/todo\";\n\n TodoTypes Todo var result = await td.TodoTypes();\n object object TodoComponent <TodoComponent ToDoResult=\"@result\"> </TodoComponent>\n TodoComponent ToDoResult @page \"/\"\n@using TodoApp.Services; \n@inject TodoApp.Services.Todo Todo; \n\n<h5> List of todos </h5>\n\n@code {\n Todo td = new Todo(); \n td.TodoURL = \"http://localhost/todo\";\n var result = await td.TodoTypes();\n}\n\n<TodoComponent ToDoResult=\"@result\"> </TodoComponent>\n"
},
{
"answer_id": 74654691,
"author": "SDHEER",
"author_id": 9799107,
"author_profile": "https://Stackoverflow.com/users/9799107",
"pm_score": 1,
"selected": false,
"text": " var response = await client.GetFromJsonAsync(TodoURL); \n return response;\n"
},
{
"answer_id": 74663178,
"author": "Benjamin Woolston",
"author_id": 20188398,
"author_profile": "https://Stackoverflow.com/users/20188398",
"pm_score": 1,
"selected": false,
"text": "@page \"/\"\n@using TodoApp.Services; \n@inject TodoApp.Services.Todo Todo; \n\n<h5> List of todos </h5>\n\n@code {\n private TodoTestModel result;\n\n protected override async Task OnInitializedAsync()\n {\n Todo td = new Todo(); \n td.TodoURL = \"http://localhost/todo\";\n result = await td.TodoTypes();\n }\n}\n <TodoComponent ToDoResult=\"@result\"> </TodoComponent>\n using TodoApp.Models.TodoTestModel;\nusing Newtonsoft.Json;\nusing System.Net.Http.Headers;\n\nnamespace Todo.Services\n{\n public class Todo \n {\n private readonly HttpClient _client;\n\n public Todo()\n {\n _client = new HttpClient();\n }\n\n public string TodoURL { get; set; }\n\n async public Task<TodoTestModel> TodoTypes()\n {\n // HTTP header stuff\n\n HttpResponseMessage response = await _client.GetAsync(TodoURL);\n response.EnsureSuccessStatusCode();\n string responseData = await response.Content.ReadAsStringAsync();\n return JsonConvert.DeserializeObject<TodoTestModel>(responseData);\n }\n }\n}\n"
},
{
"answer_id": 74669437,
"author": "thatthing",
"author_id": 624493,
"author_profile": "https://Stackoverflow.com/users/624493",
"pm_score": 0,
"selected": false,
"text": "@page \"/\"\n@using TodoApp.Services;\n@inject TodoApp.Services.Todo Todo;\n\n<h5> List of todos </h5>\n@code {\nobject result;\nprotected override async Task OnInitializedAsync()\n{\n// Create an instance of the Todo service\nTodo td = new Todo(); \n\n// Set the URL to fetch data from\ntd.TodoURL = \"http://localhost/todo\";\n\n// Fetch the data from the URL and store the result in the 'result' \nvariable\nresult = await td.TodoTypes();\n}\n"
},
{
"answer_id": 74669836,
"author": "Diego Lamarão",
"author_id": 11013622,
"author_profile": "https://Stackoverflow.com/users/11013622",
"pm_score": 0,
"selected": false,
"text": "@page \"/\"\n@using TodoApp.Services; \n@inject TodoApp.Services.Todo Todo; \n\n<h5> List of todos </h5>\n\n@code {\n Todo td; \n\n protected override async Task OnInitAsync()\n {\n td = new Todo(); \n td.TodoURL = \"..\";\n result = await td.TodoTypes();\n }\n}\n"
},
{
"answer_id": 74670176,
"author": "Akshay",
"author_id": 3881787,
"author_profile": "https://Stackoverflow.com/users/3881787",
"pm_score": 0,
"selected": false,
"text": "services.AddScoped<Todo>();\n @page \"/\"\n@using TodoApp.Services;\n@inject TodoApp.Services.Todo Todo;\n\n<h5> List of todos </h5>\n\n@code {\n // The Todo service is available as a property of the Todo variable\n var result = await Todo.TodoTypes();\n}\n <TodoComponent ToDoResult=\"@result\"> </ToDoComponent>\n"
},
{
"answer_id": 74670880,
"author": "Ataberk",
"author_id": 4857232,
"author_profile": "https://Stackoverflow.com/users/4857232",
"pm_score": 1,
"selected": false,
"text": "public void ConfigureServices(IServiceCollection services)\n{\n // Register the Todo service with the dependency injection container\n services.AddScoped<Todo>();\n\n // Other code...\n}\n @page \"/\"\n@using TodoApp.Services;\n@inject Todo Todo;\n\n<h5> List of todos </h5>\n\n@code {\n TodoTestModel result;\n\n protected override async Task OnInitializedAsync()\n {\n // Call the TodoTypes method to get the JSON data\n result = await Todo.TodoTypes();\n }\n}\n <TodoComponent ToDoResult=\"@result\"> </ToDoComponent>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13502536/"
] |
74,566,491
|
<p>I am trying to get a substring between two markers using <code>re</code> in Python, for example:</p>
<pre><code>import re
test_str = "#$ -N model_simulation 2022"
# these two lines work
# the output is: model_simulation
print(re.search("-N(.*)2022",test_str).group(1))
print(re.search(" -N(.*)2022",test_str).group(1))
# these two lines give the error: 'NoneType' object has no attribute 'group'
print(re.search("$ -N(.*)2022",test_str).group(1))
print(re.search("#$ -N(.*)2022",test_str).group(1))
</code></pre>
<p>I read the documentation of <code>re</code> <a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">here</a>. It says that "#" is intentionally ignored so that the outputs look neater.</p>
<p>But in my case, I do need to include "#" and "$". I need them to identify the part of the string that I want, because the "-N" is not unique in my entire text string for real work.</p>
<p>Is there a way to force <code>re</code> to include those? Or is there a different way without using <code>re</code>?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 74576462,
"author": "Vikram Reddy",
"author_id": 20552709,
"author_profile": "https://Stackoverflow.com/users/20552709",
"pm_score": 0,
"selected": false,
"text": "await builder.Build().RunAsync(); ...\nusing Microsoft.AspNetCore.Components.Web;\nusing Microsoft.AspNetCore.Components.WebAssembly.Hosting;\n\nvar builder = WebAssemblyHostBuilder.CreateDefault(args);\nbuilder.RootComponents.Add<App>(\"#app\");\nbuilder.RootComponents.Add<HeadOutlet>(\"head::after\");\n\nbuilder.Services.AddScoped(sp => new HttpClient { BaseAddress = new \nUri(builder.HostEnvironment.BaseAddress) });\n\n// Register services\nbuilder.Services.AddScoped<TodoService>(); // <----- Add this line\n\nawait builder.Build().RunAsync();\n public class TodoService\n{\n public string TodoURL { get; set; }\n \n public async Task<List<TodoTestModel>> GetTodoTypesAsync()\n {\n using (HttpClient client = new HttpClient())\n {\n // HTTP header stuff\n\n HttpResponseMessage response = await client.GetAsync(TodoURL);\n response.EnsureSuccessStatusCode();\n string responseData = await response.Content.ReadAsStringAsync();\n return JsonConvert.DeserializeObject<List<TodoTestModel>>(responseData);\n }\n }\n}\n @page \"/\"\n@using TodoApp.Services; \n@inject TodoService TodoService; \n\n<h5> List of todos </h5>\n@if(todoList is not null && todoList.Any())\n{\n <ul>\n @foreach(var item in todoList)\n {\n <li>@item.Name</li>\n }\n </ul>\n}\n\n@code {\n private List<TodoTestModel> todoList;\n\n protected override async Task OnInitializedAsync()\n {\n TodoServices.TodoURL = \"\"; // TODO: set the API url\n todoList = await TodoService.GetTodoTypesAsync();\n await base.OnInitializedAsync();\n }\n}\n"
},
{
"answer_id": 74613572,
"author": "Ivan Ambla",
"author_id": 11514602,
"author_profile": "https://Stackoverflow.com/users/11514602",
"pm_score": 0,
"selected": false,
"text": "using Microsoft.AspNetCore.Components.Web;\nusing Microsoft.AspNetCore.Components.WebAssembly.Hosting;\nusing BlazorApp1;\n\nvar builder = WebAssemblyHostBuilder.CreateDefault(args);\nbuilder.RootComponents.Add<App>(\"#app\");\nbuilder.RootComponents.Add<HeadOutlet>(\"head::after\");\n\nbuilder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });\nbuilder.Services.AddScoped(sp => new TodoService());\n\nawait builder.Build().RunAsync();\n namespace BlazorApp1;\n\npublic class TodoService\n{\n public TodoService()\n {\n }\n\n public List<string> GetTodos()\n {\n //write your code here that fetches the todos using the TodosUrl\n throw new NotImplementedException();\n }\n \n public string TodosUrl { get; set; } = \"https://google.com\";\n}\n @inject TodoService TodoService\n\n<ul>\n @foreach (var todo in Todos)\n {\n <li>@todo</li>\n }\n</ul>\n\n@code {\n public List<string> Todos { get; set; }\n protected override void OnInitialized()\n {\n TodoService.TodosUrl = \"https://stackoverflow.com\";\n Todos = TodoService.GetTodos();\n base.OnInitialized();\n }\n\n}\n\n"
},
{
"answer_id": 74635529,
"author": "regex",
"author_id": 9470979,
"author_profile": "https://Stackoverflow.com/users/9470979",
"pm_score": 1,
"selected": false,
"text": "new Todo td = new Todo();\n Todo TodoURL td.TodoURL = \"http://localhost/todo\";\n\n TodoTypes Todo var result = await td.TodoTypes();\n object object TodoComponent <TodoComponent ToDoResult=\"@result\"> </TodoComponent>\n TodoComponent ToDoResult @page \"/\"\n@using TodoApp.Services; \n@inject TodoApp.Services.Todo Todo; \n\n<h5> List of todos </h5>\n\n@code {\n Todo td = new Todo(); \n td.TodoURL = \"http://localhost/todo\";\n var result = await td.TodoTypes();\n}\n\n<TodoComponent ToDoResult=\"@result\"> </TodoComponent>\n"
},
{
"answer_id": 74654691,
"author": "SDHEER",
"author_id": 9799107,
"author_profile": "https://Stackoverflow.com/users/9799107",
"pm_score": 1,
"selected": false,
"text": " var response = await client.GetFromJsonAsync(TodoURL); \n return response;\n"
},
{
"answer_id": 74663178,
"author": "Benjamin Woolston",
"author_id": 20188398,
"author_profile": "https://Stackoverflow.com/users/20188398",
"pm_score": 1,
"selected": false,
"text": "@page \"/\"\n@using TodoApp.Services; \n@inject TodoApp.Services.Todo Todo; \n\n<h5> List of todos </h5>\n\n@code {\n private TodoTestModel result;\n\n protected override async Task OnInitializedAsync()\n {\n Todo td = new Todo(); \n td.TodoURL = \"http://localhost/todo\";\n result = await td.TodoTypes();\n }\n}\n <TodoComponent ToDoResult=\"@result\"> </TodoComponent>\n using TodoApp.Models.TodoTestModel;\nusing Newtonsoft.Json;\nusing System.Net.Http.Headers;\n\nnamespace Todo.Services\n{\n public class Todo \n {\n private readonly HttpClient _client;\n\n public Todo()\n {\n _client = new HttpClient();\n }\n\n public string TodoURL { get; set; }\n\n async public Task<TodoTestModel> TodoTypes()\n {\n // HTTP header stuff\n\n HttpResponseMessage response = await _client.GetAsync(TodoURL);\n response.EnsureSuccessStatusCode();\n string responseData = await response.Content.ReadAsStringAsync();\n return JsonConvert.DeserializeObject<TodoTestModel>(responseData);\n }\n }\n}\n"
},
{
"answer_id": 74669437,
"author": "thatthing",
"author_id": 624493,
"author_profile": "https://Stackoverflow.com/users/624493",
"pm_score": 0,
"selected": false,
"text": "@page \"/\"\n@using TodoApp.Services;\n@inject TodoApp.Services.Todo Todo;\n\n<h5> List of todos </h5>\n@code {\nobject result;\nprotected override async Task OnInitializedAsync()\n{\n// Create an instance of the Todo service\nTodo td = new Todo(); \n\n// Set the URL to fetch data from\ntd.TodoURL = \"http://localhost/todo\";\n\n// Fetch the data from the URL and store the result in the 'result' \nvariable\nresult = await td.TodoTypes();\n}\n"
},
{
"answer_id": 74669836,
"author": "Diego Lamarão",
"author_id": 11013622,
"author_profile": "https://Stackoverflow.com/users/11013622",
"pm_score": 0,
"selected": false,
"text": "@page \"/\"\n@using TodoApp.Services; \n@inject TodoApp.Services.Todo Todo; \n\n<h5> List of todos </h5>\n\n@code {\n Todo td; \n\n protected override async Task OnInitAsync()\n {\n td = new Todo(); \n td.TodoURL = \"..\";\n result = await td.TodoTypes();\n }\n}\n"
},
{
"answer_id": 74670176,
"author": "Akshay",
"author_id": 3881787,
"author_profile": "https://Stackoverflow.com/users/3881787",
"pm_score": 0,
"selected": false,
"text": "services.AddScoped<Todo>();\n @page \"/\"\n@using TodoApp.Services;\n@inject TodoApp.Services.Todo Todo;\n\n<h5> List of todos </h5>\n\n@code {\n // The Todo service is available as a property of the Todo variable\n var result = await Todo.TodoTypes();\n}\n <TodoComponent ToDoResult=\"@result\"> </ToDoComponent>\n"
},
{
"answer_id": 74670880,
"author": "Ataberk",
"author_id": 4857232,
"author_profile": "https://Stackoverflow.com/users/4857232",
"pm_score": 1,
"selected": false,
"text": "public void ConfigureServices(IServiceCollection services)\n{\n // Register the Todo service with the dependency injection container\n services.AddScoped<Todo>();\n\n // Other code...\n}\n @page \"/\"\n@using TodoApp.Services;\n@inject Todo Todo;\n\n<h5> List of todos </h5>\n\n@code {\n TodoTestModel result;\n\n protected override async Task OnInitializedAsync()\n {\n // Call the TodoTypes method to get the JSON data\n result = await Todo.TodoTypes();\n }\n}\n <TodoComponent ToDoResult=\"@result\"> </ToDoComponent>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9851307/"
] |
74,566,509
|
<p>I'm pretty new to neovim and vim in general and I tried to use the localleader key (default: \) and nothing happened.</p>
<p>Then I tried to set the localleader key in the config (lua) in various ways I could find online, none of which worked.</p>
<p>However when I type <code>:echo maplocalleader</code> in neovim it shows the key I set.</p>
<p>Setting maplocalleader from within neovim also yielded the same result.</p>
<p>My question is, what might be preventing my localleader key from working?</p>
|
[
{
"answer_id": 74569575,
"author": "LoneExile",
"author_id": 20253319,
"author_profile": "https://Stackoverflow.com/users/20253319",
"pm_score": 0,
"selected": false,
"text": "local opts = { noremap = true, silent = true }\nlocal keymap = vim.api.nvim_set_keymap\n\n--Remap '\\\\' as leader key\nkeymap('', '\\\\', '<Nop>', opts)\nvim.g.mapleader = '\\\\'\nvim.g.maplocalleader = '\\\\'\n"
},
{
"answer_id": 74577629,
"author": "Lukiko",
"author_id": 17037350,
"author_profile": "https://Stackoverflow.com/users/17037350",
"pm_score": 2,
"selected": true,
"text": "vim.g.maplocalleader = \";\""
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17037350/"
] |
74,566,535
|
<p>I am trying to download a zip file that is stored here:</p>
<pre><code>http://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip
</code></pre>
<p>If you paste this into the browser and hit enter, it will download the .zip folder.</p>
<p>If you inspect the browser while this is happening, you will see that there is an internal redirect going on:</p>
<p><a href="https://i.stack.imgur.com/1QOgk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1QOgk.png" alt="1" /></a></p>
<p><a href="https://i.stack.imgur.com/ChblL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ChblL.png" alt="2" /></a></p>
<p>And eventually the zip gets downloaded.</p>
<p>I am trying to automate this downloading using the python requests library by doing the following:</p>
<pre><code>import requests
requests.get(url,
allow_redirects=True,
headers={'User-Agent':'Chrome/107.0.0.0'})
</code></pre>
<p>I've tried tons of combinations, using the full header string from the HTML inspection, forcing verify=True, with and without redirects, adding a <code>HTTPBasicAuth</code> user/pass that says is required although the file seems to download fine without any credentials.</p>
<p>Honestly no clue what I'm missing, this is not my expertise. I keep getting this error:</p>
<pre><code>>>> requests.get(url,
... allow_redirects=True,
... headers={'User-Agent':'Chrome/107.0.0.0'})
Traceback (most recent call last):
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connection.py", line 174, in _new_conn
conn = connection.create_connection(
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\util\connection.py", line 95, in create_connection
raise err
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\util\connection.py", line 85, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine
actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connection.py", line 239, in request
super(HTTPConnection, self).request(method, url, body=body, headers=headers)
File "C:\Users\dere\Miniconda3\envs\blender\lib\http\client.py", line 1282, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Users\dere\Miniconda3\envs\blender\lib\http\client.py", line 1328, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Users\dere\Miniconda3\envs\blender\lib\http\client.py", line 1277, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Users\dere\Miniconda3\envs\blender\lib\http\client.py", line 1037, in _send_output
self.send(msg)
File "C:\Users\dere\Miniconda3\envs\blender\lib\http\client.py", line 975, in send
self.connect()
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connection.py", line 205, in connect
conn = self._new_conn()
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connection.py", line 186, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x0000016B76A6FE50>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\requests\adapters.py", line 489, in send
resp = conn.urlopen(
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\connectionpool.py", line 787, in urlopen
retries = retries.increment(
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\urllib3\util\retry.py", line 592, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='e4ftl01.cr.usgs.gov', port=80): Max retries exceeded with url: /MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000016B76A6FE50>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\requests\api.py", line 73, in get
return request("get", url, params=params, **kwargs)
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\requests\api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\requests\sessions.py", line 587, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\requests\sessions.py", line 701, in send
r = adapter.send(request, **kwargs)
File "C:\Users\dere\Miniconda3\envs\blender\lib\site-packages\requests\adapters.py", line 565, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='e4ftl01.cr.usgs.gov', port=80): Max retries exceeded with url: /MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000016B76A6FE50>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
</code></pre>
<p>Can someone help me arrive at the code that will result in a successful request? I know how to write the request into a zip afterwards..</p>
|
[
{
"answer_id": 74566654,
"author": "cnemri",
"author_id": 3892280,
"author_profile": "https://Stackoverflow.com/users/3892280",
"pm_score": 1,
"selected": false,
"text": "import requests\n\n# download zip file from url\nurl = \"https://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip\"\nr = requests.get(url)\nwith open(\"N45W074.SRTMGL1.hgt.zip\", \"wb\") as f:\n f.write(r.content)\n"
},
{
"answer_id": 74567020,
"author": "Derek Eden",
"author_id": 10818128,
"author_profile": "https://Stackoverflow.com/users/10818128",
"pm_score": 0,
"selected": false,
"text": "headers = {'Cookie': '_gid=GA1.2.48775707.1669266346; _hjSessionUser_606685=eyJpZCI6IjQ1MzEzM2QzLTI3MWEtNWM0YS04M2YzLWRmMmMzNDk4NjY1ZSIsImNyZWF0ZWQiOjE2NjkyNjYzNDU2MjUsImV4aXN0aW5nIjp0cnVlfQ==; ERS_production_2=b7dfade669180a6d6d250b030ffc3cf2UZZa8%2F471MfcV%2FaNuFtu6Pli%2BpP8jKOIwR4JvQjm%2B6DLPjl679vVf5SCDk7C5TLQsj7qckIev6lmtGb6Mes5RKDHUs%2BBp3EAjKW2%2BMCUpV%2Fnx0z1pdaCQQ%3D%3D; EROS_SSO_production_secure=eyJjcmVhdGVkIjoxNjY5MjY5MjEzLCJ1cGRhdGVkIjoiMjAyMi0xMS0yMyAyMzo1MzoyOCIsImF1dGhUeXBlIjoiRVJTIiwiYXV0aFNlcnZpY2UiOiJFUk9TIiwidmVyc2lvbiI6MS4xLCJzdGF0ZSI6ImVjMDY3YmMzYmRhMzBiZTUyNTkxYTNiZTYwMTMwZWNmNjAwMWU1Y2JlMGMxZmNkYTU4Y2Y4OTY0YjRlNTJkOTEiLCJpZCI6InY5U1Q4YVl3M1hRKCsyIiwic2VjcmV0IjoiPl8lMCZPYiY9MUVkclRLZTt4fHVZLVcyU1VvTiA1SE17KiQqaG12OSxvPl5%2BdyJ9; _ga_0YWDZEJ295=GS1.1.1669269458.1.0.1669269460.0.0.0; _ga=GA1.2.1055277358.1669266346; _ga_71JPYV1CCS=GS1.1.1669306300.2.1.1669306402.0.0.0; DATA=Y3_gg9uD6LmunsfDHneR9wAAARQ'}\n requests.get(url, headers=headers)\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10818128/"
] |
74,566,537
|
<p>I'm parsing a CSV file using python. I've two problem:</p>
<ol>
<li>My list is being treated as string</li>
<li>Is there a way to make my parsing more "elegant"</li>
</ol>
<p>Example CSV file</p>
<pre><code>Name, Address
host1,['192.168.x.10', '127.0.0.1']
host2,['192.168.x.12', '127.0.0.1']
host3,['192.168.x.14', '127.0.0.1']
</code></pre>
<p>My code:</p>
<pre><code>with open('myFile') as file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
for row in csv_reader:
for i in row['Address'].strip("][").replace("'","").split:
if('192.168' in i):
break
print(row[host], i)
</code></pre>
<p>Output:</p>
<pre><code>host1 192.168.x.10
host2 192.168.x.12
host3 192.168.x.14
</code></pre>
|
[
{
"answer_id": 74566814,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "padnas pandas ast.literal_eval import ast\nimport pandas as pd\n\ndf = pd.read_csv('test.csv')\ndf['Address'] = df['Address'].apply(ast.literal_eval)\n test.csv"
},
{
"answer_id": 74567507,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval reader import csv, re\naddress_pattern = r'\\w+\\.\\w+\\.\\w+\\.\\w+'\n\nwith open('myFile') as file:\n csv_reader = csv.reader(file, skipinitialspace=True)\n headers = next(csv_reader)\n address_list = [dict(zip(headers, (row[0], re.findall(address_pattern, ''.join(row))))) for row in csv_reader]\n\nprint('\\n'.join(f\"{item['Name']} {address}\" for item in address_list for address in item['Address'] if address.startswith('192.168')))\n# output:\n# host1 192.168.x.10\n# host2 192.168.x.12\n# host3 192.168.x.14\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17487397/"
] |
74,566,563
|
<p>In the code below when I return a class object in the function <code>getServerSideProps</code> through props, in the page function the variable is undefined, just like in the code below.</p>
<pre><code>export default function cars(obj){
return <h1>counter: {obj.counter}</h1> // obj is undefined, why??
}
export async function getServerSideProps({req,res}){
class Counter{
constructor(){
this.counter = 22
}
}
var counter = new Counter()
return {
props:
{
obj:JSON.stringify(counter)
}
}
}
</code></pre>
<p>I was expecting that the page parameter obj would have the object counter and not be undefined.</p>
|
[
{
"answer_id": 74566814,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "padnas pandas ast.literal_eval import ast\nimport pandas as pd\n\ndf = pd.read_csv('test.csv')\ndf['Address'] = df['Address'].apply(ast.literal_eval)\n test.csv"
},
{
"answer_id": 74567507,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval reader import csv, re\naddress_pattern = r'\\w+\\.\\w+\\.\\w+\\.\\w+'\n\nwith open('myFile') as file:\n csv_reader = csv.reader(file, skipinitialspace=True)\n headers = next(csv_reader)\n address_list = [dict(zip(headers, (row[0], re.findall(address_pattern, ''.join(row))))) for row in csv_reader]\n\nprint('\\n'.join(f\"{item['Name']} {address}\" for item in address_list for address in item['Address'] if address.startswith('192.168')))\n# output:\n# host1 192.168.x.10\n# host2 192.168.x.12\n# host3 192.168.x.14\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11783235/"
] |
74,566,583
|
<p>I have created a function to calculate my weekly profit and loss. It worked as per below and I would to break it down to have the only per symbols/pairs. I have been stucked on this aggregation. Any hints are appreciated.</p>
<pre><code>string WeeklyProfit()
{
string msg_WeeklyProfit="";
int i,hstTotal=OrdersHistoryTotal();
double profit;
datetime starttime = iTime(Symbol(), PERIOD_W1, 0);
for(i=0;i<hstTotal;i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==TRUE)
{
if(OrderOpenTime() >= starttime)
{
profit += OrderProfit() + OrderSwap() + OrderCommission();
}
}
msg_WeeklyProfit=profit+ " "+ AccountCurrency();
}
return(msg_WeeklyProfit);
</code></pre>
<p>I tried to create a symbol array but that wasn’t successful. I’m stucked on the total weekly.</p>
|
[
{
"answer_id": 74566814,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "padnas pandas ast.literal_eval import ast\nimport pandas as pd\n\ndf = pd.read_csv('test.csv')\ndf['Address'] = df['Address'].apply(ast.literal_eval)\n test.csv"
},
{
"answer_id": 74567507,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval reader import csv, re\naddress_pattern = r'\\w+\\.\\w+\\.\\w+\\.\\w+'\n\nwith open('myFile') as file:\n csv_reader = csv.reader(file, skipinitialspace=True)\n headers = next(csv_reader)\n address_list = [dict(zip(headers, (row[0], re.findall(address_pattern, ''.join(row))))) for row in csv_reader]\n\nprint('\\n'.join(f\"{item['Name']} {address}\" for item in address_list for address in item['Address'] if address.startswith('192.168')))\n# output:\n# host1 192.168.x.10\n# host2 192.168.x.12\n# host3 192.168.x.14\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19471232/"
] |
74,566,615
|
<p>Is it possible to declare multiple variable bindings in one line in SML? For example, I have the following:</p>
<pre class="lang-ml prettyprint-override"><code>let
val m1 = [1]
val m2 = [2]
val m3 = [3]
in
{...}
end
</code></pre>
<p>I would like to condense this down to something like</p>
<pre class="lang-ml prettyprint-override"><code>let
val m1 = [1], m2 = [2], m3 = [3]
in
{...}
end
</code></pre>
<p>This syntax doesn't work, but is there a way to declare multiple variable bindings in one line like this?</p>
|
[
{
"answer_id": 74566814,
"author": "npetrov937",
"author_id": 13078832,
"author_profile": "https://Stackoverflow.com/users/13078832",
"pm_score": 1,
"selected": false,
"text": "padnas pandas ast.literal_eval import ast\nimport pandas as pd\n\ndf = pd.read_csv('test.csv')\ndf['Address'] = df['Address'].apply(ast.literal_eval)\n test.csv"
},
{
"answer_id": 74567507,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "ast.literal_eval reader import csv, re\naddress_pattern = r'\\w+\\.\\w+\\.\\w+\\.\\w+'\n\nwith open('myFile') as file:\n csv_reader = csv.reader(file, skipinitialspace=True)\n headers = next(csv_reader)\n address_list = [dict(zip(headers, (row[0], re.findall(address_pattern, ''.join(row))))) for row in csv_reader]\n\nprint('\\n'.join(f\"{item['Name']} {address}\" for item in address_list for address in item['Address'] if address.startswith('192.168')))\n# output:\n# host1 192.168.x.10\n# host2 192.168.x.12\n# host3 192.168.x.14\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4537850/"
] |
74,566,634
|
<p>Is it possible to solve the following problem without a cycle? By using a math formula. It could make my app much faster.</p>
<p>How many times can 43920 be subtracted in 189503, while each subtraction result is greater than 79920</p>
<p>Example:</p>
<pre><code>189503 > 79920 so 189503-43920=145583 (1 time)
145583 > 79920 so 145583-43920=101663 (2 times)
101663 > 79920 so 101663-43920=57743 (3 times)
57743 < 43920 so it means it ran 3 times
This would be the same as 189503-(43920*3) = 57743 or 189503 % (43920*3)
</code></pre>
<p>I don't know if i wrote my question well, maybe you can help</p>
|
[
{
"answer_id": 74566663,
"author": "manuelmhtr",
"author_id": 1628009,
"author_profile": "https://Stackoverflow.com/users/1628009",
"pm_score": 2,
"selected": false,
"text": "Math.floor((189503 - 79920) / 43920) 2 79920 43920 floor"
},
{
"answer_id": 74566711,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 1,
"selected": false,
"text": "189503 - (43920 * x) = 79920\n\n189503 = 79920 + (43920 * x)\n\n189503 - 79920 = 43920x\n\nx = (189503 - 79920) / 43920\n\nx = 2.49505919854\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13720928/"
] |
74,566,635
|
<p>Here is the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int* cut(int* x, int n);
int main() {
int *x= NULL,n;
x = malloc(sizeof(int));
printf("Amount of elements: ");
scanf("%d", x);
x = realloc(x, (*x+1) * sizeof(int));
assert(x != NULL);// allocate memory and ensure that this was successful
for (int i = 1; i <= *x; i++) {
printf("%d Element: ", i);
scanf("%d", x+i);
}
printf("pper barrier: ");
scanf("%d", &n);
x = cut(x,n);
for (int i = 1; i <= *x; i++) {
printf("%d ", *(x+i));
}
printf("\n");
free(x);
}
int* cut(int *x, int n) {
int a = 1;
for (int i = 1; i <= *x; i++) {
if(*(x+i) < n) {
*(x+a) = *(x+i);
a++;
}
}
*x = a-1;
x = realloc(x, (a+1) * sizeof(int));
return x;
}
</code></pre>
<p>The code works fine however I do not unterstand the line <code>x = realloc(x, (*x+1) * sizeof(int));</code> Furthermore I don't get why the first <code>x</code> has <code>no *</code> but the second <code>(*x+1)</code> has one. Does this mean a pointer of the pointer?</p>
<p>I think it just means that the array malloc that was made is getting bigger by one value However I'm not sure and a still a bit confused what that actually means, could someone please help me out and clarify my missunderstanding?</p>
|
[
{
"answer_id": 74566663,
"author": "manuelmhtr",
"author_id": 1628009,
"author_profile": "https://Stackoverflow.com/users/1628009",
"pm_score": 2,
"selected": false,
"text": "Math.floor((189503 - 79920) / 43920) 2 79920 43920 floor"
},
{
"answer_id": 74566711,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 1,
"selected": false,
"text": "189503 - (43920 * x) = 79920\n\n189503 = 79920 + (43920 * x)\n\n189503 - 79920 = 43920x\n\nx = (189503 - 79920) / 43920\n\nx = 2.49505919854\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594382/"
] |
74,566,641
|
<p>I am trying to work out how to create a dot notation component and everything I've found on SO and Google doesn't appear to work in the way that I am expecting.</p>
<p>I have the following code for two components; at the moment, it's all in one file:</p>
<pre><code>const ThreeDotMenu : any = ({children}) => {
return (
<>
<ul className='absolute bg-primary-light text-white'>
{children}
</ul>
</>
)
}
const Item : React.FC<DefaultProps> = ({children}) => {
return (
<li>{children}</li>
)
}
ThreeDotMenu.Item = Item;
export default ThreeDotMenu;
</code></pre>
<p>And I am using it as follows:</p>
<pre><code><ThreeDotMenu>
<ThreeDotMenu.Item>item</ThreeDotMenu.Item>
<ThreeDotMenu.Item>item 2</ThreeDotMenu.Item>
</ThreeDotMenu>
</code></pre>
<p>This is working fine except the parent component isn't type. Instead I am using <code>any</code> as the type.</p>
<p>I am now trying to type it by changing the declaration to be:</p>
<pre><code>const ThreeDotMenu : React.FC<DefaultProps> = ({children}) => {}
</code></pre>
<p>The component itself is happy, however the declaration where I do <code>ThreeDotMenu.Item = Item</code> now throws an error with the following:</p>
<blockquote>
<p>Property 'Item' does not exist on type FC</p>
</blockquote>
<p>And my <code>DefaultProps</code> is typed as follows:</p>
<pre><code>export interface DefaultProps {
children: Array<React.ReactNode>|React.ReactNode
}
</code></pre>
|
[
{
"answer_id": 74566663,
"author": "manuelmhtr",
"author_id": 1628009,
"author_profile": "https://Stackoverflow.com/users/1628009",
"pm_score": 2,
"selected": false,
"text": "Math.floor((189503 - 79920) / 43920) 2 79920 43920 floor"
},
{
"answer_id": 74566711,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 1,
"selected": false,
"text": "189503 - (43920 * x) = 79920\n\n189503 = 79920 + (43920 * x)\n\n189503 - 79920 = 43920x\n\nx = (189503 - 79920) / 43920\n\nx = 2.49505919854\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/499448/"
] |
74,566,644
|
<p>I'm looking for regex expression to take the below string and get the selected data between <code>/* start */</code> and <code>/* end */</code>.</p>
<pre><code>import {str}from'envalid';import {buildEnv}from'@leno/core';const { cleanEnv, envalidConfig } = buildEnv(process['APP_ENV'] || process.env, /* start */ {
CLIENT_URL: str(),
INITIAL_ACCOUNT_PAGE: str({ default: 'dashboard', devDefault: 'test', desc: 'initial page to redirect after org selection' }),
APP_NAME: str({ default: 'CDEBase' }),
}/* end */);export{cleanEnv,envalidConfig};//# sourceMappingURL=env-config.js.map
</code></pre>
<p>The result of the selection should be</p>
<pre><code>{
CLIENT_URL: { default: false, devDefault: false },
INITIAL_ACCOUNT_PAGE: { default: true, devDefault: true },
APP_NAME: { default: true, devDefault: false },
}
</code></pre>
|
[
{
"answer_id": 74566663,
"author": "manuelmhtr",
"author_id": 1628009,
"author_profile": "https://Stackoverflow.com/users/1628009",
"pm_score": 2,
"selected": false,
"text": "Math.floor((189503 - 79920) / 43920) 2 79920 43920 floor"
},
{
"answer_id": 74566711,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 1,
"selected": false,
"text": "189503 - (43920 * x) = 79920\n\n189503 = 79920 + (43920 * x)\n\n189503 - 79920 = 43920x\n\nx = (189503 - 79920) / 43920\n\nx = 2.49505919854\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595858/"
] |
74,566,651
|
<p><img src="https://i.stack.imgur.com/4he3R.jpg" alt="VS screengrab" /></p>
<p>This is my full script</p>
<p>I get an error on line 15, beginning at the "PlayerControls" word.</p>
<blockquote>
<p>error CS0246: The type or namespace name 'PlayerControls' could not be found (are you missing a using directive or an assembly reference?)</p>
</blockquote>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace puggy
{
public class InputHandler : MonoBehaviour
{
public float horizontal;
public float vertical;
public float moveAmount;
public float mouseX;
public float mouseY;
PlayerControls inputActions;
Vector2 movementInput;
Vector2 cameraInput;
public void OnEnable()
{
if (inputActions == null)
{
inputActions = new PlayerControls();
inputActions.PlayerMovement.Movement.performed += inputActions => movementInput = inputActions.ReadValue<Vector2>();
inputActions.PlayerMovement.Camera.performed += i => cameraInput = i.ReadValue<Vector2>();
}
inputActions.Enable();
}
private void OnDisable()
{
inputActions.Disable();
}
public void TickInput(float delta)
{
MoveInput(delta);
}
private void MoveInput(float delta)
{
horizontal = movementInput.x;
vertical = movementInput.y;
moveAmount = Mathf.Clamp01(Mathf.Abs(horizontal) + Mathf.Abs(vertical));
mouseX = cameraInput.x;
mouseY = cameraInput.y;
}
}
}
</code></pre>
<p>I'm guessing it wants a reference for "PlayerControls". I'm confused though because I followed a walkthrough, I ran into other issues but was able to resolve them pretty quickly. This one is tripping me up though.</p>
<p><img src="https://i.stack.imgur.com/ApmQD.jpg" alt="enter image description here" /></p>
<p>I'm expecting to be able to attach this script to my player model and have it move based on player input.</p>
<p>I have re-typed my script and followed other forums to see if anyone else has had similar issues.</p>
<p>EDIT:</p>
<p><img src="https://i.stack.imgur.com/VHBOs.jpg" alt="PlayerControls" /></p>
|
[
{
"answer_id": 74566663,
"author": "manuelmhtr",
"author_id": 1628009,
"author_profile": "https://Stackoverflow.com/users/1628009",
"pm_score": 2,
"selected": false,
"text": "Math.floor((189503 - 79920) / 43920) 2 79920 43920 floor"
},
{
"answer_id": 74566711,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 1,
"selected": false,
"text": "189503 - (43920 * x) = 79920\n\n189503 = 79920 + (43920 * x)\n\n189503 - 79920 = 43920x\n\nx = (189503 - 79920) / 43920\n\nx = 2.49505919854\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594385/"
] |
74,566,677
|
<p>I want to loop through a list and find all the numbers that are prime</p>
<pre><code>arr = [1,2,3]
for i in range(len(arr)):
if arr[i] > 1:
for j in range(2, int(arr[i]/2)+1):
if (arr[i] % j) == 0:
print(arr[i], "is not prime")
else:
print(arr[i], "is prime")
else:
print(arr[i], "is not prime")
</code></pre>
<p>This only prints out "1 is not prime." I am guessing it has something to do with the range(len()) of the for loop.</p>
|
[
{
"answer_id": 74566695,
"author": "cnemri",
"author_id": 3892280,
"author_profile": "https://Stackoverflow.com/users/3892280",
"pm_score": -1,
"selected": false,
"text": "arr = list(range(20))\n\ndef is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n\ndef find_primes(array):\n return list(filter(is_prime, array))\n\nprint(find_primes(arr))\n"
},
{
"answer_id": 74566822,
"author": "cnemri",
"author_id": 3892280,
"author_profile": "https://Stackoverflow.com/users/3892280",
"pm_score": 0,
"selected": false,
"text": "arr = range(20)\n\nfor i in range(len(arr)):\n if arr[i] > 3:\n is_prime = True\n for j in range(2, int(arr[i]/2)+1):\n if (arr[i] % j) == 0:\n is_prime = False\n break\n else:\n continue\n print(arr[i], \"is prime\" if is_prime else \"is not prime\")\n elif arr[i] in [2,3]:\n print(arr[i], \"is prime\")\n else:\n print(arr[i], \"is not prime\")\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10929741/"
] |
74,566,687
|
<p>I am a beginner in Python so kindly do not use complex or advanced code.</p>
<pre><code>contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Print \n 7. Exit \n Enter "))
#I have already tried
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
sort_contact = input("Enter yes to print your contact")
if sort_contact in contact:
confirm = input("Do you want to print your contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
strs = [display_contact]
print(sorted(strs))
else:
print("Phone book is printed.")
else:
break
</code></pre>
<p>I tried but keep getting errors and I can't fiugre out how to make it only take string or letter as input and not numbers.</p>
<pre><code>if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
</code></pre>
<p>it is not working my code still accepts the ans in integer and string.</p>
<p>I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.</p>
|
[
{
"answer_id": 74566738,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "re.fullmatch import re\n\nwhile True:\n name = input(\"Enter the contact name \")\n if re.fullmatch(r'[a-zA-Z]+', name):\n break\n re.fullmatch(r'[a-z]+', name, flags=re.I):"
},
{
"answer_id": 74566791,
"author": "CrimsonFox88",
"author_id": 20594501,
"author_profile": "https://Stackoverflow.com/users/20594501",
"pm_score": -1,
"selected": false,
"text": "extracted_letters = \" \".join(re.findall(\"[a-zA-Z]+\", numlettersstring))\n import re"
},
{
"answer_id": 74566926,
"author": "mighty_mike",
"author_id": 4953409,
"author_profile": "https://Stackoverflow.com/users/4953409",
"pm_score": 1,
"selected": false,
"text": "def valid_input(input: str):\n # Check if any char is a number \n for char in input:\n if char.isdigit():\n print('Numbers are not allowed!')\n return False\n return True\n\n\nwhile True:\n name = input(\"Enter data:\")\n if valid_input(name):\n break\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16429052/"
] |
74,566,707
|
<p>I am creating a reusable app, which requires some configurations stored in <code>config.php</code>. This configuration file does not have any function, but the configuration are returned as an array, eg</p>
<pre><code><?php
return [
'db_name' => 'db_name',
'password' => 'password',
........
];
</code></pre>
<p>I was hoping to create a function which includes this config file, and get each config set. An example is laravel <code>config()</code> function which returns a configuration value. Is there any way to acheive this?</p>
<p>I have tried</p>
<pre><code>$filename = 'config.php';
include $filename;
$contents[] = file_get_contents($filename);
</code></pre>
<p>but this just gets whatever is in the file as a string.</p>
|
[
{
"answer_id": 74566786,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "return return <?php\n$config = [\n 'db_name' => 'db_name',\n 'password' => 'password',\n ........\n];\n require_once './config.php'; require_once ./config.php ../config.php"
},
{
"answer_id": 74566888,
"author": "igobr",
"author_id": 20085654,
"author_profile": "https://Stackoverflow.com/users/20085654",
"pm_score": 1,
"selected": false,
"text": "return <?php\n\n$config = [\n 'db_name' => 'db_name',\n 'password' => 'password',\n ........\n];\n $config file_get_contents config.php {\n \"db_name\": \"some_name\",\n \"password\": \"some_password\",\n ...\n}\n $filename = 'config.json';\n$parsed = json_decode(file_get_contents($filename), true);\necho $parsed['db_name']; // -> some_name\necho $parsed['password']; // -> some_password\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19638294/"
] |
74,566,718
|
<p>I am trying to server static files with express and them dont work, i think its express problem or something but i dont realize why it dont works.
my folders look like this:</p>
<p>app.js
public
--css
--js
--images</p>
<p>and the code i trying to run like this:</p>
<pre><code>app.use(express.static(path.join(__dirname,'public')));
</code></pre>
<p>if i do console.log of the path</p>
<pre><code>console.log(path.join(__dirname, 'public'))
</code></pre>
<p>i get the next path
C:\Users\J\Desktop\node.js\social-media-cars\public</p>
<p>and if i look at the path with the windows file explorer i see that the path is correct and i see the content inside, so i dont think its path fault</p>
<p>i also tryed :</p>
<pre><code>app.use(express.static(path.join(__dirname,'public')));
app.use('/static',express.static(path.join(__dirname, '/public')));
</code></pre>
<p>and dont works, always the same things:
<a href="https://i.stack.imgur.com/uzXlw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uzXlw.png" alt="enter image description here" /></a></p>
<p>im desesparate with this, idk why this dont works.</p>
<p>code where i use it looks like this:</p>
<pre><code>// Import the express module
const path = require('path');
const express = require("express");
// Instantiate an Express application
const app = express();
const dotenv = require("dotenv").config();
const ActionsRouter = require('./routers/actions-router');
const UserRouter = require('./routers/user-router');
const cookieparser = require('cookie-parser');
// app.use('/static',express.static(path.join(__dirname, '/public')));
//set static files that are rendered after
app.use(express.static(path.join(__dirname,'public')));
//read the cookies from response
app.use(cookieparser(path.join(__dirname, '/public')));
console.log(path.join(__dirname, 'public'))
//create the req.body
app.use(express.json());
//user
app.use("/api",UserRouter);
app.use("/useractions",ActionsRouter);
module.exports = app;
</code></pre>
<pre><code>const server = app.listen(port,()=>{
console.log(`listening on port ${port}`)});
</code></pre>
<p>get the static files with every response i get</p>
<p>also i get this error
<a href="https://i.stack.imgur.com/YyzxH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YyzxH.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74566786,
"author": "user3425506",
"author_id": 3425506,
"author_profile": "https://Stackoverflow.com/users/3425506",
"pm_score": 0,
"selected": false,
"text": "return return <?php\n$config = [\n 'db_name' => 'db_name',\n 'password' => 'password',\n ........\n];\n require_once './config.php'; require_once ./config.php ../config.php"
},
{
"answer_id": 74566888,
"author": "igobr",
"author_id": 20085654,
"author_profile": "https://Stackoverflow.com/users/20085654",
"pm_score": 1,
"selected": false,
"text": "return <?php\n\n$config = [\n 'db_name' => 'db_name',\n 'password' => 'password',\n ........\n];\n $config file_get_contents config.php {\n \"db_name\": \"some_name\",\n \"password\": \"some_password\",\n ...\n}\n $filename = 'config.json';\n$parsed = json_decode(file_get_contents($filename), true);\necho $parsed['db_name']; // -> some_name\necho $parsed['password']; // -> some_password\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20264570/"
] |
74,566,727
|
<p>The problem is that the loop is working the first time but it stops after and I want it to continue like this until the input is different than 1 to 9.</p>
<pre><code>do
{
Show-Menu
$selection = Read-Host "Please choose an option"
switch ($selection)
{
'1' {
Get-ChildItem
} '2' {
get-host|Select-Object
} '3' {
Get-NetIPConfiguration -Detailed
} '4' {
Get-NetRoute
} '5' {
Get-DnsClientCache
} '6' {
Get-Date -UFormat "%A %B/%d/%Y %T %Z"
} '7' {
Get-ItemProperty -Path HKLM:\
} '8' {
Stop-Service -Name Spooler -Force
Restart-Service -Name Spooler -Force
} '9' {
Get-Service | Where-Object {$_.Status -eq "Running"}
}
}
pause
}
until ($selection -ne 1..9)
</code></pre>
<p>I tried a while loop but it did an infinite loop...</p>
|
[
{
"answer_id": 74566790,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": -1,
"selected": false,
"text": "switch(...)\n{\n<# switch options #>\ndefault {break}\n}\n"
},
{
"answer_id": 74566851,
"author": "Santiago Squarzon",
"author_id": 15339544,
"author_profile": "https://Stackoverflow.com/users/15339544",
"pm_score": 1,
"selected": false,
"text": "-ne until ($selection -ne 1..9)\n -notin until ($selection -notin 1..9)\n -notin $selection -notin 1..9 $true $selection 1 9 -ne 'foo', 'bar', 'baz' -ne 'foo' # => 'bar', 'baz'\n $selection 1..9 $true"
},
{
"answer_id": 74567045,
"author": "postanote",
"author_id": 9132707,
"author_profile": "https://Stackoverflow.com/users/9132707",
"pm_score": 0,
"selected": false,
"text": "function Show-Menu\n{\n Param()\n\n $selection = Read-Host 'Please choose an option'\n\n switch ($selection)\n {\n '1' {\n Get-ChildItem\n } '2' {\n get-host|Select-Object\n } '3' {\n Get-NetIPConfiguration -Detailed\n } '4' {\n Get-NetRoute\n } '5' {\n Get-DnsClientCache\n } '6' {\n Get-Date -UFormat '%A %B/%d/%Y %T %Z'\n } '7' {\n Get-ItemProperty -Path HKLM:\\\n } '8' {\n Stop-Service -Name Spooler -Force\n Restart-Service -Name Spooler -Force\n } '9' {\n Get-Service | Where-Object {$_.Status -eq 'Running'}\n }\n } \n}\ndo {Show-Menu}\nuntil ($selection -match '1-9')\n\n# Results\n<#\nPlease choose an option: 0\nPlease choose an option: 10\nPlease choose an option: 20\nPlease choose an option: 11\nPlease choose an option: 4\n\n# Results\n<#\nifIndex DestinationPrefix NextHop RouteMetric ifMetric PolicyStore\n...\n#>\n do\n{\n Show-Menu\n $selection = Read-Host \"Please choose an option\"\n switch ($selection)\n {\n '1' {\n Get-ChildItem\n } '2' {\n get-host|Select-Object\n } '3' {\n Get-NetIPConfiguration -Detailed\n } '4' {\n Get-NetRoute\n } '5' {\n Get-DnsClientCache\n } '6' {\n Get-Date -UFormat \"%A %B/%d/%Y %T %Z\"\n } '7' {\n Get-ItemProperty -Path HKLM:\\\n } '8' {\n Stop-Service -Name Spooler -Force\n Restart-Service -Name Spooler -Force\n } '9' {\n Get-Service | Where-Object {$_.Status -eq \"Running\"}\n }\n }\n}\nuntil ($selection -notin 1..9)\n# Results\n<#\nuntil ($selection -notin 1..9)\nPlease choose an option: 0\nPlease choose an option: 10\n# the do exited\n\nuntil ($selection -notin 1..9)\nPlease choose an option: 11\nPlease choose an option: 110\n# the do exited\n#>\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11223645/"
] |
74,566,733
|
<p>I would like to make a script to check whether or not files are still being created inside a folder. We can consider for our problem that there are no more files being created if let's say for 5 sec the list of files present in that folder remains unchanged. Can anyone help me with this issue?</p>
|
[
{
"answer_id": 74566813,
"author": "Trimonu",
"author_id": 15324906,
"author_profile": "https://Stackoverflow.com/users/15324906",
"pm_score": 0,
"selected": false,
"text": "import os\nentries = os.listdir('my_directory/')\n len(entries)"
},
{
"answer_id": 74567125,
"author": "htrcode",
"author_id": 20581579,
"author_profile": "https://Stackoverflow.com/users/20581579",
"pm_score": 2,
"selected": true,
"text": "inotifywait inotifywait -m -e create /path/to/your/dir\n inotifywait --timeout 5 -qm -e create /path/to/your/dir\n --timeout"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12627762/"
] |
74,566,826
|
<p>I have implemented a class that handles 2-way communication between processes, and while trying to add type-safety to the API's I have run into an issue that I cannot seem to crack.</p>
<p>I am trying to essentially create a type-safe interface that allows me to use the same class in multiple process where I can define the connected API/exposed API, so that I can mitigate confusion issues:</p>
<pre><code>// Simplified example
// API definitions
interface ExternalAPI {
add(x: number, y: number): number;
}
interface InternalAPI {
subtract(x: number, y: number): number;
}
// In use:
const bridge = new IPCBridge<ExposedAPI, ConnectedAPI>({
subtract: (x, y) => x - y, // Works, compiler happy
});
bridge.invoke("add", 3, 3); // Works, compiler happy
bridge.invoke("nonexistent"); // Does not work, compiler mad
</code></pre>
<p>However, while my implementation works my types do not; and I cannot get the above generics, specifically, to compile without telling the compiler to ignore issues which I would prefer to not do.</p>
<p>I've implemented the above generics as so:</p>
<pre><code>type ValidApiType = {
[funcName: string]: (...args: unknown[]) => unknown;
};
class IPCBridge<InternalAPI extends ValidApiType, ExternalAPI extends ValidApiType> {
// . . .
}
</code></pre>
<p>However, when trying to actually use this the compiler throws an error at the first generic:</p>
<pre><code>interface ApiA {
add(x: number, y: number): number;
}
/*
Type 'ApiA' does not satisfy the constraint 'ValidApiType'.
Index signature for type 'string' is missing in type 'ApiA'.
*/
</code></pre>
<p>Similarly, if I were to try to have the interface <em>extend</em> <code>ValidApiType</code>, a similar error appears:</p>
<pre><code>interface ApiA extends ValidApiType {
add(x: number, y: number): number;
}
/*
Property 'add' of type '(x: number, y: number) => number' is not assignable to 'string' index type '(...args: unknown[]) => unknown'.
*/
</code></pre>
<p>I must be misunderstanding something. I have a selection of helper types to abstract the API function names from the interfaces keys and the args/return values of the values, and those all work just fine. I have even tried swapping the index signature to include <code>symbol</code> but still no luck. I just fail to understand how TS does not consider the keys to be a string. I've tried looking up the specific TS error codes but that did not really get me anywhere either, I just really don't understand how the types differ.</p>
<p>You can see exactly what is happening in this <a href="https://www.typescriptlang.org/play?#code/PTAECEEMGcFNQJIFsAOAbWTYDsAulcBLAe2wChcBPFeANUjUIBMBBFQgFWvgF5QBvMqGGgA2gDMArtgDGAOUhYAXKGi4AToWwBzALoqAFADoTkddugrpAa2zEA7tlG6AlKB4A+UDbuOA3GQAvgFkMmgw0IgACgDC4JpM2rAAPAh4sOrYDCxRCKCwAB64OEyR9Iys7Fw0ADSgAKJFGVloOXmFxdiloOXMbJzcXvyBZGQgDU1dWtqgTMSwkXa4oPbE6tZGZFrF6uKQMvCNnUywrLn5k929lQM0AkIikExMBgUq2JJIAEYZdZTvnx+6hcAO+GQCIzGYDka1mxFAdnUSAYoG2GT2B0iP2moBQEVOoFw8NwAAt4ElsBlCDJNmjdvt4P0WPcRKAni83gjAb9QP8uWDgaCgRDRnSMYz2OAWSJoJIvhp9rhXkKeXyPgKQfzhUFRlJZERSKAZOpYARYABVWSkSkyYpMKJrXDQAya0QIWLxZhJZJMur9cAeOruuIJb3+v3sFgeXTS4QyUhqXGOgCM7gRsHs0RDXtgLoCrPj2ETKEdACY05TM8HPYlcy58yITbhJJkxCX1Lhk3V27hS7oRUA" rel="nofollow noreferrer">typescript playground</a>.</p>
|
[
{
"answer_id": 74566813,
"author": "Trimonu",
"author_id": 15324906,
"author_profile": "https://Stackoverflow.com/users/15324906",
"pm_score": 0,
"selected": false,
"text": "import os\nentries = os.listdir('my_directory/')\n len(entries)"
},
{
"answer_id": 74567125,
"author": "htrcode",
"author_id": 20581579,
"author_profile": "https://Stackoverflow.com/users/20581579",
"pm_score": 2,
"selected": true,
"text": "inotifywait inotifywait -m -e create /path/to/your/dir\n inotifywait --timeout 5 -qm -e create /path/to/your/dir\n --timeout"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594422/"
] |
74,566,842
|
<p>I have a table with a unique constraint</p>
<pre class="lang-sql prettyprint-override"><code>CREATE temp TABLE tmp (
c1 int,
c2 text,
c3 int,
UNIQUE (c2, c3)
);
insert into tmp (c1, c2, c3)
values (1, 'a', 2),
(2, 'a', 1)
</code></pre>
<p>Is it possible to run the update below without getting a unique contraint violation and without modifying table <code>tmp</code>?</p>
<pre class="lang-sql prettyprint-override"><code>update tmp
set c3 = c1
where 1=1
</code></pre>
<pre><code>ERROR: duplicate key value violates unique constraint "tmp_c2_c3_key". Detail: Key (c2, c3)=(a, 1) already exists.
</code></pre>
|
[
{
"answer_id": 74567027,
"author": "SebDieBln",
"author_id": 10171966,
"author_profile": "https://Stackoverflow.com/users/10171966",
"pm_score": 1,
"selected": false,
"text": "UNIQUE DEFERRABLE ...\n UNIQUE (c2, c3) DEFERRABLE\n ...\n SET CONSTRAINTS tmp_c2_c3_key DEFERRED;\n SET CONSTRAINTS"
},
{
"answer_id": 74567262,
"author": "Pompedup",
"author_id": 12239272,
"author_profile": "https://Stackoverflow.com/users/12239272",
"pm_score": 2,
"selected": true,
"text": "UPDATE tmp\nSET c3 = -c1\nWHERE 1 = 1;\n UPDATE tmp\nSET c3 = c1\nWHERE 1 = 1;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4665335/"
] |
74,566,856
|
<p>I always see</p>
<pre><code> (function (e){
console.log("hi")
})
</code></pre>
<p>in libraries Like jQuery but when I try and make something like it in NodeJS it doesn't Log "hi" to the console. What does it mean?</p>
<p>I've tried searching for multiple different solutions online to see what it meant but I couldn't find anything. So, I came to see if anybody knew what it means.</p>
|
[
{
"answer_id": 74567027,
"author": "SebDieBln",
"author_id": 10171966,
"author_profile": "https://Stackoverflow.com/users/10171966",
"pm_score": 1,
"selected": false,
"text": "UNIQUE DEFERRABLE ...\n UNIQUE (c2, c3) DEFERRABLE\n ...\n SET CONSTRAINTS tmp_c2_c3_key DEFERRED;\n SET CONSTRAINTS"
},
{
"answer_id": 74567262,
"author": "Pompedup",
"author_id": 12239272,
"author_profile": "https://Stackoverflow.com/users/12239272",
"pm_score": 2,
"selected": true,
"text": "UPDATE tmp\nSET c3 = -c1\nWHERE 1 = 1;\n UPDATE tmp\nSET c3 = c1\nWHERE 1 = 1;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18498182/"
] |
74,566,861
|
<p>This file, <code>file.txt</code>:</p>
<pre><code>checking
open something
connected
open something
connected
open something
checking
open something
checking
open something
connected
open something
</code></pre>
<p>Needs to be like this, <code>file.txt</code>:</p>
<pre><code>checking
open something
connected
open something
connected
checking
checking
open something
connected
</code></pre>
<p>We have attempted many sed one liners but with no success.</p>
<p><code>sed -i "/open/{$!N;/\n.*^$/!P;D}" file.txt</code></p>
<p>Where <code>open</code> is the pattern, and <code>^$</code> is the empty line after pattern.</p>
<p>We would like to delete only the <code>open</code> pattern matching line - if the line after it is empty.</p>
<p>Can someone provide assistance?</p>
|
[
{
"answer_id": 74567027,
"author": "SebDieBln",
"author_id": 10171966,
"author_profile": "https://Stackoverflow.com/users/10171966",
"pm_score": 1,
"selected": false,
"text": "UNIQUE DEFERRABLE ...\n UNIQUE (c2, c3) DEFERRABLE\n ...\n SET CONSTRAINTS tmp_c2_c3_key DEFERRED;\n SET CONSTRAINTS"
},
{
"answer_id": 74567262,
"author": "Pompedup",
"author_id": 12239272,
"author_profile": "https://Stackoverflow.com/users/12239272",
"pm_score": 2,
"selected": true,
"text": "UPDATE tmp\nSET c3 = -c1\nWHERE 1 = 1;\n UPDATE tmp\nSET c3 = c1\nWHERE 1 = 1;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20460608/"
] |
74,566,897
|
<p>Hello I have a variable
myvar: "123,2344,567,3334"
I need to extract the value after second comma and put this on another varivle that will be used to write in file:
my code:</p>
<pre><code>myvar: "123,2344,567,3334"
var items = myvar.Split( ',');
var val=items[3]
// Add on file
string row = Convert.ToString(val) + ";" + "Amount";
StreamWriter file2 = new StreamWriter(fileName, true);
file2.WriteLine(row);
file2.Close();
</code></pre>
<p>However I got the error : Can not deserialize from string_val.</p>
<p>Is there anything wronf with my code?</p>
<p>I need to extract the value after second comma and put this on another variable.</p>
|
[
{
"answer_id": 74566958,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 0,
"selected": false,
"text": "var myvar = \"123,2344,567,3334\";\nvar items = myvar.Split(',');\nvar val = items[2];\n\n//Write to the file\nstring row = Convert.ToString(val) + \";\" + \"Amount\";\nStreamWriter file2 = new StreamWriter(\"yourfilename\", true);\nfile2.WriteLine(row);\nfile2.Close();\n"
},
{
"answer_id": 74567249,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 1,
"selected": false,
"text": "var myvar = \"123,2344,567,3334\";\nvar items = myvar.Split(',');\nvar val=items[2]; // 0-based indexing so 2 is the 3rd element.\n\n\nFile.AppendAllText(\"file.txt\", contents: val);\n var rows = new [] {\"a,aa,111,aaaa\",\n \"b,bb,222,bbbb\"};\n\nvar o = new List<string>();\nforeach(var row in rows)\n{\n var items = row.Split(',');\n o.Add(items[2]); // 0-based indexing so 2 is the 3rd element.\n}\n\nFile.WriteAllLines(\"file.txt\", contents: o); // Or File.AppendAllLines()\n\n// file.txt will contian: \n// 111\n// 222\n\n 567"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20576670/"
] |
74,566,899
|
<pre><code>var first_img = new Image();
first_img.src = 'https://avatars.mds.yandex.net/i?id=1bb1862085f1bc99c8eff04a674864838f1c53cb-4772764-images-thumbs&n=13';
var first_width;
var first_height;
first_img.onload = function(){
first_width = first_img.width;
first_height = first_img.height;
}
alert(first_width);
</code></pre>
<p>I need to save <code>first_width</code> outsie first_img.onload. Now i get <code>undefined</code></p>
<p><a href="https://jsfiddle.net/Nata_Hamster/pa5n27vq/" rel="nofollow noreferrer">https://jsfiddle.net/Nata_Hamster/pa5n27vq/</a></p>
|
[
{
"answer_id": 74566958,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 0,
"selected": false,
"text": "var myvar = \"123,2344,567,3334\";\nvar items = myvar.Split(',');\nvar val = items[2];\n\n//Write to the file\nstring row = Convert.ToString(val) + \";\" + \"Amount\";\nStreamWriter file2 = new StreamWriter(\"yourfilename\", true);\nfile2.WriteLine(row);\nfile2.Close();\n"
},
{
"answer_id": 74567249,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 1,
"selected": false,
"text": "var myvar = \"123,2344,567,3334\";\nvar items = myvar.Split(',');\nvar val=items[2]; // 0-based indexing so 2 is the 3rd element.\n\n\nFile.AppendAllText(\"file.txt\", contents: val);\n var rows = new [] {\"a,aa,111,aaaa\",\n \"b,bb,222,bbbb\"};\n\nvar o = new List<string>();\nforeach(var row in rows)\n{\n var items = row.Split(',');\n o.Add(items[2]); // 0-based indexing so 2 is the 3rd element.\n}\n\nFile.WriteAllLines(\"file.txt\", contents: o); // Or File.AppendAllLines()\n\n// file.txt will contian: \n// 111\n// 222\n\n 567"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14483289/"
] |
74,566,903
|
<p>i'm just practicing scraping with selenium</p>
<p><a href="https://i.stack.imgur.com/12mhd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/12mhd.png" alt="inspect element image" /></a></p>
<p>What i would like to do is go through each item in the unordered list</p>
<p><a href="https://i.stack.imgur.com/fAcwK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fAcwK.png" alt="href" /></a></p>
<p>get every list item</p>
<pre><code> wait.until(EC.presence_of_element_located((By.XPATH, "//*[@id='main_content']/ul" )))
ul_element = driver.find_element(By.XPATH, "//*[@id='main_content']/ul")
all_li_element = ul_element.find_elements(By.CSS_SELECTOR, "li")
</code></pre>
<p>then after i got the list items to go to each one and scrape some data</p>
<p>is there a better way because the way i'm thinking about it, it will turn into a nested list</p>
|
[
{
"answer_id": 74566958,
"author": "Jonathan Barraone",
"author_id": 17957703,
"author_profile": "https://Stackoverflow.com/users/17957703",
"pm_score": 0,
"selected": false,
"text": "var myvar = \"123,2344,567,3334\";\nvar items = myvar.Split(',');\nvar val = items[2];\n\n//Write to the file\nstring row = Convert.ToString(val) + \";\" + \"Amount\";\nStreamWriter file2 = new StreamWriter(\"yourfilename\", true);\nfile2.WriteLine(row);\nfile2.Close();\n"
},
{
"answer_id": 74567249,
"author": "tymtam",
"author_id": 581076,
"author_profile": "https://Stackoverflow.com/users/581076",
"pm_score": 1,
"selected": false,
"text": "var myvar = \"123,2344,567,3334\";\nvar items = myvar.Split(',');\nvar val=items[2]; // 0-based indexing so 2 is the 3rd element.\n\n\nFile.AppendAllText(\"file.txt\", contents: val);\n var rows = new [] {\"a,aa,111,aaaa\",\n \"b,bb,222,bbbb\"};\n\nvar o = new List<string>();\nforeach(var row in rows)\n{\n var items = row.Split(',');\n o.Add(items[2]); // 0-based indexing so 2 is the 3rd element.\n}\n\nFile.WriteAllLines(\"file.txt\", contents: o); // Or File.AppendAllLines()\n\n// file.txt will contian: \n// 111\n// 222\n\n 567"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10872352/"
] |
74,566,924
|
<p>I am working with a df similar to this:</p>
<pre><code>df <- data.frame(p1 = c("Tom", "Tom", "Tom", "Tom", "Tom", "Tom", "Brad", "Brad", "Brad", "Brad", "Brad", "Brad", "Brad","Brad", "Brad", "Brad" ),
elapsed_time = c(0, 10, 17, 28, 47, 65, 83, 100, 135, 180, 210, 225, 237, 253, 276, 281),
event_type = c("start of period", "play", "play", "timeout", "play", "play", "play", "play", "play", "timeout", "play", "play", "play", "play",
"play", "play"),
scored = c(NA, NA, "Tom", NA, NA, "Tom", NA, NA, NA, NA, NA, "Brad", NA, NA, "Brad", "Brad" ),
timesincelastbreak = c(0, 10, 17, 0, 19, 37, 0, 17, 52, 0, 30, 45, 57, 73, 96, 101))
</code></pre>
<p>that outputs this:</p>
<pre><code> p1 elapsed_time event_type scored timesincelastbreak
<chr> <dbl> <chr> <chr> <dbl>
1 Tom 0 start of period NA 0
2 Tom 10 play NA 10
3 Tom 17 play Tom 17
4 Tom 28 timeout NA 0
5 Tom 47 play NA 19
6 Tom 65 play Tom 37
7 Brad 83 play NA 0
8 Brad 100 play NA 17
9 Brad 135 play NA 52
10 Brad 180 timeout NA 0
11 Brad 210 play NA 30
12 Brad 225 play Brad 45
13 Brad 237 play NA 57
14 Brad 253 play NA 73
15 Brad 276 play Brad 96
16 Brad 281 play Brad 101
</code></pre>
<p>I'd like to add a column (<code>timesscored</code>) that adds together the number of times <code>p1 == scored</code> in the 30 seconds immediately preceding each row, based on <code>timesincelastbreak</code>.</p>
<p>Also, <code>timesscored</code> needs to reset every time that <code>timesincelastbreak</code> is equal to zero.</p>
<p>The desired output is:</p>
<pre><code>p1 elapsed_time event_type scored timesincelastbreak timesscored
<chr> <dbl> <chr> <chr> <dbl> <dbl>
1 Tom 0 start of period NA 0 0
2 Tom 10 play NA 10 0
3 Tom 17 play Tom 17 1
4 Tom 28 timeout NA 0 0
5 Tom 47 play NA 19 0
6 Tom 65 play Tom 37 1
7 Brad 83 play NA 0 0
8 Brad 100 play NA 17 0
9 Brad 135 play NA 52 0
10 Brad 180 timeout NA 0 0
11 Brad 210 play NA 30 0
12 Brad 225 play Brad 45 1
13 Brad 237 play NA 57 1
14 Brad 253 play NA 73 1
15 Brad 276 play Brad 96 1
16 Brad 281 play Brad 101 2
</code></pre>
<p>I've tried using <code>cumsum(df$p1 == df$scored)</code> but I don't know how to specify the interval of 30 for <code>timesincelastbreak</code>.</p>
|
[
{
"answer_id": 74567122,
"author": "Martin Gal",
"author_id": 12505251,
"author_profile": "https://Stackoverflow.com/users/12505251",
"pm_score": 1,
"selected": false,
"text": "dplyr tidyr timesscored library(tidyr)\nlibrary(dplyr)\n\ndf_score <- df %>% \n group_by(grp = cumsum(timesincelastbreak == 0)) %>% # reset everything for timesincelastbreak == 0\n drop_na(scored) %>% \n mutate(\n timesscored = ifelse(\n row_number() == 1, # first score is independent of timesincelastbreak\n 1, \n coalesce((p1 == scored), FALSE) * # check for p1 == scored\n (timesincelastbreak - lag(timesincelastbreak, default = 0) < 30) # check for < 30 seconds\n )\n ) %>% \n ungroup() %>% \n select(-grp)\n # A tibble: 5 × 6\n p1 elapsed_time event_type scored timesincelastbreak timesscored\n <chr> <dbl> <chr> <chr> <dbl> <dbl>\n1 Tom 17 play Tom 17 1\n2 Tom 65 play Tom 37 1\n3 Brad 225 play Brad 45 1\n4 Brad 276 play Brad 96 0\n5 Brad 281 play Brad 101 1\n cumsum df %>% \n left_join(df_score, \n by = c(\"p1\", \"elapsed_time\", \"event_type\", \"scored\", \"timesincelastbreak\")) %>%\n group_by(grp = cumsum(timesincelastbreak == 0)) %>% \n mutate(timesscored = cumsum(coalesce(timesscored, 0))) %>% \n ungroup() %>% \n select(-grp)\n # A tibble: 16 × 6\n p1 elapsed_time event_type scored timesincelastbreak timesscored\n <chr> <dbl> <chr> <chr> <dbl> <dbl>\n 1 Tom 0 start of period NA 0 0\n 2 Tom 10 play NA 10 0\n 3 Tom 17 play Tom 17 1\n 4 Tom 28 timeout NA 0 0\n 5 Tom 47 play NA 19 0\n 6 Tom 65 play Tom 37 1\n 7 Brad 83 play NA 0 0\n 8 Brad 100 play NA 17 0\n 9 Brad 135 play NA 52 0\n10 Brad 180 timeout NA 0 0\n11 Brad 210 play NA 30 0\n12 Brad 225 play Brad 45 1\n13 Brad 237 play NA 57 1\n14 Brad 253 play NA 73 1\n15 Brad 276 play Brad 96 1\n16 Brad 281 play Brad 101 2\n"
},
{
"answer_id": 74567207,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": false,
"text": "purrr::map_int() library(dplyr)\nlibrary(purrr)\n\ndf %>%\n group_by(block = cumsum(timesincelastbreak == 0)) %>%\n mutate(timescored = map_int(\n timesincelastbreak, \n \\(cur_time) sum(\n between(timesincelastbreak, cur_time - 30, cur_time) & scored == p1, \n na.rm = TRUE\n )\n )) %>%\n ungroup() %>%\n select(!block)\n # A tibble: 16 × 6\n p1 elapsed_time event_type scored timesincelastbreak timescored\n <chr> <dbl> <chr> <chr> <dbl> <int>\n 1 Tom 0 start of period <NA> 0 0\n 2 Tom 10 play <NA> 10 0\n 3 Tom 17 play Tom 17 1\n 4 Tom 28 timeout <NA> 0 0\n 5 Tom 47 play <NA> 19 0\n 6 Tom 65 play Tom 37 1\n 7 Brad 83 play <NA> 0 0\n 8 Brad 100 play <NA> 17 0\n 9 Brad 135 play <NA> 52 0\n10 Brad 180 timeout <NA> 0 0\n11 Brad 210 play <NA> 30 0\n12 Brad 225 play Brad 45 1\n13 Brad 237 play <NA> 57 1\n14 Brad 253 play <NA> 73 1\n15 Brad 276 play Brad 96 1\n16 Brad 281 play Brad 101 2\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19128163/"
] |
74,566,968
|
<p>I try to get images from Instagram and build a gallery on my site.</p>
<p>myCode:</p>
<pre class="lang-js prettyprint-override"><code>function Instagram() {
const instagramData = async () => {
const url = `https:/site.com/...`;
const data = await fetch(url);
const feed = await data.json();
console.log(feed);
};
instagramData();
return (
<>
{feed.map((feed) => { //it's not feed :(
return (
<div key={feed.id}>
<img src={feed.media_url} alt="" />
</div>
);
})}
</>
);
}
export default Instagram;
</code></pre>
<p>my Array from console:</p>
<pre><code>{data: Array(25), paging: {…}}
data: Array(25)
0: {id: '123', media_url: 'https://stuff.com/1', permalink: 'https://www.instagram.com/p/1/'}
1: {id: '456', media_url: 'https://stuff.com/2', permalink: 'https://www.instagram.com/p/2/'}
....
length: 25
[[Prototype]]:Array(0)
paging
:
{cursors: {…}, next: 'https://website/abcd'}
[[Prototype]]: Object
</code></pre>
<p>'feed' is not the right var to use. But somehow i must extract the array from the function and store it like a normal obj. But how?</p>
<p>What magical code I need to do the .map ?</p>
|
[
{
"answer_id": 74566995,
"author": "Muhammad Allak",
"author_id": 15409495,
"author_profile": "https://Stackoverflow.com/users/15409495",
"pm_score": 2,
"selected": false,
"text": "instagramData() useEffect import {useEffect} from 'react';\n\nuseEffect(() => \n instagramData();\n},[])\n"
},
{
"answer_id": 74567054,
"author": "Rousnay",
"author_id": 2037937,
"author_profile": "https://Stackoverflow.com/users/2037937",
"pm_score": 2,
"selected": false,
"text": "useState useEffect import { useState, useEffect } from \"react\";\n\nfunction Instagram() {\n const [feeds, setFeeds] = useState([]);\n useEffect(() => {\n const instagramData = async () => {\n const url = `https:/site.com/...`;\n const data = await fetch(url);\n const feeds = await data.json();\n setFeeds(feeds);\n };\n instagramData()\n }, []);\n return (\n <>\n {feeds.map((feed) => {\n return (\n <div key={feed.id}>\n <img src={feed.media_url} alt=\"\" />\n </div>\n );\n })}\n </>\n );\n}\nexport default Instagram;\n"
},
{
"answer_id": 74573325,
"author": "Spluli",
"author_id": 19749827,
"author_profile": "https://Stackoverflow.com/users/19749827",
"pm_score": 0,
"selected": false,
"text": "function Instagram() {\n const [feeds, setFeed] = useState<any[]>([]);\n\n useEffect(() => {\n const instagramData = async () => {\n const url = `https://graph.instagram.com/v15.0/me/media?fields=id,media_url,permalink&access_token=${process.env.REACT_APP_INSTAGRAM_KEY}`;\n const data = await fetch(url).then((res) => res.json());\n // const feeds = await data.json();\n console.log(data);\n setFeed(data);\n };\n instagramData();\n }, []);\n // console.log(feeds)\n // console.log(Object.values(feeds));\n return (\n <>\n {Object.values(feeds)[0]?.map((d: any) => { //use it as Obj, nested Obj\n return (\n <div key={d.id}>\n <img src={d.media_url} alt=\"\" />\n </div>\n );\n })}\n </>\n );\n}\n\nexport default Instagram;\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19749827/"
] |
74,566,977
|
<p>A user makes a booking. They enter their name, the Pickup address and a Dropoff address and a time of pickup.</p>
<p>If, the user has an internet problem and their form doesn't seem to send, they press the submit button a second time, I often end up with 2 entries both the same in the database. Sometimes, Date_added column could change by amount of seconds because of when user clicks submit button.</p>
<p>I am trying to stop 2 entries being added to the database.</p>
<p>How do I check the database to see if their first submit was a successful entry into the database and stop a second row/record being added?</p>
<p>I was going to try using UNIQUE, but the user books trips and other times and also other users could use the same address's at times.</p>
<p>My columns names are: Date_added, Username, Pick_up_Address, Drop_off_Address, PU_time</p>
<p>How do I check the database to see if it's not a duplicate entry about to be added, that is only different by under a minute.</p>
<p>I don't know where to start with this or how to do it.</p>
<p>I tried UNIQUE in query but this would not work as other users would use the address's.</p>
|
[
{
"answer_id": 74567355,
"author": "Donnan31",
"author_id": 19910876,
"author_profile": "https://Stackoverflow.com/users/19910876",
"pm_score": -1,
"selected": false,
"text": "if (!$_session['booked']){\n //Insert entry into database//\n\n $_session['booked'] = 1;\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19910876/"
] |
74,566,994
|
<p>Every HTML page has a stacking context at the root element (<code>html</code>tag).</p>
<p>In the following example the <code>html</code> tag is the (only) stacking context</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
background-color: gray;
}
body {
background: #222;
color: white;
box-sizing: border-box;
}
.box {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.box:before {
content: "";
background-color: tomato;
position: absolute;
z-index: -1;
inset: 0;
margin: -5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Header</h1>
<div class="box"></div></code></pre>
</div>
</div>
</p>
<p>The pseudo element (tomato color) is drawn behind the body background (#222) because it has a <code>z-index</code> < 0</p>
<p>If we remove the <code>html</code> tag background color:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background: #222;
color: white;
box-sizing: border-box;
}
.box {
width: 200px;
height: 200px;
background-color: blue;
position: relative;
}
.box:before {
content: "";
background-color: tomato;
position: absolute;
z-index: -1;
inset: 0;
margin: -5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Header</h1>
<div class="box"></div></code></pre>
</div>
</div>
</p>
<p>Now the pseudo element (tomato color) is drawn after the body background (#222). That means that the <code>body</code> tag now creates a stacking context.</p>
<p>There are a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context" rel="nofollow noreferrer">few rules that determine if an element creates a stacking context</a>. None of the rules explain why the <code>body</code> tag is now the root of a stacking context.</p>
<p>A <a href="https://stackoverflow.com/questions/32109258/why-doesnt-the-z-index-style-apply-to-the-body-element">similar question on SO</a> explains, from the specs, that the canvas uses the <code>body</code> background color/image if the <code>html</code> tag has none. This is possibly to match the early days of HTML when this <a href="https://stackoverflow.com/a/37342517/9938317">info was set with the <code>bgcolor</code> and <code>background</code> attributes of the <code>body</code> tag</a>.</p>
<p>The question is: which part of the CSS specification is the reason of the <code>body</code> tag creating a stacking context depended on the html background color?</p>
|
[
{
"answer_id": 74576273,
"author": "Alohci",
"author_id": 42585,
"author_profile": "https://Stackoverflow.com/users/42585",
"pm_score": 2,
"selected": true,
"text": "body {\n background: #222;\n color: white;\n box-sizing: border-box;\n border:3px solid yellow;\n}\n.box {\n width: 200px;\n height: 200px;\n background-color: blue;\n position: relative;\n}\n.box:before {\n content: \"\";\n background-color: tomato;\n\n position: absolute;\n z-index: -1;\n inset: 0;\n margin: -5px;\n} <h1>Header</h1>\n<div class=\"box\"></div> scale: 1 body {\n background: #222;\n color: white;\n box-sizing: border-box;\n border:3px solid yellow;\n scale: 1;\n}\n.box {\n width: 200px;\n height: 200px;\n background-color: blue;\n position: relative;\n}\n.box:before {\n content: \"\";\n background-color: tomato;\n\n position: absolute;\n z-index: -1;\n inset: 0;\n margin: -5px;\n} <h1>Header</h1>\n<div class=\"box\"></div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74566994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9938317/"
] |
74,567,007
|
<p>I am creating a food menu layout, the menu has categories with items.
at the top is a list of category names like drinks, sushi, etc, which is a recyclerview that scrolls horizontally, at the bottom are the category items for example under drinks there is cocacola Fanta, etc which is a recyclerview that scrolls vertically. I am trying to synch the two recyclerviews together with a behavior in which when you scroll the vertical, it scrolls the horizontal and vice versa.</p>
<p>I created this class to implement this feature.</p>
<pre><code>import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
class TwoRecyclerViews(
private val recyclerViewHorizontal: RecyclerView,
private val recyclerViewVertical: RecyclerView,
private var indices: List<Int>,
private var isSmoothScroll: Boolean = false,
) {
private var attached = false
private var horizontalRecyclerState = RecyclerView.SCROLL_STATE_IDLE
private var verticalRecyclerState = RecyclerView.SCROLL_STATE_IDLE
private val smoothScrollerVertical: RecyclerView.SmoothScroller =
object : LinearSmoothScroller(recyclerViewVertical.context) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
}
fun attach() {
recyclerViewHorizontal.adapter
?: throw RuntimeException("Cannot attach with no Adapter provided to RecyclerView")
recyclerViewVertical.adapter
?: throw RuntimeException("Cannot attach with no Adapter provided to RecyclerView")
updateFirstPosition()
notifyIndicesChanged()
attached = true
}
private fun detach() {
recyclerViewVertical.clearOnScrollListeners()
recyclerViewHorizontal.clearOnScrollListeners()
}
fun reAttach() {
detach()
attach()
}
private fun updateFirstPosition() {
Handler(Looper.getMainLooper()).postDelayed({
val view = recyclerViewHorizontal.findViewHolderForLayoutPosition(0)?.itemView
val textView = view?.findViewById<TextView>(R.id.horizontalCategoryName)
val imageView = view?.findViewById<ImageView>(R.id.categorySelectionIndicator)
imageView?.visibility = View.VISIBLE
textView?.setTypeface(null, Typeface.BOLD)
textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.primary_1))
}, 100)
}
fun isAttached() = attached
private fun notifyIndicesChanged() {
recyclerViewHorizontal.addOnScrollListener(onHorizontalScrollListener)
recyclerViewVertical.addOnScrollListener(onVerticalScrollListener)
}
private val onHorizontalScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
horizontalRecyclerState = newState
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val linearLayoutManager: LinearLayoutManager =
recyclerView.layoutManager as LinearLayoutManager?
?: throw RuntimeException("No LinearLayoutManager attached to the RecyclerView.")
var itemPosition =
linearLayoutManager.findFirstCompletelyVisibleItemPosition()
if (itemPosition == -1) {
itemPosition =
linearLayoutManager.findFirstVisibleItemPosition()
}
if (horizontalRecyclerState == RecyclerView.SCROLL_STATE_DRAGGING ||
horizontalRecyclerState == RecyclerView.SCROLL_STATE_SETTLING
) {
for (position in indices.indices) {
val view = recyclerView.findViewHolderForLayoutPosition(indices[position])?.itemView
val textView = view?.findViewById<TextView>(R.id.horizontalCategoryName)
val imageView = view?.findViewById<ImageView>(R.id.categorySelectionIndicator)
if (itemPosition == indices[position]) {
if (isSmoothScroll) {
smoothScrollerVertical.targetPosition = indices[position]
recyclerViewVertical.layoutManager?.startSmoothScroll(smoothScrollerVertical)
} else {
(recyclerViewVertical.layoutManager as LinearLayoutManager?)?.scrollToPositionWithOffset(
indices[position], 16.dpToPx()
)
}
imageView?.visibility = View.VISIBLE
textView?.setTypeface(null, Typeface.BOLD)
textView?.setTextColor(recyclerView.context.getColor(R.color.primary_1))
} else {
imageView?.visibility = View.GONE
textView?.setTypeface(null, Typeface.NORMAL)
textView?.setTextColor(recyclerView.context.getColor(R.color.secondary_5))
}
}
}
}
}
private val onVerticalScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
verticalRecyclerState = newState
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val linearLayoutManager: LinearLayoutManager =
recyclerView.layoutManager as LinearLayoutManager?
?: throw RuntimeException("No LinearLayoutManager attached to the RecyclerView.")
var itemPosition =
linearLayoutManager.findFirstCompletelyVisibleItemPosition()
if (itemPosition == -1) {
itemPosition =
linearLayoutManager.findFirstVisibleItemPosition()
}
if (verticalRecyclerState == RecyclerView.SCROLL_STATE_DRAGGING ||
verticalRecyclerState == RecyclerView.SCROLL_STATE_SETTLING
) {
for (position in indices.indices) {
val view = recyclerViewHorizontal.findViewHolderForAdapterPosition(indices[position])?.itemView
val textView = view?.findViewById<TextView>(R.id.horizontalCategoryName)
val imageView = view?.findViewById<ImageView>(R.id.categorySelectionIndicator)
if (itemPosition == indices[position]) {
(recyclerViewHorizontal.layoutManager as LinearLayoutManager?)?.scrollToPositionWithOffset(
indices[position], 16.dpToPx()
)
imageView?.visibility = View.VISIBLE
textView?.setTypeface(null, Typeface.BOLD)
textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.primary_1))
} else {
imageView?.visibility = View.GONE
textView?.setTypeface(null, Typeface.NORMAL)
textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.secondary_5))
}
}
}
}
}
}
</code></pre>
<p>the class works fine for the vertical scroll, but there is an instability with the horizontal scroll. if you also have a better solution than the class i created kindly share.</p>
|
[
{
"answer_id": 74576273,
"author": "Alohci",
"author_id": 42585,
"author_profile": "https://Stackoverflow.com/users/42585",
"pm_score": 2,
"selected": true,
"text": "body {\n background: #222;\n color: white;\n box-sizing: border-box;\n border:3px solid yellow;\n}\n.box {\n width: 200px;\n height: 200px;\n background-color: blue;\n position: relative;\n}\n.box:before {\n content: \"\";\n background-color: tomato;\n\n position: absolute;\n z-index: -1;\n inset: 0;\n margin: -5px;\n} <h1>Header</h1>\n<div class=\"box\"></div> scale: 1 body {\n background: #222;\n color: white;\n box-sizing: border-box;\n border:3px solid yellow;\n scale: 1;\n}\n.box {\n width: 200px;\n height: 200px;\n background-color: blue;\n position: relative;\n}\n.box:before {\n content: \"\";\n background-color: tomato;\n\n position: absolute;\n z-index: -1;\n inset: 0;\n margin: -5px;\n} <h1>Header</h1>\n<div class=\"box\"></div>"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9140491/"
] |
74,567,051
|
<p>How can i match a series of expressions with OR's? This is for scrubbing plain text data which may contain imbedded spaces or tabs at the front of each row. This is in preparation for a <code>.split</code> at newlines.</p>
<pre><code>const oldStr = `abc
abc
abc`;
</code></pre>
<p>I want to replace:</p>
<pre><code>newline + 0 or more spaces OR tabs
</code></pre>
<p>with</p>
<pre><code>newline
</code></pre>
<p>This achieves what i want</p>
<pre><code>newStr = oldStr.replaceAll(/\n */g, "\n"); // newline + spaces
newStr = newStr.replaceAll(/\n\t*/g, "\n"); // newline + tabs
</code></pre>
<p>How to do that in a single statement? The following fail:</p>
<p>Attempt, with pipe:</p>
<pre><code>newStr = oldStr.replaceAll(/\n *|\t*/g, "\n");
</code></pre>
<p>Attempt, with parens around the OR:</p>
<pre><code>newStr = oldStr.replaceAll(/\n( *|\t*)/g, "\n");
</code></pre>
<p>Attempt, with slashes around the OR:</p>
<pre><code>newStr = oldStr.replaceAll(/\n/ *|\t*/g, "\n");
</code></pre>
<p>Attempt, with square brackets instead of pipe:</p>
<pre><code>newStr = oldStr.replaceAll(/\n[ *\t*]/g, "\n");
</code></pre>
<p>Attempt, with quotes and pipe:</p>
<pre><code>newStr = oldStr.replaceAll("\n *\t|*/g", "\n");
</code></pre>
<p>Attempt, with quotes and pipe and parens:</p>
<pre><code>newStr = oldStr.replaceAll("\n( *|\t*)/g, "\n");
</code></pre>
<p>Attempt, with quotes and square brackets:</p>
<pre><code>newStr = oldStr.replaceAll("\n[ *\t*]/g", "\n");
</code></pre>
<p>Feel free to offer a solution which combines the cleaning with a <code>.split</code> statement, or a non-regex solution.</p>
|
[
{
"answer_id": 74567130,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 3,
"selected": true,
"text": "\\n text = ` How razorback-jumping \n frogs \ncan\n \\t level six \\t\n \\t piqued gymnasts!` \n \nconsole.log(text.trim().split(/[ \\t]*\\n[ \\t]*/g))"
},
{
"answer_id": 74567137,
"author": "Peter B",
"author_id": 1220550,
"author_profile": "https://Stackoverflow.com/users/1220550",
"pm_score": 1,
"selected": false,
"text": "* + newStr = oldStr.replaceAll(/\\n[ \\t]+/g, \"\\n\");\n + let text = `ABC\n DEF\n \\t\\tGHI\n\\t\\tJKL\nMNO`;\nconsole.log(text.split(\"\\n\"));\n\ntext = text.replaceAll(/\\n[ \\t]+/g, \"\\n\");\nconsole.log(text.split(\"\\n\"))"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209942/"
] |
74,567,052
|
<p>I am not sure what is wrong:</p>
<p>I have an enum like the following:</p>
<pre><code>#[derive(Debug,PartialEq)]
pub enum Tree {
Leaf,
Node(Box<Tree>,i32,Box<Tree>)
}
</code></pre>
<p>Now for some reason when I try to find the sum of all of the leaves in this tree:</p>
<pre><code>pub fn tree_sum(t:&Tree) -> i32 {
match t {
Tree::Leaf => 0,
Tree::Node(Leaf, x, Leaf) => *x
}
}
</code></pre>
<p>The compiler decides to give me a very strange error:</p>
<pre><code>error[E0416]: identifier `Leaf` is bound more than once in the same pattern
--> src/functions.rs:11:28
|
11 | Tree::Node(Leaf,x, Leaf) => *x,
| ^^^^ used in a pattern more than once
</code></pre>
<p>Can someone explain to me what went wrong and what it should be instead?</p>
|
[
{
"answer_id": 74567163,
"author": "Allan J.",
"author_id": 9680087,
"author_profile": "https://Stackoverflow.com/users/9680087",
"pm_score": 0,
"selected": false,
"text": "pub fn tree_sum(t:&Tree) -> i32 {\n match t {\n Tree::Leaf => 0,\n Tree::Node(Leaf, x, Leaf2) => *x\n // ^^^ different name\n }\n}\n"
},
{
"answer_id": 74567189,
"author": "SirDarius",
"author_id": 393701,
"author_profile": "https://Stackoverflow.com/users/393701",
"pm_score": 3,
"selected": true,
"text": "Tree::Node Box<Tree> match t {\n Tree::Leaf => 0,\n Tree::Node(leaf1, x, leaf2) => ...\n}\n leaf1 leaf2 &Box<Tree> match match *x match t {\n Tree::Leaf => 0,\n Tree::Node(_, x, _) => *x,\n}\n match t {\n Tree::Leaf => 0,\n Tree::Node(leaf1, x, leaf2)\n if matches!(**leaf1, Tree::Leaf) && matches!(**leaf2, Tree::Leaf) =>\n {\n *x\n }\n Tree::Node(_, _, _) => todo!()\n}\n leaf1 leaf2 t"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20064859/"
] |
74,567,066
|
<p>"Sets can be declared using instances of the Set and RangeSet classes or by assigning set expressions. The simplest set declaration creates a set and postpones creation of its members."</p>
<p>That isn't a definition, what should a set be used for?</p>
|
[
{
"answer_id": 74567163,
"author": "Allan J.",
"author_id": 9680087,
"author_profile": "https://Stackoverflow.com/users/9680087",
"pm_score": 0,
"selected": false,
"text": "pub fn tree_sum(t:&Tree) -> i32 {\n match t {\n Tree::Leaf => 0,\n Tree::Node(Leaf, x, Leaf2) => *x\n // ^^^ different name\n }\n}\n"
},
{
"answer_id": 74567189,
"author": "SirDarius",
"author_id": 393701,
"author_profile": "https://Stackoverflow.com/users/393701",
"pm_score": 3,
"selected": true,
"text": "Tree::Node Box<Tree> match t {\n Tree::Leaf => 0,\n Tree::Node(leaf1, x, leaf2) => ...\n}\n leaf1 leaf2 &Box<Tree> match match *x match t {\n Tree::Leaf => 0,\n Tree::Node(_, x, _) => *x,\n}\n match t {\n Tree::Leaf => 0,\n Tree::Node(leaf1, x, leaf2)\n if matches!(**leaf1, Tree::Leaf) && matches!(**leaf2, Tree::Leaf) =>\n {\n *x\n }\n Tree::Node(_, _, _) => todo!()\n}\n leaf1 leaf2 t"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13635877/"
] |
74,567,073
|
<p>Hope I'm phrasing this question correctly... I have begun working through some coding examples for a <a href="https://github.com/raspberrypi/pico-examples" rel="nofollow noreferrer"><em>micrcontroller device</em></a>, and I see many expressions similar to the following:</p>
<pre><code>#define REG_CONFIG _u(0xF5)
</code></pre>
<p>I <em>think</em> this preprocessor directive declares that <code>REG_CONFIG</code> is a constant of type <code>unsigned int</code> and value <code>0xF5</code>. What I don't understand is the use of <code>_u(value)</code>; <code>_u</code> is apparently a data type but AFAIK, it's not a standard type (like <code>unsigned int</code>). I'm also under the impression that data types are declared as a <em>suffix</em> instead of a prefix.</p>
<p>Could someone explain this to an inexperienced programmer?</p>
|
[
{
"answer_id": 74567114,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 3,
"selected": true,
"text": "u u platform_defs.h #ifndef _u\n#ifdef __ASSEMBLER__\n#define _u(x) x\n#else\n#define _u(x) x ## u\n#endif\n#endif\n"
},
{
"answer_id": 74567121,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 1,
"selected": false,
"text": "_u(3) 3u _u u"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5395338/"
] |
74,567,078
|
<p>I am new to programming and today I wanted to try out the LeetCode problem <a href="https://leetcode.com/problems/palindrome-linked-list/" rel="nofollow noreferrer">234. Palindrome Linked List</a>:</p>
<blockquote>
<p>Given the <code>head</code> of a singly linked list, return <code>true</code> if it is a palindrome or <code>false</code> otherwise.</p>
<h3>Example 1:</h3>
<pre><code>Input: head = [1,2,2,1]
Output: true
</code></pre>
</blockquote>
<p>but I couldn't even manage the first problem.</p>
<p>I first tried to convert the linked list to a string and compare like:</p>
<pre><code>String[i] == String[length-i-1]
</code></pre>
<p>which worked for small lists but not for the gigantic test list where I got:</p>
<blockquote>
<p>Time Limit Exceeded</p>
</blockquote>
<p>In my second attempt I used recursion like this:</p>
<pre><code>/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
class Solution {
bool isPalindrome(ListNode? head) {
ListNode? current = head;
while(current?.next != null)
current = current?.next;
if (current?.val != head?.val)
return false;
else{
current = null;
isPalindrome(head?.next);
}
return true;
}
}
</code></pre>
<p>This also works with small lists, but for the test list I get a run time error:</p>
<blockquote>
<p>Stack overflow</p>
</blockquote>
<p>I wonder where this issue comes from.</p>
<p>Is it due to the maximum number of nested calls? And where can I find the recursion depth of Dart?
Or is there just a way simpler solution for this?</p>
|
[
{
"answer_id": 74567573,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 0,
"selected": false,
"text": "\n\n // Definition for singly-linked list.\n// class ListNode {\n// int val;\n// ListNode? next;\n// ListNode([this.val = 0, this.next]);\n// }\n \nclass Solution {\n bool isPalindrome(ListNode? head) {\n List<int> stack = [];\n ListNode? p = head;\n\n while (p != null) {\n stack.add(p.val);\n p = p.next;\n }\n print(stack);\n bool isP = true;\n \n while(head!.next!=null&&isP){\n var a = stack.removeLast();\n print('removed $a');\n print('head val ${head.val}');\n isP = head.val==a;\n head=head.next!;\n }\n return isP;\n }\n}\n current while (current?.next != null) {\n current = current?.next;\n }\n LinkedList if (current?.val != head?.val)\n return false;\n head else {\n current = null;\n isPalindrome(head?.next);\n}\n current while (current?.next != null) {\n current = current?.next;\n }\n if (current?.val != head?.val)\n {\n return false;\n }\n"
},
{
"answer_id": 74569271,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "current = null null next null return true false bool isPalindrome(ListNode? head) {\n ListNode? current = head;\n ListNode? prev = null;\n while(current?.next != null) {\n prev = current; // follow behind current\n current = current?.next;\n }\n if (current?.val != head?.val)\n return false; \n else if (prev == null)\n return true; // List has only one node\n else {\n prev?.next = null; // Detach the tail node\n return isPalindrome(head?.next); // Return the recursive result!\n }\n }\n while class Solution {\n int listSize(ListNode? head) {\n int size = 0;\n while(head?.next != null) {\n head = head?.next;\n size++;\n }\n return size;\n }\n\n ListNode? nodeAt(ListNode? head, int index) {\n while(head?.next != null && index > 0) {\n head = head?.next;\n index--;\n }\n return index == 0 ? head : null;\n }\n\n ListNode? reverse(ListNode? head) {\n ListNode? prev = null;\n ListNode? next;\n while (head != null) {\n next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n\n bool isEqual(ListNode? head1, ListNode? head2) {\n // Only compares the nodes that both lists have:\n while (head1 != null && head2 != null) {\n if (head1.val != head2.val) return false;\n head1 = head1.next;\n head2 = head2.next;\n }\n return true;\n }\n\n bool isPalindrome(ListNode? head) {\n return isEqual(head, reverse(nodeAt(head, listSize(head) >> 1)));\n }\n }"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14999171/"
] |
74,567,106
|
<p>I'm currently attempting a do very specific kind of navigation bar for my website. The main 'feature' of it is that on hover over each menu item, the item itself grows, while both the item before and the item after moves <em>x</em> pixels away from the item.</p>
<p>The styling of these elements is what would perform these transformations, using the following:</p>
<pre><code>.navitem{
display:inline;
transition: transform .75s ease-in-out;
}
.navitemRight {
transform: translate(10px);
}
.navitemLeft{
transform: translate(-10px);
}
.navitemCenter{
text-shadow:0px 0px 1px black;
transform: scale(1.20);
}
</code></pre>
<p>The problem is that there seems to be no way to apply these style whenever an item is hovered. It seems as though for each item, they should have these kind of stylings :</p>
<pre><code>.item2 : hover ~ item 1{
blabla
}
.item2 : hover ~ item 3{
blabla
}
</code></pre>
<p>but they should generated somehow, since the navigation bar's items are dynamic.</p>
<p>I tried using React and really thought I was going to get away with it, where onMouseEnter and onMouseLeave changed the state of the component, and everytime, it would re-render the navbar, with the correct style, like so:</p>
<p><a href="https://i.stack.imgur.com/3iOHg.gif" rel="nofollow noreferrer">almost working but ugly when hover out</a></p>
<p>But it does not satisfy me because we only get the transform when hovering, and lose the transition whenever the state changes, which is why the change is so ugly when I hover out. For reference, here's an example of what it looks like when you have the same trasnform and transition:</p>
<p><a href="https://i.stack.imgur.com/PuTTe.gif" rel="nofollow noreferrer">simple transform</a></p>
<p>Anyways, I am sure there is a way to do it, using Javascript probably, maybe sass or Jquery, both of which im not really familiar with. If you have any idea, or maybe a reference to tools that could help me with that, it would be very apprecited!Thanks</p>
|
[
{
"answer_id": 74567573,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 0,
"selected": false,
"text": "\n\n // Definition for singly-linked list.\n// class ListNode {\n// int val;\n// ListNode? next;\n// ListNode([this.val = 0, this.next]);\n// }\n \nclass Solution {\n bool isPalindrome(ListNode? head) {\n List<int> stack = [];\n ListNode? p = head;\n\n while (p != null) {\n stack.add(p.val);\n p = p.next;\n }\n print(stack);\n bool isP = true;\n \n while(head!.next!=null&&isP){\n var a = stack.removeLast();\n print('removed $a');\n print('head val ${head.val}');\n isP = head.val==a;\n head=head.next!;\n }\n return isP;\n }\n}\n current while (current?.next != null) {\n current = current?.next;\n }\n LinkedList if (current?.val != head?.val)\n return false;\n head else {\n current = null;\n isPalindrome(head?.next);\n}\n current while (current?.next != null) {\n current = current?.next;\n }\n if (current?.val != head?.val)\n {\n return false;\n }\n"
},
{
"answer_id": 74569271,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "current = null null next null return true false bool isPalindrome(ListNode? head) {\n ListNode? current = head;\n ListNode? prev = null;\n while(current?.next != null) {\n prev = current; // follow behind current\n current = current?.next;\n }\n if (current?.val != head?.val)\n return false; \n else if (prev == null)\n return true; // List has only one node\n else {\n prev?.next = null; // Detach the tail node\n return isPalindrome(head?.next); // Return the recursive result!\n }\n }\n while class Solution {\n int listSize(ListNode? head) {\n int size = 0;\n while(head?.next != null) {\n head = head?.next;\n size++;\n }\n return size;\n }\n\n ListNode? nodeAt(ListNode? head, int index) {\n while(head?.next != null && index > 0) {\n head = head?.next;\n index--;\n }\n return index == 0 ? head : null;\n }\n\n ListNode? reverse(ListNode? head) {\n ListNode? prev = null;\n ListNode? next;\n while (head != null) {\n next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n\n bool isEqual(ListNode? head1, ListNode? head2) {\n // Only compares the nodes that both lists have:\n while (head1 != null && head2 != null) {\n if (head1.val != head2.val) return false;\n head1 = head1.next;\n head2 = head2.next;\n }\n return true;\n }\n\n bool isPalindrome(ListNode? head) {\n return isEqual(head, reverse(nodeAt(head, listSize(head) >> 1)));\n }\n }"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11155733/"
] |
74,567,119
|
<p>I have the following line of code which run when I send {"key":"1234"} to the server.</p>
<pre><code>if (
(req.path === '/start' || req.path === '/start/') &&
(req.method === 'PUT') && (req.body.key === '1234')
)
</code></pre>
<p>However the app I am using sends this content as {"key": 1234} to the server without the quotes around the number and therefore the if statement is getting ignored.</p>
<p>How would I write the if statement above so that req.body.key matches 1234 without the need of the quotes.</p>
<p>Thanks for the help</p>
|
[
{
"answer_id": 74567573,
"author": "Soliev",
"author_id": 19945688,
"author_profile": "https://Stackoverflow.com/users/19945688",
"pm_score": 0,
"selected": false,
"text": "\n\n // Definition for singly-linked list.\n// class ListNode {\n// int val;\n// ListNode? next;\n// ListNode([this.val = 0, this.next]);\n// }\n \nclass Solution {\n bool isPalindrome(ListNode? head) {\n List<int> stack = [];\n ListNode? p = head;\n\n while (p != null) {\n stack.add(p.val);\n p = p.next;\n }\n print(stack);\n bool isP = true;\n \n while(head!.next!=null&&isP){\n var a = stack.removeLast();\n print('removed $a');\n print('head val ${head.val}');\n isP = head.val==a;\n head=head.next!;\n }\n return isP;\n }\n}\n current while (current?.next != null) {\n current = current?.next;\n }\n LinkedList if (current?.val != head?.val)\n return false;\n head else {\n current = null;\n isPalindrome(head?.next);\n}\n current while (current?.next != null) {\n current = current?.next;\n }\n if (current?.val != head?.val)\n {\n return false;\n }\n"
},
{
"answer_id": 74569271,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 1,
"selected": false,
"text": "current = null null next null return true false bool isPalindrome(ListNode? head) {\n ListNode? current = head;\n ListNode? prev = null;\n while(current?.next != null) {\n prev = current; // follow behind current\n current = current?.next;\n }\n if (current?.val != head?.val)\n return false; \n else if (prev == null)\n return true; // List has only one node\n else {\n prev?.next = null; // Detach the tail node\n return isPalindrome(head?.next); // Return the recursive result!\n }\n }\n while class Solution {\n int listSize(ListNode? head) {\n int size = 0;\n while(head?.next != null) {\n head = head?.next;\n size++;\n }\n return size;\n }\n\n ListNode? nodeAt(ListNode? head, int index) {\n while(head?.next != null && index > 0) {\n head = head?.next;\n index--;\n }\n return index == 0 ? head : null;\n }\n\n ListNode? reverse(ListNode? head) {\n ListNode? prev = null;\n ListNode? next;\n while (head != null) {\n next = head.next;\n head.next = prev;\n prev = head;\n head = next;\n }\n return prev;\n }\n\n bool isEqual(ListNode? head1, ListNode? head2) {\n // Only compares the nodes that both lists have:\n while (head1 != null && head2 != null) {\n if (head1.val != head2.val) return false;\n head1 = head1.next;\n head2 = head2.next;\n }\n return true;\n }\n\n bool isPalindrome(ListNode? head) {\n return isEqual(head, reverse(nodeAt(head, listSize(head) >> 1)));\n }\n }"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18535938/"
] |
74,567,128
|
<p>I have a problem and I am new to SQL so I am not sure how to solve it. I have a table with two columns and I want to start at the earliest date and take the next occurrence (of the name column) as the end date.</p>
<p>I know I want to group by Name, but I am not sure what to do after that:</p>
<pre><code> Name Date
x Jan-01
y Feb-01
z Mar-01
x Jan-02
y Feb-02
z Mar-02
x Jan-03
y Feb-03
z Mar-03
x Jan-04
y Feb-04
z Mar-04
x Jan-05
y Feb-05
z Mar-05
</code></pre>
<p>I want the resulting table to look like this:</p>
<pre><code> Name DateStart DateEnd
x Jan-01 Jan-02
y Feb-01 Feb-02
z Mar-01 Mar-02
x Jan-03 Jan-04
y Feb-03 Feb-04
z Mar-03 Mar-04
x Jan-05 NULL
y Feb-05 NULL
z Mar-05 NULL
</code></pre>
|
[
{
"answer_id": 74567183,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "WITH cte AS (\n SELECT *, ROW_NUMBER() OVER (ORDER BY Date) rn1,\n ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date) rn2\n FROM yourTable\n)\n\nSELECT Name, MIN(Date) AS DateStart, MAX(Date) AS DateEnd\nFROM cte\nGROUP BY Name, rn1 - rn2\nORDER BY MIN(Date);\n"
},
{
"answer_id": 74570429,
"author": "Zhorov",
"author_id": 6578080,
"author_profile": "https://Stackoverflow.com/users/6578080",
"pm_score": 0,
"selected": false,
"text": "Name SELECT *\nINTO Data\nFROM (VALUES\n ('x', CONVERT(date, 'Jan 01 2022', 106)), \n ('y', CONVERT(date, 'Feb 01 2022', 106)),\n ('z', CONVERT(date, 'Mar 01 2022', 106)),\n ('x', CONVERT(date, 'Jan 02 2022', 106)),\n ('y', CONVERT(date, 'Feb 02 2022', 106)),\n ('z', CONVERT(date, 'Mar 02 2022', 106)),\n ('x', CONVERT(date, 'Jan 03 2022', 106)),\n ('y', CONVERT(date, 'Feb 03 2022', 106)),\n ('z', CONVERT(date, 'Mar 03 2022', 106)),\n ('x', CONVERT(date, 'Jan 04 2022', 106)),\n ('y', CONVERT(date, 'Feb 04 2022', 106)),\n ('z', CONVERT(date, 'Mar 04 2022', 106)),\n ('x', CONVERT(date, 'Jan 05 2022', 106)),\n ('y', CONVERT(date, 'Feb 05 2022', 106)),\n ('z', CONVERT(date, 'Mar 05 2022', 106))\n) v (Name, Date)\n SELECT \n Name, \n StartDate = MIN(CASE WHEN (Rn - 1) % 2 = 0 THEN Date END),\n EndDate = MAX(CASE WHEN (Rn - 1) % 2 = 1 THEN Date END)\nFROM ( \n SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date) AS Rn\n FROM Data\n) t\nGROUP BY Name, ((Rn - 1) / 2)\nORDER BY Name\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17892584/"
] |
74,567,180
|
<p>I have two interfaces:</p>
<pre><code>interface Project {
...
CurrentProjectPhase : number
...
}
</code></pre>
<p>and</p>
<pre><code>interface Phase {
PhaseId : number
Projects$ : Observable<Project[]>
...
}
</code></pre>
<p>both are returned from individual http services as oberservables.</p>
<p>I'm trying to sort the projects via their currentPhase attribute into the phases. Before I did this via subscribing to both and attaching a filtered subset of all project elements to the phase:</p>
<pre><code>this.phaseService.loadAllPhases().subscribe((ph) => {
this.projectService.loadAllProjects().subscribe((pj) => {
ph.forEach((p : Phase) => {
p.Projects = pj.filter(project => project.CurrentProjectPhase === p.Id);
});
this.phases = ph;
this.projects = pj;
})
})
</code></pre>
<p>In that case the Phase had a Projects: Project[] instead of the Observable.</p>
<p>I would like to refactor this to stay as observables as long as possible. I've tried this:</p>
<pre><code>this.projects$ = this.projectService.getProjects();
this.phases$ = this.phaseService.getPhases().pipe(
tap(phases => phases.map(phase=>
phase.Projects$ = this.projects$?.pipe(
map(projects=> projects.filter(project => project.CurrentProjectPhase == phase.Id)))
))
)
</code></pre>
<p>But (ofcourse) it doesn't work. Any suggestions?</p>
|
[
{
"answer_id": 74567183,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": false,
"text": "WITH cte AS (\n SELECT *, ROW_NUMBER() OVER (ORDER BY Date) rn1,\n ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date) rn2\n FROM yourTable\n)\n\nSELECT Name, MIN(Date) AS DateStart, MAX(Date) AS DateEnd\nFROM cte\nGROUP BY Name, rn1 - rn2\nORDER BY MIN(Date);\n"
},
{
"answer_id": 74570429,
"author": "Zhorov",
"author_id": 6578080,
"author_profile": "https://Stackoverflow.com/users/6578080",
"pm_score": 0,
"selected": false,
"text": "Name SELECT *\nINTO Data\nFROM (VALUES\n ('x', CONVERT(date, 'Jan 01 2022', 106)), \n ('y', CONVERT(date, 'Feb 01 2022', 106)),\n ('z', CONVERT(date, 'Mar 01 2022', 106)),\n ('x', CONVERT(date, 'Jan 02 2022', 106)),\n ('y', CONVERT(date, 'Feb 02 2022', 106)),\n ('z', CONVERT(date, 'Mar 02 2022', 106)),\n ('x', CONVERT(date, 'Jan 03 2022', 106)),\n ('y', CONVERT(date, 'Feb 03 2022', 106)),\n ('z', CONVERT(date, 'Mar 03 2022', 106)),\n ('x', CONVERT(date, 'Jan 04 2022', 106)),\n ('y', CONVERT(date, 'Feb 04 2022', 106)),\n ('z', CONVERT(date, 'Mar 04 2022', 106)),\n ('x', CONVERT(date, 'Jan 05 2022', 106)),\n ('y', CONVERT(date, 'Feb 05 2022', 106)),\n ('z', CONVERT(date, 'Mar 05 2022', 106))\n) v (Name, Date)\n SELECT \n Name, \n StartDate = MIN(CASE WHEN (Rn - 1) % 2 = 0 THEN Date END),\n EndDate = MAX(CASE WHEN (Rn - 1) % 2 = 1 THEN Date END)\nFROM ( \n SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date) AS Rn\n FROM Data\n) t\nGROUP BY Name, ((Rn - 1) / 2)\nORDER BY Name\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613849/"
] |
74,567,197
|
<blockquote>
<p>This is a follow-up to <a href="https://stackoverflow.com/q/74566316/4756173">this question</a>, asking if all this was even possible.</p>
</blockquote>
<p>The <a href="https://pub.dev/packages/webview_flutter/install" rel="nofollow noreferrer"><code>WebView</code> package</a> seems really dope. But so far it seems really obscure and dense to me.</p>
<p>Almost all of the examples I've been able to find refer to seeing other existing web pages and then altering them, but my use case was about having an empty page, in which I would use the more mature JS visual libraries to plot charts or graphs.</p>
<p>And it's not clear to me, but is this package about adding views for non-web environments? If it is, what about using it on Flutter Web? Maybe this is obvious for someone with experience with that package, but to those starting with it, it's not clear at all...</p>
<p>For example, I'm trying to implement <a href="https://www.w3schools.com/ai/ai_d3js.asp" rel="nofollow noreferrer">this simple D3.js example</a>, and, in the package's documentation, there's this simple example:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:io';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewExample extends StatefulWidget {
@override
WebViewExampleState createState() => WebViewExampleState();
}
class WebViewExampleState extends State<WebViewExample> {
@override
void initState() {
super.initState();
// Enable virtual display.
if (Platform.isAndroid) WebView.platform = AndroidWebView();
}
@override
Widget build(BuildContext context) {
return WebView(
initialUrl: 'https://flutter.dev',
);
}
}
</code></pre>
<p>I don't know what I would do for <code>WebView.platform</code> in the case of Web, there's no option for it. And, when I try it on Chrome, I get — I used Chrome on Linux, and the rest of my app <em>does</em> work —:</p>
<pre><code>The following UnsupportedError was thrown building WebView(dirty, state: _WebViewState#2d89e):
Unsupported operation: Trying to use the default webview implementation for TargetPlatform.linux
but there isn't a default one
</code></pre>
<p>I did try other variations of the code above, including trying to make it a <code>StatelessWidget</code> without <code>initState</code>, but the result was the same:</p>
<pre class="lang-dart prettyprint-override"><code>class WebViewExample extends StatelessWidget {
const WebViewExample({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: WebView(
initialUrl: 'https://flutter.dev',
),
);
}
}
</code></pre>
<p>Is anyone able to pull off <a href="https://www.w3schools.com/ai/ai_d3js.asp" rel="nofollow noreferrer">the simple D3.js example I mentioned</a> on Flutter Web (even better if you could send the data from Dart to JS...)? That would be of great help.</p>
|
[
{
"answer_id": 74568365,
"author": "Alifa Al Farizi",
"author_id": 16363643,
"author_profile": "https://Stackoverflow.com/users/16363643",
"pm_score": -1,
"selected": false,
"text": " const WebView({\n Key? key,\n this.onWebViewCreated,\n this.initialUrl,\n this.initialCookies = const <WebViewCookie>[],\n this.javascriptMode = JavascriptMode.disabled,\n this.javascriptChannels,\n this.navigationDelegate,\n this.gestureRecognizers,\n this.onPageStarted,\n this.onPageFinished,\n this.onProgress,\n this.onWebResourceError,\n this.debuggingEnabled = false,\n this.gestureNavigationEnabled = false,\n this.userAgent,\n this.zoomEnabled = true,\n this.initialMediaPlaybackPolicy =\n AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,\n this.allowsInlineMediaPlayback = false,\n this.backgroundColor,\n }) : assert(javascriptMode != null),\n assert(initialMediaPlaybackPolicy != null),\n assert(allowsInlineMediaPlayback != null),\n super(key: key);\n"
},
{
"answer_id": 74572376,
"author": "Lorenzo Pichilli",
"author_id": 4637638,
"author_profile": "https://Stackoverflow.com/users/4637638",
"pm_score": 2,
"selected": true,
"text": "webview_flutter flutter_inappwebview 6.x.x flutter_inappwebview import 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_inappwebview/flutter_inappwebview.dart';\n\nFuture main() async {\n WidgetsFlutterBinding.ensureInitialized();\n if (!kIsWeb &&\n kDebugMode &&\n defaultTargetPlatform == TargetPlatform.android) {\n await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);\n }\n runApp(const MaterialApp(home: MyApp()));\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final GlobalKey webViewKey = GlobalKey();\n\n InAppWebViewController? webViewController;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: const Text(\"InAppWebView test\"),\n ),\n body: Column(children: <Widget>[\n Expanded(\n child: InAppWebView(\n key: webViewKey,\n initialData: InAppWebViewInitialData(\n data: \"\"\"\n<!DOCTYPE html>\n<html>\n<head>\n <script src=\"https://d3js.org/d3.v4.js\"></script>\n</head>\n<body>\n <h2>D3.js Scatter-Plot</h2>\n <svg id=\"myPlot\" style=\"width:500px;height:500px\"></svg>\n <script>\n // Set Dimensions\n const xSize = 500;\n const ySize = 500;\n const margin = 40;\n const xMax = xSize - margin * 2;\n const yMax = ySize - margin * 2;\n\n // Create Random Points\n const numPoints = 100;\n const data = [];\n for (let i = 0; i < numPoints; i++) {\n data.push([Math.random() * xMax, Math.random() * yMax]);\n }\n\n // Append SVG Object to the Page\n const svg = d3.select(\"#myPlot\")\n .append(\"svg\")\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin + \",\" + margin + \")\");\n\n // X Axis\n const x = d3.scaleLinear()\n .domain([0, 500])\n .range([0, xMax]);\n\n svg.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + yMax + \")\")\n .call(d3.axisBottom(x));\n\n // Y Axis\n const y = d3.scaleLinear()\n .domain([0, 500])\n .range([yMax, 0]);\n\n svg.append(\"g\")\n .call(d3.axisLeft(y));\n\n // Dots\n svg.append('g')\n .selectAll(\"dot\")\n .data(data).enter()\n .append(\"circle\")\n .attr(\"cx\", function (d) { return d[0] })\n .attr(\"cy\", function (d) { return d[1] })\n .attr(\"r\", 3)\n .style(\"fill\", \"Red\");\n </script>\n</body>\n</html>\n\"\"\"\n ),\n onWebViewCreated: (controller) {\n webViewController = controller;\n },\n ),\n ),\n ]));\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4756173/"
] |
74,567,208
|
<p>I have a task to accomplish in Python with only one sentence:
I need to return lines of my txt-file that include words which have more than 6 characters and start with the letter "A".</p>
<p>My code is the following:</p>
<pre><code>[line for line in open('test.txt') if line.split().count('A') > 6]
</code></pre>
<p>I am not sure how to implement another command in order to say that my word starts with "A" and has to have more than 6 characters. That is the furthest I could do. I thank you for your time.</p>
<p>Greetings</p>
|
[
{
"answer_id": 74568365,
"author": "Alifa Al Farizi",
"author_id": 16363643,
"author_profile": "https://Stackoverflow.com/users/16363643",
"pm_score": -1,
"selected": false,
"text": " const WebView({\n Key? key,\n this.onWebViewCreated,\n this.initialUrl,\n this.initialCookies = const <WebViewCookie>[],\n this.javascriptMode = JavascriptMode.disabled,\n this.javascriptChannels,\n this.navigationDelegate,\n this.gestureRecognizers,\n this.onPageStarted,\n this.onPageFinished,\n this.onProgress,\n this.onWebResourceError,\n this.debuggingEnabled = false,\n this.gestureNavigationEnabled = false,\n this.userAgent,\n this.zoomEnabled = true,\n this.initialMediaPlaybackPolicy =\n AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,\n this.allowsInlineMediaPlayback = false,\n this.backgroundColor,\n }) : assert(javascriptMode != null),\n assert(initialMediaPlaybackPolicy != null),\n assert(allowsInlineMediaPlayback != null),\n super(key: key);\n"
},
{
"answer_id": 74572376,
"author": "Lorenzo Pichilli",
"author_id": 4637638,
"author_profile": "https://Stackoverflow.com/users/4637638",
"pm_score": 2,
"selected": true,
"text": "webview_flutter flutter_inappwebview 6.x.x flutter_inappwebview import 'package:flutter/foundation.dart';\nimport 'package:flutter/material.dart';\nimport 'package:flutter_inappwebview/flutter_inappwebview.dart';\n\nFuture main() async {\n WidgetsFlutterBinding.ensureInitialized();\n if (!kIsWeb &&\n kDebugMode &&\n defaultTargetPlatform == TargetPlatform.android) {\n await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);\n }\n runApp(const MaterialApp(home: MyApp()));\n}\n\nclass MyApp extends StatefulWidget {\n const MyApp({Key? key}) : super(key: key);\n\n @override\n State<MyApp> createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n final GlobalKey webViewKey = GlobalKey();\n\n InAppWebViewController? webViewController;\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: const Text(\"InAppWebView test\"),\n ),\n body: Column(children: <Widget>[\n Expanded(\n child: InAppWebView(\n key: webViewKey,\n initialData: InAppWebViewInitialData(\n data: \"\"\"\n<!DOCTYPE html>\n<html>\n<head>\n <script src=\"https://d3js.org/d3.v4.js\"></script>\n</head>\n<body>\n <h2>D3.js Scatter-Plot</h2>\n <svg id=\"myPlot\" style=\"width:500px;height:500px\"></svg>\n <script>\n // Set Dimensions\n const xSize = 500;\n const ySize = 500;\n const margin = 40;\n const xMax = xSize - margin * 2;\n const yMax = ySize - margin * 2;\n\n // Create Random Points\n const numPoints = 100;\n const data = [];\n for (let i = 0; i < numPoints; i++) {\n data.push([Math.random() * xMax, Math.random() * yMax]);\n }\n\n // Append SVG Object to the Page\n const svg = d3.select(\"#myPlot\")\n .append(\"svg\")\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin + \",\" + margin + \")\");\n\n // X Axis\n const x = d3.scaleLinear()\n .domain([0, 500])\n .range([0, xMax]);\n\n svg.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + yMax + \")\")\n .call(d3.axisBottom(x));\n\n // Y Axis\n const y = d3.scaleLinear()\n .domain([0, 500])\n .range([yMax, 0]);\n\n svg.append(\"g\")\n .call(d3.axisLeft(y));\n\n // Dots\n svg.append('g')\n .selectAll(\"dot\")\n .data(data).enter()\n .append(\"circle\")\n .attr(\"cx\", function (d) { return d[0] })\n .attr(\"cy\", function (d) { return d[1] })\n .attr(\"r\", 3)\n .style(\"fill\", \"Red\");\n </script>\n</body>\n</html>\n\"\"\"\n ),\n onWebViewCreated: (controller) {\n webViewController = controller;\n },\n ),\n ),\n ]));\n }\n}\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594803/"
] |
74,567,217
|
<p>My Oracle table define with date type for one of the date column requestedDate.</p>
<p>While persisting, I am setting the value like below</p>
<pre><code>.setRequestedDate(Date.valueOf(LocalDate.now())))
</code></pre>
<p>And JPA entity defined like below,</p>
<pre><code>@Column(name = "REQ_DT")
@Temporal(TemporalType.DATE)
private Date requestedDate;
</code></pre>
<p>I am expecting value like "2022-05-12", but it gets stored like "2022-05-12 00:00:00.0"? I want to get rid of the timestamp when it gets inserted into the database.</p>
<p>Do I need to change the date definition in Oracle DB like creating view to truncate the timestamp?</p>
|
[
{
"answer_id": 74567663,
"author": "pmdba",
"author_id": 12913491,
"author_profile": "https://Stackoverflow.com/users/12913491",
"pm_score": 2,
"selected": false,
"text": "DATE to_char select to_char(sysdate,'YYYY-MM-DD') from dual;\n\nTO_CHAR(SY\n----------\n2022-11-24 \n"
},
{
"answer_id": 74568924,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 2,
"selected": false,
"text": "SQL> create table test (id number, datum date);\n\nTable created.\n SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';\n\nSession altered.\n SQL> select sysdate value_with_date_and_time,\n 2 trunc(sysdate) date_only\n 3 from dual;\n\nVALUE_WITH_DATE_AND DATE_ONLY\n------------------- -------------------\n25.11.2022 07:11:21 25.11.2022 00:00:00\n SQL> insert into test (id, datum)\n 2 select 1, sysdate from dual union all\n 3 select 2, trunc(sysdate) from dual;\n\n2 rows created.\n SQL> select * from test order by id;\n\n ID DATUM\n---------- -------------------\n 1 25.11.2022 07:11:48 --> both date and time\n 2 25.11.2022 00:00:00 --> also date AND time, but time is set to midnight\n to_char SQL> select id, to_char(datum, 'dd.mm.yyyy') display_date\n 2 from test order by id;\n\n ID DISPLAY_DA\n---------- ----------\n 1 25.11.2022\n 2 25.11.2022\n\nSQL>\n"
},
{
"answer_id": 74575875,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 3,
"selected": true,
"text": "DATE TIMESTAMP WITHOUT TIME ZONE DATE DATE TIMESTAMP WITHOUT TIME ZONE LocalDateTime DATE java.time.LocalDateTime LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;\n LocalDate java.time.LocalDate LocalDate ld = ldt.toLocalDate() ;\n ZoneId z = ZoneId.of( \"Asia/Tokyo\" ) ; // Or ZoneId.systemDefault()\nLocalDate ld = LocalDate.now( z ) ;\n DATE LocalDateTime ldt = ld.atStartOfDay() ; // Assign a time-of-day of 00:00:00 to the date-only `LocalDate` object, returning a `LocalDateTime` object.\nmyPreparedStatement.setObject( … , ldt ) ;\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/957359/"
] |
74,567,219
|
<p>I'm trying to send HTTPS requests as quickly as possible. I know this would have to be concurrent requests due to my <strong>goal being 150 to 500+ requests a second</strong>. I've searched everywhere, but get no Python 3.11+ answer or one that doesn't give me errors. I'm trying to avoid AIOHTTP as the rigmarole of setting it up was a pain, which didn't even work.</p>
<p><em>The input should be an array or URLs and the output an array of the html string.</em></p>
|
[
{
"answer_id": 74567446,
"author": "atl",
"author_id": 2162861,
"author_profile": "https://Stackoverflow.com/users/2162861",
"pm_score": 0,
"selected": false,
"text": "GET from treq import get\nfrom twisted.internet import reactor\n\ndef done(response):\n if response.code == 200:\n get(\"http://localhost:3000\").addCallback(done)\n\nget(\"http://localhost:3000\").addCallback(done)\n\nreactor.callLater(10, reactor.stop)\nreactor.run()\n pip3 install treq\npython3 a.py # code from above\n mkdir myapp\ncd myapp\nnpm init\nnpm install express\nnode app.js\n const express = require('express')\nconst app = express()\nconst port = 3000\n\napp.get('/', (req, res) => {\n res.send('Hello World!')\n})\n\napp.listen(port, () => {\n console.log(`Example app listening on port ${port}`)\n})\n grep GET wireshark.csv | head\n\"5\",\"0.000418\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"13\",\"0.002334\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"17\",\"0.003236\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"21\",\"0.004018\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"25\",\"0.004803\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\ngrep GET wireshark.csv | tail\n\"62145\",\"9.994184\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62149\",\"9.995102\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62153\",\"9.995860\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62157\",\"9.996616\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62161\",\"9.997307\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\n"
},
{
"answer_id": 74588957,
"author": "Surgemus",
"author_id": 12950945,
"author_profile": "https://Stackoverflow.com/users/12950945",
"pm_score": 0,
"selected": false,
"text": "pip install import time\nimport requests\nimport concurrent.futures\n\nstart = int(time.time()) # get time before the requests are sent\n\nurls = [] # input URLs/IPs array\nresponses = [] # output content of each request as string in an array\n\n# create an list of 5000 sites to test with\nfor y in range(5000):urls.append(\"https://example.com\")\n\ndef send(url):responses.append(requests.get(url).content)\n\nwith concurrent.futures.ThreadPoolExecutor(max_workers=10000) as executor:\n futures = []\n for url in urls:futures.append(executor.submit(send, url))\n \nend = int(time.time()) # get time after stuff finishes\nprint(str(round(len(urls)/(end - start),0))+\"/sec\") # get average requests per second\n 286.0/sec with concurrent.futures.ThreadPoolExecutor(max_workers=10000) as executor:\n futures = []\n for url in urls:\n futures.append(executor.submit(send, url))\n for future in concurrent.futures.as_completed(futures):\n responses.append(future.result())\n max_workers=10000"
},
{
"answer_id": 74658865,
"author": "Louis Lac",
"author_id": 6324055,
"author_profile": "https://Stackoverflow.com/users/6324055",
"pm_score": 2,
"selected": true,
"text": "import asyncio\nimport aiohttp\nfrom time import perf_counter\n\n\ndef urls(n_reqs: int):\n for _ in range(n_reqs):\n yield \"https://python.org\"\n\nasync def get(session: aiohttp.ClientSession, url: str):\n async with session.get(url) as response:\n _ = await response.text()\n \nasync def main(n_reqs: int):\n async with aiohttp.ClientSession() as session:\n await asyncio.gather(\n *[get(session, url) for url in urls(n_reqs)]\n )\n\n\nif __name__ == \"__main__\":\n n_reqs = 10_000\n \n start = perf_counter()\n asyncio.run(main(n_reqs))\n end = perf_counter()\n \n print(f\"{n_reqs / (end - start)} req/s\")\n ClientSession asyncio.gather() asyncio.TaskGroup async def main(n_reqs: int):\n async with aiohttp.ClientSession() as session:\n async with asyncio.TaskGroup() as group:\n for url in urls(n_reqs):\n group.create_task(get(session, url))\n async def main(n_reqs: int):\n let connector = aiohttp.TCPConnector(limit=0)\n async with aiohttp.ClientSession(connector=connector) as session:\n ...\n\n"
}
] |
2022/11/24
|
[
"https://Stackoverflow.com/questions/74567219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12950945/"
] |
74,567,254
|
<p>I am trying to make two fetch requests. The second one cannot be completed until MemberId is retrieved from the first one. I have tried putting them in separate async functions but keep getting the below error.</p>
<p>Any insights on the best way to do this would be much appreciated.</p>
<p>Error message:
<em>Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.</em></p>
<pre><code>import { StatusBar } from "expo-status-bar";
import { useEffect, useState } from "react";
import { StyleSheet, Image, Text, View } from "react-native";
export default async function App() {
const [isLoading, setLoading] = useState(true);
const [isLoadingMp, setLoadingMp] = useState(true);
const [data, setData] = useState([]);
const [mpData, setMpData] = useState([]);
let memberId = 0;
useEffect(() => {
fetch(
`https://members-api.parliament.uk/api/Members/Search?Name=Boris%20Johnson`
)
.then((response) => response.json())
.then((json) => {
setMpData(json);
memberId = json.items[0].value.id;
console.log("memberId:", memberId);
})
.catch((error) => console.error(error))
.then(
fetch(
`https://commonsvotes-api.parliament.uk/data/divisions.json/membervoting?memberId=${memberId}`
)
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false))
.finally(() => {
setLoadingMp(false);
})
);
});
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading || isLoadingMp ? (
<Text>Loading...</Text>
) : (
<View style={styles.container}>
<Text>
<Image
source={{
uri: `${mpData.items[0].value.thumbnailUrl}`,
width: 60,
height: 60,
}}
/>
<Text>{`${mpData.items[0].value.id}\n`}</Text>
{data.map((individualData) => {
return `\nDate: ${
individualData.PublishedDivision.Date
}\nDivision id: ${
individualData.PublishedDivision.Date
}\nDivision title: ${
individualData.PublishedDivision.Title
}\nVoted: ${!!individualData.MemberVotedAye ? "Yes" : "No"}\n`;
})}
</Text>
<StatusBar style="auto" />
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
</code></pre>
|
[
{
"answer_id": 74567446,
"author": "atl",
"author_id": 2162861,
"author_profile": "https://Stackoverflow.com/users/2162861",
"pm_score": 0,
"selected": false,
"text": "GET from treq import get\nfrom twisted.internet import reactor\n\ndef done(response):\n if response.code == 200:\n get(\"http://localhost:3000\").addCallback(done)\n\nget(\"http://localhost:3000\").addCallback(done)\n\nreactor.callLater(10, reactor.stop)\nreactor.run()\n pip3 install treq\npython3 a.py # code from above\n mkdir myapp\ncd myapp\nnpm init\nnpm install express\nnode app.js\n const express = require('express')\nconst app = express()\nconst port = 3000\n\napp.get('/', (req, res) => {\n res.send('Hello World!')\n})\n\napp.listen(port, () => {\n console.log(`Example app listening on port ${port}`)\n})\n grep GET wireshark.csv | head\n\"5\",\"0.000418\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"13\",\"0.002334\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"17\",\"0.003236\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"21\",\"0.004018\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"25\",\"0.004803\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\ngrep GET wireshark.csv | tail\n\"62145\",\"9.994184\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62149\",\"9.995102\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62153\",\"9.995860\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62157\",\"9.996616\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\"62161\",\"9.997307\",\"::1\",\"::1\",\"HTTP\",\"139\",\"GET / HTTP/1.1 \"\n\n"
},
{
"answer_id": 74588957,
"author": "Surgemus",
"author_id": 12950945,
"author_profile": "https://Stackoverflow.com/users/12950945",
"pm_score": 0,
"selected": false,
"text": "pip install import time\nimport requests\nimport concurrent.futures\n\nstart = int(time.time()) # get time before the requests are sent\n\nurls = [] # input URLs/IPs array\nresponses = [] # output content of each request as string in an array\n\n# create an list of 5000 sites to test with\nfor y in range(5000):urls.append(\"https://example.com\")\n\ndef send(url):responses.append(requests.get(url).content)\n\nwith concurrent.futures.ThreadPoolExecutor(max_workers=10000) as executor:\n futures = []\n for url in urls:futures.append(executor.submit(send, url))\n \nend = int(time.time()) # get time after stuff finishes\nprint(str(round(len(urls)/(end - start),0))+\"/sec\") # get average requests per second\n 286.0/sec with concurrent.futures.ThreadPoolExecutor(max_workers=10000) as executor:\n futures = []\n for url in urls:\n futures.append(executor.submit(send, url))\n for future in concurrent.futures.as_completed(futures):\n responses.append(future.result())\n max_workers=10000"
},
{
"answer_id": 74658865,
"author": "Louis Lac",
"author_id": 6324055,
"author_profile": "https://Stackoverflow.com/users/6324055",
"pm_score": 2,
"selected": true,
"text": "import asyncio\nimport aiohttp\nfrom time import perf_counter\n\n\ndef urls(n_reqs: int):\n for _ in range(n_reqs):\n yield \"https://python.org\"\n\nasync def get(session: aiohttp.ClientSession, url: str):\n async with session.get(url) as response:\n _ = await response.text()\n \nasync def main(n_reqs: int):\n async with aiohttp.ClientSession() as session:\n await asyncio.gather(\n *[get(session, url) for url in urls(n_reqs)]\n )\n\n\nif __name__ == \"__main__\":\n n_reqs = 10_000\n \n start = perf_counter()\n asyncio.run(main(n_reqs))\n end = perf_counter()\n \n print(f\"{n_reqs / (end - start)} req/s\")\n ClientSession asyncio.gather() asyncio.TaskGroup async def main(n_reqs: int):\n async with aiohttp.ClientSession() as session:\n async with asyncio.TaskGroup() as group:\n for url in urls(n_reqs):\n group.create_task(get(session, url))\n async def main(n_reqs: int):\n let connector = aiohttp.TCPConnector(limit=0)\n async with aiohttp.ClientSession(connector=connector) as session:\n ...\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19813094/"
] |
74,567,273
|
<p>According to <a href="https://peps.python.org/pep-0585/#id6" rel="nofollow noreferrer">pep-0585</a> for the latest versions of Python, it appears we can use <code>List</code> and <code>list</code> interchangeably for type declarations. So which should I use?</p>
<p>Assume:</p>
<ol>
<li>no requirement for backward compatibility</li>
<li>using the latest version of python</li>
</ol>
<pre><code>from typing import List
def hello_world_1(animals: list[str]) -> list[str]:
return animals
def hello_world_2(animals: List[str]) -> List[str]:
return animals
</code></pre>
<p>How can I set up a python linter to enforce consistency and only allow either upper or lowercase <code>List</code> for example?</p>
|
[
{
"answer_id": 74567345,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 1,
"selected": false,
"text": "typing.List list typing.List"
},
{
"answer_id": 74567396,
"author": "benjimin",
"author_id": 5104777,
"author_profile": "https://Stackoverflow.com/users/5104777",
"pm_score": 2,
"selected": false,
"text": "typing"
},
{
"answer_id": 74567848,
"author": "msailor",
"author_id": 10155119,
"author_profile": "https://Stackoverflow.com/users/10155119",
"pm_score": 3,
"selected": true,
"text": "typing.List"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/833960/"
] |
74,567,311
|
<p>In my XML file [studentinfo.xml] is there a way to loop through the xml file and change specific tags (and specific child tags) [there will be multiple ones that need to change] and add a number on the end?</p>
<p>**The file is significantly larger</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<stu:StudentBreakdown>
<stu:Studentdata>
<stu:StudentScreening>
<st:name>Sam Davies</st:name>
<st:age>15</st:age>
<st:hair>Black</st:hair>
<st:eyes>Blue</st:eyes>
<st:grade>10</st:grade>
<st:teacher>Draco Malfoy</st:teacher>
<st:dorm>Innovation Hall</st:dorm>
<st:name>Master Splinter</st:name>
</stu:StudentScreening>
<stu:StudentScreening>
<st:name>Cassie Stone</st:name>
<st:age>14</st:age>
<st:hair>Science</st:hair>
<st:grade>9</st:grade>
<st:teacher>Luna Lovegood</st:teacher>
<st:name>Kelly Clarkson</st:name>
</stu:StudentScreening>
<stu:StudentScreening>
<st:name>Derek Brandon</st:name>
<st:age>17</st:age>
<st:eyes>green</st:eyes>
<st:teacher>Ron Weasley</st:teacher>
<st:dorm>Hogtie Manor</st:dorm>
<st:name>Miley Cyrus</st:name>
</stu:StudentScreening>
</stu:Studentdata>
</stu:StudentBreakdown>
</code></pre>
<p>Each tag should be unique for each Student Screening and I want to make them unique by adding a number on the end, see below for desired ouput:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<stu:StudentBreakdown>
<stu:Studentdata>
<stu:StudentScreening>
<st:name0>Sam Davies</st:name0>
<st:age>15</st:age>
<st:hair>Black</st:hair>
<st:eyes>Blue</st:eyes>
<st:grade>10</st:grade>
<st:teacher>Draco Malfoy</st:teacher>
<st:dorm>Innovation Hall</st:dorm>
<st:name1>Master Splinter</st:name1>
<st:name2>Peter Griffin</st:name2>
<st:name3>Louis Griffin</st:name3>
</stu:StudentScreening>
<stu:StudentScreening>
<st:name0>Cassie Stone</st:name0>
<st:age>14</st:age>
<st:hair>Science</st:hair>
<st:grade>9</st:grade>
<st:teacher>Luna Lovegood</st:teacher>
<st:name1>Kelly Clarkson</st:name1>
<st:name2>Stewie Griffin</st:name2>
</stu:StudentScreening>
<stu:StudentScreening>
<st:name0>Derek Brandon</st:name0>
<st:age>17</st:age>
<st:eyes>green</st:eyes>
<st:teacher>Ron Weasley</st:teacher>
<st:dorm>Hogtie Manor</st:dorm>
<st:name1>Miley Cyrus</st:name1>
</stu:StudentScreening>
</stu:Studentdata>
</stu:StudentBreakdown>
</code></pre>
|
[
{
"answer_id": 74570024,
"author": "Charles Han",
"author_id": 11514907,
"author_profile": "https://Stackoverflow.com/users/11514907",
"pm_score": 0,
"selected": false,
"text": "import lxml.etree as ET\n\nXSL = '''\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\" />\n </xsl:copy>\n </xsl:template>\n <xsl:template match=\"stu:StudentScreening/st:name\">\n <xsl:element name=\"st:name{count(preceding-sibling::st:name)}\"><xsl:apply-templates select=\"@*|node()\" /></xsl:element>\n </xsl:template>\n</xsl:stylesheet>\n'''\n\ndom = ET.parse('students.xml')\ntransform = ET.XSLT(ET.fromstring(XSL))\nnewdom = transform(dom)\nprint(ET.tostring(newdom))\n\nnewdom.write(\"out.xml\", pretty_print=True)\n students.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<stu:StudentBreakdown xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n<stu:Studentdata>\n <stu:StudentScreening>\n <st:name>Sam Davies</st:name>\n <st:age>15</st:age>\n <st:hair>Black</st:hair>\n <st:eyes>Blue</st:eyes>\n <st:grade>10</st:grade>\n <st:teacher>Draco Malfoy</st:teacher>\n <st:dorm>Innovation Hall</st:dorm>\n <st:name>Master Splinter</st:name>\n <st:name>Peter Griffin</st:name>\n <st:name>Louis Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Cassie Stone</st:name>\n <st:age>14</st:age>\n <st:hair>Science</st:hair>\n <st:grade>9</st:grade>\n <st:teacher>Luna Lovegood</st:teacher>\n <st:name>Kelly Clarkson</st:name>\n <st:name>Stewie Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Derek Brandon</st:name>\n <st:age>17</st:age>\n <st:eyes>green</st:eyes>\n <st:teacher>Ron Weasley</st:teacher>\n <st:dorm>Hogtie Manor</st:dorm>\n <st:name>Miley Cyrus</st:name>\n </stu:StudentScreening>\n</stu:Studentdata>\n</stu:StudentBreakdown>\n out.xml"
},
{
"answer_id": 74570172,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 2,
"selected": true,
"text": "Tag.name = 'NEW_NAME' xmlStr xSoup = BeautifulSoup(xmlStr, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces\n\nenumTags = ['st:name', 'stu:studentscreening']\nfor d in [c for c in xSoup.descendants if c.name]:\n for name in enumTags:\n for i, t in enumerate(d.find_all(name, recursive=False)):\n t.name = f'{t.name}{i}'\n studentscreening recursive=False find print(xSoup) <?xml version=\"1.0\" encoding=\"UTF-8\"?><html><body><stu:studentbreakdown>\n<stu:studentdata>\n<stu:studentscreening0>\n<st:name0>Sam Davies</st:name0>\n<st:age>15</st:age>\n<st:hair>Black</st:hair>\n<st:eyes>Blue</st:eyes>\n<st:grade>10</st:grade>\n<st:teacher>Draco Malfoy</st:teacher>\n<st:dorm>Innovation Hall</st:dorm>\n<st:name1>Master Splinter</st:name1>\n</stu:studentscreening0>\n<stu:studentscreening1>\n<st:name0>Cassie Stone</st:name0>\n<st:age>14</st:age>\n<st:hair>Science</st:hair>\n<st:grade>9</st:grade>\n<st:teacher>Luna Lovegood</st:teacher>\n<st:name1>Kelly Clarkson</st:name1>\n</stu:studentscreening1>\n<stu:studentscreening2>\n<st:name0>Derek Brandon</st:name0>\n<st:age>17</st:age>\n<st:eyes>green</st:eyes>\n<st:teacher>Ron Weasley</st:teacher>\n<st:dorm>Hogtie Manor</st:dorm>\n<st:name1>Miley Cyrus</st:name1>\n</stu:studentscreening2>\n</stu:studentdata>\n</stu:studentbreakdown>\n</body></html>\n with open('x.xml', 'wb') as f: f.write(xSoup.prettify('utf-8'))"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18696224/"
] |
74,567,332
|
<p>I wanted to solve my Oprimization model in Python by Cplex so I installed Cplex in my system (Windows 11) and based on Cplex help insttall setup.py with this command:
python C:\Program Files\IBM\ILOG\CPLEX_Studio221\python\setup.py install</p>
<p>There are two examples in IBM "Docplex.cp" and "Docplex.mp". I run these exampleas using the vscode and jupyter. All exampleas of "Docplex.cp" run correctly but when I run examples of "Docplex.mp" I see Cplex runtime error.</p>
<p>This is one simple linear model that I have tried:</p>
<pre><code># Define the Model
from docplex.mp.model import Model
MWMS_model=Model(name="Linear Program")
# Variables
x=MWMS_model.continuous_var(name='x', lb=0)
y=MWMS_model.continuous_var(name='y', lb=0)
# Constraints
c1=MWMS_model.add_constraint(x+y>=8,ctname="c1")
c2=MWMS_model.add_constraint(2*x+y>=10,ctname="c2")
c3=MWMS_model.add_constraint(x+4*y>=11,ctname="c3")
# Objective Function
obj=5*x+4*y
MWMS_model.set_objective('min', obj)
MWMS_model.print_information()
# Solvig
MWMS_model.solve()
# Output
MWMS_model.print_solution()
</code></pre>
<p>This is the error: <em>"docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found."</em></p>
|
[
{
"answer_id": 74570024,
"author": "Charles Han",
"author_id": 11514907,
"author_profile": "https://Stackoverflow.com/users/11514907",
"pm_score": 0,
"selected": false,
"text": "import lxml.etree as ET\n\nXSL = '''\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\" />\n </xsl:copy>\n </xsl:template>\n <xsl:template match=\"stu:StudentScreening/st:name\">\n <xsl:element name=\"st:name{count(preceding-sibling::st:name)}\"><xsl:apply-templates select=\"@*|node()\" /></xsl:element>\n </xsl:template>\n</xsl:stylesheet>\n'''\n\ndom = ET.parse('students.xml')\ntransform = ET.XSLT(ET.fromstring(XSL))\nnewdom = transform(dom)\nprint(ET.tostring(newdom))\n\nnewdom.write(\"out.xml\", pretty_print=True)\n students.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<stu:StudentBreakdown xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n<stu:Studentdata>\n <stu:StudentScreening>\n <st:name>Sam Davies</st:name>\n <st:age>15</st:age>\n <st:hair>Black</st:hair>\n <st:eyes>Blue</st:eyes>\n <st:grade>10</st:grade>\n <st:teacher>Draco Malfoy</st:teacher>\n <st:dorm>Innovation Hall</st:dorm>\n <st:name>Master Splinter</st:name>\n <st:name>Peter Griffin</st:name>\n <st:name>Louis Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Cassie Stone</st:name>\n <st:age>14</st:age>\n <st:hair>Science</st:hair>\n <st:grade>9</st:grade>\n <st:teacher>Luna Lovegood</st:teacher>\n <st:name>Kelly Clarkson</st:name>\n <st:name>Stewie Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Derek Brandon</st:name>\n <st:age>17</st:age>\n <st:eyes>green</st:eyes>\n <st:teacher>Ron Weasley</st:teacher>\n <st:dorm>Hogtie Manor</st:dorm>\n <st:name>Miley Cyrus</st:name>\n </stu:StudentScreening>\n</stu:Studentdata>\n</stu:StudentBreakdown>\n out.xml"
},
{
"answer_id": 74570172,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 2,
"selected": true,
"text": "Tag.name = 'NEW_NAME' xmlStr xSoup = BeautifulSoup(xmlStr, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces\n\nenumTags = ['st:name', 'stu:studentscreening']\nfor d in [c for c in xSoup.descendants if c.name]:\n for name in enumTags:\n for i, t in enumerate(d.find_all(name, recursive=False)):\n t.name = f'{t.name}{i}'\n studentscreening recursive=False find print(xSoup) <?xml version=\"1.0\" encoding=\"UTF-8\"?><html><body><stu:studentbreakdown>\n<stu:studentdata>\n<stu:studentscreening0>\n<st:name0>Sam Davies</st:name0>\n<st:age>15</st:age>\n<st:hair>Black</st:hair>\n<st:eyes>Blue</st:eyes>\n<st:grade>10</st:grade>\n<st:teacher>Draco Malfoy</st:teacher>\n<st:dorm>Innovation Hall</st:dorm>\n<st:name1>Master Splinter</st:name1>\n</stu:studentscreening0>\n<stu:studentscreening1>\n<st:name0>Cassie Stone</st:name0>\n<st:age>14</st:age>\n<st:hair>Science</st:hair>\n<st:grade>9</st:grade>\n<st:teacher>Luna Lovegood</st:teacher>\n<st:name1>Kelly Clarkson</st:name1>\n</stu:studentscreening1>\n<stu:studentscreening2>\n<st:name0>Derek Brandon</st:name0>\n<st:age>17</st:age>\n<st:eyes>green</st:eyes>\n<st:teacher>Ron Weasley</st:teacher>\n<st:dorm>Hogtie Manor</st:dorm>\n<st:name1>Miley Cyrus</st:name1>\n</stu:studentscreening2>\n</stu:studentdata>\n</stu:studentbreakdown>\n</body></html>\n with open('x.xml', 'wb') as f: f.write(xSoup.prettify('utf-8'))"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11663096/"
] |
74,567,333
|
<p>I'm trying to join a new column to my current query that uses aggregate functions. I create this column with a new query that also uses an aggregate function from a different table but I'm not sure if a <code>JOIN</code> will work for me since I need to join it to its respective row.</p>
<p><strong>TABLE A</strong> (employees that are enrolled or were enrolled in a project)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>DEPARTMENT</th>
<th>ENROLLED</th>
<th>PROJECT</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>MARKETING</td>
<td>Yes</td>
<td>ARQ</td>
</tr>
<tr>
<td>2</td>
<td>MARKETING</td>
<td>Yes</td>
<td>TC</td>
</tr>
<tr>
<td>3</td>
<td>MARKETING</td>
<td>No</td>
<td>ARQ</td>
</tr>
<tr>
<td>4</td>
<td>MARKETING</td>
<td>No</td>
<td>TC</td>
</tr>
<tr>
<td>5</td>
<td>FINANCE</td>
<td>Yes</td>
<td>ARQ</td>
</tr>
<tr>
<td>6</td>
<td>FINANCE</td>
<td>Yes</td>
<td>TC</td>
</tr>
<tr>
<td>7</td>
<td>FINANCE</td>
<td>No</td>
<td>ARQ</td>
</tr>
<tr>
<td>8</td>
<td>FINANCE</td>
<td>Yes</td>
<td>TC</td>
</tr>
</tbody>
</table>
</div>
<p>This table has more departments and more projects, but I simplified.</p>
<p><strong>TABLE B</strong> (relation with departments and employees)</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>DEPARTMENT</th>
<th>TOTAL_EMPLOYEES</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>MARKETING</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>MARKETING</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>FINANCE</td>
<td>4</td>
</tr>
<tr>
<td>4</td>
<td>FINANCE</td>
<td>8</td>
</tr>
</tbody>
</table>
</div>
<p>In my first query I was asked to achieve the following result - using only table A:</p>
<pre><code> (employees enrolled) (employees not enrolled)
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>ARQ_E</th>
<th>TC_E</th>
<th>TOTAL_ENROLLED</th>
<th>ARQ_N</th>
<th>TC_N</th>
<th>TOTAL_NOT_ENROLLED</th>
<th>TOTAL</th>
</tr>
</thead>
<tbody>
<tr>
<td>MARKETING</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>FINANCE</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>Using the following query:</p>
<pre><code>SELECT tableA.department,
sum(case when enrolled = 'Yes' and tableA.project = 'ARQ' then 1 else 0 end) as ARQ_E,
sum(case when enrolled = 'Yes' and tableA.project = 'TC' then 1 else 0 end) as TC_E,
sum(case when enrolled = 'Yes' then 1 else 0 end) as TOTAL_ENROLLED,
sum(case when enrolled != 'Yes' and tableA.project = 'ARQ' then 1 else 0 end) as ARQ_N,
sum(case when enrolled != 'Yes' and tableA.project = 'TC' then 1 else 0 end) as TC_N,
sum(case when enrolled != 'Yes' then 1 else 0 end) as TOTAL_NOT_ENROLLED,
count (*) AS Total
FROM tableA
GROUP BY tableA.department;
</code></pre>
<p>My second query gets departments and their total employees from table B:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>TOTAL_EMPLOYEES</th>
</tr>
</thead>
<tbody>
<tr>
<td>MARKETING</td>
<td>5</td>
</tr>
<tr>
<td>FINANCE</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p>Using the following query:</p>
<pre><code>SELECT tableB.department,
sum(tableB.total_employees) AS TOTAL_EMPLOYEES
FROM tableB
GROUP BY tableB.department;
</code></pre>
<p>I need to add the column <code>TOTAL_EMPLOYEES</code> to my first query, next to <code>TOTAL</code> will be <code>TOTAL_EMPLOYEES</code>. But it has to be placed with its respective department row. I need this to compare this 2 columns and see how many employees were not assigned to any project.</p>
<p>This is my expected result.</p>
<pre><code> (employees enrolled) (employees not enrolled)
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>DEPARTMENT</th>
<th>ARQ_E</th>
<th>TC_E</th>
<th>TOTAL_ENROLLED</th>
<th>ARQ_N</th>
<th>TC_N</th>
<th>TOTAL_NOT_ENROLLED</th>
<th>TOTAL</th>
<th>T_EMPL</th>
</tr>
</thead>
<tbody>
<tr>
<td>MARKETING</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>FINANCE</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>4</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried to achieve this using the following query:</p>
<pre><code>SELECT tableA.department,
sum(case when enrolled = 'Yes' and tableA.project = 'ARQ' then 1 else 0 end) as ARQ_E,
sum(case when enrolled = 'Yes' and tableA.project = 'TC' then 1 else 0 end) as TC_E,
sum(case when enrolled = 'Yes' then 1 else 0 end) as TOTAL_ENROLLED,
sum(case when enrolled != 'Yes' and tableA.project = 'ARQ' then 1 else 0 end) as ARQ_N,
sum(case when enrolled != 'Yes' and tableA.project = 'TC' then 1 else 0 end) as TC_N,
sum(case when enrolled != 'Yes' then 1 else 0 end) as TOTAL_NOT_ENROLLED,
count (*) AS Total,
sum (tableB.total_employees) AS T_EMPL
FROM tableA
JOIN tableB
ON tableA.department = tableB.department
GROUP BY tableA.department;
</code></pre>
<p>But the numbers I get in my query are completely wrong since the JOINS repeat my rows and my SUMS duplicate.</p>
<p>I don't know if I really need to use a join or a subquery to place my <code>sum(tableB.department)</code> in its respective row.</p>
<p>I'm using PostgreSQL but since I'm using Standard 92 any SQL solution will help.</p>
|
[
{
"answer_id": 74570024,
"author": "Charles Han",
"author_id": 11514907,
"author_profile": "https://Stackoverflow.com/users/11514907",
"pm_score": 0,
"selected": false,
"text": "import lxml.etree as ET\n\nXSL = '''\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\" />\n </xsl:copy>\n </xsl:template>\n <xsl:template match=\"stu:StudentScreening/st:name\">\n <xsl:element name=\"st:name{count(preceding-sibling::st:name)}\"><xsl:apply-templates select=\"@*|node()\" /></xsl:element>\n </xsl:template>\n</xsl:stylesheet>\n'''\n\ndom = ET.parse('students.xml')\ntransform = ET.XSLT(ET.fromstring(XSL))\nnewdom = transform(dom)\nprint(ET.tostring(newdom))\n\nnewdom.write(\"out.xml\", pretty_print=True)\n students.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<stu:StudentBreakdown xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n<stu:Studentdata>\n <stu:StudentScreening>\n <st:name>Sam Davies</st:name>\n <st:age>15</st:age>\n <st:hair>Black</st:hair>\n <st:eyes>Blue</st:eyes>\n <st:grade>10</st:grade>\n <st:teacher>Draco Malfoy</st:teacher>\n <st:dorm>Innovation Hall</st:dorm>\n <st:name>Master Splinter</st:name>\n <st:name>Peter Griffin</st:name>\n <st:name>Louis Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Cassie Stone</st:name>\n <st:age>14</st:age>\n <st:hair>Science</st:hair>\n <st:grade>9</st:grade>\n <st:teacher>Luna Lovegood</st:teacher>\n <st:name>Kelly Clarkson</st:name>\n <st:name>Stewie Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Derek Brandon</st:name>\n <st:age>17</st:age>\n <st:eyes>green</st:eyes>\n <st:teacher>Ron Weasley</st:teacher>\n <st:dorm>Hogtie Manor</st:dorm>\n <st:name>Miley Cyrus</st:name>\n </stu:StudentScreening>\n</stu:Studentdata>\n</stu:StudentBreakdown>\n out.xml"
},
{
"answer_id": 74570172,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 2,
"selected": true,
"text": "Tag.name = 'NEW_NAME' xmlStr xSoup = BeautifulSoup(xmlStr, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces\n\nenumTags = ['st:name', 'stu:studentscreening']\nfor d in [c for c in xSoup.descendants if c.name]:\n for name in enumTags:\n for i, t in enumerate(d.find_all(name, recursive=False)):\n t.name = f'{t.name}{i}'\n studentscreening recursive=False find print(xSoup) <?xml version=\"1.0\" encoding=\"UTF-8\"?><html><body><stu:studentbreakdown>\n<stu:studentdata>\n<stu:studentscreening0>\n<st:name0>Sam Davies</st:name0>\n<st:age>15</st:age>\n<st:hair>Black</st:hair>\n<st:eyes>Blue</st:eyes>\n<st:grade>10</st:grade>\n<st:teacher>Draco Malfoy</st:teacher>\n<st:dorm>Innovation Hall</st:dorm>\n<st:name1>Master Splinter</st:name1>\n</stu:studentscreening0>\n<stu:studentscreening1>\n<st:name0>Cassie Stone</st:name0>\n<st:age>14</st:age>\n<st:hair>Science</st:hair>\n<st:grade>9</st:grade>\n<st:teacher>Luna Lovegood</st:teacher>\n<st:name1>Kelly Clarkson</st:name1>\n</stu:studentscreening1>\n<stu:studentscreening2>\n<st:name0>Derek Brandon</st:name0>\n<st:age>17</st:age>\n<st:eyes>green</st:eyes>\n<st:teacher>Ron Weasley</st:teacher>\n<st:dorm>Hogtie Manor</st:dorm>\n<st:name1>Miley Cyrus</st:name1>\n</stu:studentscreening2>\n</stu:studentdata>\n</stu:studentbreakdown>\n</body></html>\n with open('x.xml', 'wb') as f: f.write(xSoup.prettify('utf-8'))"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20594481/"
] |
74,567,334
|
<p>I have two columns. The first one is longer and has multiple values such as:</p>
<pre><code>0 'A'
1 'B'
2 'B'
3 'C'
4 'A'
5 'A'
</code></pre>
<p>All the values in the first column are listed in the second column:</p>
<pre><code>0 'A'
1 'B'
2 'C'
</code></pre>
<p>The result I want is to have a list/series/column whatever of indecies of the values from the first column in the second column, as such:</p>
<pre><code>0 'A' 0
1 'B' 1
2 'B' 1
3 'C' 2
4 'A' 0
5 'A' 0
</code></pre>
<p>Edit: in the actual problem that I have the number of values is very big so listing them by hand is not an option</p>
|
[
{
"answer_id": 74570024,
"author": "Charles Han",
"author_id": 11514907,
"author_profile": "https://Stackoverflow.com/users/11514907",
"pm_score": 0,
"selected": false,
"text": "import lxml.etree as ET\n\nXSL = '''\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\" />\n </xsl:copy>\n </xsl:template>\n <xsl:template match=\"stu:StudentScreening/st:name\">\n <xsl:element name=\"st:name{count(preceding-sibling::st:name)}\"><xsl:apply-templates select=\"@*|node()\" /></xsl:element>\n </xsl:template>\n</xsl:stylesheet>\n'''\n\ndom = ET.parse('students.xml')\ntransform = ET.XSLT(ET.fromstring(XSL))\nnewdom = transform(dom)\nprint(ET.tostring(newdom))\n\nnewdom.write(\"out.xml\", pretty_print=True)\n students.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<stu:StudentBreakdown xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n<stu:Studentdata>\n <stu:StudentScreening>\n <st:name>Sam Davies</st:name>\n <st:age>15</st:age>\n <st:hair>Black</st:hair>\n <st:eyes>Blue</st:eyes>\n <st:grade>10</st:grade>\n <st:teacher>Draco Malfoy</st:teacher>\n <st:dorm>Innovation Hall</st:dorm>\n <st:name>Master Splinter</st:name>\n <st:name>Peter Griffin</st:name>\n <st:name>Louis Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Cassie Stone</st:name>\n <st:age>14</st:age>\n <st:hair>Science</st:hair>\n <st:grade>9</st:grade>\n <st:teacher>Luna Lovegood</st:teacher>\n <st:name>Kelly Clarkson</st:name>\n <st:name>Stewie Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Derek Brandon</st:name>\n <st:age>17</st:age>\n <st:eyes>green</st:eyes>\n <st:teacher>Ron Weasley</st:teacher>\n <st:dorm>Hogtie Manor</st:dorm>\n <st:name>Miley Cyrus</st:name>\n </stu:StudentScreening>\n</stu:Studentdata>\n</stu:StudentBreakdown>\n out.xml"
},
{
"answer_id": 74570172,
"author": "Driftr95",
"author_id": 6146136,
"author_profile": "https://Stackoverflow.com/users/6146136",
"pm_score": 2,
"selected": true,
"text": "Tag.name = 'NEW_NAME' xmlStr xSoup = BeautifulSoup(xmlStr, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces\n\nenumTags = ['st:name', 'stu:studentscreening']\nfor d in [c for c in xSoup.descendants if c.name]:\n for name in enumTags:\n for i, t in enumerate(d.find_all(name, recursive=False)):\n t.name = f'{t.name}{i}'\n studentscreening recursive=False find print(xSoup) <?xml version=\"1.0\" encoding=\"UTF-8\"?><html><body><stu:studentbreakdown>\n<stu:studentdata>\n<stu:studentscreening0>\n<st:name0>Sam Davies</st:name0>\n<st:age>15</st:age>\n<st:hair>Black</st:hair>\n<st:eyes>Blue</st:eyes>\n<st:grade>10</st:grade>\n<st:teacher>Draco Malfoy</st:teacher>\n<st:dorm>Innovation Hall</st:dorm>\n<st:name1>Master Splinter</st:name1>\n</stu:studentscreening0>\n<stu:studentscreening1>\n<st:name0>Cassie Stone</st:name0>\n<st:age>14</st:age>\n<st:hair>Science</st:hair>\n<st:grade>9</st:grade>\n<st:teacher>Luna Lovegood</st:teacher>\n<st:name1>Kelly Clarkson</st:name1>\n</stu:studentscreening1>\n<stu:studentscreening2>\n<st:name0>Derek Brandon</st:name0>\n<st:age>17</st:age>\n<st:eyes>green</st:eyes>\n<st:teacher>Ron Weasley</st:teacher>\n<st:dorm>Hogtie Manor</st:dorm>\n<st:name1>Miley Cyrus</st:name1>\n</stu:studentscreening2>\n</stu:studentdata>\n</stu:studentbreakdown>\n</body></html>\n with open('x.xml', 'wb') as f: f.write(xSoup.prettify('utf-8'))"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10843767/"
] |
74,567,340
|
<p>Datepicker has <a href="https://jqueryui.com/datepicker/#alt-field" rel="nofollow noreferrer">this function</a> which allows you to ship the date into an alternative input with an alternate date format. In my program, I'm hiding the datepicker input and trigger open the calendar with a button. How do I get the date from this alternate input?</p>
<p>My code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*
open calendar
*/
$(document).on('click','.openDatePicker',function(){
$('#popupDatepicker').datepicker({
changeMonth: true,
changeYear: true,
altField: "#alternateDateField",
altFormat: "DD, d MM, yy"
});
$('#popupDatepicker').show().focus().hide();
})
/*
get date from alternate field
*/
$(document).on('change','#alternateDateField',function(){
var fulldate = $('#alternateDateField').val();
console.log(fulldate)
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<button class="openDatePicker">Calendar</button>
<input type="text" style="display: none;" id="popupDatepicker">
<input type="hidden" id="alternateDateField" size="30"></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74567481,
"author": "anhnt",
"author_id": 14292069,
"author_profile": "https://Stackoverflow.com/users/14292069",
"pm_score": 0,
"selected": false,
"text": "altField onSelect $(\"#popupDatepicker\").datepicker({\n onSelect: function(dateText) {\n console.log(\"Selected date: \" + dateText + \"; input's current value: \" + this.value);\n }\n});\n"
},
{
"answer_id": 74568777,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 2,
"selected": true,
"text": "change onSelect change setInterval /*\n\nopen calendar\n\n*/\n$(document).on('click', '.openDatePicker', function() {\n\n $('#popupDatepicker').datepicker({\n changeMonth: true,\n changeYear: true,\n altField: \"#alternateDateField\",\n altFormat: \"DD, d MM, yy\",\n onSelect: function(datestring, dp) {\n $('#alternateDateField').trigger('change');\n }\n });\n $('#popupDatepicker').show().focus().hide();\n})\n\n/*\n\nget date from alternate field\n\n*/\n$(document).on('change', '#alternateDateField', function() {\n\n var fulldate = $('#alternateDateField').val();\n console.log(fulldate)\n\n\n}) <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css\">\n<link rel=\"stylesheet\" href=\"/resources/demos/style.css\">\n<script src=\"https://code.jquery.com/jquery-3.6.0.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.13.2/jquery-ui.js\"></script>\n\n<button class=\"openDatePicker\">Calendar</button>\n<input type=\"text\" style=\"display: none;\" id=\"popupDatepicker\">\n<input type=\"hidden\" id=\"alternateDateField\" size=\"30\"> onSelect setInterval()"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12687061/"
] |
74,567,354
|
<p>So I have the following code:</p>
<pre><code>private var googleButton: some View {
Button {
// Empty
} label: {
HStack(alignment: .firstTextBaseline) {
Image(systemName: "globe")
Text("Continue with Google")
.font(.headline)
.frame(height: 35)
}
.foregroundColor(.black)
.frame(maxWidth: .infinity)
}
.tint(.white)
.buttonStyle(.borderedProminent)
.controlSize(.regular)
}
</code></pre>
<p>Which produces this look:</p>
<p><a href="https://i.stack.imgur.com/eVz5W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eVz5W.png" alt="enter image description here" /></a></p>
<p>How do I properly apply a border with the proper corner radius?</p>
<p>I have tried applying <code>.border</code>, etc.. to the button but it's all causing errors.</p>
|
[
{
"answer_id": 74568088,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 1,
"selected": false,
"text": " Label(\"Continue with Google\", systemImage: \"heart\")\n .padding()\n .background {\n Color.gray\n }.foregroundColor(.white)\n .clipShape(RoundedRectangle(cornerRadius: 10.0, style: .continuous))\n"
},
{
"answer_id": 74569773,
"author": "George Rosescu",
"author_id": 16059484,
"author_profile": "https://Stackoverflow.com/users/16059484",
"pm_score": 0,
"selected": false,
"text": "Button {\n print(\"example\")\n } label: {\n HStack(alignment: .firstTextBaseline) {\n Image(systemName: \"globe\")\n Text(\"Continue with Google\")\n .font(.headline)\n .frame(height: 35)\n }\n .foregroundColor(.black)\n .frame(maxWidth: .infinity)\n }\n .background(.white)\n .controlSize(.regular)\n .cornerRadius(5) // Have your custom value here\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19566858/"
] |
74,567,426
|
<pre class="lang-none prettyprint-override"><code>docker build -t max-audio-embedding-generator .
[+] Building 1.9s (6/10)
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 32B 0.0s
=> [internal] load .dockerignore 0.1s
=> => transferring context: 35B 0.0s
=> [internal] load metadata for quay.io/codait/max-base:v1.4.0 1.0s
=> CANCELED [internal] load build context 0.7s
=> => transferring context: 6.04MB 0.6s
=> CACHED [1/6] FROM quay.io/codait/max-base:v1.4.0@sha256:1f09c52c5461b4a13b3a2e6166acac5165596a6e3f65b5c168a880cd4ac6bebe 0.0s
=> ERROR [2/6] RUN wget -nv --show-progress --progress=bar:force:noscroll https://max-cdn.cdn.appdomain.cloud/max-audio-embedding-generator/1.0.0/assets.tar.gz --output-document=assets/a 0.7s
------
> [2/6] RUN wget -nv --show-progress --progress=bar:force:noscroll https://max-cdn.cdn.appdomain.cloud/max-audio-embedding-generator/1.0.0/assets.tar.gz --output-document=assets/assets.tar.gz && tar -x -C assets/ -f assets/assets.tar.gz -v && rm assets/assets.tar.gz:
#5 0.554 wget: unable to resolve host address ‘max-cdn.cdn.appdomain.cloud’
------
executor failed running [/bin/sh -c wget -nv --show-progress --progress=bar:force:noscroll ${model_bucket}/${model_file} --output-document=assets/${model_file} && tar -x -C assets/ -f assets/${model_file} -v && rm assets/${model_file}]: exit code: 4`
</code></pre>
<p>trying to build an image locally from cloned repo
and getting this error.</p>
|
[
{
"answer_id": 74567731,
"author": "Artem Kotelevych",
"author_id": 20595254,
"author_profile": "https://Stackoverflow.com/users/20595254",
"pm_score": 0,
"selected": false,
"text": "hosts"
},
{
"answer_id": 74567737,
"author": "Dash",
"author_id": 11542834,
"author_profile": "https://Stackoverflow.com/users/11542834",
"pm_score": 1,
"selected": false,
"text": "wget: unable to resolve host address ‘max-cdn.cdn.appdomain.cloud’ model_buckets https://codait-cos-max.s3.us.cloud-object-storage.appdomain.cloud/max-audio-embedding-generator/1.0.0"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19225532/"
] |
74,567,437
|
<p>I have been stuck trying to figure out this one part of my introduction to coding assignment. I know what it is asking but have no idea what the code is supposed to look like.</p>
<p>Define a function named Rotate that takes a string as input and returns a copy of that string in which all characters are rotated one position to the left. This means that the second character should be shifted from index 1 to index 0, the third character should be shifted from index 2 to index 1, and so on. The first character should be shifted so that it appears at the end of the string. For example, the function call Rotate('abcde') should return the string 'bcdea'. Insert this function definition into your string.js library file.</p>
<p>I know this code is probably dead wrong but the lecture slides my professor gave did not help at all.</p>
<pre><code>function Rotate()
{
var firstLetter; restString; end;
firstLetter = str.charAt(0);
restString = str.substring(1,str.length);
end = restString.toLowerCase() + firstLetter.toLowerCase();
return end;
}
</code></pre>
|
[
{
"answer_id": 74567501,
"author": "Đạt Huỳnh",
"author_id": 20595083,
"author_profile": "https://Stackoverflow.com/users/20595083",
"pm_score": 2,
"selected": false,
"text": "function Rotate(str){\n return str.substring(1)+str[0]\n}\n"
},
{
"answer_id": 74567509,
"author": "Alberto Chiesa",
"author_id": 1395758,
"author_profile": "https://Stackoverflow.com/users/1395758",
"pm_score": 1,
"selected": false,
"text": "function Rotate(str) {\n var initial, rest;\n initial = str.charAt(0);\n // if you don't pass the second argument, you get everything up to the end of the string\n rest = str.substring(1);\n return rest + initial;\n}\n\n// please note you don't need separate var statements:\nfunction Rotate(str) {\n var initial = str.charAt(0);\n var rest = str.substring(1);\n return rest + initial;\n}\n\n// or:\nfunction Rotate(str) {\n // substring from the second char + substring of the first char\n return str.substring(1) + str.substring(0, 1);\n}\n\n// you could even extend Rotate to support multiple chars:\nfunction Rotate(str, count) {\n if (count === undefined) count = 1;\n return str.substring(count) + str.substring(0, count);\n}\n\n"
}
] |
2022/11/25
|
[
"https://Stackoverflow.com/questions/74567437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20006845/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.