qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,298,426 | <p>I am having a array called valueArray. I need to remove values which are ending with "/". Like I need to remove my-app/ , my-app/public/, my-app/src/.</p>
<pre><code>const valueArray = [
'my-app/',
'my-app/.env',
'my-app/.gitignore',
'my-app/package-lock.json',
'my-app/package.json',
'my-app/public/',
'my-app/public/manifest.json',
'my-app/public/robots.txt',
'my-app/README.md',
'my-app/src/',
'my-app/src/App.css',
'my-app/src/App.js',
'my-app/src/App.test.js',
'my-app/src/index.css',
'my-app/src/index.js',
'my-app/src/reportWebVitals.js',
'my-app/src/setupTests.js'
]
for (let index = 0; index < valueArray.length; index++) {
if(valueArray[index].charAt(valueArray[index].length-1) === "/"){
valueArray.splice(valueArray[index],1);
}
}
console.log(valueArray);
</code></pre>
<p>I tried using splice and followed the syntax but it is not working. I am missing something. Can someone help with this?</p>
| [
{
"answer_id": 74298437,
"author": "vighnesh153",
"author_id": 8822610,
"author_profile": "https://Stackoverflow.com/users/8822610",
"pm_score": 2,
"selected": true,
"text": "splice"
},
{
"answer_id": 74298480,
"author": "Phat Vo",
"author_id": 12331258,
"author_profile": "https://Stackoverflow.com/users/12331258",
"pm_score": 0,
"selected": false,
"text": " valueArray.splice(index, 1);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19672461/"
] |
74,298,446 | <p>I'm trying to combine elements within a PCollection<KV<Long,Double>></p>
<pre><code>public class StreamPipelineBuilder {
public void execute() {
final List<UserTxn> txn = Utils.getUserTxnList().subList(0, 10);
// create Pipeline
final Pipeline pipeline = Pipeline.create();
TestStream.Builder<KV<Long, UserTxn>>
streamBuilder = TestStream.create(UserTxnKVCoder.of());
// add all lines with timestamps to the TestStream
final List<TimestampedValue<KV<Long, UserTxn>>> timestamped =
txn.stream().map(i -> {
final KV<Long, UserTxn> kv = KV.of(i.getId(), i);
final LocalDateTime time = i.getTime();
final long millis = time.toInstant(ZoneOffset.UTC).toEpochMilli();
final Instant instant = new Instant(millis);
return TimestampedValue.of(kv, instant);
}).collect(Collectors.toList());
for (TimestampedValue<KV<Long, UserTxn>> value : timestamped) {
streamBuilder = streamBuilder.addElements(value);
}
// create the unbounded PCollection from TestStream
PCollection<KV<Long, UserTxn>> input = pipeline.apply(streamBuilder.advanceWatermarkToInfinity());
PCollection<KV<Long, UserTxn>> windowed =
input.apply(Window.<KV<Long, UserTxn>>into(FixedWindows.of(Duration.standardSeconds(5)))
.discardingFiredPanes()
.triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(2)))
.withAllowedLateness(Duration.ZERO));
PCollection<KV<Long, Double>> added = windowed.apply("aggregate", new PTransform<>() {
@Override
public PCollection<KV<Long, Double>> expand(PCollection<KV<Long, UserTxn>> input) {
return input.apply(
MapElements.into(
TypeDescriptors.kvs(TypeDescriptors.longs(), TypeDescriptors.doubles())
).via((record) -> KV.of(record.getKey(), record.getValue().getAmount()))
).apply(Combine.globally((SerializableFunction<Iterable<KV<Long, Double>>, KV<Long, Double>>) input1 -> {
AtomicLong keys = new AtomicLong();
AtomicDouble amounts = new AtomicDouble();
input1.forEach(e -> {
keys.addAndGet(e.getKey());
amounts.addAndGet(e.getValue());
});
return KV.of(keys.get(), amounts.get());
}).withoutDefaults());
}
});
added.apply(PrintPCollection.with());
pipeline.run().waitUntilFinish();
}
}
</code></pre>
<p>each Key is different and I want to add them up like sum(key),sum(value)
but when I run my code it does not work I get this</p>
<pre><code>[INFO] 2022-11-03 00:12:21.010 PrintPCollection - KV{1, 821.21}
[INFO] 2022-11-03 00:12:21.014 PrintPCollection - KV{6, 973.31}
[INFO] 2022-11-03 00:12:21.014 PrintPCollection - KV{8, 980.26}
[INFO] 2022-11-03 00:12:21.014 PrintPCollection - KV{4, 37.53}
[INFO] 2022-11-03 00:12:21.014 PrintPCollection - KV{2, 541.95}
[INFO] 2022-11-03 00:12:21.014 PrintPCollection - KV{7, 705.49}
[INFO] 2022-11-03 00:12:21.014 PrintPCollection - KV{3, 384.09}
[INFO] 2022-11-03 00:12:21.015 PrintPCollection - KV{9, 106.96}
[INFO] 2022-11-03 00:12:21.015 PrintPCollection - KV{5, 207.3}
[INFO] 2022-11-03 00:12:21.015 PrintPCollection - KV{10, 675.48}
</code></pre>
<p>What I was expecting to get were 5 records since the window fires after every 2 elements and the collection starts with 10 but it is not working, what I'm doing wrong?</p>
<p>Thank you!</p>
| [
{
"answer_id": 74304487,
"author": "Jeff Klukas",
"author_id": 1260237,
"author_profile": "https://Stackoverflow.com/users/1260237",
"pm_score": 1,
"selected": false,
"text": "withLateFirings"
},
{
"answer_id": 74325066,
"author": "Frederick Álvarez",
"author_id": 4170988,
"author_profile": "https://Stackoverflow.com/users/4170988",
"pm_score": 1,
"selected": true,
"text": "package dev.donhk.stream;\n\nimport com.google.common.util.concurrent.AtomicDouble;\nimport dev.donhk.pojos.UserTxn;\nimport dev.donhk.transform.PrintPCollection;\nimport dev.donhk.utilities.Utils;\nimport org.apache.beam.sdk.Pipeline;\nimport org.apache.beam.sdk.testing.TestStream;\nimport org.apache.beam.sdk.transforms.*;\nimport org.apache.beam.sdk.transforms.windowing.*;\nimport org.apache.beam.sdk.values.*;\nimport org.apache.logging.log4j.LogManager;\nimport org.apache.logging.log4j.Logger;\nimport org.joda.time.Instant;\n\nimport java.time.LocalDateTime;\nimport java.time.ZoneOffset;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicLong;\nimport java.util.stream.Collectors;\nimport java.util.stream.StreamSupport;\n\npublic class StreamPipelineBuilder {\n private static final Logger LOG = LogManager.getLogger(StreamPipelineBuilder.class);\n\n public void execute() {\n final List<UserTxn> txn = Utils.getUserTxnList().subList(0, 10);\n // create Pipeline\n final Pipeline pipeline = Pipeline.create();\n TestStream.Builder<KV<Long, UserTxn>>\n streamBuilder = TestStream.create(UserTxnKVCoder.of());\n // add all lines with timestamps to the TestStream\n final List<TimestampedValue<KV<Long, UserTxn>>> timestamped =\n txn.stream().map(i -> {\n final KV<Long, UserTxn> kv = KV.of(i.getId(), i);\n final LocalDateTime time = i.getTime();\n final long millis = time.toInstant(ZoneOffset.UTC).toEpochMilli();\n final Instant instant = new Instant(millis);\n return TimestampedValue.of(kv, instant);\n }).collect(Collectors.toList());\n\n for (TimestampedValue<KV<Long, UserTxn>> value : timestamped) {\n streamBuilder = streamBuilder.addElements(value);\n }\n\n // create the unbounded PCollection from TestStream\n PCollection<KV<Long, UserTxn>> input = pipeline.apply(streamBuilder.advanceWatermarkToInfinity());\n PCollection<KV<Long, UserTxn>> windowed =\n input.apply(Window.<KV<Long, UserTxn>>into(new GlobalWindows())\n .triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(5)))\n .discardingFiredPanes()\n .withOnTimeBehavior(Window.OnTimeBehavior.FIRE_IF_NON_EMPTY));\n\n PCollection<KV<Long, Double>> added = windowed.apply(\"aggregate\", new PTransform<>() {\n @Override\n public PCollection<KV<Long, Double>> expand(PCollection<KV<Long, UserTxn>> input) {\n return input.apply(\n MapElements.into(\n TypeDescriptors.kvs(TypeDescriptors.longs(), TypeDescriptors.doubles())\n ).via((record) -> KV.of(record.getKey(), record.getValue().getAmount()))\n ).apply(Combine.globally((SerializableFunction<Iterable<KV<Long, Double>>, KV<Long, Double>>) input1 -> {\n AtomicLong myLong = new AtomicLong();\n AtomicDouble myDouble = new AtomicDouble();\n StreamSupport\n .stream(input1.spliterator(), false)\n .forEach(e -> {\n LOG.info(e.getKey());\n myLong.addAndGet(e.getKey());\n myDouble.addAndGet(e.getValue());\n });\n LOG.info(\"new window\");\n return KV.of(myLong.get(), myDouble.get());\n }));\n }\n });\n\n added.apply(PrintPCollection.with());\n\n pipeline.run().waitUntilFinish();\n }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4170988/"
] |
74,298,497 | <p>I have array A and I am trying to concat it to array B while array B keeps the same amount of indices.</p>
<p>for example:</p>
<pre><code>const array_A = [1, 2, 3, 4];
const array_B = [0, 0, 0, 0, 0, 0, 0];
</code></pre>
<p>the result should look like this</p>
<pre><code>const result = [1, 2, 3, 4, 0, 0, 0];
</code></pre>
<p>I tried this approach</p>
<pre><code>const result = array_A.concat(array_B);
console.log(result);
</code></pre>
<p>but then I got array of 11 indices which I only want array of 7 indices.</p>
<pre><code>[1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0];
</code></pre>
| [
{
"answer_id": 74298547,
"author": "adiga",
"author_id": 3082296,
"author_profile": "https://Stackoverflow.com/users/3082296",
"pm_score": 2,
"selected": true,
"text": "map"
},
{
"answer_id": 74298563,
"author": "Sujit Libi",
"author_id": 4935491,
"author_profile": "https://Stackoverflow.com/users/4935491",
"pm_score": 1,
"selected": false,
"text": "const array_A = [1, 2, 3, 4];\nconst array_B = [0, 0, 0, 0, 0, 0, 0];\n\nfor (let i = array_A.length - 1; i >= 0; i--) {\n array_B.pop()\n array_B.unshift(array_A[i])\n}\n\nconsole.log(array_B)"
},
{
"answer_id": 74298680,
"author": "PawanSinghla",
"author_id": 10387214,
"author_profile": "https://Stackoverflow.com/users/10387214",
"pm_score": 0,
"selected": false,
"text": "const A = [1, 2, 3, 4];\nconst B = [0, 0, 0, 0, 0, 0, 0];\n\nA.forEach((val, i) => {\n B[i] = val;\n})\n\nconsole.log(B) // [ 1, 2, 3, 4, 0, 0, 0 ]"
},
{
"answer_id": 74305218,
"author": "Scott Sauyet",
"author_id": 1243641,
"author_profile": "https://Stackoverflow.com/users/1243641",
"pm_score": 0,
"selected": false,
"text": "Object.assign"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18836219/"
] |
74,298,516 | <p>I have this line of code ("model.predict(image=img)") that I want to stop executing if it is taking longer than 5 minutes. Is there an easy way or library in python I can use to achieve this?</p>
<pre><code>for filename in os.listdir():
if filename.endswith(".jpg") or filename.endswith(".png"):
print(filename)
img = DataURI.from_file(filename)
#This should run for no longer than 5 minutes
output = model.predict(image=img)
#if this took more than 5 minutes to run, use "continue"
#continue
</code></pre>
| [
{
"answer_id": 74298804,
"author": "user19723070",
"author_id": 19723070,
"author_profile": "https://Stackoverflow.com/users/19723070",
"pm_score": 0,
"selected": false,
"text": "for filename in os.listdir():\nif filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n print(filename)\n\n for x in range(0, 300) #Converting Minutes to seconds so 300\n try:\n img = DataURI.from_file(filename)\n output = model.predict(image=img)\n break\n \n except:\n time.sleep(1)\n \n\n #if this took more than 5 minutes to run, use \"continue\"\n #continue\n"
},
{
"answer_id": 74309262,
"author": "Veysel Olgun",
"author_id": 10556711,
"author_profile": "https://Stackoverflow.com/users/10556711",
"pm_score": 0,
"selected": false,
"text": "model.predict()"
},
{
"answer_id": 74314957,
"author": "danangjoyoo",
"author_id": 17292547,
"author_profile": "https://Stackoverflow.com/users/17292547",
"pm_score": 1,
"selected": false,
"text": "python-worker"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12894091/"
] |
74,298,518 | <p>Im running this code and getting below error</p>
<pre><code>df = pd.read_sql(f"select id, jsonresponse from ResponseDetails;", engine)
all_df = df[['id', 'jsonresponse']].values.tolist()
for x in all_df:
jsn1 = x[1]
print(jsn1)
print(json.loads(jsn1))
Output:
>
{\"request_id\":\"2312\",\"task_id\":\"423432\",\"group_id\":\"43r23\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}
---------------------------------------------------------------------------
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code></pre>
<p>To produce above error i have stored above json string into variable. But this time it works perfectly.</p>
<pre><code>jsn2 = '{\"request_id\":\"2312\",\"task_id\":\"423432\",\"group_id\":\"43r23\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}'
print(json.loads(jsn2))
Output:
>
{'request_id': '2312',
'task_id': '423432',
'group_id': '43r23',
'success': True,
'response_code': '100',
'response_message': 'Valid Authentication'}
</code></pre>
<p>How come <code>jsn2</code> is different from <code>jsn1</code>. And how can I <code>json.load()</code> <code>jsn1</code> variable.</p>
<p>EDIT:
tried below code still</p>
<pre><code>for x in all_df:
jsn1 = x[1]
dmp = json.dumps(jsn1)
print(dmp)
print(json.loads(dmp))
</code></pre>
<p>Output:</p>
<pre><code>"{\\\"request_id\\\":\\\"7a4974bb-8b43-4ff0-bc7c-8a0923aef03d\\\",\\\"task_id\\\":\\\"ce57782d-a56e-4be7-a803-18dcd71588a2\\\",\\\"group_id\\\":\\\"268eba73-fe5a-4cd2-a80e-11fc2d06f127\\\",\\\"success\\\":true,\\\"response_code\\\":\\\"100\\\",\\\"response_message\\\":\\\"Valid Authentication\\\"}"
{\"request_id\":\"7a4974bb-8b43-4ff0-bc7c-8a0923aef03d\",\"task_id\":\"ce57782d-a56e-4be7-a803-18dcd71588a2\",\"group_id\":\"268eba73-fe5a-4cd2-a80e-11fc2d06f127\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}
</code></pre>
| [
{
"answer_id": 74298550,
"author": "Ankit Tiwari",
"author_id": 14457833,
"author_profile": "https://Stackoverflow.com/users/14457833",
"pm_score": 3,
"selected": true,
"text": "json.dumps()"
},
{
"answer_id": 74298649,
"author": "Mogli141",
"author_id": 15395276,
"author_profile": "https://Stackoverflow.com/users/15395276",
"pm_score": 1,
"selected": false,
"text": "for x in all_df:\n jsn1 = x[1].replace('\\\\\"','\"')\n print(json.loads(jsn1))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15395276/"
] |
74,298,533 | <p>I need to use an iFrame within another page, and I want to make it fit the entire web page that it's embedding without the need to scroll. So, how can I set the iFrame height to the height of the web page?</p>
<p>I tried just setting the iFrame height to 100%, but for obvious reasons, that did not work.</p>
<p>I'm sure the answer is simple, I'm better at the back end.</p>
| [
{
"answer_id": 74298550,
"author": "Ankit Tiwari",
"author_id": 14457833,
"author_profile": "https://Stackoverflow.com/users/14457833",
"pm_score": 3,
"selected": true,
"text": "json.dumps()"
},
{
"answer_id": 74298649,
"author": "Mogli141",
"author_id": 15395276,
"author_profile": "https://Stackoverflow.com/users/15395276",
"pm_score": 1,
"selected": false,
"text": "for x in all_df:\n jsn1 = x[1].replace('\\\\\"','\"')\n print(json.loads(jsn1))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19891669/"
] |
74,298,544 | <p>Converting this to a while loop is turning out to be more trouble than initially thought.
Any tips or tricks on how to solve this would be appreciated</p>
<pre><code>sum = 0
for i in range (10,0,-1):
sum = sum +1
print(i,sum)
</code></pre>
<p>this is as close as i can get -</p>
<pre><code>i=1
while i in range(10,0,-1):
print(i)
print(i, end=' ')
i=i+1
</code></pre>
<p>the hard part seems to be the range numbers
this is a specific questions ( i know a for loop is a better solution than a while loop)</p>
| [
{
"answer_id": 74299929,
"author": "rilshok",
"author_id": 19452763,
"author_profile": "https://Stackoverflow.com/users/19452763",
"pm_score": 0,
"selected": false,
"text": "s = i = 10\nwhile i > 0:\n print(i, s-i+1)\n i=i-1\n"
},
{
"answer_id": 74303600,
"author": "blueberry",
"author_id": 20210591,
"author_profile": "https://Stackoverflow.com/users/20210591",
"pm_score": 2,
"selected": true,
"text": "i=1\nwhile i in range(10,0,-1):\nprint(len(list(range(10,0,-1)))-i+1,i)\ni=i+1\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19638154/"
] |
74,298,603 | <p>I have a <code>AuthProvider</code> at in my application that will automatically redirect to the login page if the user is not logged in</p>
<pre class="lang-js prettyprint-override"><code>interface IAuthContext {
token: string | undefined;
}
export const AuthContext = createContext<IAuthContext>({ token: undefined });
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [token, setToken] = useState<string | undefined>();
const navigate = useNavigate();
useEffect(() => {
const authToken = localStorage.getItem('authToken');
if (!authToken) {
navigate('/login');
}
setToken(token);
}, []);
return <AuthContext.Provider value={{ token }}>{children}</AuthContext.Provider>;
};
</code></pre>
<p><code>MyComp</code> is a child of <code>AuthProvider</code>. Therefore, <code>token</code> should always be defined, because if it doesn't exist, then <code>AuthProvider</code> will redirect to the login page and <code>MyComp</code> will never be rendered.</p>
<pre class="lang-js prettyprint-override"><code>export const MyComp = () => {
const { token } = useContext(AuthContext);
if (!token) {
throw new Error('missing token');
}
const data = useMemo(() => fetchData(token), token);
return <div>{data}</div>;
};
</code></pre>
<p>It's annoying having assert that token is not undefined every time I need to use it. I have to type <code>token</code> as <code>string | undefined</code>, because I need to pass a default value to <code>createContext</code></p>
<p>Is there a way to better type this so I don't need to assert that the token is defined and to not have to give a default value to <code>createContext</code>?</p>
| [
{
"answer_id": 74299929,
"author": "rilshok",
"author_id": 19452763,
"author_profile": "https://Stackoverflow.com/users/19452763",
"pm_score": 0,
"selected": false,
"text": "s = i = 10\nwhile i > 0:\n print(i, s-i+1)\n i=i-1\n"
},
{
"answer_id": 74303600,
"author": "blueberry",
"author_id": 20210591,
"author_profile": "https://Stackoverflow.com/users/20210591",
"pm_score": 2,
"selected": true,
"text": "i=1\nwhile i in range(10,0,-1):\nprint(len(list(range(10,0,-1)))-i+1,i)\ni=i+1\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6592293/"
] |
74,298,604 | <p>I'm new beginner in react-native and JavaScript here, i am using a if-else condition.</p>
<p>i want to check the first the condition is correct if it's correct then it will works in a different different function.
Here is my codes:</p>
<pre><code>const ab = true;
let x;
if (ab === false){
// i want here to stop passing value of x;
//write a code so that x value can't be passed to console.log(x).
}
else if (ab=== true){
x= [1,2,3]
}
console.log(x);
</code></pre>
<p>only when ab equals true, x value able to use.
anyone can help me to write a codes for if statement where it will stop to passing values when the condition is correct.</p>
<p>Thanks for your trying in advance!</p>
| [
{
"answer_id": 74299929,
"author": "rilshok",
"author_id": 19452763,
"author_profile": "https://Stackoverflow.com/users/19452763",
"pm_score": 0,
"selected": false,
"text": "s = i = 10\nwhile i > 0:\n print(i, s-i+1)\n i=i-1\n"
},
{
"answer_id": 74303600,
"author": "blueberry",
"author_id": 20210591,
"author_profile": "https://Stackoverflow.com/users/20210591",
"pm_score": 2,
"selected": true,
"text": "i=1\nwhile i in range(10,0,-1):\nprint(len(list(range(10,0,-1)))-i+1,i)\ni=i+1\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19983659/"
] |
74,298,617 | <p>I am using Google map in my flutter application and added below line in pubspec.yaml file :</p>
<pre><code>custom_marker: ^1.0.0
</code></pre>
<p>performed pub get, but it gives me below error :</p>
<blockquote>
<p>Because flutter_html >=2.0.0-nullsafety.1 <3.0.0-alpha.1 depends on flutter_svg >=0.22.0 <1.0.0 and every version of custom_marker depends on flutter_svg ^1.0.1, flutter_html >=2.0.0-nullsafety.1 <3.0.0-alpha.1 is incompatible with custom_marker.
So, because mahotsav depends on both custom_marker ^1.0.0 and flutter_html ^2.2.0, version solving failed.
pub get failed (1; So, because mahotsav depends on both custom_marker ^1.0.0 and flutter_html ^2.2.0, version solving failed.)</p>
</blockquote>
<p>What might be the issue?</p>
| [
{
"answer_id": 74299510,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 2,
"selected": false,
"text": "flutter_html"
},
{
"answer_id": 74299578,
"author": "TANIMUL ISLAM",
"author_id": 18262004,
"author_profile": "https://Stackoverflow.com/users/18262004",
"pm_score": 3,
"selected": true,
"text": "dependencies:\n flutter_html: ^3.0.0-alpha.3\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4827817/"
] |
74,298,628 | <p>I want to create a Text widget that has on top left an icon that will allow the Text to be edited by the user, but I can't manage to put the icon on the top left of the Text, like in the photo attached below for the text "Home". I've searched similar questions, but I've did not encountered anything similar.</p>
<p><a href="https://i.stack.imgur.com/YhcFA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YhcFA.png" alt="Desired state" /></a></p>
<p>Do you have any idea how can I achieve what I desire?</p>
| [
{
"answer_id": 74299510,
"author": "LacticWhale",
"author_id": 11962301,
"author_profile": "https://Stackoverflow.com/users/11962301",
"pm_score": 2,
"selected": false,
"text": "flutter_html"
},
{
"answer_id": 74299578,
"author": "TANIMUL ISLAM",
"author_id": 18262004,
"author_profile": "https://Stackoverflow.com/users/18262004",
"pm_score": 3,
"selected": true,
"text": "dependencies:\n flutter_html: ^3.0.0-alpha.3\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15356605/"
] |
74,298,656 | <p>I have text and want to find the number of letters like 'a', 'i', and also the word 'it'. I've been able to find the number of letters 'a' and 'i', but for the word 'that' I can't find</p>
<pre><code>let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ["a", "i", "it"]
result_a = [];
result_i = [];
result_it = [];
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < text.length; j++) {
if (words[i] == text[j] && words[i] == words[0]) {
result_a.push(text[j]);
} else if (words[i] == text[j] && words[i] == words[1]) {
result_i.push(text[j])
} else if (words[i] == text[j] && words[i] == words[2]) {
result_it.push(text[j])
}
}
}
console.log(result_a.length) //13
console.log(result_i.length) //24
console.log(result_it.length) //0
</code></pre>
<p>The output I expect is the number of each word searched for, for example the number of 'a' in the text variable is 13</p>
<p>my code is too long, is there a more concise way? and how to find 'it'</p>
| [
{
"answer_id": 74298780,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "var text = \"Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis.\";\nvar letters = [\"a\", \"i\"];\n\nfor (var i=0; i < letters.length; ++i) {\n var num = text.length - text.replace(new RegExp(letters[i], \"g\"), \"\").length;\n console.log(\"number of \" + letters[i] + \": \" + num);\n}"
},
{
"answer_id": 74298807,
"author": "Ravi Makwana",
"author_id": 6631280,
"author_profile": "https://Stackoverflow.com/users/6631280",
"pm_score": 0,
"selected": false,
"text": "RegExp"
},
{
"answer_id": 74298809,
"author": "Zakaria Ahmed",
"author_id": 6911807,
"author_profile": "https://Stackoverflow.com/users/6911807",
"pm_score": 0,
"selected": false,
"text": "let text = \"Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis.\"\nlet words = ['a', 'i', 'it'];\nlet wordCount = {\n 'a': 0,\n 'i': 0,\n 'it': 0\n};\n\nfor (let i = 0; i < text.length; i++) {\n for (const word of words) {\n if (text.substring(i).startsWith(word)) {\n wordCount[word]++;\n }\n }\n}\n"
},
{
"answer_id": 74298814,
"author": "Muhtasim Ulfat Tanmoy",
"author_id": 7769239,
"author_profile": "https://Stackoverflow.com/users/7769239",
"pm_score": 3,
"selected": true,
"text": "searchElement"
},
{
"answer_id": 74298901,
"author": "levani",
"author_id": 16339815,
"author_profile": "https://Stackoverflow.com/users/16339815",
"pm_score": 0,
"selected": false,
"text": "let words = [\"a\", \"i\", \"it\"]\n"
},
{
"answer_id": 74298932,
"author": "Nusrat Jahan",
"author_id": 20315115,
"author_profile": "https://Stackoverflow.com/users/20315115",
"pm_score": 0,
"selected": false,
"text": "let text = \"Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis.\"\nlet words = [\"a\", \"i\", \"it\"]\n\nresult_a = 0;\nresult_i = 0;\nresult_it = 0;\n\nfor (let i = 0; i < text.length; i++) {\n if (text[i] == words[0]) \n result_a++;\n if(text[i] == words[1]) \n result_i++;\n if (text[i] == words[2][0] && text[i+1] == words[2][1]) \n result_it++; \n}\n\nconsole.log(result_a) //13\nconsole.log(result_i) //24\nconsole.log(result_it) //4"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20326895/"
] |
74,298,662 | <p>Im trying to create variables like these using a for loop..</p>
<pre><code>TPidL1 = Load('TPidL1', '')
TPidL2 = Load('TPidL2', '')
TPidL3 = Load('TPidL3', '')
TPidL4 = Load('TPidL4', '')
TPidL5 = Load('TPidL5', '')
</code></pre>
<p>After reading other posts, I tried this but no luck</p>
<pre><code>for z = 1, 5, 1 do
"TPidL"..z = Load('TPidL'..tostring(z), '')
end
</code></pre>
<p>Any ideas how I could approach this better?</p>
<p>thanks</p>
| [
{
"answer_id": 74299784,
"author": "Mike V.",
"author_id": 7504558,
"author_profile": "https://Stackoverflow.com/users/7504558",
"pm_score": 1,
"selected": false,
"text": "_G"
},
{
"answer_id": 74299788,
"author": "Robert",
"author_id": 10953006,
"author_profile": "https://Stackoverflow.com/users/10953006",
"pm_score": 0,
"selected": false,
"text": "MyVariable = \"Hello\"\nfor Key, Value in pairs(_ENV) do\n print(Key,Value)\nend\n"
},
{
"answer_id": 74299897,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 3,
"selected": true,
"text": "TPidLs = {}\nfor z = 1, 5, 1 do \n TPidLs[z] = Load('TPidL' .. tostring(z), '')\nend\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403398/"
] |
74,298,686 | <p>I have getting 200 OK response on POST method. But data getting in DB is null. And get method working well if I manually put data in DB</p>
<p>my recipie model: Recipie.cs:</p>
<pre><code> public Guid RecipieId {get; set;}
public string RecipieTitle{get; set;}
public string RecipieDescription {get; set;}
public string RecipiePhotoName{get; set;}
</code></pre>
<pre><code>[HttpPost]
public ActionResult<Recipie> AddRecipies(Recipie addnewRecipie){
recipieDbContext.Recipies.Add(addnewRecipie);
recipieDbContext.SaveChanges();
return new JsonResult(addnewRecipie);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Ol14d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ol14d.png" alt="Row 1 & 2 output when I used POSTmethod, 3&4 I manually added" /></a></p>
<p>trying to pass this input in JSON format using postman</p>
<pre><code>{
"RecipieTitle": "Test1",
"RecipieDescription": "Lorem Ipsum",
"RecipiePhotoName": "photo.png"
}
</code></pre>
<p>Im using Postgres. The uuid generates automatically but the data I given not getting in Db. Is there any missing details to resolve this?</p>
| [
{
"answer_id": 74314459,
"author": "Chen",
"author_id": 18789859,
"author_profile": "https://Stackoverflow.com/users/18789859",
"pm_score": 2,
"selected": true,
"text": "public class Recipie\n {\n public Guid RecipieId { get; set; }\n public string RecipieTitle { get; set; }\n public string RecipieDescription { get; set; }\n public string RecipiePhotoName { get; set; }\n }\n"
},
{
"answer_id": 74314547,
"author": "Sami Ullah",
"author_id": 11525439,
"author_profile": "https://Stackoverflow.com/users/11525439",
"pm_score": 0,
"selected": false,
"text": "public ActionResult<Recipie> AddRecipies([FromBody] Recipie addnewRecipie)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20039061/"
] |
74,298,719 | <p>With 'Android Studio Dolphin | 2021.3.1', I am trying to get logs for my application with the Classname (which is used as TAG for Logs) but nothing is showing up.
Sometimes, it doesn't show any logs with the filter package:mine or package:'my.package.name'.
Is this a known issue?</p>
<p>Update: reported on google's board : <a href="https://issuetracker.google.com/issues/258502193" rel="nofollow noreferrer">https://issuetracker.google.com/issues/258502193</a></p>
| [
{
"answer_id": 74314459,
"author": "Chen",
"author_id": 18789859,
"author_profile": "https://Stackoverflow.com/users/18789859",
"pm_score": 2,
"selected": true,
"text": "public class Recipie\n {\n public Guid RecipieId { get; set; }\n public string RecipieTitle { get; set; }\n public string RecipieDescription { get; set; }\n public string RecipiePhotoName { get; set; }\n }\n"
},
{
"answer_id": 74314547,
"author": "Sami Ullah",
"author_id": 11525439,
"author_profile": "https://Stackoverflow.com/users/11525439",
"pm_score": 0,
"selected": false,
"text": "public ActionResult<Recipie> AddRecipies([FromBody] Recipie addnewRecipie)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1964609/"
] |
74,298,737 | <p>How to call Fragment method from RecyclerView layoutmanager?
Here are my Adapter:</p>
<pre><code>public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList ;
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public TextView mTextView3;
public TextView mTextView4;
public ExampleViewHolder(@NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.Icon_homework);
mTextView1 = itemView.findViewById(R.id.Line_1);
mTextView2 = itemView.findViewById(R.id.Line_2);
mTextView3 = itemView.findViewById(R.id.line_3);
mTextView4 = itemView.findViewById(R.id.line_4);
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList){
mExampleList = exampleList;
}
@NonNull
@Override
public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_stundenplan, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
@Override
public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {
ExampleItem currentitem = mExampleList.get(position);
holder.mImageView.setImageResource(currentitem.getImageRessource());
holder.mTextView1.setText(currentitem.getText1());
holder.mTextView2.setText(currentitem.getText2());
holder.mTextView3.setText(currentitem.getText3());
holder.mTextView4.setText(currentitem.getText4());
}
@Override
public int getItemCount() {
return mExampleList.size();
}
}
</code></pre>
<p>Here are my Items:</p>
<pre><code>public class ExampleItem {
private int mImageRessource;
private String mText1;
private String mText2;
private String mText3;
private String mText4;
public ExampleItem(int imageRessource, String text1, String text2, String text3, String text4){
mImageRessource = imageRessource;
mText1 = text1;
mText2 = text2;
mText3 = text3;
mText4 = text4;
}
public int getImageRessource(){
return mImageRessource;
}
public String getText1(){
return mText1;
}
public String getText2(){
return mText2;
}
public String getText3(){
return mText3;
}
public String getText4(){
return mText4;
}
}
</code></pre>
<p>And here are my Fragment code, i tried to find the problem, because when i open the app and click on the Fragmnet, it automatically close the app, and I think it is up to the layout manager and/or the Adapter.</p>
<pre><code>public class StundenplanFragment extends Fragment {
private RecyclerView mrecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public StundenplanFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment StundenplanFragment.
*/
// TODO: Rename and change types and number of parameters
public static StundenplanFragment newInstance(String param1, String param2) {
StundenplanFragment fragment = new StundenplanFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<ExampleItem> exampleList = new ArrayList<>();
exampleList.add(new ExampleItem(R.drawable.backpack, "Fach", "7:50-9:30", "2.0", "Raum:15"));
mAdapter = new ExampleAdapter(exampleList);
mLayoutManager = new LinearLayoutManager(getContext());
mrecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mrecyclerView.setAdapter(mAdapter);
//mAdapter.notifyDataSetChanged();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stundenplan, container, false);
mrecyclerView= view.findViewById(R.id.recyclerview);
return view;
//recyclerView.setHasFixedSize(true);
//return inflater.inflate(R.layout.fragment_stundenplan, container, false);
}
}
</code></pre>
| [
{
"answer_id": 74314459,
"author": "Chen",
"author_id": 18789859,
"author_profile": "https://Stackoverflow.com/users/18789859",
"pm_score": 2,
"selected": true,
"text": "public class Recipie\n {\n public Guid RecipieId { get; set; }\n public string RecipieTitle { get; set; }\n public string RecipieDescription { get; set; }\n public string RecipiePhotoName { get; set; }\n }\n"
},
{
"answer_id": 74314547,
"author": "Sami Ullah",
"author_id": 11525439,
"author_profile": "https://Stackoverflow.com/users/11525439",
"pm_score": 0,
"selected": false,
"text": "public ActionResult<Recipie> AddRecipies([FromBody] Recipie addnewRecipie)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20237757/"
] |
74,298,739 | <pre><code> dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
classpath 'com.google.gms:google-services:4.3.14'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
</code></pre>
<p><a href="https://i.stack.imgur.com/HttrB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HttrB.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74314459,
"author": "Chen",
"author_id": 18789859,
"author_profile": "https://Stackoverflow.com/users/18789859",
"pm_score": 2,
"selected": true,
"text": "public class Recipie\n {\n public Guid RecipieId { get; set; }\n public string RecipieTitle { get; set; }\n public string RecipieDescription { get; set; }\n public string RecipiePhotoName { get; set; }\n }\n"
},
{
"answer_id": 74314547,
"author": "Sami Ullah",
"author_id": 11525439,
"author_profile": "https://Stackoverflow.com/users/11525439",
"pm_score": 0,
"selected": false,
"text": "public ActionResult<Recipie> AddRecipies([FromBody] Recipie addnewRecipie)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944002/"
] |
74,298,759 | <p>(I am a total beginner in Xcode, so try to simplify the answer if you can...)</p>
<p>I have created a random card generator. More specifically I have four cards, when I click a button, a random card among the four cards appears.</p>
<p>The problem is I want to create four pages for each card. For instance, if a random card(image1) appears, I can click the card and go to a page(image1 page), whereas if a random card(image2) appears, I am also able to click the card and go to a page(image2 page)etc....</p>
<pre><code> private var imgs = ["image1", "image2", "image3", "image4"]
@State private var imgsnumbers = [0, 1, 2, 3]
@State var buttonTapped = false
var body: some View {
VStack {
Image(imgs[imgsnumbers[1]])
.resizable()
.frame(width:150 , height:212.63)
Button(action: {
self.imgsnumbers[1] = Int.random(in:0...self.imgs.count - 1)
self.buttonTapped.toggle()
}){
Text("DEAL")
}
.disabled(buttonTapped)
}
}
</code></pre>
| [
{
"answer_id": 74314459,
"author": "Chen",
"author_id": 18789859,
"author_profile": "https://Stackoverflow.com/users/18789859",
"pm_score": 2,
"selected": true,
"text": "public class Recipie\n {\n public Guid RecipieId { get; set; }\n public string RecipieTitle { get; set; }\n public string RecipieDescription { get; set; }\n public string RecipiePhotoName { get; set; }\n }\n"
},
{
"answer_id": 74314547,
"author": "Sami Ullah",
"author_id": 11525439,
"author_profile": "https://Stackoverflow.com/users/11525439",
"pm_score": 0,
"selected": false,
"text": "public ActionResult<Recipie> AddRecipies([FromBody] Recipie addnewRecipie)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404377/"
] |
74,298,774 | <p>When I copy some values from text file to a list a "\n" is also being printed. How can I remove that. I tried split(), replace(), remove() and so many ways but didn't work.</p>
<p>I am expecting to remove the "\n" when values are copied from text file to list</p>
| [
{
"answer_id": 74298816,
"author": "Shakya Dissanayake",
"author_id": 20054793,
"author_profile": "https://Stackoverflow.com/users/20054793",
"pm_score": -1,
"selected": false,
"text": "file = open('textfile.txt', 'r')\nLines = file.readlines()\n\nwordlist = []\n\nfor line in Lines:\n word = (line.split()[0])\n wordlist.append(word)\n \n"
},
{
"answer_id": 74298821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "strip()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20147336/"
] |
74,298,778 | <p>Here I am using Django 3.0 and Python 3.7</p>
<p>Here I am getting time from django template and i need to combine this time and today date as save it in database as DateTimeField</p>
<p>Here is my models.py</p>
<pre><code>class WorkTime(models.Model):
client = models.ForeignKey(Client,on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
total_time = models.TimeField(blank=True, null=True)
</code></pre>
<p>Here is my views.py</p>
<pre><code>class AddWorkTimeView(View):
def get(self, request):
client = request.user.client
return render(request,'core/work_time_form.django.html')
def post(self, request):
c = request.user.client
start_time = request.POST.get('start_time') # print start_time - 11:15
end_time = request.POST.get('end_time') # print end_time - 14:15
WorkTime.objects.create(client=c,start_time=start_time,end_time=end_time)
return redirect('work_times')
</code></pre>
<p>Here is my work_time_form.django.html</p>
<pre><code><form class="form-horizontal" method="post">
{% csrf_token %}
<div class="row">
<div class="span10 offset1">
<div class="control-group">
<label class="control-label pull-left">Start Time</label>
<input type="time" step="900" class="input_box" name="start_time">
</div>
<div class="control-group">
<label class="control-label pull-left">End Time</label>
<input type="time" step="900" class="input_box" name="end_time">
</div>
<div id="form-buttons-container" class="form-actions">
<div class="controls">
<input type="submit" class="btn btn-inverse" value="Save">
</div>
</div>
</div>
</div>
</form>
</code></pre>
<p>Here what format i want it to save to my datebase</p>
<pre><code>Example: 2020-11-03 10:30:00 (here date is today date)
</code></pre>
<p>And also calculate the time difference between start_time and end_time in minutes and save it to total_time field</p>
<p>To achieve this what changes i need to do to my code</p>
<p>Please help me to solve this issue</p>
| [
{
"answer_id": 74298816,
"author": "Shakya Dissanayake",
"author_id": 20054793,
"author_profile": "https://Stackoverflow.com/users/20054793",
"pm_score": -1,
"selected": false,
"text": "file = open('textfile.txt', 'r')\nLines = file.readlines()\n\nwordlist = []\n\nfor line in Lines:\n word = (line.split()[0])\n wordlist.append(word)\n \n"
},
{
"answer_id": 74298821,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "strip()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749532/"
] |
74,298,781 | <p>When using Spring Api RequestParam, is it possible to disallow "" or whitespace without additional check if code?</p>
<pre class="lang-java prettyprint-override"><code>@GetMapping("/test")
public List<StatesInfoVO> getTestStates(@RequestParam(required = true) List<String> states) {
//...
}
</code></pre>
<p>Could there be an error when this request is received?</p>
<p><code>/test?states=""</code> or <code>/test?states=" "</code></p>
| [
{
"answer_id": 74299197,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 2,
"selected": false,
"text": "@Validated"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18436153/"
] |
74,298,819 | <pre><code>def outer_fun(func):
print('outer function ran')
def inner_function():
print('inner function ran')
return func()
return inner_function()
def fun():
print("Hi")
fun = outer_fun(fun)
print(fun)
</code></pre>
<p>the output is:</p>
<pre><code>outer function ran
inner function ran
Hi
None
</code></pre>
<p>why the none here?</p>
<p>when I do</p>
<pre><code>fun = outer_fun(fun)
</code></pre>
<p>and calls it immediately inside the <code>inner_function</code> it runs fun() and makes the fun a none object? why?
Also if I try to run <code>fun = outer_fun(fun)</code> again it says object is not callable</p>
| [
{
"answer_id": 74299197,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 2,
"selected": false,
"text": "@Validated"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19213110/"
] |
74,298,826 | <p>I am a starter in Unity and developing a soccer game. I have a problem ,my IF statements conflict each other. Let me explain it in detail.
In order for a ball to stick to player, I have used IF operator, so whenever the distance between the player and the ball is less than < 0.5 , the ball sticks to player and move together with it. Now when I try to set up shooting the ball (I try with "addforce") it doesnt let me, cause the ball is still attached to player and distance is <0.5.</p>
<p>This one is the balls script.</p>
<pre><code>public bool sticktoplayer;
public transform player;
//gameobject Player is attached
float distancetoplayer;
Rigidbody rb;
//balls rigidbody
void Awake ()
{
rb = getComponent<Rigidbody>();
}
void Update()
{
If (!sticktoplayer)
{
float distancetoplayer = Vector3.Distance (player.position, transform.position);
if(distancetoplayer < 0.5f)
{
sticktoplayer = true;
}
}
else
{
transform.position = player.position;
}
if(Input.GetKeyDown(KeyCode.Space))
{
rb.addforce(20, 0, 0, ForceMode.Impulse);
sticktoplayer = false;
}
</code></pre>
<p>When the player is not controlling the ball the force is succesfully applied to the ball, but when the ball is attached (distancetoplayer<0.5) then the other IF statements blocks it from shooting.
Maybe there are some work arounds ? Thanks.</p>
<p>I tried to make another if statement.</p>
| [
{
"answer_id": 74299197,
"author": "birca123",
"author_id": 10231374,
"author_profile": "https://Stackoverflow.com/users/10231374",
"pm_score": 2,
"selected": false,
"text": "@Validated"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404570/"
] |
74,298,829 | <p>I'm very new to programming. I've tried to search the website for similar problems, but can't find the information I need.</p>
<p>I have a list that contains multiple strings showing year, month, day and hour. I need to split this list into four lists of years, months, days and hours. The values have to be integers in the four lists.</p>
<p>The time format is: 'dd.mm.yyyy hh', example: '01.11.2020 02'</p>
<p>I'm able to split the string '01.11.2020 02' using this code:</p>
<pre><code>timeStamp = '01.11.2020 02'
def getYear(timeStampStr):
yearStr = timeStampStr[6:10]
year = int(yearStr)
return year
def getMonth(timeStampStr):
monthStr = timeStampStr[3:5]
month = int(monthStr)
return month
def getDay(timeStampStr):
dayStr = timeStampStr[0:2]
day = int(dayStr)
return day
def getHour(timeStampStr):
hourStr = timeStampStr[11:13]
hour = int(hourStr)
return hour
</code></pre>
<p>I can then get the wanted result with:</p>
<pre><code>print(getMonth(timeStamp))
</code></pre>
<p>However, this doesnt work when timeStamp is a list;</p>
<pre><code>timeStamp = ['01.11.2020 00:00', '01.11.2020 01:00', '01.11.2020 02:00', etc].
</code></pre>
<p>What can I do to split it into four?</p>
| [
{
"answer_id": 74298884,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 1,
"selected": false,
"text": "map"
},
{
"answer_id": 74298897,
"author": "Amrutha Gandhi",
"author_id": 20397301,
"author_profile": "https://Stackoverflow.com/users/20397301",
"pm_score": 0,
"selected": false,
"text": "timeStamp.split('.')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404388/"
] |
74,298,902 | <p>I want to know how to run Node.js project connected with MongoDB, { downloaded from GitHub } in my pc</p>
<p>Project link <a href="https://github.com/john-smilga/node-express-course/tree/main/06-jobs-api/final" rel="nofollow noreferrer">https://github.com/john-smilga/node-express-course/tree/main/06-jobs-api/final</a></p>
<p>In its read me file it has been written that</p>
<pre class="lang-none prettyprint-override"><code>#### Project Setup
In order to spin up the project, in the root create .env with these two variables, with your own values.
MONGO_URI
JWT_SECRET
After that run this command
```bash
npm install && npm start
```
</code></pre>
<p>I have installed MongoDB community version, but need help in setting up and run this project<a href="https://i.stack.imgur.com/2ROVB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ROVB.png" alt="this is the error iam getting, after running npm install, run and start" /></a></p>
<p>I want to run this project in my laptop</p>
| [
{
"answer_id": 74298884,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 1,
"selected": false,
"text": "map"
},
{
"answer_id": 74298897,
"author": "Amrutha Gandhi",
"author_id": 20397301,
"author_profile": "https://Stackoverflow.com/users/20397301",
"pm_score": 0,
"selected": false,
"text": "timeStamp.split('.')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404591/"
] |
74,298,919 | <p>I've searched the web and this site and been messing around all day, trying 100 ways to get this simple little program working. I'm practicing endless While loops and string user inputs. Can anyone explain what I'm doing wrong? Thank you!</p>
<pre><code>while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.islower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
</code></pre>
| [
{
"answer_id": 74298950,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "answer.islower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17416128/"
] |
74,298,937 | <p>For testing purposes, I deploy two versions of my application on the same machine. On production, only one application instance runs in one cloud Kubernetes cluster and uses the ingress-nginx controller to expose its API.</p>
<p>I use kind to run a Kubernetes cluster locally and deploy the application versions into two different namespaces. I configure the ingress controller according to the <a href="https://kind.sigs.k8s.io/docs/user/ingress/#ingress-nginx" rel="nofollow noreferrer">kind</a> and ingress-nginx <a href="https://kubernetes.github.io/ingress-nginx/user-guide/multiple-ingress/" rel="nofollow noreferrer">Multiple controllers</a> documentation. The first instance of my app works as expected, but when I deploy the second one, the controller pod fails to start with the following message:</p>
<pre><code>0/6 nodes are available: 1 node(s) didn't have free ports for the requested pod ports, 5 node(s) didn't match Pod's node affinity/selector
</code></pre>
<p>As far as I understand, two ingress controller pods are scheduled on the same node and cannot share the same port. Please advise how to proceed further. Should the second controller pod be scheduled to a different node? As kind maps node ports to the host machine, is it possible to map the same ports of multiple nodes to the host machine?</p>
| [
{
"answer_id": 74298950,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "answer.islower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6376725/"
] |
74,298,973 | <p>I am new to development and trying first time this functionality. I am trying to download the file which is coming from the server as this form
`</p>
<pre><code>%PDF-1.2
%����
3 0 obj
<<
/Linearized 1
/O 5
/H [ 760 157 ]
/L 3908
/E 3658
/N 1
/T 3731
>>
endobj
xref
3 15
0000000016 00000 n
0000000644 00000 n
0000000917 00000 n
0000001068 00000 n
0000001224 00000 n
0000001410 00000 n
0000001589 00000 n
0000001768 00000 n
0000002197 00000 n
0000002383 00000 n
0000002769 00000 n
0000003172 00000 n
0000003351 00000 n
0000000760 00000 n
0000000897 00000 n
trailer
<<
/Size 18
/Info 1 0 R
/Root 4 0 R
/Prev 3722
/ID[<d70f46c5ba4fe8bd49a9dd0599b0b151><d70f46c5ba4fe8bd49a9dd0599b0b151>]
>>
startxref
0
%EOF
4 0 obj
<<
/Type /Catalog
/Pages 2 0 R
/OpenAction [ 5 0 R /XYZ null null null ]
/PageMode /UseNone
>>
endobj
16 0 obj
<< /S 36 /Filter /FlateDecode /Length 17 0 R >>
stream
H�b``�e``��
</code></pre>
<p>`
Now in the UI I have did like this</p>
<pre><code>
</code></pre>
<pre><code>downloadFile () {
api.get(`ips/downloadAttachedFile/` + this.claimId, { responseType: 'Blob' }).then( res => {
const downloadUrl = window.URL.createObjectURL(new Blob([res]),{ type: "application/pdf" });
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', 'test.pdf');
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(link.href)
})
}
</code></pre>
<pre><code>
</code></pre>
<p>when I am trying to download it, pdf is coming as blank file.</p>
<p>I want the data inside that pdf file to be displayed and if I have more type of files like .jpg, .doc etc so how can I download them with their extension. Can anyone help me with this</p>
| [
{
"answer_id": 74298950,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "answer.islower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74298973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20042604/"
] |
74,299,028 | <p>I have a question, my template content does not have a fixed value, this template content value is random and comes from what the user input and stores in the table, but the variable of the content is set.</p>
<p>For example few template content values (For <strong>schedule.TemplateContent</strong>) :</p>
<pre><code>1. My name is {name}.
2. My name is {name}. My last name is {lastName}
3. Her name is {name}. She is a {sex}. She like play {activity}
</code></pre>
<p>Below is my code, I just only know how to replace 1 word in the template content, not sure how to replace if loop the template content has multiple variables need to replace:</p>
<pre class="lang-html prettyprint-override"><code>
foreach (SAASQueuePatList pat in patList)
{
pat.PatName = "{name}";
pat.PatLastName = "{lastName}";
pat.PatSex= "{sex}";
pat.PatActivity = "{activity}";
string fullContent = schedule.TemplateContent.Replace("{name}", pat.PatName);
}
</code></pre>
<p>Hope someone can guide me on how to solve this problem. Thanks.</p>
| [
{
"answer_id": 74298950,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "answer.islower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14562541/"
] |
74,299,030 | <p>I am building an app using Vite, React, and TS. I have the following code which is causing vite to fail:</p>
<pre><code>export type UseSearchFilters<T> = ReturnType<typeof useSearchFilters<T>>
</code></pre>
<p>It throws the following error:</p>
<pre><code>[plugin:vite:react-babel] useSearchFilters.ts: Unexpected token, expected "," (6:68)
6 | export type UseSearchFilters<T> = ReturnType<typeof useSearchFilters<T>>
</code></pre>
<p>Specifically it is getting bugged out by the final <code>></code>, but if I delete it, it wants it back. tsc is fine with this, but babel and prettier are not for whatever reason.</p>
<p>I have no idea what I could be doing to cause this, since I have seen plenty of examples of people online passing a generic to a <code>ReturnType<typeof GenericConsumer<T>></code> with no issues. My team is totally baffled by this and it is killing the functionality.</p>
<p>Any help would be appreciated here.</p>
<p>Dependencies:</p>
<pre><code> "@babel/core": "^7.16.7",
"@babel/preset-env": "^7.16.8",
"@babel/preset-react": "^7.16.7",
"@babel/preset-typescript": "^7.16.7",
"react": "^17.0.0",
"react-dom": "^17.0.0",
"typescript": "^4.3.2",
"vite": "^3.0.4",
</code></pre>
| [
{
"answer_id": 74298950,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "answer.islower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12218719/"
] |
74,299,040 | <p>I have a list named 'cords' with all the x-y coordinates in a list.
<a href="https://i.stack.imgur.com/cO5Ue.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cO5Ue.png" alt="List of x, y co-ordinates" /></a>
I need to calculate the distance between 1st(x,y) and 2nd(x,y) then 2nd(x,y) and 3rd(x,y) coordinates and so on until the end of the list. The values in the list are in float.</p>
<p>i am using</p>
<p>def find_distance():</p>
<pre><code> for i in range (0, (len(cords))):
res = [float(ele) for ele in cords[i]]
dis. append(res)
for j in range (1, ((len(cords))-1)):
dist=math.sqrt((cm.dis[i][0] - cm.dis[j][0])**2 + (cm.dis[i][1] - cm.dis[j][1])**2)
dista. append(dist)
return res , dista
</code></pre>
<pre><code>
</code></pre>
<p>This throws an error that list index is out of range, how can i solve this?</p>
| [
{
"answer_id": 74298950,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": 2,
"selected": true,
"text": "answer.islower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404637/"
] |
74,299,058 | <p>For the following tables:</p>
<pre><code>-- People
id | category | count
----+----------+-------
1 | a | 2
1 | a | 3
1 | b | 2
2 | a | 2
2 | b | 3
3 | a | 1
3 | a | 2
</code></pre>
<p>I know that I can find the max count for each id in each category by doing:</p>
<pre><code>SELECT id, category, max(count) from People group by category, id;
</code></pre>
<p>With result:</p>
<pre><code> id | category | max
----+----------+-------
1 | a | 3
1 | b | 2
2 | a | 2
2 | b | 3
3 | a | 2
</code></pre>
<p>But what if now I want to label the max values differently, like:</p>
<pre><code> id | max_b_count | max_a_count
----+-------------+------------
1 | 2 | 3
2 | 3 | 2
3 | Null | 2
</code></pre>
<p>Should I do something like the following?</p>
<pre><code>WITH t AS (SELECT id, category, max(count) from People group by category, id)
SELECT t.id, t.count as max_a_count from t where t.category = 'a'
FULL OUTER JOIN t.id, t.count as max_b_count from t where t.category = 'b'
on t.id;
</code></pre>
<p>It looks weird to me.</p>
| [
{
"answer_id": 74299376,
"author": "VBoka",
"author_id": 6565038,
"author_profile": "https://Stackoverflow.com/users/6565038",
"pm_score": 0,
"selected": false,
"text": "with T as (select id, category, max(count_ab) maks\nfrom people\ngroup by id, category\norder by id)\nselect t3.id\n , (select t1.maks from T t1 where category = 'b' and t1.id = t3.id) max_b_count \n , (select t2.maks from T t2 where category = 'a' and t2.id = t3.id) max_a_count \nfrom T t3\ngroup by t3.id\norder by t3.id\n"
},
{
"answer_id": 74304421,
"author": "Marmite Bomber",
"author_id": 4808122,
"author_profile": "https://Stackoverflow.com/users/4808122",
"pm_score": 3,
"selected": true,
"text": "aggregate_name ( * ) [ FILTER ( WHERE filter_clause ) ]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055667/"
] |
74,299,065 | <pre><code>airlock = input("Has the air pressure equalised Y/N: ")
airlock = airlock.lower
if airlock == "n":
print("They wait until the air pressure equalises.")
airlock = input("Has the air pressure equalised Y/N: ");
elif airlock == "y":
light = input("Does the airlock pressured light show green? Y/N");
else:
airlock = input("Has the air pressure equalised Y/N: ");
light = light.lower
if light == "n":
print("The air lock continues to pressurise.")
light = input("Does the airlock pressured light show green? Y/N: ");
elif light == "y":
print("The air lock is pressuresed.");
print("Corporal Alecks opens the inner airlock door and enters the moonbase with Commander Lorene")
print("Corporal Alecks takes Commander Lorene to the med bay")
print("Mission complete")
</code></pre>
<p>"light" input not defined when run. What should I do?</p>
<p>Tried running this code and it says that "light" is not defined</p>
| [
{
"answer_id": 74299125,
"author": "ljdyer",
"author_id": 17568469,
"author_profile": "https://Stackoverflow.com/users/17568469",
"pm_score": 0,
"selected": false,
"text": "lower"
},
{
"answer_id": 74299139,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 2,
"selected": true,
"text": "lower"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16932391/"
] |
74,299,082 | <p>As title, I want to remove the page number text box in each slide which was created by old version of MS powerpoint 10 years old in following format</p>
<p>page 1 of 47</p>
<p>My 1st attempted code is</p>
<pre><code>With ActivePresentation.Slides.Find
.Forward = True
.Wrap = wdFindStop
.Text = "*/47"
.Replacement.Text = ""
.Replace = wdReplaceAll
.MatchCase = False
End With
</code></pre>
<p>My 2nd attempted code is</p>
<pre><code>Sub ClNumbers()
Dim oSl As Slide
Dim oSh As Shape
Dim oTxtRng As TextRange
Dim sTextToFind As String
sTextToFind = "*/47"
For Each oSl In ActivePresentation.Slides
For Each oSh In oSl.Shapes
If oSh.HasTextFrame Then
If oSh.TextFrame.HasText Then
If InStr(oSh.TextFrame.TextRange.Text, sTextToFind) > 0 Then
Set oTxtRng = oSh.TextFrame.TextRange.Characters(InStr(oSh.TextFrame.TextRange.Text, sTextToFind), Len(sTextToFind))
Debug.Print oTxtRng.Text
With oTxtRng
.Font.Bold = True
End With
End If
End If
End If
Next
Next
End Sub
</code></pre>
<p>neither does work, would you please help to correct my code to remove all page number by VBA. thanks in advance.</p>
<p>please correct me vba code or provide your elegant method.</p>
| [
{
"answer_id": 74299125,
"author": "ljdyer",
"author_id": 17568469,
"author_profile": "https://Stackoverflow.com/users/17568469",
"pm_score": 0,
"selected": false,
"text": "lower"
},
{
"answer_id": 74299139,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 2,
"selected": true,
"text": "lower"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404787/"
] |
74,299,098 | <p>I write in React. On the page I have a scroll up button.</p>
<p><a href="https://i.stack.imgur.com/MKAeM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MKAeM.png" alt="enter image description here" /></a></p>
<p>When scrolling on some blocks, it is not visible due to the fact that the colors match.</p>
<p><a href="https://i.stack.imgur.com/E5Bj6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E5Bj6.png" alt="enter image description here" /></a></p>
<p>How to make it so that when it touches certain blocks of the same color as the button, it turns white.</p>
<p><a href="https://i.stack.imgur.com/aoKxS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aoKxS.png" alt="enter image description here" /></a></p>
<p>How to track the contact of a button with a specific block? What listeners to put?</p>
| [
{
"answer_id": 74299621,
"author": "Sanjay",
"author_id": 11468488,
"author_profile": "https://Stackoverflow.com/users/11468488",
"pm_score": 3,
"selected": true,
"text": "position: fixed"
},
{
"answer_id": 74303217,
"author": "sayandcode",
"author_id": 18620006,
"author_profile": "https://Stackoverflow.com/users/18620006",
"pm_score": 0,
"selected": false,
"text": "blend-mode:difference"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16765604/"
] |
74,299,103 | <p>I want to delete those objectσ which <code>refId</code> id that dont match with any id of array of object, if <code>refId</code> is null dont delete it</p>
<pre><code>[
{id: 1 , refId:null, name:'jhon'},
{id: 2 , refId:null, name:'sam'},
{id: 3 , refId:1, name:'fam'},
{id: 4 , refId:2, name:'jam'},
{id: 5 , refId:16, name:'ram'},
{id: 6 , refId:15, name:'nam'}
]
</code></pre>
<p>result: should b:</p>
<pre><code>[
{id: 1 , refId:null, name:'jhon'},
{id: 2 , refId:null, name:'sam'},
{id: 3 , refId:1, name:'fam'},
{id: 4 , refId:2, name:'jam'},
]
</code></pre>
| [
{
"answer_id": 74299172,
"author": "Drashti Kheni",
"author_id": 10535718,
"author_profile": "https://Stackoverflow.com/users/10535718",
"pm_score": 3,
"selected": true,
"text": "const arr1 = [\n { id: 1, refId: null, name: \"jhon\" },\n { id: 2, refId: null, name: \"sam\" },\n { id: 3, refId: 1, name: \"fam\" },\n { id: 4, refId: 2, name: \"jam\" },\n { id: 5, refId: 16, name: \"ram\" },\n { id: 6, refId: 15, name: \"nam\" },\n];\n\nconsole.log(\n arr1.filter((obj) => {\n return obj.refId === null || arr1.some((o) => o.id === obj.refId);\n })\n);"
},
{
"answer_id": 74299414,
"author": "vaira",
"author_id": 6384776,
"author_profile": "https://Stackoverflow.com/users/6384776",
"pm_score": 0,
"selected": false,
"text": "let nodes = [\n {id: 1 , refId:null, name:'jhon'},\n {id: 2 , refId:null, name:'sam'}, \n {id: 3 , refId:1, name:'fam'},\n {id: 4 , refId:2, name:'jam'}, \n {id: 5 , refId:16, name:'ram'}, \n {id: 6 , refId:15, name:'nam'}\n]\n\nlet dictionary = nodes.reduce((dic, node) => { dic[node.id] = true; return dic; }, { [null]: true });\nlet result = nodes.filter((node) => dictionary[node.refId]);\n\nconsole.log(result);"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7482821/"
] |
74,299,132 | <p>Here, I am trying to implement pie chart (donut series) in angular.
These are my html, css and ts files.
I am following this resource. <a href="https://apexcharts.com/angular-chart-demos/pie-charts/simple-donut/" rel="nofollow noreferrer">https://apexcharts.com/angular-chart-demos/pie-charts/simple-donut/</a></p>
<p>Link to CodeSandBox - <a href="https://codesandbox.io/s/apx-donut-simple-8fnji?from-embed" rel="nofollow noreferrer">https://codesandbox.io/s/apx-donut-simple-8fnji?from-embed</a></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>import { Component, OnInit, ViewChild } from '@angular/core';
import { ChartComponent } from "ng-apexcharts";
import {
ApexNonAxisChartSeries,
ApexResponsive,
ApexChart
} from "ng-apexcharts";
export type ChartOptions = {
series: ApexNonAxisChartSeries;
chart: ApexChart;
responsive: ApexResponsive[];
labels: any;
};
@Component({
selector: 'app-second-page',
templateUrl: './second-page.component.html',
styleUrls: ['./second-page.component.css']
})
export class SecondPageComponent implements OnInit {
@ViewChild("chart") chart: ChartComponent;
public chartOptions: Partial<ChartOptions>;
constructor() {
this.chartOptions = {
series: [44, 55, 13, 43, 22],
chart: {
type: "donut"
},
labels: ["Team A", "Team B", "Team C", "Team D", "Team E"],
responsive: [
{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: "bottom"
}
}
}
]
};
}
ngOnInit(): void {
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> #chart {
max-width: 380px;
margin: 35px auto;
padding: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="chart">
<apx-chart
[series]="chartOptions.series"
[chart]="chartOptions.chart"
[labels]="chartOptions.labels"
[responsive]="chartOptions.responsive"
></apx-chart>
</div></code></pre>
</div>
</div>
</p>
<p>I am facing the undefined issue, but its working for them in the tutorial. Somebody please help me on this.</p>
<pre><code>Error: src/app/second-page/second-page.component.html:32:8 - error TS2322: Type 'ApexNonAxisChartSeries | undefined' is not assignable to type 'ApexAxisChartSeries | ApexNonAxisChartSeries'.
Type 'undefined' is not assignable to type 'ApexAxisChartSeries | ApexNonAxisChartSeries'.
32 [series]="chartOptions.series"
~~~~~~
src/app/second-page/second-page.component.ts:19:16
19 templateUrl: './second-page.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component SecondPageComponent.
Error: src/app/second-page/second-page.component.html:33:8 - error TS2322: Type 'ApexChart | undefined' is not assignable to type 'ApexChart'.
Type 'undefined' is not assignable to type 'ApexChart'.
33 [chart]="chartOptions.chart"
~~~~~
src/app/second-page/second-page.component.ts:19:16
19 templateUrl: './second-page.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component SecondPageComponent.
Error: src/app/second-page/second-page.component.html:35:8 - error TS2322: Type 'ApexResponsive[] | undefined' is not assignable to type 'ApexResponsive[]'.
Type 'undefined' is not assignable to type 'ApexResponsive[]'.
35 [responsive]="chartOptions.responsive"
~~~~~~~~~~
src/app/second-page/second-page.component.ts:19:16
19 templateUrl: './second-page.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component SecondPageComponent.
Error: src/app/second-page/second-page.component.ts:23:23 - error TS2564: Property 'chart' has no initializer and is not definitely assigned in the constructor.
23 @ViewChild("chart") chart: ChartComponent;
~~~~~
✖ Failed to compile.
</code></pre>
| [
{
"answer_id": 74299172,
"author": "Drashti Kheni",
"author_id": 10535718,
"author_profile": "https://Stackoverflow.com/users/10535718",
"pm_score": 3,
"selected": true,
"text": "const arr1 = [\n { id: 1, refId: null, name: \"jhon\" },\n { id: 2, refId: null, name: \"sam\" },\n { id: 3, refId: 1, name: \"fam\" },\n { id: 4, refId: 2, name: \"jam\" },\n { id: 5, refId: 16, name: \"ram\" },\n { id: 6, refId: 15, name: \"nam\" },\n];\n\nconsole.log(\n arr1.filter((obj) => {\n return obj.refId === null || arr1.some((o) => o.id === obj.refId);\n })\n);"
},
{
"answer_id": 74299414,
"author": "vaira",
"author_id": 6384776,
"author_profile": "https://Stackoverflow.com/users/6384776",
"pm_score": 0,
"selected": false,
"text": "let nodes = [\n {id: 1 , refId:null, name:'jhon'},\n {id: 2 , refId:null, name:'sam'}, \n {id: 3 , refId:1, name:'fam'},\n {id: 4 , refId:2, name:'jam'}, \n {id: 5 , refId:16, name:'ram'}, \n {id: 6 , refId:15, name:'nam'}\n]\n\nlet dictionary = nodes.reduce((dic, node) => { dic[node.id] = true; return dic; }, { [null]: true });\nlet result = nodes.filter((node) => dictionary[node.refId]);\n\nconsole.log(result);"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13517148/"
] |
74,299,140 | <p>I was playing around with a small program that should find the average of numbers and the list of below, above average numbers in that list.</p>
<pre><code>
num = input("Enter a number: ")
total = 0
count = 0
lst = []
below_ave = []
equal_ave = []
above_ave = []
while num != '':
n = int(num)
total += n
count += 1
lst.append(n)
num = input("Enter a number: ")
average = total // count
for i in range(0, len(lst)-1): # Here why it should be len(lst) instead of len(lst)-1
# I played around with it a bit, if i use len(lst)-1 then
# the last number in the list (lst) will not be displayed
# But as you can see i tried to see if i made a mistake by
# printing out each individual element of the list, lst[4]
# does print out the last number, but it does not show up
# in above_ave.
if lst[i] < average:
below_ave.append(lst[i])
elif lst[i] == average:
equal_ave.append(lst[i])
elif lst[i] > average:
above_ave.append(lst[i])
print(lst[0])
print(lst[1])
print(lst[2])
print(lst[3])
print(lst[4])
print(f"lentgh of the list is {len(lst)}")
print(average)
print(below_ave)
print(equal_ave)
print(above_ave)
</code></pre>
<pre><code>output
Enter a number: 5
Enter a number: 8
Enter a number: 6
Enter a number: 12
Enter a number: 9
Enter a number:
5
8
6
12
9
lentgh of the list is 5
8
[5, 6]
[8]
[12]
Process finished with exit code 0
</code></pre>
<p>As commented in the program. I'm confused with the index of the element in a list. 0th element should represent the first element in a list, however, the output of the program does not show that. I have encountered this problem before, i ignored it but i don't think i should.</p>
<p>So when should one use len(list)-1 and len(list) in similar situations like mine? I usually use len(list)-1 and it works but sometimes it doesn't like in this code.</p>
<p>Appreciate the help!</p>
| [
{
"answer_id": 74299172,
"author": "Drashti Kheni",
"author_id": 10535718,
"author_profile": "https://Stackoverflow.com/users/10535718",
"pm_score": 3,
"selected": true,
"text": "const arr1 = [\n { id: 1, refId: null, name: \"jhon\" },\n { id: 2, refId: null, name: \"sam\" },\n { id: 3, refId: 1, name: \"fam\" },\n { id: 4, refId: 2, name: \"jam\" },\n { id: 5, refId: 16, name: \"ram\" },\n { id: 6, refId: 15, name: \"nam\" },\n];\n\nconsole.log(\n arr1.filter((obj) => {\n return obj.refId === null || arr1.some((o) => o.id === obj.refId);\n })\n);"
},
{
"answer_id": 74299414,
"author": "vaira",
"author_id": 6384776,
"author_profile": "https://Stackoverflow.com/users/6384776",
"pm_score": 0,
"selected": false,
"text": "let nodes = [\n {id: 1 , refId:null, name:'jhon'},\n {id: 2 , refId:null, name:'sam'}, \n {id: 3 , refId:1, name:'fam'},\n {id: 4 , refId:2, name:'jam'}, \n {id: 5 , refId:16, name:'ram'}, \n {id: 6 , refId:15, name:'nam'}\n]\n\nlet dictionary = nodes.reduce((dic, node) => { dic[node.id] = true; return dic; }, { [null]: true });\nlet result = nodes.filter((node) => dictionary[node.refId]);\n\nconsole.log(result);"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9308700/"
] |
74,299,173 | <p>How can I add a fixed number of pixels to the initial height of an element?</p>
<p>Pseudo-CSS:</p>
<pre><code>.zoom {
padding: 0px;
transition: transform .2s;
margin: 0 auto;
}
.zoom:hover {
width: <initial-width> + 4px;
height: <initial-height> + 4px;
}
</code></pre>
<p>When I use <code>transform: scale(...)</code> instead, the resulting difference is dependent of the initial size of the element, which I don't want. I am intending to use this on buttons and their initial size will depend on the contents on them.</p>
<p>Also, I don't want the contents to scale with the button.</p>
<p>In the following snippet you see the problem:</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>.container {
margin: 10px 100px 10px 100px;
}
.zoom {
padding: 0px;
transition: transform .2s;
margin-top: 10px
}
.zoom:hover {
transform: scale(1.2);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<button type="button" class="zoom">Short content</button><br />
<button type="button" class="zoom">Very very very very very very very very very long content</button>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>EDIT:</strong></p>
<p>In fact, I want a look like <code>transform: scale()</code> (in terms of not affecting the neighbors), but by a number of pixels in each direction and not by a factor.</p>
| [
{
"answer_id": 74299329,
"author": "Darshil Jani",
"author_id": 19232446,
"author_profile": "https://Stackoverflow.com/users/19232446",
"pm_score": 2,
"selected": false,
"text": "padding-block"
},
{
"answer_id": 74301013,
"author": "A Haworth",
"author_id": 10867454,
"author_profile": "https://Stackoverflow.com/users/10867454",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n\n<head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <style>\n .container {\n margin: 10px 100px 10px 100px;\n }\n \n .zoom {\n padding: 0px;\n transition: all .2s linear;\n --margintop: 10px;\n margin-top: var(--margintop);\n }\n \n .zoom:hover {\n --padding: 2px;\n padding: var(--padding);\n --minuspadding: calc(-1 * var(--padding));\n margin: calc(var(--margintop) + var(--minuspadding)) var(--minuspadding) var(--minuspadding);\n }\n </style>\n</head>\n\n<body>\n\n <div class=\"container\">\n <button type=\"button\" class=\"zoom\">Short content</button><br>\n <button type=\"button\" class=\"zoom\">Very very very very very very very very very long content</button>\n </div>\n</body>\n\n</html>"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4415146/"
] |
74,299,209 | <p>I have a function which produces output to os.Stdout that I would like to unit test. How can I capture the output into a string which I can compare in my unit tests?</p>
<pre><code> func f() {
// How to capture "hello\n"?
fmt.Fprintln(out, "hello")
}
</code></pre>
| [
{
"answer_id": 74299329,
"author": "Darshil Jani",
"author_id": 19232446,
"author_profile": "https://Stackoverflow.com/users/19232446",
"pm_score": 2,
"selected": false,
"text": "padding-block"
},
{
"answer_id": 74301013,
"author": "A Haworth",
"author_id": 10867454,
"author_profile": "https://Stackoverflow.com/users/10867454",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n\n<head>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <style>\n .container {\n margin: 10px 100px 10px 100px;\n }\n \n .zoom {\n padding: 0px;\n transition: all .2s linear;\n --margintop: 10px;\n margin-top: var(--margintop);\n }\n \n .zoom:hover {\n --padding: 2px;\n padding: var(--padding);\n --minuspadding: calc(-1 * var(--padding));\n margin: calc(var(--margintop) + var(--minuspadding)) var(--minuspadding) var(--minuspadding);\n }\n </style>\n</head>\n\n<body>\n\n <div class=\"container\">\n <button type=\"button\" class=\"zoom\">Short content</button><br>\n <button type=\"button\" class=\"zoom\">Very very very very very very very very very long content</button>\n </div>\n</body>\n\n</html>"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
74,299,231 | <p>how can i change the background color based on text in power bi as per attach. For example, critical is red, reorder is yellow, ideal is green and etc.</p>
<p><a href="https://i.stack.imgur.com/wZGdx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZGdx.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74299649,
"author": "Peter",
"author_id": 7108589,
"author_profile": "https://Stackoverflow.com/users/7108589",
"pm_score": 1,
"selected": false,
"text": "Color = \nSWITCH(\n TRUE(),\n 'Table'[Status] = \"Critical\", \"#FF0000\",\n 'Table'[Status] = \"Ideal\", \"#008000\"\n)\n"
},
{
"answer_id": 74300252,
"author": "M. P.",
"author_id": 20396112,
"author_profile": "https://Stackoverflow.com/users/20396112",
"pm_score": 0,
"selected": false,
"text": "Background Color = SWITCH(TRUE(),\n Table[Status] = \"Critical\", \"#FF0000\",\n Table[Status] = \"Reorder\", \"#FFFF00\",\n Table[Status] = \"Ideal\", \"#00FF00\",\n Table[Status] = \"Overflow\", \"#0000FF\"\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12036505/"
] |
74,299,241 | <p>I have a the following use case where I want to model accounting accounts.</p>
<p>The <strong>Accounts</strong> can be</p>
<ul>
<li>External if they are assigned to a client.</li>
<li>Internal if they are not assigned to a client.</li>
</ul>
<p>There must exist a many to many relation bewteen external and internal accounts, where one external account can be mapped to one internal account and one internal account can be mapped to many external accounts.</p>
<p>The accounts whether they are external or internal should have the same columns, except for the external that should have a clientId foreign key.</p>
<p>Should I create?</p>
<p><strong>Option A</strong>: 2 tables for accounts (ExternalAccount, InternalAccount) and 1 table for the mapping (AccountMapping)</p>
<p>or</p>
<p><strong>Option B</strong>: 1 table for accounts (Account) and 1 table for the mapping (AccountMapping)? external accounts would have clientId defined, and internal would have clientId=NULL</p>
<p>With option A, it's easier to restrict the mapping in the AccountMapping table, any of the foreign keys refers to a different table and entity.</p>
<p>With option B, how could I restrict in the AccountMapping table that 2 external accounts cannot be linked together?</p>
| [
{
"answer_id": 74299444,
"author": "StefanR",
"author_id": 3584153,
"author_profile": "https://Stackoverflow.com/users/3584153",
"pm_score": 0,
"selected": false,
"text": "ID | Name | External | ForeignKeys\n1 | Internal Account | 0 | NULL\n2 | External Acccount | 1 | 1\n"
},
{
"answer_id": 74301191,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT\n a.ACC_ID, a.ACC_TYPE, \n c.CUST_ID \"CUST_ID\", c.CUST_NAME \"CUST_NAME\",\n CASE WHEN a.CUST_ID Is Null THEN Null ELSE al1.ACC_ID_INT END \"ACC_ID_INT\"\nFROM\n ACCOUNTS a\nLEFT JOIN\n ACCOUNTS_LINKS al1 ON(\n (al1.ACC_ID_EXT = a.ACC_ID And ACC_TYPE = 'EXTERNAL')\n OR\n (al1.ACC_ID_INT = a.ACC_ID And ACC_TYPE = 'INTERNAL')\n )\nLEFT JOIN\n CUSTOMERS c ON(c.CUST_ID = a.CUST_ID)\nORDER BY \n a.ACC_ID, c.CUST_ID\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18710793/"
] |
74,299,254 | <p>it's easier to explain what I want to do if you look at the code first but essentially I think I want to use lapply on a condition but I wasn't able to do it.</p>
<pre><code>library("tidyverse")
names <- rep(c("City A", "City B"), each = 11)
year <- rep(c(2010:2020), times = 2)
col_1 <- c(1, 17, 34, 788, 3, 4, 78, 98, 650, 45, 20,
23, 45, 56, 877, 54, 12, 109, 167, 12, 19, 908)
col_2 <- c(3, 4, 23, 433, 2, 45, 34, 123, 98, 76, 342,
760, 123, 145, 892, 23, 5, 90, 40, 12, 67, 98)
df <- as.data.frame(cbind(names, year, col_1, col_2))
df <- df %>%
mutate(col_1 = as.numeric(col_1),
col_2 = as.numeric(col_2))
</code></pre>
<p>I want every numeric column in the year 2018 and later to be rounded with round_any to a value which is a multiple of three (plyr::round_any, 3)
What I tried is this:</p>
<pre><code>df_2018 <- df %>%
filter(year >= 2018)
df <- df %>%
filter(!(year >= 2018))
df_2018[, c(3:4)] <- lapply(df_2018[, c(3:4)], plyr::round_any, 3)
df <- rbind(df, df_2018)
</code></pre>
<p>In reality, there's about 50 numeric columns and tons of rows. What I tried works in theory but I would like to achieve it with less code and cleaner.
I am new to using lapply and I failed trying to combine it with an ifelse because I don't want it to change my year column.</p>
<p>Thank you for everyone who takes the time out of their day to look at this :)</p>
| [
{
"answer_id": 74299767,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 3,
"selected": true,
"text": "dplyr::across"
},
{
"answer_id": 74300032,
"author": "det",
"author_id": 12148402,
"author_profile": "https://Stackoverflow.com/users/12148402",
"pm_score": 0,
"selected": false,
"text": "data.table"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16074941/"
] |
74,299,262 | <p>My Scenario is to filter out the records which are having the value "RED" in any of the column</p>
<p>For eg: table name : Colors</p>
<pre><code>ID Col1 Col2 Col3
1 BLUE RED YELLOW
2 RED GREEN PINK
3 YELLOW BLACK BLUE
4 WHITE GREY RED
</code></pre>
<p>I have to retrieve the records 1,2,4 because they have RED in at least one of its column. I tried below query for the 3-column table</p>
<pre><code>Select * from Colors
where Col1= 'RED' or Col2= 'RED' or Col3 ='RED'
</code></pre>
<p>But what if i have 100+ columns in the table Colors. Is there any other way to filter for this condition?</p>
| [
{
"answer_id": 74299767,
"author": "stefan",
"author_id": 12993861,
"author_profile": "https://Stackoverflow.com/users/12993861",
"pm_score": 3,
"selected": true,
"text": "dplyr::across"
},
{
"answer_id": 74300032,
"author": "det",
"author_id": 12148402,
"author_profile": "https://Stackoverflow.com/users/12148402",
"pm_score": 0,
"selected": false,
"text": "data.table"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11781901/"
] |
74,299,265 | <pre><code>def Pythagorean_Triplets(N) :
c = 4
m = 2
while c < N :
for n in range(1, m) :
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
if c > N :
break
print([a, b, c])
m = m + 1
N = int(input("\nEnter the value of N uptil which you want to get the Pythagorean Triplets: "))
print(f"\nPythagorean Triplets uptil {N} are: ")
Pythagorean_Triplets(N)
</code></pre>
<h1>Output as per my code</h1>
<pre><code>Enter the value of N uptil which you want to get the Pythagorean Triplets: 20
Pythagorean Triplets uptil 20 are:
[3, 4, 5]
[8, 6, 10]
[5, 12, 13]
[15, 8, 17]
[12, 16, 20]
</code></pre>
<p>How to get an output in the below-mentioned format, with serial numbers in words for every list of output?</p>
<h1>Required Output</h1>
<pre><code>Enter the value of N uptil which you want to get the Pythagorean Triplets: 20
Pythagorean Triplets uptil 20 are:
First list : [3, 4, 5]
Second list : [8, 6, 10]
Third list : [5, 12, 13]
Fourth list : [15, 8, 17]
Fifth list : [12, 16, 20]
</code></pre>
<p>and so on depending upon output.</p>
| [
{
"answer_id": 74299400,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 0,
"selected": false,
"text": "First"
},
{
"answer_id": 74299406,
"author": "Giuseppe La Gualano",
"author_id": 20249888,
"author_profile": "https://Stackoverflow.com/users/20249888",
"pm_score": 1,
"selected": false,
"text": "pip install num2words\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19748912/"
] |
74,299,267 | <p>I am having two application one written in java where required to zip string of data and other in golang and required to unzip the record zipped by first application</p>
<p><strong>Java program to Creating Zipped of string data</strong></p>
<pre><code>public static byte[] createZipForLicenses(String string) throws UnsupportedEncodingException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);
try {
if (string != null && string.length() > 0) {
ZipEntry zipEntry = new ZipEntry("data");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(string.getBytes("UTF-8"));
zipOutputStream.closeEntry();
}
zipOutputStream.close();
} catch (IOException e) {
}
return outputStream.toByteArray();
}
</code></pre>
<p><strong>Golang program to unzip the string data</strong></p>
<p>func Unzip(data []byte) (string, error) {</p>
<pre><code>rdata := bytes.NewReader(data)
r, err := zlib.NewReader(rdata) //**Error**-> "zlib: invalid header
if err != nil {
return "", err
}
s, err := io.ReadAll(r)
if err != nil {
return "", err
}
return string(s), nil
</code></pre>
<p>}</p>
<p>I tried using compress/flate lib also but with this getting error "flate: corrupt input before offset 5"</p>
| [
{
"answer_id": 74299421,
"author": "oleg.cherednik",
"author_id": 3461397,
"author_profile": "https://Stackoverflow.com/users/3461397",
"pm_score": -1,
"selected": false,
"text": "public static byte[] createZipForLicenses(String string) throws IOException {\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n ZipOutputStream zipOutputStream = new ZipOutputStream(out);\n zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);\n\n if (string != null && string.length() > 0) {\n ZipEntry zipEntry = new ZipEntry(\"data\");\n zipOutputStream.putNextEntry(zipEntry);\n zipOutputStream.write(string.getBytes(\"UTF-8\"));\n zipOutputStream.closeEntry();\n }\n\n zipOutputStream.close();\n\n return out.toByteArray();\n}\n"
},
{
"answer_id": 74489327,
"author": "Raju Yadav",
"author_id": 5996120,
"author_profile": "https://Stackoverflow.com/users/5996120",
"pm_score": 1,
"selected": false,
"text": "func Unzip(data []byte) (string, error) {\nzipReader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))\nif err != nil {\n panic(err)\n}\nif len(zipReader.File) == 0 {\n return \"\", nil // No file to open / extract\n}\nf, err := zipReader.File[0].Open()\nif err != nil {\n panic(err)\n}\np, err := ioutil.ReadAll(f)\nif err != nil {\n return \"\", err\n}\nreturn string(p), nil\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5996120/"
] |
74,299,280 | <p>One of my api response with boolean(with the name: <code>used</code>), my logic is if the response is used will show <code>red_light</code> and <code>green_light</code> if not used.</p>
<pre><code>const red_light = <div className="h-2.5 w-2.5 rounded-full bg-red-700 mr-2"></div>
const green_light = <div className="h-2.5 w-2.5 rounded-full bg-green-400 mr-2"></div>
function lighting(code) {
fetch(`API`)
.then((response) => {
if (!response.ok) {
throw new Error(
`This is an HTTP error: The status is ${response.status}`
);
}
return response.json();
})
.then((actualData) => {
return (actualData.used ? red_light : green_light)
})}
const MembershipLight = (code) => {
return (
lighting(code)
);
};
export default MembershipLight;
</code></pre>
<p>but the page gone blank, which part i am doing wrong?</p>
<p>i try to <code>console.log</code> with the <code>actualData</code>, it shows the whole part of the response including <code>used</code> with <code>true</code>/<code>false</code>, but when i <code>console.log("actualData.used")</code>, it shows <code>undefined</code> in the console.</p>
<p><code>actureData</code> (from postman)</p>
<pre><code>[
{
"used": true,
"create_date": "1644490502",
"update_date": "1666694655"
}
]
</code></pre>
| [
{
"answer_id": 74299343,
"author": "zhulien",
"author_id": 8412959,
"author_profile": "https://Stackoverflow.com/users/8412959",
"pm_score": 0,
"selected": false,
"text": "lighting"
},
{
"answer_id": 74299416,
"author": "lpizzinidev",
"author_id": 13211263,
"author_profile": "https://Stackoverflow.com/users/13211263",
"pm_score": 2,
"selected": false,
"text": "used"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13678307/"
] |
74,299,282 | <pre><code>#li = [1,1,2,2,4,4,4,7,5,5]
#dict_index = [1,2,3,4,5,6,7,8,9,10]
to make this▽
make_dict = {1:[2],2:[3,4],3:[x],4:[5,6,7],5:[9,10],6:[x],7:[8],8:[x],9:[x],10:[x]}
</code></pre>
<p>I want to make a "make_dict" like the one below by referring to "li" and "dict_index"...
It seems like a tree of data structures.
How can I solve this..?</p>
<pre><code>
</code></pre>
<p><img src="https://i.stack.imgur.com/nzyYH.png" alt="make_dict(Tree)" title="Tree" /></p>
| [
{
"answer_id": 74299464,
"author": "thestarwarsnerd",
"author_id": 18931013,
"author_profile": "https://Stackoverflow.com/users/18931013",
"pm_score": 1,
"selected": false,
"text": "dict_index"
},
{
"answer_id": 74299576,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "li"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404845/"
] |
74,299,288 | <p>For example, method <code>switchCase()</code>. How do I write test code for it? I can just create 3 different tests just with different values for each test, respective to the switch case value, but I want to try a more efficient way of doing this.</p>
<pre><code> @InjectMocks
private RepoFactory repoFactory;
</code></pre>
<pre><code> public void switchCase() {
ConsentApplication consentApplication = repoFactory.getConsentApplicationRepo()
.findOne(consentApplicationVo.getId());
switch (CrestApiServiceNameEnum.getByCode(serviceNameEnum.getCode())) {
case CUST_DATA:
newCrestApiTrack.setRepRefNo(null);
httpHeaders.add("API-KEY", custDataApiKey);
break;
case CREDIT_PARAM:
httpHeaders.add("API-KEY", creditParamApiKey);
break;
case CONFIRM_MUL_ENT:
httpHeaders.add("API-KEY", multiEntitiApiKey);
break;
default:
LOGGER.info("Unexpected value: " + CrestApiServiceNameEnum.getByCode(serviceNameEnum.getCode()));
}
}
</code></pre>
<p>What I tried was, using <code>@RunWith(JUnitParamsRunner.class)</code>, <code>@ValueSource</code> and <code>@ParameterizedTest</code>. However, this always produces <code>NullPointerException</code> at the first <code>when</code> and <code>java.lang.Exception: Method testSwitchCase_SUCCESS should have no parameters</code>. Can help me on this?</p>
<pre><code>
@ParameterizedTest
@ValueSource(strings = {"value1", "value2"})
void testSwitchCase_SUCCESS(String s) {
//have something
when(repoFactory.getConsentApplicationRepo().findOne(anyString()))
.thenReturn(consentApplication);
}
</code></pre>
| [
{
"answer_id": 74299464,
"author": "thestarwarsnerd",
"author_id": 18931013,
"author_profile": "https://Stackoverflow.com/users/18931013",
"pm_score": 1,
"selected": false,
"text": "dict_index"
},
{
"answer_id": 74299576,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "li"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14144231/"
] |
74,299,325 | <p>I have 2 different tables data has <code>order_id</code> and I want to sort it in laravel blade foreach.</p>
<p>My Controller:</p>
<pre><code>$questions = Question::where('quiz_id', $quiz->id)->orderBy('order_id', 'asc')->get();
$explanations = Explanations::where('quiz_id', $quiz->id)->orderBy('order_id', 'asc')->get();
</code></pre>
<p>My Blade: (I want to sort this 2 foreach by order_id)</p>
<pre><code>@foreach($questions as $question)
<p>{{$question->title}}</p>
@endforeach
@foreach($explanations as $explanation)
<p>{{$explanation->title}}</p>
@endforeach
</code></pre>
<p>My Result:</p>
<pre><code><p>First Question</p> //order_id: 1
<p>Second Question Question</p> //order_id: 3
<p>First Explanation</p> //order_id: 2
<p>SecondExplanation</p> //order_id: 4
</code></pre>
<p>Result I Want:</p>
<pre><code> <p>First Question</p> //order_id: 1
<p>First Explanation</p> //order_id: 2
<p>Second Question</p> //order_id: 3
<p>Second Explanation</p> //order_id: 4
</code></pre>
| [
{
"answer_id": 74299464,
"author": "thestarwarsnerd",
"author_id": 18931013,
"author_profile": "https://Stackoverflow.com/users/18931013",
"pm_score": 1,
"selected": false,
"text": "dict_index"
},
{
"answer_id": 74299576,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "li"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19312269/"
] |
74,299,345 | <p>I'm using VSCode 1.72.2 with Remote-SSH v0.90.1 on Windows to develop against an AWS EC2 VM running Ubuntu 22.04 LTS. A couple days ago, I was working in my project source folder in <code>/opt/t4/</code> on the target host. When I was finished, I stopped the VM from the AWS console, forgetting that VS Code was still SSHed in.</p>
<p>When I brought the VM back up, I can reconnect VS Code/Remote-SSH to the host as before, <em>except</em> that I can no longer connect using <code>/opt/t4/</code> as my working directory. I can use any directory except the one I was using when I disconnected.</p>
<p>I can navigate down to it and work in it if I use <code>/opt/</code> as my working directory. I can navigate to it by manually SSHing to the remote host. I can create a subfolder in a remote shell at <code>/opt/t4/test/</code>, and then connect VS Code using that subfolder as my working directory. I can <em>see</em> and <em>select</em> <code>/opt/t4/</code> in the Open Folder dialog in VS Code. But when I try to connect using that working directory, the connection times out with a not-particularly-useful error message:</p>
<pre><code>[00:05:49.867] SSH Resolver called for "ssh-remote+my.remote.host", attempt 2, (Reconnection)
[00:05:49.868] SSH Resolver called for host: my.remote.host
[00:05:49.868] Setting up SSH remote "my.remote.host"
[00:05:49.870] Using commit id "d045a5eda657f4d7b676dedbfa7aab8207f8a075" and quality "stable" for server
[00:05:49.872] Install and start server if needed
[00:05:49.874] Using SSH config file "C:\Users\me\.ssh\config"
[00:05:49.874] Running script with connection command: ssh -T -D 1518 -F "C:\Users\me\.ssh\config" "my.remote.host" bash
[00:05:49.875] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[00:06:06.876] Resolver error: Error: Connecting with SSH timed out
at g.Timeout (c:\Users\me\.vscode\extensions\ms-vscode-remote.remote-ssh-0.90.1\out\extension.js:1:585348)
at Timeout._onTimeout (c:\Users\me\.vscode\extensions\ms-vscode-remote.remote-ssh-0.90.1\out\extension.js:1:679743)
at listOnTimeout (node:internal/timers:559:17)
at process.processTimers (node:internal/timers:502:7)
[00:06:06.877] ------
</code></pre>
<ul>
<li>I tried <code>Remote-SSH: Uninstall VS Code Server from Host</code> from VS Code.</li>
<li>I tried deleting <code>~/.vscode-server</code> on the Linux host from an SSH session.</li>
<li>I tried <code>Remote-SSH: Kill VS Code Server on Host</code> from VS Code.</li>
<li>I tried <code>Remote-SSH: Kill Local Connection Server for Host</code> from VS Code.</li>
<li>I tried deleting and recreating the host connection details in the local config file from SSH-Remote.</li>
<li>I tried rebooting both local and target hosts.</li>
<li>I tried setting <code>/opt/</code> as my working dir, then deleting and recreating <code>/opt/t4</code>. I <em>was</em> able to do this, but as soon as I try reconnecting using <code>/opt/t4</code> as the working dir, VS Code still fails to connect.</li>
</ul>
<p>I'm... stumped. My suspicion is that there is something corrupt cached Windows-side, but I don't know where to look for that.</p>
| [
{
"answer_id": 74299464,
"author": "thestarwarsnerd",
"author_id": 18931013,
"author_profile": "https://Stackoverflow.com/users/18931013",
"pm_score": 1,
"selected": false,
"text": "dict_index"
},
{
"answer_id": 74299576,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "li"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4820910/"
] |
74,299,351 | <p>I have the following object:</p>
<pre><code>const obj = {
A: [{
capacity: 100
}, {
capacity: 100
}, {
capacity: 100
}],
B: [{
capacity: 500
}, {
capacity: 500
}, {
capacity: 500
}],
C: [{
capacity: 300
}, {
capacity: 300
}, {
capacity: 300
}]
}
</code></pre>
<p>I need to transform to an object with the same shape but with the keys sorted by capacity. To note, the capacity of each object in the arrays (A, B, C) is always the same within the same object. So we can take the first occurrence for example</p>
<p>Expected result:</p>
<pre><code>const obj = {
A: [{
capacity: 100
}, {
capacity: 100
}, {
capacity: 100
}],
C: [{
capacity: 300
}, {
capacity: 300
}, {
capacity: 300
}],
B: [{
capacity: 500
}, {
capacity: 500
}, {
capacity: 500
}]
}
</code></pre>
<p>None of my approaches worked out. An example:</p>
<pre><code>const sortByPosition = obj => {
const order = [], res = {};
Object.keys(obj).forEach(key => {
return order[obj[key][1]['capacity'] - 1] = key;
});
order.forEach(key => {
res[key] = obj[key];
});
return res;
}
console.log(sortByPosition(obj));
</code></pre>
<p>Here's a <a href="https://jsfiddle.net/Fmcg/0px35kq1/" rel="nofollow noreferrer">fiddle</a></p>
| [
{
"answer_id": 74299394,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 3,
"selected": true,
"text": "const obj = {\n A: [ { capacity: 100 }, { capacity: 100 }, { capacity: 100 } ],\n B: [ { capacity: 500 }, { capacity: 500 }, { capacity: 500 } ],\n C: [ { capacity: 300 }, { capacity: 300 }, { capacity: 300 } ]\n};\n\nconsole.log(Object.fromEntries(Object.entries(obj)\n .sort(([i,a],[j,b])=>a[0].capacity-b[0].capacity)));"
},
{
"answer_id": 74299840,
"author": "talent-jsdev",
"author_id": 15087608,
"author_profile": "https://Stackoverflow.com/users/15087608",
"pm_score": 1,
"selected": false,
"text": "const sortByPosition = obj => {\n let sortable = [];\n let objSorted = {};\n \n for (let key in obj) {\n sortable.push([key, obj[key]]);\n }\n\n sortable.sort(function(a, b) {\n return a[1][0].capacity - b[1][0].capacity;\n });\n \n \n sortable.forEach(function(item){\n objSorted[item[0]] = item[1]\n })\n \n return objSorted;\n}\n\nconsole.log(sortByPosition(obj));\nconsole.log(Object.keys(sortByPosition(obj)));\nconsole.log(Object.keys(obj));\n"
},
{
"answer_id": 74334547,
"author": "Hitmands",
"author_id": 4099454,
"author_profile": "https://Stackoverflow.com/users/4099454",
"pm_score": 1,
"selected": false,
"text": "Pair[]"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10132040/"
] |
74,299,370 | <p>I want to include Google Maps in an ionic capacitor angular project so I followed their <a href="https://capacitorjs.com/docs/apis/google-maps" rel="nofollow noreferrer">documentation</a> to do so. But when I build I get the following error:</p>
<pre><code>Error: node_modules/@capacitor/google-maps/dist/typings/definitions.d.ts:1:23 - error TS2688: Cannot find type definition file for 'google.maps'.
[ng] 1 /// <reference types="google.maps" />
</code></pre>
<p>I searched everywhere, checked the documentation, even followed the answers in this <a href="https://stackoverflow.com/questions/51084724/types-googlemaps-index-d-ts-is-not-a-module">stack overflow question</a> none which seemed to help:</p>
<p>UPDATE:</p>
<p>package.json</p>
<pre><code>{
"name": "Project",
"version": "0.0.1",
"author": "Ionic Framework",
"homepage": "https://ionicframework.com/",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^14.2.5",
"@angular/cdk": "^14.2.4",
"@angular/common": "^14.0.0",
"@angular/core": "^14.0.0",
"@angular/forms": "^14.0.0",
"@angular/material": "^14.0.4",
"@angular/platform-browser": "^14.0.0",
"@angular/platform-browser-dynamic": "^14.0.0",
"@angular/router": "^14.0.0",
"@capacitor/android": "4.1.0",
"@capacitor/app": "^4.1.0",
"@capacitor/browser": "^4.0.1",
"@capacitor/camera": "^4.1.3",
"@capacitor/core": "^4.3.0",
"@capacitor/geolocation": "^4.0.1",
"@capacitor/google-maps": "^4.3.0",
"@capacitor/haptics": "^4.0.1",
"@capacitor/ios": "^4.3.0",
"@capacitor/keyboard": "^4.0.1",
"@capacitor/status-bar": "^4.0.1",
"@ionic-native/core": "^5.36.0",
"@ionic/angular": "^6.1.12",
"@ionic/pwa-elements": "^3.1.1",
"@ionic/storage": "^3.0.6",
"ngx-color-picker": "^13.0.0",
"rxjs": "~6.6.0",
"swiper": "^8.4.4",
"tslib": "^2.2.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^14.0.0",
"@angular-eslint/builder": "~13.0.1",
"@angular-eslint/eslint-plugin": "~13.0.1",
"@angular-eslint/eslint-plugin-template": "~13.0.1",
"@angular-eslint/template-parser": "~13.0.1",
"@angular/cli": "^14.0.0",
"@angular/compiler": "^14.0.0",
"@angular/compiler-cli": "^14.0.0",
"@angular/language-service": "^14.0.0",
"@capacitor/cli": "^4.1.0",
"@ionic/angular-toolkit": "^6.0.0",
"@ionic/lab": "3.2.13",
"@types/googlemaps": "^3.43.3",
"@types/jasmine": "~3.6.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
"@typescript-eslint/eslint-plugin": "5.3.0",
"@typescript-eslint/parser": "5.3.0",
"eslint": "^7.6.0",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jsdoc": "30.7.6",
"eslint-plugin-prefer-arrow": "1.2.2",
"jasmine-core": "~3.8.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~6.3.2",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"typescript": "~4.7.3"
},
"description": "An Ionic project"
}
</code></pre>
| [
{
"answer_id": 74299865,
"author": "Morty",
"author_id": 12189042,
"author_profile": "https://Stackoverflow.com/users/12189042",
"pm_score": 0,
"selected": false,
"text": "npm install -f\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20060542/"
] |
74,299,383 | <p>I have an API where data is structured like this:</p>
<pre><code>
{
"questions"
|
|
"question": "What is 2+2?"
"options"
|
|
"Option 1": 2
"Option 2": 6
"Option 3": 1
"question": "What is the capitol of Sweden?"
"Option 1": "Stockholm"
"Option 2": "South America"
"Option 3": "Oceania"
}
</code></pre>
<p>I want to display one question and it's alternatives at a time, then on click of a "Next"-button display the next question. The amount of questions and whatnot changes, so it has to be dynamically rendered.</p>
<p>I figured I can't do it with *ngFor as I only want to render the next one upon clicking the button so I'm a bit unsure how to do it.</p>
<p>Might be possible to figure out the length of the "questions"-array and render the next one by saving which question-index you're currently at and change to the next one by doing something like</p>
<pre><code><h2>${questions[i].question}</h2>
<p *ngFor="option of questions[i].options">${questions[i].options}</p>
</code></pre>
<p>But I'm unsure exactly how that would be implemented.</p>
| [
{
"answer_id": 74299865,
"author": "Morty",
"author_id": 12189042,
"author_profile": "https://Stackoverflow.com/users/12189042",
"pm_score": 0,
"selected": false,
"text": "npm install -f\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15785914/"
] |
74,299,397 | <p>When I use <strong>df.apply(pd.Series.str.upper)</strong> shows me an error -</p>
<p>Although <strong>df.apply(pd.Series.min)</strong> is running absolutely fine! and <strong>df.apply(lambda x: x.str.upper())</strong> is running fine too.</p>
<pre><code>df = pd.DataFrame(
{
"Name":[
"Harry","Sam", "Jack"], "Gender": ["M","M","F"]})
df.apply(pd.Series.str.lower)
</code></pre>
<pre><code>Error - Series' object has no attribute '_inferred_dtype'
</code></pre>
| [
{
"answer_id": 74299479,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 1,
"selected": false,
"text": "upper()"
},
{
"answer_id": 74299518,
"author": "Abhi",
"author_id": 7430727,
"author_profile": "https://Stackoverflow.com/users/7430727",
"pm_score": 2,
"selected": false,
"text": "pd.Series.str"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10348574/"
] |
74,299,410 | <p>I updated my Xcode to 14.1. but when I want to add a language in Setting, it stays on this page and I can't do any thing.</p>
<p>All I can do is Erase All content and Setting to return to normal state. It works on my MacBook Air M1, but no on my MacBook Pro 2019 Intel i7</p>
<p><a href="https://i.stack.imgur.com/20v32.png" rel="noreferrer"><img src="https://i.stack.imgur.com/20v32.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74621528,
"author": "Joachim Deelen",
"author_id": 3714842,
"author_profile": "https://Stackoverflow.com/users/3714842",
"pm_score": 1,
"selected": false,
"text": "simctl"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2642720/"
] |
74,299,423 | <p>i'm trying to visit multiple links from one page, and then go back to the same page.</p>
<pre><code>links = driver.find_elements(By.CSS_SELECTOR,'a')
for link in links:
link.click() # visit page
# scrape page
driver.back() # get back to previous page, and click the next link in next iteration
</code></pre>
<p>The code says it all</p>
| [
{
"answer_id": 74621528,
"author": "Joachim Deelen",
"author_id": 3714842,
"author_profile": "https://Stackoverflow.com/users/3714842",
"pm_score": 1,
"selected": false,
"text": "simctl"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405132/"
] |
74,299,426 | <p>I want to merge 2 Stirng arrays
the first one is merged okay but the second one keeps having null values even though it isn't empty
no errors just wrong values
what is the problem here?</p>
<pre><code>public class Q4 {
public static void main(String[] args){
String array1[] = new String[]{"Ahmad", "Adam"};
String array2[] = new String[]{"Mick", "Ali"};
int n1 = array1.length;
int n2 = array2.length;
String []array3 = new String[n1+n2];
for(int i = 0; i < n1; i++)
array3[i] = array1[i];
for(int i = n1; i<n2; i++) {
int j = 0;
array3[i] = array2[j++];
}
for(int i = 0; i<array3.length; i++)
System.out.print(array3[i] + " ");
}
}
</code></pre>
<p>the output should be</p>
<blockquote>
<p>Ahmad Adam Mick Ali</p>
</blockquote>
<p>but this is what I get</p>
<blockquote>
<p>Ahmad Adam null null</p>
</blockquote>
| [
{
"answer_id": 74299678,
"author": "Icarus",
"author_id": 11275562,
"author_profile": "https://Stackoverflow.com/users/11275562",
"pm_score": 0,
"selected": false,
"text": "for(int i = n1; i<n2; i++) {\n"
},
{
"answer_id": 74300149,
"author": "TANIMUL ISLAM",
"author_id": 18262004,
"author_profile": "https://Stackoverflow.com/users/18262004",
"pm_score": 3,
"selected": true,
"text": "public class Q4 {\n public static void main(String[] args){\n String array1[] = new String[]{\"Ahmad\", \"Adam\"};\n String array2[] = new String[]{\"Mick\", \"Ali\"};\n int n1 = array1.length;\n int n2 = array2.length;\n String []array3 = new String[n1+n2];\n\n for(int i = 0; i < n1; i++){\n array3[i] = array1[i];\n }\n\n for(int i = 0; i<n2; i++) {\n array3[n1++] = array2[i];\n }\n\n for(int i = 0; i<array3.length; i++)\n System.out.print(array3[i] + \" \");\n }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20050419/"
] |
74,299,457 | <p>Need to find the sequential difference and average between within a columns of two rows group by brand column and order by bill_id column and find the difference of worth column between rows in a single query.</p>
<p>I have a data</p>
<pre><code>brand bill_id worth
Moto 1 2550
Samsung 1 3430
Samsung 2 3450
Moto 2 2500
Moto 3 2530
</code></pre>
<p>Expected Output</p>
<pre><code>brand bill_id worth net_diff avg_diff
Moto 1 2550 0 00
Moto 2 2560 10 5
Moto 3 2540 -20 -5
Samsung 1 3430 0 0
Samsung 2 3450 20 10
</code></pre>
| [
{
"answer_id": 74299699,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE T (brand VARCHAR(16), bill_id INT, worth DECIMAL(16,2))\nINSERT INTO T VALUES \n('Moto', 1, 2550),\n('Samsung', 1, 3430),\n('Samsung', 2, 3450),\n('Moto', 2, 2500),\n('Moto', 3, 2530);\n"
},
{
"answer_id": 74308554,
"author": "Belayer",
"author_id": 7623856,
"author_profile": "https://Stackoverflow.com/users/7623856",
"pm_score": 0,
"selected": false,
"text": "bill_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13896398/"
] |
74,299,497 | <p>There already is <a href="https://stackoverflow.com/questions/7303948/how-to-auto-scroll-to-end-of-div-when-data-is-added">an answer for autoscrolling</a>, but that has a problem. If the user has manually scrolled it up to read old logs, that code keeps auto-scrolling, interfering the user's reading. So, I want it to auto-scroll only when it is showing the last line (i.e., either the user has never scrolled it up, or scrolled it up and then scrolled down to the bottom). How can I determine that?</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>var output;
var i = 0;
function onLoad() {
output = document.getElementById("output");
onTimeout();
}
function onTimeout() {
i++;
var line = document.createElement("div");
line.innerText = "Log " + i;
output.appendChild(line);
var isShowingTheLastLine = true;
if (isShowingTheLastLine) {
output.scrollTop = output.scrollHeight;
}
setTimeout(onTimeout, 1000);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="onLoad()">
<div id="output" style="overflow-y:scroll; height:200px; width:300px; background:yellow"></div>
</body></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74299699,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE T (brand VARCHAR(16), bill_id INT, worth DECIMAL(16,2))\nINSERT INTO T VALUES \n('Moto', 1, 2550),\n('Samsung', 1, 3430),\n('Samsung', 2, 3450),\n('Moto', 2, 2500),\n('Moto', 3, 2530);\n"
},
{
"answer_id": 74308554,
"author": "Belayer",
"author_id": 7623856,
"author_profile": "https://Stackoverflow.com/users/7623856",
"pm_score": 0,
"selected": false,
"text": "bill_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455796/"
] |
74,299,534 | <p>I have file .csv file, I read all files together using <code>tidyverse</code> library. Now if I want to write the file then all file merged in to one file. How Can I write files separately?</p>
<pre><code>library(tidyverse)
df <-
list.files(path = "D:/Data file", pattern = "*.csv") %>%
map_df(~read_csv(.))
library(zoo)
df$PAHs <- na.approx(df[,3])
</code></pre>
<p>that the data after I multiple uploads, did interpolation then write it
on the other hand the files did not comes as serial maintained, like
After A1, A10, A9, A2 like this</p>
<pre><code>structure(list(X = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L,
24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L,
37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L,
50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L,
63L, 24567L, 24568L, 24569L, 24570L, 24571L, 24572L, 24573L),
Station = c("A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "B9", "B9", "B9", "B9", "B9",
"B9", "B9"), Depth.m. = c(3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L,
23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L,
35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L,
47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L,
59L, 60L, 61L, 62L, 63L, 64L, 65L, 1494L, 1495L, 1496L, 1497L,
1498L, 1499L, 1500L), PAHs = c(25, 25, 25, 25, 25, 25, 25,
25, 24.93333333, 24.86666667, 24.8, 24.73333333, 24.66666667,
24.6, 24.53333333, 24.46666667, 24.4, 24.33333333, 24.26666667,
24.2, 24.13333333, 24.06666667, 24, 23.88, 23.76, 23.64,
23.52, 23.4, 23.28, 23.16, 23.04, 22.92, 22.8, 22.68, 22.56,
22.44, 22.32, 22.2, 22.08, 21.96, 21.84, 21.72, 21.6, 21.48,
21.36, 21.24, 21.12, 21, 20.93333333, 20.86666667, 20.8,
20.73333333, 20.66666667, 20.6, 20.53333333, 20.46666667,
20.4, 20.33333333, 20.26666667, 20.2, 20.13333333, 20.06666667,
20, 5.3804, 5.367, 5.3536, 5.3402, 5.3268, 5.3134, 5.3)), class = "data.frame", row.names = c(NA,
-70L))
</code></pre>
<p>There are more data like A1, A2, A3, A4,....., B1, B2,.....C1...
but for word limitation I am showing A1 & B9</p>
| [
{
"answer_id": 74299699,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE T (brand VARCHAR(16), bill_id INT, worth DECIMAL(16,2))\nINSERT INTO T VALUES \n('Moto', 1, 2550),\n('Samsung', 1, 3430),\n('Samsung', 2, 3450),\n('Moto', 2, 2500),\n('Moto', 3, 2530);\n"
},
{
"answer_id": 74308554,
"author": "Belayer",
"author_id": 7623856,
"author_profile": "https://Stackoverflow.com/users/7623856",
"pm_score": 0,
"selected": false,
"text": "bill_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14711964/"
] |
74,299,542 | <p>I have given a string <strong>"my1kiran4name2is3"</strong> and my expected output is <strong>"my name is kiran"</strong></p>
<p>Explanation1</p>
<pre><code>my - 1
kiran - 4
name - 2
is - 3
</code></pre>
<p>I have to arrange the words based on the numbers.
the string only contains numbers from 1 to 9.</p>
<p>So my output is <strong>"my name is kiran"</strong></p>
<p>been trying to solve this problem from past two days but not finding any way just started learning java, any kind of help would be appreciated.</p>
| [
{
"answer_id": 74299719,
"author": "YCF_L",
"author_id": 5558072,
"author_profile": "https://Stackoverflow.com/users/5558072",
"pm_score": 1,
"selected": true,
"text": "StringBuilder"
},
{
"answer_id": 74300354,
"author": "S8Z",
"author_id": 16414510,
"author_profile": "https://Stackoverflow.com/users/16414510",
"pm_score": 1,
"selected": false,
"text": " String string = \"my1kiran4name2is3\";\n Map<Integer, String> map =\n Arrays.asList(string\n .split(\"(?<=\\\\d)\"))\n .stream()\n .map(s -> s.split(\"(?=\\\\d)\"))\n .collect(Collectors.toMap((e -> Integer.parseInt(e[1])), e -> e[0]));\n string = map\n .values()\n .stream()\n .collect((Collectors.joining(\" \")));\n System.out.println(string);\n"
},
{
"answer_id": 74300537,
"author": "Maurice Perry",
"author_id": 7036419,
"author_profile": "https://Stackoverflow.com/users/7036419",
"pm_score": 1,
"selected": false,
"text": " Pattern re = Pattern.compile(\"([^0-9]+)([0-9]+)\");\n String input = \"my1kiran4name2is3\";\n Map<Integer,String> words = new TreeMap<>();\n Matcher matcher = re.matcher(input);\n while (matcher.find()) {\n words.put(Integer.valueOf(matcher.group(2)), matcher.group(1));\n }\n String output = String.join(\" \", words.values());\n System.out.println(output);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337068/"
] |
74,299,545 | <p>I am implementing a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-create-iterate-pattern-section.html" rel="nofollow noreferrer">choice loop</a> within a Step Function and am trying to create some safety mechanism to prevent too many loops accidentally occurring. In the docs they suggest creating a Lambda to update an iteration/count:</p>
<pre class="lang-js prettyprint-override"><code> let index = event.iterator.index
let step = event.iterator.step
let count = event.iterator.count
index = index + step
</code></pre>
<p>I was wondering if there was a way to dynamically update a counter within the Step Function, and avoid the need for an additional Lambda?</p>
| [
{
"answer_id": 74299815,
"author": "fedonev",
"author_id": 1103511,
"author_profile": "https://Stackoverflow.com/users/1103511",
"pm_score": 2,
"selected": true,
"text": "\"counter.$\": \"States.MathAdd($.counter, 1)\"\n"
},
{
"answer_id": 74301889,
"author": "JimmyTheCode",
"author_id": 11664580,
"author_profile": "https://Stackoverflow.com/users/11664580",
"pm_score": 0,
"selected": false,
"text": "{\n \"Comment\": \"A description of my state machine\",\n \"StartAt\": \"Initial Pass\",\n \"States\": {\n \"Initial Pass\": {\n \"Type\": \"Pass\",\n \"Next\": \"Choice\",\n \"Parameters\": {\n \"payload.$\": \"$.payload\",\n \"safetyCount.$\": \"States.MathAdd($.safetyCount, 1)\"\n }\n },\n \"Choice\": {\n \"Type\": \"Choice\",\n \"Choices\": [\n {\n \"Variable\": \"$.safetyCount\",\n \"NumericLessThan\": 3,\n \"Next\": \"Wait\"\n }\n ],\n \"Default\": \"End Pass\"\n },\n \"Wait\": {\n \"Type\": \"Wait\",\n \"Seconds\": 5,\n \"Next\": \"Initial Pass\"\n },\n \"End Pass\": {\n \"Type\": \"Pass\",\n \"End\": true\n }\n }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11664580/"
] |
74,299,592 | <p>Dears,</p>
<p>How to add copy/paste menu in an Entery using Python/PySimpleGUI?
Bellow is and example where I want to add "Copy/Paste" menu for copying inputtext enteries to clipboard and paste it somewhere else :</p>
<pre><code>import PySimpleGUI as sg
layout = [
[sg.Text('UserName:', size=(15,1)), sg.InputText(default_text='',key='USERNAME',size=(15,1))],
[sg.Text('Password:', size=(15,1)), sg.InputText(default_text='',key='PASSWORD',size=(15,1))],
[sg.Button('Exit', bind_return_key=True)],
]
window = sg.Window('Copy/Paste', layout, element_justification='c')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == 'Exit':
user_text = values[0]
print(user_text)
window.close()
</code></pre>
<p>Thanks in advance</p>
| [
{
"answer_id": 74299815,
"author": "fedonev",
"author_id": 1103511,
"author_profile": "https://Stackoverflow.com/users/1103511",
"pm_score": 2,
"selected": true,
"text": "\"counter.$\": \"States.MathAdd($.counter, 1)\"\n"
},
{
"answer_id": 74301889,
"author": "JimmyTheCode",
"author_id": 11664580,
"author_profile": "https://Stackoverflow.com/users/11664580",
"pm_score": 0,
"selected": false,
"text": "{\n \"Comment\": \"A description of my state machine\",\n \"StartAt\": \"Initial Pass\",\n \"States\": {\n \"Initial Pass\": {\n \"Type\": \"Pass\",\n \"Next\": \"Choice\",\n \"Parameters\": {\n \"payload.$\": \"$.payload\",\n \"safetyCount.$\": \"States.MathAdd($.safetyCount, 1)\"\n }\n },\n \"Choice\": {\n \"Type\": \"Choice\",\n \"Choices\": [\n {\n \"Variable\": \"$.safetyCount\",\n \"NumericLessThan\": 3,\n \"Next\": \"Wait\"\n }\n ],\n \"Default\": \"End Pass\"\n },\n \"Wait\": {\n \"Type\": \"Wait\",\n \"Seconds\": 5,\n \"Next\": \"Initial Pass\"\n },\n \"End Pass\": {\n \"Type\": \"Pass\",\n \"End\": true\n }\n }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301481/"
] |
74,299,596 | <p>If we have structure with flexible member array like :-</p>
<pre><code>struct test{
int n;
int b[];
};
</code></pre>
<p>Then even before malloc is done, If we try to print like :-</p>
<pre><code>struct test t;
printf("%lu",sizeof(t.b[0]);
</code></pre>
<p>Does this fall under Undefined behaviour?</p>
<p>C99 says this about flexible member arrays :-</p>
<blockquote>
<p>"If this array would have no elements, it behaves as if
it had one element but the behaviour is undefined if any attempt is made to access that
element or to generate a pointer one past it."</p>
</blockquote>
<p>So accessing <code>b[0]</code> is undefined behaviour but will it apply to sizeof operator too given it is compile-time operator and <code>t.b[0]</code> is never accessed here at runtime?</p>
<p>When I tried this in gcc compiler, I have output as 4 bytes but if it falls under undefined behaviour, then we cannot take this output for granted until and unless gcc has given some extension which I am not sure in this case.</p>
| [
{
"answer_id": 74299729,
"author": "Sourav Ghosh",
"author_id": 2173917,
"author_profile": "https://Stackoverflow.com/users/2173917",
"pm_score": 3,
"selected": false,
"text": "sizeof"
},
{
"answer_id": 74299732,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "sizeof"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6223341/"
] |
74,299,641 | <p>I have this array of objects with nested objects "children".. the number of nested children arrays that can be is not defined</p>
<pre><code>let a = [
{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] },
{ id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] },
{ id: 5, title: 'c', children: [] },
{ id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },
]
</code></pre>
<p>and I need foreach them, take to the array.. with level of nested:</p>
<pre><code>let b = [
{ id: 0, title: 'a', level: 0 },
{ id: 1, title: 'aa', level: 1 },
{ id: 2, title: 'aaa', level: 2 },
{ id: 3, title: 'b', level: 0 },
{ id: 4, title: 'bb', level: 1 },
{ id: 5, title: 'c', level: 0 },
{ id: 6, title: 'd', level: 0 },
{ id: 7, title: 'dd', level: 1 },
{ id: 8, title: 'ddd', level: 2 },
]
</code></pre>
<p>I tired recursively code, but its not working.. thank for help</p>
| [
{
"answer_id": 74299729,
"author": "Sourav Ghosh",
"author_id": 2173917,
"author_profile": "https://Stackoverflow.com/users/2173917",
"pm_score": 3,
"selected": false,
"text": "sizeof"
},
{
"answer_id": 74299732,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "sizeof"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20302089/"
] |
74,299,658 | <p>Following other answers, it seems that the recommended way of building dynamic query is to use fragments in this manner:</p>
<pre><code>const series1Q = gql`
fragment series1 on timeseriesDataQuery {
series1: timeseriesData(sourceId: "source1") {
data {
time
value
}
}
}
}
const series2Q = gql`
fragment series2 on timeseriesDataQuery {
series2: timeseriesData(sourceId: "source2") {
data {
time
value
}
}
}
}
</code></pre>
<p>And joining them with:</p>
<pre><code>export const mainQuery = gql`
query fetchData {
...series1
...series2
}
${series1Q}
${series2Q}
`
</code></pre>
<p>However in my case, I do not know the number of items as the user can add a number of item to it so I end up with an array eg,</p>
<pre><code>const series =
[
gql`
fragment series1 on timeseriesDataQuery {
series1: timeseriesData(sourceId: "source1") {
data {
time
value
}
}
}
`,
gql`
fragment series2 on timeseriesDataQuery {
series2: timeseriesData(sourceId: "source2") {
data {
time
value
}
}
}
`
]
</code></pre>
<p>I cant seem to join them in the gql func, have tried different ways eg,</p>
<pre><code>export const mainQuery = gql`
${...series}
query fetchData {
...series1
...series2
}
`
</code></pre>
<p>or</p>
<pre><code>export const mainQuery = gql`
{...series}
query fetchData {
...series1
...series2
}
`
</code></pre>
<p>and all seems to be in the wrong format,</p>
<p>CodeSandbox: <a href="https://codesandbox.io/s/compassionate-germain-hs16ti?file=/src/App.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/compassionate-germain-hs16ti?file=/src/App.tsx</a></p>
<p>Have anyone managed to create a dynamic query from array?</p>
| [
{
"answer_id": 74299729,
"author": "Sourav Ghosh",
"author_id": 2173917,
"author_profile": "https://Stackoverflow.com/users/2173917",
"pm_score": 3,
"selected": false,
"text": "sizeof"
},
{
"answer_id": 74299732,
"author": "Lundin",
"author_id": 584518,
"author_profile": "https://Stackoverflow.com/users/584518",
"pm_score": 2,
"selected": false,
"text": "sizeof"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2442424/"
] |
74,299,677 | <p>thanks for helping me out. I can't create new column in a dataframe.</p>
<p>So far I have tried using lambdas, isin method, contains method.</p>
<p>I have a dataframe with these values (first two columns are dtype = object, Column c is what i want to get):</p>
<pre><code>Country code| Countries || Column c |
KR | KR~CN_SG~PH || Valid |
RO | CN~PK || Invalid |
NL | CZ_BE~NL_IT~DE || Valid |
SG | HK~SK_DZ_AL_CN_GR_RU~SA~SG || Valid |
US | ZA~SE~ES~CH_UA || Invalid |
</code></pre>
<p>Valid - When Country Code is in Countries</p>
<p>Invalid - When it isn't</p>
<p>This is my first time doing code at my first Python job, sorry if this is stupid question :D</p>
| [
{
"answer_id": 74299742,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "numpy.where"
},
{
"answer_id": 74299786,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "df['Column c'] = ['Valid' if x in l else 'Invalid'\n for x, l in zip(df['Country code'], df['Countries'])]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398258/"
] |
74,299,708 | <p>We have the following dummy dataframe that scrapes many messages:</p>
<pre><code>temp = pd.DataFrame(np.array([['I am feeling very well',],['It is hard to believe this happened',],
['What is love?',], ['Amazing day today',]]),
columns = ['message',])
</code></pre>
<p>Output:</p>
<pre><code> message
0 I hate the weather today
1 It is hard to believe this happened
2 What is love
3 Amazing day today
</code></pre>
<p>I iterate through each individual message in order to extract the sentiment from them</p>
<pre><code>for i in temp.message:
x = model.predict(i, 'roberta')
</code></pre>
<p>where <strong>x</strong> is a dictionary of the form:</p>
<pre><code>x = {
"Love" : 0.0931,
"Hate" : 0.9169,
}
</code></pre>
<p>How can I add all of the values in the dictionary to the data frame while iterating through each?</p>
<pre><code>for i in temp.message:
x = model.predict(i, 'roberta')
y = pd.DataFrame.from_dict(x,orient='index')
y = y.T
# what would the next step be?
</code></pre>
<p>Maybe creating the columns with null values and then creating a left join on every iteration on the message column would be a plausible solution? What would be most optimal?</p>
<p>Expected output:</p>
<pre><code> message Love Hate
0 I hate the weather today 0.0931 0.9169
1 It is hard to believe this happened 0.444 0.556
...
</code></pre>
| [
{
"answer_id": 74299832,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "df = temp.join(pd.json_normalize([model.predict(i, 'roberta')\n for i in temp.message]))\n\n# OR\ndf = temp.join(pd.DataFrame([model.predict(i, 'roberta')\n for i in temp.message]))\n"
},
{
"answer_id": 74299857,
"author": "Ranjgith Sivakumar",
"author_id": 15922255,
"author_profile": "https://Stackoverflow.com/users/15922255",
"pm_score": 1,
"selected": false,
"text": "np.NaN"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8972207/"
] |
74,299,780 | <p>Below is my code.</p>
<pre><code>import requests
import re
import pandas as pd
from bs4 import BeautifulSoup
r = requests.get("https://www.gutenberg.org/browse/scores/top")
soup = BeautifulSoup(r.content,"lxml")
List1 = soup.find_all('ol')
List1
newlist = []
for List in List1:
ulList = List.find_all('li')
extend_list = []
for li in ulList:
#extend_list = []
for link in li.find_all('a'):
a = link.get_text()
print(a)
</code></pre>
<p>my output is</p>
<p><a href="https://i.stack.imgur.com/6ryNx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6ryNx.png" alt="enter image description here" /></a></p>
<ol>
<li><p>I want to convert the output into list of list</p>
<pre><code>[['A Room with a View by E. M. Forster (37480)'], ['Middlemarch by George Eliot (34900)'],['Little Women; Or, Meg, Jo, Beth, and Amy by Louisa May Alcott (31929)']]
</code></pre>
</li>
<li><p>Split the list into two parts</p>
<pre><code>[["A Room with a View by E. M. Forster", "37480"], ["Middlemarch by George Eliot", "34900"],["Little Women; Or, Meg, Jo, Beth, and Amy by Louisa May Alcott", "31929"]]
</code></pre>
</li>
<li><p>Load the data into data frame</p>
</li>
</ol>
<p><a href="https://i.stack.imgur.com/gnmsa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gnmsa.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74299937,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 1,
"selected": false,
"text": "for e in soup.select('ol a'):\n data.append({\n 'Ebook':e.text.split('(')[0].strip(),\n 'Code':e.text.split('(')[-1].strip(')')\n })\n"
},
{
"answer_id": 74299975,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "str.extract"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12374617/"
] |
74,299,790 | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>dept_id</th>
<th>course_id</th>
<th>student_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>CS</td>
<td>101</td>
<td>11</td>
</tr>
<tr>
<td>Math</td>
<td>101</td>
<td>11</td>
</tr>
<tr>
<td>CS</td>
<td>101</td>
<td>12</td>
</tr>
<tr>
<td>CS</td>
<td>201</td>
<td>22</td>
</tr>
<tr>
<td>Math</td>
<td>301</td>
<td>22</td>
</tr>
<tr>
<td>EE</td>
<td>102</td>
<td>33</td>
</tr>
<tr>
<td>Math</td>
<td>201</td>
<td>33</td>
</tr>
</tbody>
</table>
</div>
<p>This is the current sql table called "enrolled" and
I need to select all the departments with the highest number of enrolments.</p>
<p>I tried</p>
<pre><code>SELECT dept_id,COUNT(dept_id) as "enrollments"
FROM enrolled
GROUP BY dept_id;
</code></pre>
<p>to get the number of enrollments for each department. But then I am unsure on how to get all the departments with the maximum enrollment.</p>
<p>The final result should be a single column with "CS" and "Math".</p>
| [
{
"answer_id": 74299937,
"author": "HedgeHog",
"author_id": 14460824,
"author_profile": "https://Stackoverflow.com/users/14460824",
"pm_score": 1,
"selected": false,
"text": "for e in soup.select('ol a'):\n data.append({\n 'Ebook':e.text.split('(')[0].strip(),\n 'Code':e.text.split('(')[-1].strip(')')\n })\n"
},
{
"answer_id": 74299975,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "str.extract"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20347901/"
] |
74,299,851 | <p>How to trim only zeroes in a leading position in a string?</p>
<p>I'm writing a DB2 script that removes all leading zeroes from a string that could be only 13 characters long.
What I wrote so far:</p>
<blockquote>
<p>ltrim(replace(Field, '00000',''))</p>
</blockquote>
<p>That works as follows:</p>
<pre><code>0000012345678111 -> 12345678111
0000012300000174 -> 123174
</code></pre>
<p>Now, I need to delete ONLY the five leading zeroes, not the zeroes in the middle and I already tried to convert to decimal, but if I have, for example, only two zeroes leading, I want to leave them in the same position.</p>
<p>For example (converting to decimal) :</p>
<pre><code>001234566890000 -> 1234566890000
</code></pre>
<p>I want no Changes in the left string.</p>
<p>How could I solve it?</p>
<p>Thanks</p>
| [
{
"answer_id": 74300619,
"author": "Hellye",
"author_id": 20405313,
"author_profile": "https://Stackoverflow.com/users/20405313",
"pm_score": -1,
"selected": true,
"text": "substr( replace( ltrim( replace(Field,'00000', ' ')), ' ', '0'), 1, 13) "
},
{
"answer_id": 74306343,
"author": "data_henrik",
"author_id": 4923755,
"author_profile": "https://Stackoverflow.com/users/4923755",
"pm_score": 1,
"selected": false,
"text": "CHAR(LTRIM(inputvalue, '0'), 13)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405313/"
] |
74,299,875 | <p>I am trying to do to a bulk collect inside a loop which have dynamic SQL and execute multiple times based on input from loop then inserting into a table (and it is taking time approx. 4 mins to insert 193234 records).
So as to try different different approach I think of using the bulk collect on select inside the loop and fill up a collection with each iteration of that loop lets say 1st iteration gives 10 rows then second gives 0 rows and 3rd returns 15 rows then the collection should hold 15 records at end of the loop.
After exiting the loop I will use forall with collection I filled up inside loop to do an Insert at one go instead to doing insert for each iteration inside loop.</p>
<p>below is a sample code which is similar to application procedure I just use different tables to simplify question.</p>
<pre><code>create table test_tab as select owner, table_name, column_name from all_tab_cols where 1=2;
create or replace procedure p_test
as
l_sql varchar2(4000);
type t_tab is table of test_tab%rowtype index by pls_integer;
l_tab t_tab;
l_tab1 t_tab;
l_cnt number := 0;
begin
for i in (with tab as (select 'V_$SESSION' table_name from dual
union all
select 'any_table' from dual
union all
select 'V_$TRANSACTION' from dual
union all
select 'test_table' from dual
)
select table_name from tab )
loop
l_sql := 'select owner, table_name, column_name from all_tab_cols where table_name = '''||i.table_name||'''';
-- dbms_output.put_line(l_sql );
execute immediate l_sql bulk collect into l_tab;
dbms_output.put_line(l_sql ||' > '||l_tab.count);
l_cnt := l_cnt +1;
if l_tab.count<>0
then
l_tab1(l_cnt) := l_tab(l_cnt);
end if;
end loop;
dbms_output.put_line(l_tab1.count);
forall i in indices of l_tab1
insert into test_tab values (l_tab1(i).owner, l_tab1(i).table_name, l_tab1(i).column_name);
end;
</code></pre>
<p>It is inserting only 2 rows in test_tab table whereas as per my system it should insert 150 rows.</p>
<pre><code>select owner, table_name, column_name from all_tab_cols where table_name = 'V_$SESSION' > 103
select owner, table_name, column_name from all_tab_cols where table_name = 'any_table' > 0
select owner, table_name, column_name from all_tab_cols where table_name = 'V_$TRANSACTION' > 47
select owner, table_name, column_name from all_tab_cols where table_name = 'test_table' > 0
2
</code></pre>
<p>Above is DBMS_OUTPUT from my system you may change the table names in loop if the example table names does not exists in your DB.</p>
<p>Oracle Version --</p>
<pre><code>Oracle Database 19c Standard Edition 2 Release 19.0.0.0.0 - Production
</code></pre>
<p><em><strong>EDIT</strong></em>
Below screenshot shows highlighted timings from PLSQL_PROFILER with Actual insert...select... written in procedure at line# 114 and with bulk collect and forall with nested table at line# 132 and multiset and seems like we are saving atleast 40 secs here with bulk collect, multiset and forall.</p>
<p><a href="https://i.stack.imgur.com/9dCjz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9dCjz.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74300619,
"author": "Hellye",
"author_id": 20405313,
"author_profile": "https://Stackoverflow.com/users/20405313",
"pm_score": -1,
"selected": true,
"text": "substr( replace( ltrim( replace(Field,'00000', ' ')), ' ', '0'), 1, 13) "
},
{
"answer_id": 74306343,
"author": "data_henrik",
"author_id": 4923755,
"author_profile": "https://Stackoverflow.com/users/4923755",
"pm_score": 1,
"selected": false,
"text": "CHAR(LTRIM(inputvalue, '0'), 13)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3997124/"
] |
74,299,887 | <p>I have a react app where I am trying to create an axios post request, and the parameters doesn't seem to work. Strange part is I have other axios post calls in other components and they work just fine, it is just this component here that is not working right.</p>
<p>My backend is golang based, and everything is working well, tested on postman so I'm sure it's the frontend parameters that are causing the issue.
For reference, here is the postman test: <a href="https://i.stack.imgur.com/SSIub.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SSIub.png" alt="enter image description here" /></a></p>
<p>Let me point out the part where I think the error is coming from:</p>
<pre><code>let param = JSON.stringify({ userrefer: JSON.stringify(userID), productrefer: JSON.stringify(itemID), quantity: JSON.stringify(order[itemID]) })
</code></pre>
<p>At first, I did not have the JSON.stringify portion, it was simply</p>
<pre><code>let param = { userrefer: userID, productrefer: itemID, quantity: order[itemID] }
</code></pre>
<p>but it didn't work, and I thought I went wrong with my syntax somewhere, so I spent a great amount of time editing and trying all sorts of combinations of the syntax but it didn't help. After some searching online I then found a recommendation to serialise it hence I added the JSON stringify but to no avail.</p>
<p>The response I get back is always 400, no matter what I do. Here is a screenshot.
<a href="https://i.stack.imgur.com/3By5A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3By5A.png" alt="enter image description here" /></a></p>
<p>This is the whole code for the particular component where I'm having trouble:</p>
<pre><code>import React from 'react';
import Card from './Card';
import axios from "axios";
import { useEffect } from 'react';
import { useState } from 'react';
function Products({ isLoggedIn, userID }) {
const [instruments, setInstruments] = useState([]);
const [order, setOrder] = useState({});
const handleOrderChange = (event, itemID) => {
const value = event.target.value;
setOrder({ ...order, [itemID]: value });
};
useEffect(() => {
async function getInstruments() {
await axios
.get(
`http://127.0.0.1:3000/api/products`
)
.then((res) => {
setInstruments(res.data.message)
})
}
getInstruments()
}, [])
const handleBuy = async (event, itemID, qty) => {
event.preventDefault();
if (order[itemID] > qty) {
alert(`You cannot buy more than the quantity of ${qty}!`)
}
else if (order[itemID] <= 0) {
alert(`You cannot buy 0 or less instruments...`)
}
else {
let param = JSON.stringify({ userrefer: JSON.stringify(userID), productrefer: JSON.stringify(itemID), quantity: JSON.stringify(order[itemID]) })
console.log(param)
await axios
.post(
`http://127.0.0.1:3000/api/orders`, param
)
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log("err", err);
});
}
};
return (
isLoggedIn === true ? (<div>
<h1>
Products
</h1>
<h4>
Here are the musical products for sale.
</h4>
{instruments.map((element) => {
return (
<>
<Card name={element.name} img={element.img} price={element.price} qty={element.qty} description={element.description} />
<input type="number" id="qty" name="qty"
onChange={(e) => handleOrderChange(e, element.id)}
min="0"
max={element.qty} />
<button onClick={(e) => handleBuy(e, element.id, element.qty)}>Buy</button>
</>
)
})}
</div>) : (<div>
<h1>
Products
</h1>
<h4>
Here are the musical products for sale.
</h4>
{instruments.map((element) => {
return (
<>
<Card name={element.name} img={element.img} price={element.price} qty={element.qty} description={element.description} />
</>
)
})}
</div>)
)
}
export default Products
</code></pre>
<p>For my other components where axios post works, I used react useState to pass in the parameters. I am not sure whether it's because I'm not using useState for this component's input paramters for axios, that's why this is an issue. Appreciate any guidance/tips!</p>
| [
{
"answer_id": 74300258,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 3,
"selected": true,
"text": "let param = JSON.stringify({ userrefer: JSON.stringify(userID), productrefer: JSON.stringify(itemID), quantity: JSON.stringify(order[itemID]) })\n \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10285712/"
] |
74,299,906 | <p>I am trying to add some validation to my json schema . I am validating json schema against json using this website <a href="https://www.jsonschemavalidator.net/" rel="nofollow noreferrer">https://www.jsonschemavalidator.net/</a>. I am not able to put validation on eventPayload/totalAmount based on value present in eventName. It is not failing when it should fail. Should I give the whole path of eventName attribute as it is not present in eventPayload ? If yes, how to do<a href="https://i.stack.imgur.com/JdCaw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JdCaw.png" alt="enter image description here" /></a> that.</p>
<pre><code> "totalAmount": {
"type": [
"integer",
"number"
],
"minLength": 1,
"multipleOf": 0.01,
"if": {
"properties": {
"eventName": {
"enum": [
"Test10",
"Test12"
]
}
}
},
"then": {
"properties": {
"totalAmount": {
"exclusiveMinimum": 0
}
}
},
"else": {
"if": {
"properties": {
"eventName": {
"enum": [
"Test1",
"Test2",
"Test3"
]
}
}
},
"then": {
"properties": {
"totalAmount": {
"exclusiveMaximum": 0
}
}
}
}
}
</code></pre>
| [
{
"answer_id": 74308276,
"author": "Ether",
"author_id": 40468,
"author_profile": "https://Stackoverflow.com/users/40468",
"pm_score": 0,
"selected": false,
"text": "properties"
},
{
"answer_id": 74324238,
"author": "Byted",
"author_id": 5032258,
"author_profile": "https://Stackoverflow.com/users/5032258",
"pm_score": 2,
"selected": true,
"text": "totalAmount"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115835/"
] |
74,299,913 | <p>This is in reference to F#'s <a href="https://fsharp.github.io/fsharp-core-docs/reference/fsharp-control-fsharpasync.html#StartImmediate" rel="nofollow noreferrer"><code>Async.StartImmediate</code></a> method. Possibly a diversion, but this method is confusingly named because <code>Async.Start</code> <em>also</em> starts the <code>async</code> process immediately, just on a thread pool.</p>
<p>Anyway, the documentation states that <code>Async.StartImmediate</code> starts the process using the calling thread. Does the <code>async</code> process continue to execute on that same thread throughout the lifetime of the process? Or is it possible it switches at some point? To my knowledge, <code>Async.Start</code> allows the process to switch underlying threads since it runs on top of a thread pool.</p>
<p>Edit: To clarify the question, I am thinking about an <code>async</code> that doesn't contain any other usage of <code>async</code>, <code>let!</code>, <code>do!</code>, <code>return!</code>, etc. for example:</p>
<pre class="lang-ml prettyprint-override"><code>async { printfn "testing" }
</code></pre>
| [
{
"answer_id": 74324947,
"author": "bmitc",
"author_id": 17800932,
"author_profile": "https://Stackoverflow.com/users/17800932",
"pm_score": 2,
"selected": false,
"text": "Async.StartImmediate"
},
{
"answer_id": 74342729,
"author": "CaringDev",
"author_id": 2894770,
"author_profile": "https://Stackoverflow.com/users/2894770",
"pm_score": 2,
"selected": false,
"text": "StartImmediate"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17800932/"
] |
74,299,990 | <p>I'm trying to convert the following schema:</p>
<pre class="lang-none prettyprint-override"><code> |-- a: struct (nullable = true)
| |-- b: struct (nullable = true)
| | |-- one: double (nullable = true)
| | |-- two: array (nullable = true)
| | | |-- element: string (containsNull = true)
| | |-- three: string (nullable = true)
| | |-- four: boolean (nullable = true)
| |-- c: struct (nullable = true)
| | |-- one: double (nullable = true)
| | |-- two: array (nullable = true)
| | | |-- element: string (containsNull = true)
| | |-- three: string (nullable = true)
| | |-- four: boolean (nullable = true)
</code></pre>
<p>into this:</p>
<pre class="lang-none prettyprint-override"><code> |-- a: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- struct_key: string (nullable = true)
| | |-- one: double (nullable = true)
| | |-- two: array (nullable = true)
| | | |-- element: string (containsNull = true)
| | |-- three: string (nullable = true)
| | |-- four: boolean (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- struct_key: string (nullable = true)
| | |-- one: double (nullable = true)
| | |-- two: array (nullable = true)
| | | |-- element: string (containsNull = true)
| | |-- three: string (nullable = true)
| | |-- four: boolean (nullable = true)
</code></pre>
<p>Really just trying to get the struct key and convert it into a string and add it into a column. The <code>b</code>/<code>c</code> structs in the dataset are numerous, so will need some wildcard to convert them.</p>
<p>I'm using Spark 3.2.1.</p>
<p>The data is generated from JSON, so is read like this:</p>
<pre class="lang-py prettyprint-override"><code>df = spark.read.json(json_file)
</code></pre>
| [
{
"answer_id": 74324947,
"author": "bmitc",
"author_id": 17800932,
"author_profile": "https://Stackoverflow.com/users/17800932",
"pm_score": 2,
"selected": false,
"text": "Async.StartImmediate"
},
{
"answer_id": 74342729,
"author": "CaringDev",
"author_id": 2894770,
"author_profile": "https://Stackoverflow.com/users/2894770",
"pm_score": 2,
"selected": false,
"text": "StartImmediate"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74299990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405242/"
] |
74,300,013 | <p>I'm trying to create a new POST endpoint using Spring Boot using the following code:</p>
<pre class="lang-java prettyprint-override"><code>@Controller
@Path("/my")
@MultipartConfig(maxFileSize = 1024*1024*1024, maxRequestSize = 1024*1024*1024)
public class MyResource {
@POST
@Path("parseFile")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "400", description = "Invalid format")})
})
public Response parseFile(@RequestParam("file") MultipartFile file) {
// Use file
}
}
</code></pre>
<p>I've added config in application.yml file:</p>
<pre class="lang-yaml prettyprint-override"><code>spring:
servlet:
multipart:
enabled: true
max-file-size: 2MB
file-size-threshold: 3MB
</code></pre>
<p>Based on the <a href="https://docs.spring.io/spring-boot/docs/2.5.2/reference/htmlsingle/#howto.spring-mvc.multipart-file-uploads" rel="nofollow noreferrer">docs here</a>, it should automagically work and allow requests, but I'm getting the following response:</p>
<pre class="lang-json prettyprint-override"><code>{
"timestamp": 1667463311931,
"status": 415,
"error": "Unsupported Media Type",
"path": "/app/api/my/parseFile"
}
</code></pre>
<p>I've also tried adding AutoConfig elements manually as well in a <code>@Configuration</code> class like:</p>
<pre class="lang-java prettyprint-override"><code>@Bean
public MultipartAutoConfiguration multipartAutoConfiguration() {
var props = new MultipartProperties();
props.setMaxFileSize(DataSize.ofMegabytes(10));
props.setEnabled(true);
return new MultipartAutoConfiguration(props);
}
</code></pre>
<p>On the server side I'm only seeing the following log:</p>
<pre class="lang-json prettyprint-override"><code>{"@timestamp":"2022-11-03T08:10:34.066Z","message":"0:0:0:0:0:0:0:1 - - [03/Nov/2022:08:10:34 +0000] \"POST /app/api/my/parseFile HTTP/1.1\" 415 126 \"-\" \"PostmanRuntime/7.29.2\"","request_id":"-","local_request_id":"4f9396ff817861e9","ext":{"accessLog":true,"cloudId":"fake","host":"0:0:0:0:0:0:0:1","method":"POST","protocol":"HTTP/1.1","statusCode":"415","requestedUri":"/app/api/my/parseFile","requestPath":"/app/api/my/parseFile","responseContentLength":"126","elapsedTimeMs":"5"}}
</code></pre>
<p>Postman Request:
<a href="https://i.stack.imgur.com/QZt8Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QZt8Z.png" alt="Postman Body" /></a></p>
<p><a href="https://i.stack.imgur.com/n5sZy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n5sZy.png" alt="enter image description here" /></a></p>
<p>The file type that I'm trying to upload is of type <code>*.ics</code> and is a text file.</p>
<p>I'm using Spring Boot version 2.5.2.</p>
| [
{
"answer_id": 74300796,
"author": "grekier",
"author_id": 1540177,
"author_profile": "https://Stackoverflow.com/users/1540177",
"pm_score": 1,
"selected": false,
"text": "@POST"
},
{
"answer_id": 74300897,
"author": "Elbashir Saror",
"author_id": 20033482,
"author_profile": "https://Stackoverflow.com/users/20033482",
"pm_score": 0,
"selected": false,
"text": " @PostMapping(value=\"/parsefile\", consumes =\"multipart/form-data\")\n public Response parseFile(@RequestParam(value = \"file\") MultipartFile file) \n {\n // Use file\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719089/"
] |
74,300,019 | <p>In the code below I want to use .windowResizability only if #available(macOS 13.0, *) == true or @ available(macOS 13.0, *) cause it doesn't available under macOS 13. I can not find the solution by myself.</p>
<pre><code>//
// Test_HowAviableApp.swift
// Test HowAviable
//
// Created by Sebastien REMY on 03/11/2022.
//
import SwiftUI
import UniformTypeIdentifiers
@main
struct Test_HowAviableApp: App {
var body: some Scene {
DocumentGroup(newDocument: MyDocument()) { file in
MyView(document: file.$document)
}
// @available(macOS 13.0, *) // <- DOESN'T WORK!
//.windowResizability(.contentSize) // Only for macOs 13+
}
}
struct MyDocument: FileDocument, Codable {
static var readableContentTypes = [UTType(exportedAs:"com.test.test")]
var test = "test"
init() {
}
init(configuration: ReadConfiguration) throws {
if let data = configuration.file.regularFileContents {
self = try JSONDecoder().decode(MyDocument.self, from: data)
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = try JSONEncoder().encode(self)
return FileWrapper(regularFileWithContents: data)
}
}
struct MyView: View {
@Binding var document: MyDocument
var body: some View {
Text("Hello")
}
}
</code></pre>
| [
{
"answer_id": 74300125,
"author": "Anton Ozeryanskyy",
"author_id": 20405540,
"author_profile": "https://Stackoverflow.com/users/20405540",
"pm_score": -1,
"selected": false,
"text": "if #available(macOS 13, *) {\n .windowResizability(.contentSize)\n}\n"
},
{
"answer_id": 74300608,
"author": "RTXGamer",
"author_id": 6576315,
"author_profile": "https://Stackoverflow.com/users/6576315",
"pm_score": 1,
"selected": false,
"text": "return"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3405792/"
] |
74,300,037 | <p>I'm using smallrye.jwt as authorization tool. My quarkus app does not generate jwt tokens, but verifies them having secret key.</p>
<p>Problem is that incoming tokens have <code>sub</code> claim of non-string type, but parser expects <code>java.lang.String</code> (I receive <code>45</code> instead of <code>"45"</code>). I don't have access to token generation, so I need it to work with what I have. Apparently there's no way to make it work with microprofile. How can I achieve it?</p>
<p>The error I get (I replaced a few values with <code>...</code>):</p>
<pre><code>Caused by: org.jose4j.jwt.consumer.InvalidJwtException: JWT (claims->{"iss":"...","iat":...,"exp":...,"nbf":...,"jti":"...","sub":45,"prv":"...","pid": ...}) rejected due to invalid claims or other invalid content. Additional details: [[18] The value of the 'sub' claim is not the expected type (1517 - Cannot cast java.lang.Long to java.lang.String)]
</code></pre>
<p>My <code>application.properties</code>:</p>
<pre><code>smallrye.jwt.verify.key-format=JWK
smallrye.jwt.verify.key.location=JWTSecret.jwk
smallrye.jwt.verify.algorithm=HS256
</code></pre>
| [
{
"answer_id": 74300125,
"author": "Anton Ozeryanskyy",
"author_id": 20405540,
"author_profile": "https://Stackoverflow.com/users/20405540",
"pm_score": -1,
"selected": false,
"text": "if #available(macOS 13, *) {\n .windowResizability(.contentSize)\n}\n"
},
{
"answer_id": 74300608,
"author": "RTXGamer",
"author_id": 6576315,
"author_profile": "https://Stackoverflow.com/users/6576315",
"pm_score": 1,
"selected": false,
"text": "return"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7976987/"
] |
74,300,040 | <p>I am a beginner who is learning HTML recently. I put the same HTML file and image in the same folder as below, but only the image icon is displayed and does not print out. Please help me.</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-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-wid">
<title>Typing Text</title>
<img src="https://cdn-icons-png.flaticon.com/512/2889/2889312.png" alt= "img" width="1000", height="500">
<link herf="typr.css" rel="stylesheet">
</head>
<body>
<p id="dynamic" class="ig-text">
Learn To HTML
</p>
<p class="sm text" > LAilac
</p>
</body>
</html></code></pre>
</div>
</div>
</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-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-wid">
<title>Typing Text</title>
<img src="https://cdn-icons-png.flaticon.com/512/2889/2889312.png" alt= "img" width="1000", height="500">
<link herf="typr.css" rel="stylesheet">
</head>
<body>
<p id="dynamic" class="ig-text">
Learn To HTML
</p>
<p class="sm text" > LAilac
</p>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74300125,
"author": "Anton Ozeryanskyy",
"author_id": 20405540,
"author_profile": "https://Stackoverflow.com/users/20405540",
"pm_score": -1,
"selected": false,
"text": "if #available(macOS 13, *) {\n .windowResizability(.contentSize)\n}\n"
},
{
"answer_id": 74300608,
"author": "RTXGamer",
"author_id": 6576315,
"author_profile": "https://Stackoverflow.com/users/6576315",
"pm_score": 1,
"selected": false,
"text": "return"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405233/"
] |
74,300,051 | <p>This is my code for uploading to google drive with python requests using google-drive-api.</p>
<pre><code>import sys
import json
import requests
from tqdm import tqdm
import requests_toolbelt
from requests.exceptions import JSONDecodeError
class ProgressBar(tqdm):
def update_to(self, n: int) -> None:
self.update(n - self.n)
def upload_file(access_token:str, filename:str, filedirectory:str):
metadata = {
"title": filename,
}
files = {}
session = requests.session()
with open(filedirectory, "rb") as fp:
files["file"] = fp
files["data"] = ('metadata', json.dumps(metadata), 'application/json')
encoder = requests_toolbelt.MultipartEncoder(files)
with ProgressBar(
total=encoder.len,
unit="B",
unit_scale=True,
unit_divisor=1024,
miniters=1,
file=sys.stdout,
) as bar:
monitor = requests_toolbelt.MultipartEncoderMonitor(
encoder, lambda monitor: bar.update_to(monitor.bytes_read)
)
r = session.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
data=monitor,
allow_redirects=False,
headers={"Authorization": "Bearer " + access_token},
)
try:
resp = r.json()
print(resp)
except JSONDecodeError:
sys.exit(r.text)
upload_file("access_token", "test.txt", "test.txt")
</code></pre>
<p>When i am trying send file with data attribute in post request then file name did not send and with files attribute in post request then requests-toolbelt not working. How to fix this error ?</p>
| [
{
"answer_id": 74300870,
"author": "DaImTo",
"author_id": 1841839,
"author_profile": "https://Stackoverflow.com/users/1841839",
"pm_score": 0,
"selected": false,
"text": " metadata = {\n \"name\": filename,\n }\n\n\n r = session.post(\n url,\n json=json.dumps(metadata),\n allow_redirects=False,\n headers={\"Authorization\": \"Bearer \" + access_token},\n )\n"
},
{
"answer_id": 74302878,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "r = session.post(\n url,\n data=monitor,\n allow_redirects=False,\n headers={\"Authorization\": \"Bearer \" + access_token},\n)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17915481/"
] |
74,300,084 | <p>In scala I am wondering if there is a way I can define a new type including itself
For example</p>
<pre><code>type A = Tuple(e1: Int, e2: A)
</code></pre>
<p>Ofcourse type <code>A = List[A]</code> is illegal so is there another way to do this?</p>
<p>I tried doing this with type <code>Any</code> and <code>Option</code> but it didn't go well, and I am not sure this is a right way to do this</p>
| [
{
"answer_id": 74300145,
"author": "Dmytro Mitin",
"author_id": 5249621,
"author_profile": "https://Stackoverflow.com/users/5249621",
"pm_score": 2,
"selected": false,
"text": "sealed trait A\ncase class Tuple(e1: Int, e2: A) extends A\n"
},
{
"answer_id": 74304419,
"author": "Tim",
"author_id": 7662670,
"author_profile": "https://Stackoverflow.com/users/7662670",
"pm_score": 1,
"selected": false,
"text": "type A = Tuple2[Int, A]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405518/"
] |
74,300,100 | <p>I have 2 tables in Mysql. I want to regroup and count the Number of Orderid per month for each customer. If there is no order, I would like to add 0.</p>
<p>Customer Table</p>
<pre><code>CustomerID
1
2
3
</code></pre>
<p>Order Table</p>
<pre><code>OrderId CustomerID Date
1 1 2022-01-02
2 1 2022-01-04
3 2 2022-02-03
4 2 2022-03-03
</code></pre>
<p>Expect results</p>
<pre><code> CustomerID Date CountOrderID
1 2022-01 2
2 2022-01 1
3 2022-01 0
1 2022-02 0
2 2022-02 1
3 2022-02 0
1 2022-03 0
2 2022-03 1
3 2022-03 0
</code></pre>
<p>How I can do this in Mysql?</p>
| [
{
"answer_id": 74300145,
"author": "Dmytro Mitin",
"author_id": 5249621,
"author_profile": "https://Stackoverflow.com/users/5249621",
"pm_score": 2,
"selected": false,
"text": "sealed trait A\ncase class Tuple(e1: Int, e2: A) extends A\n"
},
{
"answer_id": 74304419,
"author": "Tim",
"author_id": 7662670,
"author_profile": "https://Stackoverflow.com/users/7662670",
"pm_score": 1,
"selected": false,
"text": "type A = Tuple2[Int, A]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9861647/"
] |
74,300,118 | <p>Determine a date (as day, month, year) starting from two integer numbers that represent the year and the number of the day in that year.</p>
<p>i'm new to coding and I don't know where to start even.</p>
| [
{
"answer_id": 74300145,
"author": "Dmytro Mitin",
"author_id": 5249621,
"author_profile": "https://Stackoverflow.com/users/5249621",
"pm_score": 2,
"selected": false,
"text": "sealed trait A\ncase class Tuple(e1: Int, e2: A) extends A\n"
},
{
"answer_id": 74304419,
"author": "Tim",
"author_id": 7662670,
"author_profile": "https://Stackoverflow.com/users/7662670",
"pm_score": 1,
"selected": false,
"text": "type A = Tuple2[Int, A]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405643/"
] |
74,300,126 | <p>I have a very simple react code, which I use to track containers location on a territory. After a new container get's into the territory I have props.operationsList changed. So I send get response to server API when props.operationsList changes</p>
<pre><code> useEffect(() => {
async function fetchContainerLocation() {
const response = await CoordinatesService.getContainersPosition()
console.log('response = ', response.data.features)
setContainersList(response.data.features)
console.log('containersList = ', containersList)
}
fetchContainerLocation()
}, [props.operationsList])
</code></pre>
<p>I need to update containersList const, that I use to rerender a map API where I should locate the containers. I define it like that:</p>
<pre><code> const [containersList, setContainersList] = useState([])
</code></pre>
<p>I need to set containersList in accordance with that response fron server (response.data.features) to make my map rerender. What's strange,</p>
<blockquote>
<p>console.log('response = ', response.data.features)</p>
</blockquote>
<p>shows accurate and correct data from server, but the next</p>
<blockquote>
<p>console.log('containersList = ', containersList)</p>
</blockquote>
<p>is not equal with this response</p>
<p><a href="https://i.stack.imgur.com/nT43s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nT43s.png" alt="enter image description here" /></a></p>
<p>Instad of getting the map rendered with the right data from server response, I have wrong data. So, I do now understand why such an straightforward approch do not work and how to fix it</p>
| [
{
"answer_id": 74300145,
"author": "Dmytro Mitin",
"author_id": 5249621,
"author_profile": "https://Stackoverflow.com/users/5249621",
"pm_score": 2,
"selected": false,
"text": "sealed trait A\ncase class Tuple(e1: Int, e2: A) extends A\n"
},
{
"answer_id": 74304419,
"author": "Tim",
"author_id": 7662670,
"author_profile": "https://Stackoverflow.com/users/7662670",
"pm_score": 1,
"selected": false,
"text": "type A = Tuple2[Int, A]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15901109/"
] |
74,300,138 | <p>I'm trying to create a generic "pipe" function that accepts a series of map functions that transform an input and eventually returns the output of the final map function. I started with a basic function that only accepts one map function as a parameter:</p>
<pre><code>const pipe = <T, U>(map: (input: T) => U) => (initial: T): U => map(initial);
</code></pre>
<p>However, when I try and use it with an identity function, I get <code>unknown</code> back:</p>
<pre><code>// test is unknown
const test = pipe(i => i)(1);
</code></pre>
<p>Ideally, <code>test</code> should be <code>number</code> in this example.</p>
<p>My hypothesis here is that <code>pipe(i => i)</code> is evaluated as <code>pipe(unknown => unknown)</code>, and this doesn't get updated with any inference from the returned function. When I call <code>pipe(unknown => unknown)(1)</code>, it's fine passing a number into a function that accepts <code>unknown</code>, but because that function also returns <code>unknown</code>, that's what eventually gets returned.</p>
<p>I'm wondering if my hypothesis here is correct, and if so, whether there's any activity regarding it somewhere in the TypeScript dev scene.</p>
<p>Is there any way in TypeScript currently to achieve what I'm looking for?</p>
| [
{
"answer_id": 74301937,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 1,
"selected": false,
"text": "unknown"
},
{
"answer_id": 74302441,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 0,
"selected": false,
"text": "const test = pipe((i: number) => i)(1);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2832969/"
] |
74,300,154 | <p>I've got the following code that filters a particular search on an auction site.
I can display the titles of each value & also the len of all returned values:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
url = requests.get("https://www.trademe.co.nz/a/marketplace/music-instruments/instruments/guitar-bass/electric-guitars/search?search_string=prs&condition=used")
soup = BeautifulSoup(url.text, "html.parser")
listings = soup.findAll("div", attrs={"class":"tm-marketplace-search-card__title"})
print(len(listings))
for listing in listings:
print(listing.text)
</code></pre>
<p>This prints out the following:</p>
<pre><code>#print(len(listings))
3
#for listing in listings:
# print(listing.text)
PRS. Ten Top Custom 24, faded Denim, Piezo.
PRS SE CUSTOM 22
PRS Tremonti SE *With Seymour Duncan Pickups*
</code></pre>
<p>I know what I want to do next, but don't know how to code it. Basically I want to only display new results. I was thinking storing the len of the listings (3 at the moment) as a variable & then comparing that with another GET request (2nd variable) that maybe runs first thing in the morning. Alternatively compare both text values instead of the len. If it doesn't match, then it shows the new listings. Is there a better or different way to do this? Any help appreciated thank you</p>
| [
{
"answer_id": 74301937,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 1,
"selected": false,
"text": "unknown"
},
{
"answer_id": 74302441,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 0,
"selected": false,
"text": "const test = pipe((i: number) => i)(1);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7770930/"
] |
74,300,169 | <p>I have an app , but night mode changes colors (white to black) in Piker from @react-native-picker/picker. I tried</p>
<pre><code><item name="android:forceDarkAllowed">false</item>
</code></pre>
<p>and</p>
<pre><code>AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
</code></pre>
<p>but it's not helped
How to force disable night mode for Piker ?</p>
<pre><code>compileSdkVersion = 31
kotlinVersion = "1.6.20"
buildToolsVersion = "30.0.2"
"react-native": "0.68.0",
</code></pre>
| [
{
"answer_id": 74301937,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 1,
"selected": false,
"text": "unknown"
},
{
"answer_id": 74302441,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 0,
"selected": false,
"text": "const test = pipe((i: number) => i)(1);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11884052/"
] |
74,300,177 | <p>Sorry for being noob but I am really confused on how to work on this. So I followed the instructions on this <a href="https://github.com/i18next/next-i18next" rel="nofollow noreferrer">https://github.com/i18next/next-i18next</a> but confused when it comes to index.js. Whenever I click my toggle switch for /de in my landing page it translates alright in url "http://localhost:3000/de".</p>
<p>But in another page like "About" or in any other page it doesn't translate but the url switch to "http://localhost:3000/de/about". It doesnt go to my 404 error page. But I don't get it why it doesn't translate.</p>
<p>In my index.js if I removed "Service" component which contained all the components of landing page. And replace with other component file like "About" component page it translate alright.</p>
<p>It seems "http://localhost:3000/de" url only works in translation. But in different url path it doesn't. How to do this? Thank you..</p>
<p>Kindly see my code..</p>
<p>My locales path</p>
<pre><code>public/locales/de/common.json
</code></pre>
<p>src/pages/_app.js</p>
<pre><code>import nextI18NextConfig from '../../next-i18next.config'
<Component {...pageProps} />
export default appWithTranslation(App, nextI18NextConfig);
</code></pre>
<p>src/pages/index.js</p>
<pre><code> import React from 'react';
import Service from 'views/Service';
import i18nextConfig from '../../next-i18next.config';
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
const IndexPage = () => {
return (
<Service/> <— this contains my landing page the only can be translated as “localhost:/3000/de” (src/pages/views/service)
)
};
export async function getServerSideProps({ locale }) {
return { props: {
...(await serverSideTranslations(locale, ['common', 'footer', 'stripe', ‘navbar'], i18nextConfig))
} }
}
export default IndexPage;
</code></pre>
<p>in my navbar it is in global component I put my toggle language switcher
src/layouts/Main/components/Navbar/Navbar.js</p>
<pre><code> const onToggleLanguageClick = (locale) => {
const { pathname, asPath, query } = router
router.push({ pathname, query }, asPath, { locale })
}
const changeTo = router.locale === 'de' ? 'en' : 'de'
return (
<button onClick={() => onToggleLanguageClick(changeTo)}>
{t('change-locale', { changeTo })}
</button>
)
</code></pre>
<p>this is my next-i18next.config</p>
<pre><code>const path = require('path');
module.exports = {
i18n: {
locales: ['en', 'de'],
defaultLocale: 'en',
localePath: path.resolve('./public/locales')
},
}
</code></pre>
<p>my next.config.js</p>
<pre><code>const nextConfig = {
i18n,
…some code
}
module.exports = nextConfig
</code></pre>
<p>src/pages/_document.js</p>
<pre><code>import i18nextConfig from '../../next-i18next.config';
export default class MyDocument extends Document {
render() {
const currentLocale = this.props.__NEXT_DATA__.query.locale ?? i18nextConfig.i18n.defaultLocale;
return (
<Html lang={currentLocale}>
.....
</code></pre>
| [
{
"answer_id": 74301937,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 1,
"selected": false,
"text": "unknown"
},
{
"answer_id": 74302441,
"author": "Svetoslav Petkov",
"author_id": 11612861,
"author_profile": "https://Stackoverflow.com/users/11612861",
"pm_score": 0,
"selected": false,
"text": "const test = pipe((i: number) => i)(1);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18428268/"
] |
74,300,217 | <p>I am using Regex Substring to filter out values that have 'p' in the start and ends before '-'. p is followed by 6 digits.</p>
<p>My Code :</p>
<pre><code> code,REGEXP_SUBSTR(CODE,'^[p][^-]+')
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th><code>CODE</code></th>
<th><code>REGEXP_SUBSTR(CODE,'^[P][^-]+')</code></th>
</tr>
</thead>
<tbody>
<tr>
<td>p700401-</td>
<td>p700401</td>
</tr>
<tr>
<td>p791701-</td>
<td>p791701</td>
</tr>
<tr>
<td>100-,p788001-,</td>
<td>null</td>
</tr>
</tbody>
</table>
</div>
<p>This is the result , but I am struggling to handle cases like in 3rd Row.</p>
<p><code>100-,p788001-</code></p>
<p>Can Someone Please guide me to handle such cases</p>
| [
{
"answer_id": 74300305,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> with test (code) as\n 2 (select 'p700401-' from dual union all\n 3 select 'p791701-' from dual union all\n 4 select '100-,p788001-,' from dual\n 5 )\n 6 select code,\n 7 regexp_substr(code, 'p\\d{6}') result\n 8 from test;\n\nCODE RESULT\n-------------- --------------\np700401- p700401\np791701- p791701\n100-,p788001-, p788001\n\nSQL>\n"
},
{
"answer_id": 74300957,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 3,
"selected": true,
"text": "SELECT code,\n REGEXP_SUBSTR(code, '(^|,)(p\\d{6})-(,|$)', 1, 1, NULL, 2) AS result\nFROM table_name;\n"
},
{
"answer_id": 74301223,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "REGEXP_REPLACE()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19854398/"
] |
74,300,222 | <p>Programming is all fine but I don't know the meaning of idx for idx.
I know function enumerate(): for idx, c in enumerate
but what is idx for idx meaning??</p>
<p>input</p>
<pre><code>x = 'An apple a day, keeps the doctor away'
j = [idx for idx, c in enumerate(x, start = 0) if c == 'a']
print(j)
</code></pre>
<p>output
[3, 9, 12, 33, 35]</p>
| [
{
"answer_id": 74300305,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 1,
"selected": false,
"text": "SQL> with test (code) as\n 2 (select 'p700401-' from dual union all\n 3 select 'p791701-' from dual union all\n 4 select '100-,p788001-,' from dual\n 5 )\n 6 select code,\n 7 regexp_substr(code, 'p\\d{6}') result\n 8 from test;\n\nCODE RESULT\n-------------- --------------\np700401- p700401\np791701- p791701\n100-,p788001-, p788001\n\nSQL>\n"
},
{
"answer_id": 74300957,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 3,
"selected": true,
"text": "SELECT code,\n REGEXP_SUBSTR(code, '(^|,)(p\\d{6})-(,|$)', 1, 1, NULL, 2) AS result\nFROM table_name;\n"
},
{
"answer_id": 74301223,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "REGEXP_REPLACE()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405631/"
] |
74,300,235 | <p>I am preparing a Quarto presentation using beamer and would like to add the frame number at the bottom of each slide (analogous to the slide-number option in revealjs).
Could anybody tell me how I can do this?</p>
<p>I already figured out that the slide-number option does not exist for beamer.</p>
| [
{
"answer_id": 74300524,
"author": "Maël",
"author_id": 13460602,
"author_profile": "https://Stackoverflow.com/users/13460602",
"pm_score": 1,
"selected": false,
"text": "Boadilla"
},
{
"answer_id": 74300549,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 3,
"selected": true,
"text": "---\ntitle: \"Presentation\"\nformat: \n beamer: \n aspectratio: 32\n navigation: horizontal\n header-includes: |\n \\setbeamertemplate{navigation symbols}{}\n \\setbeamertemplate{footline}[page number]\n---\n\n# Intro\n\n\n## second slide\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19045136/"
] |
74,300,277 | <p>I am trying to extract all the headlines from this website: <a href="https://www.theguardian.com/international" rel="nofollow noreferrer">https://www.theguardian.com/international</a>. I have tried so many xpaths, but none gives me the headlines, although the code works. Any ideas on what I'm doing wrong? Thanks!</p>
<p>This is my code:</p>
<pre><code>
guardian_url <- "https://www.theguardian.com/international"
guardian <- read_html(guardian_url)
headlines <- guardian %>%
html_elements(xpath = '//html/body/div[3]/div') %>%
html_text2()
</code></pre>
| [
{
"answer_id": 74300895,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": -1,
"selected": true,
"text": "library(tidyverse)\nlibrary(rvest)\n#> \n#> Attaching package: 'rvest'\n#> The following object is masked from 'package:readr':\n#> \n#> guess_encoding\n\n\"https://www.theguardian.com/international\" %>% \n read_html %>% \n html_elements(\".fc-item__title\") %>% \n html_text2()\n\n#> [1] \"UK Dover asylum centre not operating legally, concedes minister\" \n#> [2] \"Exclusive Bahraini death row prisoner pleads with pope to aid his release\" \n#> [3] \"Live Russia-Ukraine war: Blinken hails Turkish help as grain export deal resumes\" \n#> [4] \"‘We’re facing a defining moment’ Biden urges Americans to take a stand against political violence\" \n#> [5] \"Live UK: biggest interest rate rise in decades expected as Bank of England battles inflation\" \n#> [6] \"North Korea ICBM launch may have been a failure, South’s military says\" \n#> [7] \"Twitter Company may ‘halve its workforce’ as key investor backs job cuts\" \n#> [8] \"China Father of three-year-old blames zero-Covid policy for son’s death\" \n#> [9] \"Hong Kong Exiles in UK unnerved by ‘weak’ response to beating of protester\" \n#> [10] \"Myanmar Experts warn of aid ‘catastrophe’, after junta law change\" \n#> [11] \"Analysis Grain deal U-turn offers lesson in calling Putin’s bluff\" \n#> [12] \"At a glance What we know on day 253 of the invasion\" \n#> [13] \"UK Kremlin to summon British ambassador over drone attacks on Black Sea fleet\" \n#> [14] \"Roman Abramovich UK adds two ‘business associates’ of former Chelsea owner to Russia sanctions list\" \n#> [15] \"‘He is poised to open the floodgates’ Can Twitter survive Elon Musk – or even thrive?\" \n#> [16] \"The long read The many meanings of moss\" \n#> [17] \"No fun rides but plenty of spirit Studio Ghibli offers anime fans a new walk in the park\" \n#> [18] \"Germany's balancing act Scholz heads to China amid questions over strategy\" \n#> [19] \"Weird: The Al Yankovic Story review Daniel Radcliffe biopic packed with wacky walk-ons\" \n#> [20] \"‘No darkness is for ever’ Can an activist in exile persuade the Taliban to allow teaching on TV?\" \n#> [21] \"Nil By Mouth review Gary Oldman’s overwhelming study of family violence\" \n#> [22] \"‘More dignity’ Aid organisations switch to cash in drought-hit Ethiopia\" \n#> [23] \"Europe Climate warming at twice rate of global average, says report\" \n#> [24] \"No more drinking water, little food: our island is a field of bones\" \n#> [25] \"Rishi Sunak PM U-turns on decision not to attend Cop27\" \n#> [26] \"Cop27 Egyptian hunger striker may die in prison, Nobel laureates warn world leaders attending summit\" \n#> [27] \"Fossil fuel burning once caused a mass extinction – now we’re risking another\" \n#> [28] \"World leaders at Cop27 in Egypt must demand the release of Alaa Abd El-Fattah\" \n#> [29] \"The ProPublica-Vanity Fair report on Covid-19’s origins is explosive. Is it reliable?\" \n#> [30] \"Benjamin Netanyahu may be back – but the true victory belongs to Israel’s far right\" \n#> [31] \"Can you ‘lose’ an accent? And more importantly, why would you want to?\" \n#> [32] \"With the global economy on the rocks, quiet quitting is no longer a thing\" \n#> [33] \"Qatar calling its critics racist opens a debate that may be worth having\" \n#> [34] \"Pancakes, shakes and KFC When Barkley tried to eat his way out of the 76ers\" \n#> [35] \"‘Any problem you have, it’s nothing’ Rico’s brotherly inspiration\" \n#> [36] \"World Series Astros silence Phillies in Game 4 with rare no-hitter\" \n#> [37] \"Cricket Yorkshire racism hearing to be held in public after request from Rafiq\" \n#> [38] \"T20 World Cup Australia wary of ‘pushing too hard’ to improve run rate\" \n#> [39] \"Chelsea 2-1 Dinamo Zagreb Chilwell set to miss World Cup with hamstring injury\" \n#> [40] \"To criticise or not to criticise Are women’s football pundits too nice?\" \n#> [41] \"Europe French-German friendship ‘still alive’ as Macron meets Scholz amid tensions\" \n#> [42] \"‘Nobody forced us’ The Greek builder who saved 80 Afghans from the sea\" \n#> [43] \"Italy Fall of Liz Truss gives far right a lesson in what not to do\" \n#> [44] \"‘Get Igor Girkin’ Hopes MH17 suspect could be captured fighting in Ukraine\" \n#> [45] \"Israel election Netanyahu thanks voters as rightwing bloc extends Israeli election lead\" \n#> [46] \"Africa Invasive mosquito could disrupt ‘landscape of malaria’ after cases rise\" \n#> [47] \"Twitter exodus Company faces murky future as top managers flee the nest\" \n#> [48] \"Climate crisis Big agriculture warns farming must change or risk ‘destroying the planet’\" \n#> [49] \"Hillsong Church Founder Brian Houston breaks silence with video stating ‘I will fight’ criminal charge in Australia\" \n#> [50] \"Denmark election Result keeps Social Democrats at the helm\" \n#> [51] \"Seoul crowd crush Local police offices raided in investigation\" \n#> [52] \"Exclusive UN poverty envoy tells Britain this is ‘worst time’ for more austerity\" \n#> [53] \"Ethiopian civil war Parties agree truce to end hostilities\" \n#> [54] \"Just Stop Oil Protesters who targeted Girl with a Pearl Earring jailed by Dutch court\" \n#> [55] \"Good Night Oppy review Cutesy Spielberg-assisted Mars documentary\" \n#> [56] \"Dinosaurs by Lydia Millet review Can a wealthy man be good?\" \n#> [57] \"‘Did I notice a dark side?’ The true story behind serial killer drama The Good Nurse\" \n#> [58] \"Selena Gomez My Mind & Me review: a fascinating and frustrating pop doc\" \n#> [59] \"Avatar: The Way of Water James Cameron releases extended trailer\" \n#> [60] \"Killer Sally review A warped true-crime tale of bodybuilder murder\" \n#> [61] \"How to cook the perfect ... Pumpkin gnocchi\" \n#> [62] \"Rail route of the month The slow train to Skagen, Denmark, where the North Sea meets the Baltic\" \n#> [63] \"A moment that changed me I threw away the sheet music and all the colour and passion I had for the harp came back to me\"\n#> [64] \"Pushing Buttons Pushing Buttons: Freaky games form some of my most vivid childhood memories\" \n#> [65] \"Kitchen aide Why parmesan rinds are a cook’s secret ingredient\" \n#> [66] \"From pirates’ hideout to Dalí’s bolthole Cadaqués, star of Spain’s Costa Brava\" \n#> [67] \"US midterm elections 2022 Republicans and Democrats spend big on ads\" \n#> [68] \"US midterm elections 2022 Why is Nike founder Phil Knight so desperate to prevent a Democratic win in Oregon?\" \n#> [69] \"Cambodia’s modern slavery nightmare The human trafficking crisis overlooked by authorities\" \n#> [70] \"Psychology I was an unhappy teenager, among lonely people, in thrall to a charismatic leader – had I joined a cult?\" \n#> [71] \"‘This is apartheid’ Cape Town slum residents condemn forced removals\" \n#> [72] \"‘I can’t work in the office safely’ The over-50s leaving the UK labour force\" \n#> [73] \"Russians Tell us what you think about Putin’s escalation of war in Ukraine\" \n#> [74] \"Iranians Share your views on the protests following Mahsa Amini’s death\" \n#> [75] \"Tell us How have you been affected by the situation in Ukraine?\" \n#> [76] \"Get in touch Share a story with the Guardian\" \n#> [77] \"Podcast Can Twitter survive Elon Musk? (And can Musk survive Twitter?)\" \n#> [78] \"Listen to previous episodes\" \n#> [79] \"Anywhere but Washington Moral panic, culture wars and Ron DeSantis: will Florida stay red in 2022?\" \n#> [80] \"Ukraine A village brutalised by Russia, and the youth rebuilding homes and hope\" \n#> [81] \"Rishi Sunak How he became UK PM: three days in three minutes\" \n#> [82] \"China Could Xi follow Putin's example and try to annex Taiwan?\" \n#> [83] \"US Can abortion rights swing the midterm elections?\" \n#> [84] \"Heating and eating Can cost of living and climate protesters join forces?\" \n#> [85] \"Ukraine How Russia’s strategy failed, not the tank\" \n#> [86] \"'I feel like the Beyoncé of Brazilian politics' The trans woman fighting back against Bolsonaro\" \n#> [87] \"Iran What the latest footage tells us about the regime\" \n#> [88] \"Galloping horses, spears and adrenaline In tent pegging 'anything can happen'\" \n#> [89] \"‘Extraordinary treasure trove’ Saul Leiter’s unseen images\" \n#> [90] \"Wednesday’s best photos Panda diplomacy and circus skills\" \n#> [91] \"The things left behind Seould police display belongings found after crowd crush – in pictures\" \n#> [92] \"Indigenous Australians Vigils held across Australia for Cassius Turvey\" \n#> [93] \"Village people The rituals of rural life\" \n#> [94] \"Mexico Day of the Dead celebrations\" \n#> [95] \"Grain deal U-turn offers lesson in calling Vladimir Putin’s bluff\" \n#> [96] \"Live Russia-Ukraine war live news: Blinken hails Turkish help as grain export deal resumes\" \n#> [97] \"Hong Kong exiles in UK unnerved by ‘weak’ response to beating of protester\" \n#> [98] \"‘We need your help’: young girl throws note over fence at Manston\" \n#> [99] \"North Korea ICBM launch may have been a failure, South’s military says\" \n#> [100] \"Zelenskiy labels Putin U-turn on Ukraine grain deal a ‘failure of Russian aggression’\" \n#> [101] \"Bahraini death row prisoner pleads with pope to aid his release\" \n#> [102] \"No more drinking water, little food: our island is a field of bones\" \n#> [103] \"Russia-Ukraine war at a glance: what we know on day 253 of the invasion\" \n#> [104] \"Father of three-year-old blames China’s zero-Covid policy for son’s death\"\n"
},
{
"answer_id": 74301578,
"author": "Gowthaman Ravindran",
"author_id": 10747860,
"author_profile": "https://Stackoverflow.com/users/10747860",
"pm_score": 0,
"selected": false,
"text": "//a[@data-link-name='article'and not(contains(@class, 'u-faux-block-link__overlay'))]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16027441/"
] |
74,300,291 | <p>I have a value of 64800 which is 18:00 in seconds, so I am in need of converting current time to seconds format which I would need to compare if it is after the 64800 or before.</p>
<pre><code>int minutes=64800;
long hours = TimeUnit.SECONDS.toHours(Long.valueOf(minutes));
long remainMinutes = minutes - TimeUnit.HOURS.toSeconds(hours);
System.out.println(String.format("%02d:%02d", hours, remainMinutes));
</code></pre>
<p>If I use <code>System.currentTimeMillis</code> I am unable to convert it</p>
| [
{
"answer_id": 74300734,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 1,
"selected": false,
"text": "Duration"
},
{
"answer_id": 74301134,
"author": "Roberto",
"author_id": 661140,
"author_profile": "https://Stackoverflow.com/users/661140",
"pm_score": 0,
"selected": false,
"text": "System.currentTimeMillis()"
},
{
"answer_id": 74329594,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "System.currentTimeMillis()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19584654/"
] |
74,300,298 | <p>I am new to WebRTC and trying to build a video chat. At the moment, all the functionality is implemented except for screen sharing. I took the React video chat example and upgrade it. Of course, I can turn on the screen sharing itself and it is shown at the host, but not transmitted to another users.</p>
<p><a href="https://github.com/rRaijin/video-chat-webrtc" rel="nofollow noreferrer">https://github.com/rRaijin/video-chat-webrtc</a></p>
<p>Tell me, please, is it necessary to use socket.emit in the case of sharing and process it for recipients, or should some method be called on RTCPeerConnection instance?</p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 74300734,
"author": "Arvind Kumar Avinash",
"author_id": 10819573,
"author_profile": "https://Stackoverflow.com/users/10819573",
"pm_score": 1,
"selected": false,
"text": "Duration"
},
{
"answer_id": 74301134,
"author": "Roberto",
"author_id": 661140,
"author_profile": "https://Stackoverflow.com/users/661140",
"pm_score": 0,
"selected": false,
"text": "System.currentTimeMillis()"
},
{
"answer_id": 74329594,
"author": "Thomas",
"author_id": 637853,
"author_profile": "https://Stackoverflow.com/users/637853",
"pm_score": 3,
"selected": true,
"text": "System.currentTimeMillis()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9018283/"
] |
74,300,302 | <p>I wrote a handler for my keypad. Whenever press a button on keypad my board will interrupt but I think I have an bouncing problem.</p>
<p>I have a 4 x SSD, when I press the button, all 4 digits are going to same number. When I try on debugging mode, everything is okay.</p>
<p>How can I fix this? I wrote some delays but it still not working. I am using 4x4 keypad but I am just using 4x3 with 3 input, 4 output pins.</p>
<p>This is my IRQHandler :</p>
<pre><code>/* Interrupt Handler */
void EXTI4_15_IRQHandler(void){
/* keypad press from C1 */
KeypadAllRows_RESET();
GPIOB->ODR |= (1U << 0); //Row4
if((GPIOB->IDR & (1U << 5)) == (1U << 5)) //2
KeyPress = 0;
KeypadAllRows_RESET();
GPIOA->ODR |= (1U << 8); //Row1
if((GPIOB->IDR & (1U << 4)) == (1U << 4)) //1
KeyPress = 1;
if((GPIOB->IDR & (1U << 5)) == (1U << 5)) //2
KeyPress = 2;
if((GPIOB->IDR & (1U << 9)) == (1U << 9)) //3
KeyPress = 3;
KeypadAllRows_RESET();
GPIOB->ODR |= (1U << 8); //Row2
if((GPIOB->IDR & (1U << 4)) == (1U << 4)) //4
KeyPress = 4;
if((GPIOB->IDR & (1U << 5)) == (1U << 5)) //5
KeyPress = 5;
if((GPIOB->IDR & (1U << 9)) == (1U << 9)) //6
KeyPress = 6;
KeypadAllRows_RESET();
GPIOB->ODR |= (1U << 2); //Row3
if((GPIOB->IDR & (1U << 4)) == (1U << 4)) //7
KeyPress = 7;
if((GPIOB->IDR & (1U << 5)) == (1U << 5)) //8
KeyPress = 8;
if((GPIOB->IDR & (1U << 9)) == (1U << 9)) //9
KeyPress = 9;
SSD_Digit1 = SSD_Digit2;
SSD_Digit2 = SSD_Digit3;
SSD_Digit3 = SSD_Digit4;
SSD_Digit4 = KeyPress;
EXTI->RPR1 |= (1U << 4);
EXTI->RPR1 |= (1U << 5);
EXTI->RPR1 |= (1U << 9);
KeypadAllRows_SET();
</code></pre>
<p>And also this is my Loop , ( I think my loop is okay ) :</p>
<pre><code>SSD_Close();
GPIOA->ODR |= (1U << 7); //D4
SSD_SET(SSD_Digit4);
delay(200);
SSD_Close();
GPIOB->ODR |= (1U << 7); //D3
SSD_SET(SSD_Digit3);
delay(200);
SSD_Close();
GPIOA->ODR |= (1U << 15); //D2
SSD_SET(SSD_Digit2);
delay(200);
SSD_Close();
GPIOA->ODR |= (1U << 9); //D1
SSD_SET(SSD_Digit1);
delay(200);
</code></pre>
<p>I Edited the code,</p>
<p>*Delays in Handler are removed.</p>
<p>*Row3 is working. But another numbers are not working well. The row I wrote at the bottom in the Handler only works properly. When I click on the numbers in the other Rows, the digits of all SSDs become the same number.</p>
| [
{
"answer_id": 74346122,
"author": "AnatolianPerseus",
"author_id": 20204406,
"author_profile": "https://Stackoverflow.com/users/20204406",
"pm_score": 1,
"selected": true,
"text": "EXTI->RPR1 |= (1U << 4);\nEXTI->RPR1 |= (1U << 5);\nEXTI->RPR1 |= (1U << 9);\nKeypadAllRows_SET();\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20204406/"
] |
74,300,332 | <p>I'm getting different return values when using square bracket and was wondering what the bracket is for in this scenario?</p>
<pre><code>SELECT COUNT (distinct customer_id), customer_type
FROM Customers
GROUP BY customer_type
</code></pre>
<p>VS</p>
<pre><code>SELECT COUNT (distinct([customer_id])), customer_type
FROM Customers
GROUP BY customer_type
</code></pre>
<p>Thanks</p>
<p>I ran the query and it was showing two different results - I'm trying to find out what the bracket does in this situation.</p>
| [
{
"answer_id": 74346122,
"author": "AnatolianPerseus",
"author_id": 20204406,
"author_profile": "https://Stackoverflow.com/users/20204406",
"pm_score": 1,
"selected": true,
"text": "EXTI->RPR1 |= (1U << 4);\nEXTI->RPR1 |= (1U << 5);\nEXTI->RPR1 |= (1U << 9);\nKeypadAllRows_SET();\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405800/"
] |
74,300,338 | <p>I am a bit puzzled on how to achieve this after trying so many times.
It needs to start with 2 numbers, first number must be 9, then hyphen, then A-Za-z, then dot, then A-Za-z, then hyphen, and end must have 4 digits.</p>
<p>Simple terms for those who don't understand the question:
"9<1 digit here>-<sometext.sometext>-<4digits>"</p>
<p>Problem starts with the character dot in the middle of the string.
Here is my regex:</p>
<pre><code>^([9])([a-zA-Z0-9]*-*\.){2}[a-zA-Z0-9]\d{4}$
</code></pre>
<p>Example input:</p>
<ul>
<li>90-Amir.h-8394</li>
<li>91-Hamzah.K-4752</li>
</ul>
<p>Tried figuring out where to put the syntax for the Regex to detect the character dot. But it is not working.</p>
| [
{
"answer_id": 74346122,
"author": "AnatolianPerseus",
"author_id": 20204406,
"author_profile": "https://Stackoverflow.com/users/20204406",
"pm_score": 1,
"selected": true,
"text": "EXTI->RPR1 |= (1U << 4);\nEXTI->RPR1 |= (1U << 5);\nEXTI->RPR1 |= (1U << 9);\nKeypadAllRows_SET();\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405761/"
] |
74,300,361 | <p>At the top of the page I get a url:</p>
<pre><code>$posturl = $_GET['posturl'];
</code></pre>
<p>Works, I got the URl.</p>
<p>The I have a series of checkboxes to delete attachments within a form post:</p>
<pre><code><form action="" method="post">
<?php
$attachments = get_posts(array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' =>'any',
'post_parent' => $_GET['post_id']
));
if ($attachments) {
foreach ( $attachments as $attachment ) {
$myNewImg = wp_get_attachment_url( $attachment->ID );
$pathtofile = $myNewImg;
$info = pathinfo($pathtofile);
if ( ($info["extension"] == "jpg") || ($info["extension"] == "png") || ($info["extension"] == "JPG") || ($info["extension"] == "jpeg") || ($info["extension"] == "gif") ) { ?>
<img src="<?php echo $myNewImg; ?>" class="bnr_img img-fluid mx-auto d-block" alt="">
<input type="checkbox" class="img_delete" name="img_delete[]" value="<?php echo $attachment->ID; ?>">
<?php } else { ?>
<video src="<?php echo $myNewImg; ?>" controls></video>
<input type="checkbox" class="img_delete" name="img_delete[]" value="<?php echo $attachment->ID; ?>">
<?php }
}
}
?>
<input class="btn btn-dark" type="submit" name="delete_media" value="Delete media">
</form>
</code></pre>
<p>All works fine, I get the media attachments and a checkbox next to it:</p>
<p>I now want to delete media files checked, so they're an array (img_delete[]) so I do:</p>
<pre><code><?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['delete_media'])) {
foreach($_POST['img_delete'] as $value) {
wp_delete_attachment( $value, true);
}
header('Location: '.$posturl);
}
}
?>
</code></pre>
<p>It's ok but:</p>
<ol>
<li>page doesn't refresh</li>
<li>page stays there but it only shows one item (even tho 2 have been deleted)</li>
<li>if i refresh the page, then I see both have been deleted</li>
</ol>
<p>So basically I'm trying to redirect the page so that user sees the live page without media attachments.</p>
| [
{
"answer_id": 74301927,
"author": "Krishan Kaushik",
"author_id": 11901990,
"author_profile": "https://Stackoverflow.com/users/11901990",
"pm_score": -1,
"selected": false,
"text": "<?php\n if ($_SERVER['REQUEST_METHOD'] === 'POST') {\n if (isset($_POST['delete_media'])) {\n foreach($_POST['img_delete'] as $value) {\n wp_delete_attachment( $value, true);\n } \n header('Location: '.$posturl);\n }\n }\n?>\n"
},
{
"answer_id": 74302024,
"author": "Cornel Raiu",
"author_id": 3741900,
"author_profile": "https://Stackoverflow.com/users/3741900",
"pm_score": 2,
"selected": true,
"text": "header()"
},
{
"answer_id": 74315530,
"author": "ASHIK.M.B",
"author_id": 15598965,
"author_profile": "https://Stackoverflow.com/users/15598965",
"pm_score": 0,
"selected": false,
"text": "<?php\n if($_SERVER['REQUEST_METHOD'] === 'POST'){\n if(isset($_POST['delete_media'])){\n foreach($_POST['img_delete'] as $value) {\n wp_delete_attachment( $value, true);\n } \n wp_redirect($posturl); \n \n }\n }\n?>\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018804/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.