qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,637,707
|
<p>The problem is the drop-down behavior (here's the <a href="https://codepen.io/alexakarpov/pen/OJEoYOM" rel="nofollow noreferrer">codepen</a> to the problematic html, the original layout was taken from <a href="https://github.com/veryacademy/django-ecommerce-project/blob/main/Part-10%20Pytest%20Testing%201/templates/base.html" rel="nofollow noreferrer">here</a>).</p>
<pre><code><header class="pb-3">
<nav class="navbar navbar-expand-md navbar-light bg-white border-bottom">
<div class="d-flex w-100 navbar-collapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li>
<div style="width: 100px; height: 100px">
<a href="#">
<img src="../static/store_logo.png" alt="logo" />
</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-none d-md-block fw500" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Product categories
</a>
<ul class="dropdown-menu rounded-0 border-0">
<a href="#">
<li>Foo</li>
</a>
<a href="#">
<li>Bar</li>
</a>
<a href="#">
<li>Baz</li>
</a>
</ul>
</li>
</ul>
</div>
</nav>
</header>
</code></pre>
<p>In the original source the problem is hidden by the fact that a logo image/placeholder inside the nav > .navbar ul is tiny. When I used a larger image, it becomes manifest (I used a div with fixed 100 by 100 px to mimic it in the pen).
The problem is the behavior of a drop-down in the same nav. The list of items in .dropdown-menu (ul) doesn't attach to the bottom of the .dropdown-toggle element - instead it's attached to the bottom of the .navbar-nav ul. Which, naturally, is affected by the size of the li containing the image/placeholder.</p>
<p>Being a css noob, I don't know what is the real cause of the problem. Is it a conflict
beyween some of the bootstrap classes? I even tried adding a z-index to the .dropdown-menu ul, to no avail. Basic dropdown example in the Bootstrap docs doesn't seem to require any additional tweaks - but there's no navs/navbars involved in there (not to mention a dozen other parent elements).</p>
<p>Thank you all for your time!</p>
|
[
{
"answer_id": 74638101,
"author": "Delowar Hossen",
"author_id": 6602096,
"author_profile": "https://Stackoverflow.com/users/6602096",
"pm_score": 2,
"selected": true,
"text": "body .navbar-expand-md .navbar-nav .dropdown-menu {\n top: 30px !important;\n}\n"
},
{
"answer_id": 74663408,
"author": "alexakarpov",
"author_id": 809584,
"author_profile": "https://Stackoverflow.com/users/809584",
"pm_score": 0,
"selected": false,
"text": ".navbar-expand-md .navbar-nav .dropdown-menu {\n position: static;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809584/"
] |
74,637,713
|
<p>As my project is expo ejected react native project and I'm getting the error [native] Could not find image on path</p>
<p><strong>'file:///var/mobile/Containers/Data/Application/..../Library/Application%20Support/.expo-internal/assets/...'</strong></p>
<p><code> "react": "17.0.1", "react-native": "0.64.0", "expo": "~41.0.1", "expo-error-recovery": "^2.1.0", "expo-font": "~9.1.0", "expo-modules-core": "^0.2.0", "expo-splash-screen": "^0.10.3", "expo-status-bar": "~1.0.4", "expo-updates": "^0.5.5",</code></p>
<p>I have tried this solutions but not working any solution for my code</p>
<p><a href="https://stackoverflow.com/questions/43193215/firebase-cloud-messaging-handling-logout">Firebase Cloud Messaging - Handling logout</a></p>
<p><a href="https://stackoverflow.com/questions/69968225/expo-react-native-cant-find-image-file-after-ejecting-to-bare-workflow">Expo/React Native: Can't find image file after ejecting to bare workflow</a></p>
|
[
{
"answer_id": 74638101,
"author": "Delowar Hossen",
"author_id": 6602096,
"author_profile": "https://Stackoverflow.com/users/6602096",
"pm_score": 2,
"selected": true,
"text": "body .navbar-expand-md .navbar-nav .dropdown-menu {\n top: 30px !important;\n}\n"
},
{
"answer_id": 74663408,
"author": "alexakarpov",
"author_id": 809584,
"author_profile": "https://Stackoverflow.com/users/809584",
"pm_score": 0,
"selected": false,
"text": ".navbar-expand-md .navbar-nav .dropdown-menu {\n position: static;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18028026/"
] |
74,637,737
|
<p>I want to make multiple texts with multiple colors like red, green, yellow something like that now it is working for only one color I need each text in a different color please help me
here is the code
<a href="https://codesandbox.io/s/quizzical-fire-qhu3hd?file=/src/App.js" rel="nofollow noreferrer">https://codesandbox.io/s/quizzical-fire-qhu3hd?file=/src/App.js</a></p>
<pre><code>import React from "react";
function App() {
const highlightText = (text, textToMatch) => {
const matchRegex = RegExp(textToMatch.join("|"), "ig");
const matches = [...text.matchAll(matchRegex)];
console.log(matches);
return text.split(matchRegex).map((nonBoldText, index, arr) => (
<div key={index}>
{nonBoldText}
{index + 1 !== arr.length && <mark>{matches[index]}</mark>}
</div>
));
};
return (
<h4>
{highlightText(
"The aim of this study was to someting in vitro the potential of Aloe Vera juice as a skin permeation enhancer; worong text is added here to which Aloe Vera itself permeates the skin. Saturated solutions of caffeine, colchicine, mefenamic acid, oxybutynin, and quinine were prepared at 32 degrees C in Aloe Vera juice and water (control) and used to dose porcine ear skin",
["Aloe Vera", "and", "study"]
)}
</h4>
);
}
export default App;
</code></pre>
|
[
{
"answer_id": 74638280,
"author": "Tejashree Surve",
"author_id": 15197074,
"author_profile": "https://Stackoverflow.com/users/15197074",
"pm_score": 1,
"selected": false,
"text": " const highlightText = (text, textToMatch) => {\n const matchRegex = RegExp(textToMatch.join(\"|\"), \"ig\");\n const matches = [...text.matchAll(matchRegex)];\n// this consist of the color array \n const color = [\"green\", \"red\", \"yellow\"];\n return text.split(matchRegex).map((nonBoldText, index, arr) => (\n <div key={index}>\n {nonBoldText}\n {index + 1 !== arr.length && (\n <mark\n style={{\n// and this match the color index and textMatchIndex\n backgroundColor:\n color[\n matches[index] ? textToMatch.indexOf(matches[index][0]) : \"\"\n ]\n }}\n >\n {matches[index]}\n </mark>\n )}\n </div>\n ));\n };\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9994689/"
] |
74,637,747
|
<p>How can I reduce the number of bits from 24 bits to a number between 0 and 8 bits and distribute the bits for the three colors Red, Green and Blue</p>
<p>Any idea ?</p>
|
[
{
"answer_id": 74638280,
"author": "Tejashree Surve",
"author_id": 15197074,
"author_profile": "https://Stackoverflow.com/users/15197074",
"pm_score": 1,
"selected": false,
"text": " const highlightText = (text, textToMatch) => {\n const matchRegex = RegExp(textToMatch.join(\"|\"), \"ig\");\n const matches = [...text.matchAll(matchRegex)];\n// this consist of the color array \n const color = [\"green\", \"red\", \"yellow\"];\n return text.split(matchRegex).map((nonBoldText, index, arr) => (\n <div key={index}>\n {nonBoldText}\n {index + 1 !== arr.length && (\n <mark\n style={{\n// and this match the color index and textMatchIndex\n backgroundColor:\n color[\n matches[index] ? textToMatch.indexOf(matches[index][0]) : \"\"\n ]\n }}\n >\n {matches[index]}\n </mark>\n )}\n </div>\n ));\n };\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16480714/"
] |
74,637,828
|
<p>I am not able to run java in vs code [my code]</p>
<pre><code>public class hello {
public static void main(String args[]) {
System.out.print("Hello World")
}
}
</code></pre>
<p>. I don't even have an option of run code in terminal in my settings..It is not showing any error or anything too![erased the semi-colon; but not showing any error].JDK-19 is installed and working.</p>
<p>I watched vids on youtube for a solution everyone is saying check "run code in terminal" option. I also downloaded an extention named code runner by which finally "run code in terminal" option was there I checked it and it still didn't work.</p>
|
[
{
"answer_id": 74638280,
"author": "Tejashree Surve",
"author_id": 15197074,
"author_profile": "https://Stackoverflow.com/users/15197074",
"pm_score": 1,
"selected": false,
"text": " const highlightText = (text, textToMatch) => {\n const matchRegex = RegExp(textToMatch.join(\"|\"), \"ig\");\n const matches = [...text.matchAll(matchRegex)];\n// this consist of the color array \n const color = [\"green\", \"red\", \"yellow\"];\n return text.split(matchRegex).map((nonBoldText, index, arr) => (\n <div key={index}>\n {nonBoldText}\n {index + 1 !== arr.length && (\n <mark\n style={{\n// and this match the color index and textMatchIndex\n backgroundColor:\n color[\n matches[index] ? textToMatch.indexOf(matches[index][0]) : \"\"\n ]\n }}\n >\n {matches[index]}\n </mark>\n )}\n </div>\n ));\n };\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653060/"
] |
74,637,830
|
<p>Problem Statement:
<a href="https://i.stack.imgur.com/fahQR.png" rel="nofollow noreferrer">In shown image, default profile pic is visible but i need uploaded photo to be displayed here when i upload and saved in the database.I am using django framework. </a></p>
<p>What have I Tried here?</p>
<p>In setting.html file,The below is the HTML code for what is have tried to display image, bio, location. The problem may be at first div image tag. Though the default profile picture is visible but which i have uploaded is not displaying in the page nor able to save in database.</p>
<pre><code><form action="" method ="POST">
{% csrf_token %}
<div class="grid grid-cols-2 gap-3 lg:p-6 p-4">
<div class="col-span-2">
<label for="">Profile Image</label>
<img width = "100" height = "100" src="{{user_profile.profileimg.url}}"/>
<input type="file" name='image' value = "" placeholder="No file chosen" class="shadow-none bg-gray-100">
</div>
<div class="col-span-2">
<label for="about">Bio</label>
<textarea id="about" name="bio" rows="3" class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea>
</div>
<div class="col-span-2">
<label for=""> Location</label>
<input type="text" name = "location" value = "{{user_profile.location}}" placeholder="" class="shadow-none bg-gray-100">
</div>
</div>
<div class="bg-gray-10 p-6 pt-0 flex justify-end space-x-3">
<button class="p-2 px-4 rounded bg-gray-50 text-red-500"> <a href="/"> Cancel</a> </button>
<button type="submit" class="button bg-blue-700"> Save </button>
</div>
</form>
</code></pre>
<p>In views.py file,the below function is the views file settings page logic for displaying the image, bio, location. If the image is not uploaded, it will be default profile picture. If image is not none then the uploaded image is displayed. But I am not getting what is the mistake here in my code.</p>
<pre><code>@login_required(login_url='signin')
def settings(request):
user_profile = Profile.objects.get(user = request.user)
if request.method == "POST":
if request.FILES.get('image')== None:
image = user_profile.profileimg
bio = request.POST['bio']
location = request.POST['location']
else:
image = request.FILES.get('image')
bio = request.POST['bio']
location = request.POST['location']
user_profile.profileimg = image
user_profile.bio = bio
user_profile.location = location
user_profile.save()
return redirect("settings")
return render(request, 'setting.html', {'user_profile': user_profile})
</code></pre>
<p>I am expecting to know what the mistake in the code is. Only profileimg cannot be saved in database. the other data is able to save like bio, location.</p>
<p>The below is the model.py file.</p>
<pre><code>from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
id_user = models.IntegerField()
bio = models.TextField(blank=True)
profileimg = models.ImageField(upload_to = 'profile_images', default= 'blank-profile-picture.png')
location = models.CharField(max_length = 100, blank = True)
def __str__(self):
return self.user.username
</code></pre>
<p>The below is the media folder in settings.py file.</p>
<pre><code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code></pre>
<p>urls.py</p>
<pre><code>from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
</code></pre>
<p>Photo is not displaying.
<img src="https://i.stack.imgur.com/YfHio.png" alt="Photo is not displaying." /></p>
|
[
{
"answer_id": 74637888,
"author": "Manoj Tolagekar",
"author_id": 17808039,
"author_profile": "https://Stackoverflow.com/users/17808039",
"pm_score": 0,
"selected": false,
"text": "<img width = \"100\" height = \"100\" src=\"/media/{{user_profile.profileimg}}\"/>\n upload_to='profile_images/'\n urlpatterns = [\n\n]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n"
},
{
"answer_id": 74639703,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 1,
"selected": false,
"text": "src=\"/media/{{user_profile.profileimg}}\"\n"
},
{
"answer_id": 74640080,
"author": "Naser Fazal khan",
"author_id": 19313399,
"author_profile": "https://Stackoverflow.com/users/19313399",
"pm_score": 1,
"selected": false,
"text": " if request.method == \"POST\" and \"image\" in request.FILES:\n image= request.FILES['image']\n"
},
{
"answer_id": 74640233,
"author": "Vijay Krishna Narsingoju",
"author_id": 20652967,
"author_profile": "https://Stackoverflow.com/users/20652967",
"pm_score": 0,
"selected": false,
"text": "<form action=\"\" method =\"POST\" enctype = \"multipart/form-data\">\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20652967/"
] |
74,637,834
|
<p>I am trying to install <code>zipline-reloaded</code> using <code>conda</code> but am encountering a <code>PackagesNotFoundError</code>—this despite running the install command for <code>zipline-reloaded</code> provided on the <a href="https://anaconda.org/ml4t/zipline-reloaded" rel="nofollow noreferrer">package's page</a> on anaconda.org. What might be going wrong here, and how can I resolve it?</p>
<p>My steps this far:</p>
<ol>
<li><code>conda create -n zipline python=3.8</code></li>
<li><code>conda activate zipline</code></li>
<li><code>conda install -c ml4t zipline-reloaded</code> (this is directly from the package's page on anaconda.org, linked above, but raises <code>PackagesNotFoundError</code>)</li>
</ol>
<p>Note that trying to install, e.g., <code>scipy</code>, yields no similar error. Also, using <code>mamba</code> instead of <code>conda</code> leads to the same <code>PackagesNotFoundError</code> error.</p>
<p>The output of <code>conda info</code> is below:</p>
<pre><code>active environment : zipline
active env location : /opt/homebrew/Caskroom/miniforge/base/envs/zipline
shell level : 1
user config file : /Users/name/.condarc
populated config files : /opt/homebrew/Caskroom/miniforge/base/.condarc
/Users/name/.condarc
conda version : 22.9.0
conda-build version : not installed
python version : 3.9.15.final.0
virtual packages : __osx=12.4=0
__unix=0=0
__archspec=1=arm64
base environment : /opt/homebrew/Caskroom/miniforge/base (writable)
conda av data dir : /opt/homebrew/Caskroom/miniforge/base/etc/conda
conda av metadata url : None
channel URLs : https://conda.anaconda.org/ml4t/osx-arm64
https://conda.anaconda.org/ml4t/noarch
https://conda.anaconda.org/conda-forge/osx-arm64
https://conda.anaconda.org/conda-forge/noarch
https://repo.anaconda.com/pkgs/main/osx-arm64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/r/osx-arm64
https://repo.anaconda.com/pkgs/r/noarch
https://conda.anaconda.org/ranaroussi/osx-arm64
https://conda.anaconda.org/ranaroussi/noarch
package cache : /opt/homebrew/Caskroom/miniforge/base/pkgs
/Users/name/.conda/pkgs
envs directories : /opt/homebrew/Caskroom/miniforge/base/envs
/Users/name/.conda/envs
platform : osx-arm64
user-agent : conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
UID:GID : 501:20
netrc file : None
offline mode : False
</code></pre>
<p>I've tried running:</p>
<pre class="lang-bash prettyprint-override"><code>conda clean -all
conda clean --index-cache
conda update conda
</code></pre>
<p>I've also made sure to set offline mode to false (<code>conda config --set offline false</code>), which it is, per the output above.</p>
<p>Finally, running <code>conda search -c ml4t zipline-reloaded -vvv</code> outputs:</p>
<pre class="lang-bash prettyprint-override"><code>DEBUG conda.gateways.logging:set_verbosity(236): verbosity set to 3
Loading channels: ...working... TRACE conda.gateways.disk.test:file_path_is_writable(24): checking path is writable /opt/homebrew/Caskroom/miniforge/base/pkgs/urls.txt
DEBUG conda.core.package_cache_data:_check_writable(268): package cache directory '/opt/homebrew/Caskroom/miniforge/base/pkgs' writable: True
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://conda.anaconda.org/ml4t/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/b4814506.json
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://conda.anaconda.org/ml4t/noarch/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/091140c5.json
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://repo.anaconda.com/pkgs/r/noarch/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/4ea078d6.json
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://conda.anaconda.org/ranaroussi/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/639ecbbd.json
DEBUG conda.core.subdir_data:_load(267): Using cached repodata for https://conda.anaconda.org/conda-forge/noarch/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/09cdf8bf.json. Timeout in 42 sec
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://repo.anaconda.com/pkgs/r/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/8bd55712.json
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://repo.anaconda.com/pkgs/main/noarch/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/3e39a7aa.json
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/09cdf8bf.q
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://conda.anaconda.org/ranaroussi/noarch/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/f2f1db2e.json
DEBUG conda.core.subdir_data:_load(267): Using cached repodata for https://conda.anaconda.org/conda-forge/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/a850f475.json. Timeout in 37 sec
DEBUG conda.core.subdir_data:_load(273): Local cache timed out for https://repo.anaconda.com/pkgs/main/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/9e99ffaf.json
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/a850f475.q
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): conda.anaconda.org:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): conda.anaconda.org:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): conda.anaconda.org:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): conda.anaconda.org:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG urllib3.connectionpool:_new_conn(1003): Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG urllib3.connectionpool:_make_request(456): https://conda.anaconda.org:443 "GET /ml4t/osx-arm64/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /ml4t/osx-arm64/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Sun, 27 Nov 2022 23:15:46 GMT
<<HTTPS 304 Not Modified
< CF-Cache-Status: DYNAMIC
< CF-Ray: 7729c305af6cc3f0-EWR
< Date: Thu, 01 Dec 2022 06:28:16 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=5_iHfkEj0MHUfLTzo1_JU44eFH7k.fkG4MefCLHFwCs-1669876096-0-Afv4K+DTTGsbF/EJ55ZMcprcOQU03A9xjLx1fVCxk220/+qEj2KgM0D9KShLZZMNwWIGCF/SrfFT/0yOU8PYUb3c1sef5rFCHNw00EumeSIB; path=/; expires=Thu, 01-Dec-22 06:58:16 GMT; domain=.anaconda.org; HttpOnly; Secure; SameSite=None
< Strict-Transport-Security: max-age=31536000
< Vary: Accept-Encoding
< Connection: keep-alive
< Elapsed: 00:00.374252
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://conda.anaconda.org/ml4t/osx-arm64/repodata.json'. Updating mtime and loading from disk
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/b4814506.json
DEBUG urllib3.connectionpool:_make_request(456): https://conda.anaconda.org:443 "GET /ranaroussi/osx-arm64/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /ranaroussi/osx-arm64/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Sat, 10 Jul 2021 20:29:09 GMT
<<HTTPS 304 Not Modified
< CF-Cache-Status: DYNAMIC
< CF-Ray: 7729c305b931c436-EWR
< Date: Thu, 01 Dec 2022 06:28:16 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=L8JbFm6EySvGhs3b0c54CFobV5MnnDkLYszHBXNbkOE-1669876096-0-AXqlxjWUQxlASGQq2FDCPHAie99ZATvZmSa+RepV64uBbnR2GAeRM3oe+VMrkj23RXFUNlC8xP/j689pu+kPxuVwr5M1u96nKabCLWSujD5q; path=/; expires=Thu, 01-Dec-22 06:58:16 GMT; domain=.anaconda.org; HttpOnly; Secure; SameSite=None
< Strict-Transport-Security: max-age=31536000
< Vary: Accept-Encoding
< Connection: keep-alive
< Elapsed: 00:00.449782
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://conda.anaconda.org/ranaroussi/osx-arm64/repodata.json'. Updating mtime and loading from disk
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/639ecbbd.json
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/b4814506.q
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/639ecbbd.q
DEBUG urllib3.connectionpool:_make_request(456): https://conda.anaconda.org:443 "GET /ml4t/noarch/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /ml4t/noarch/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Sun, 27 Nov 2022 23:15:46 GMT
<<HTTPS 304 Not Modified
< CF-Cache-Status: DYNAMIC
< CF-Ray: 7729c306acba17a5-EWR
< Date: Thu, 01 Dec 2022 06:28:17 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=OUlfjhiwUIls5GRrkrvx_gSvGNQ8jSFq4C4FQHuUEkI-1669876097-0-AeZAUF8zYwue32HP8rVUfV7ws8cYe8P/MZIXlS5tWbRONDfIemqH4Ze4eE1R6UuAdqaqqw/Rh2jJscMkBWdApRdTtKFIYda2yA5HJ44Urw+N; path=/; expires=Thu, 01-Dec-22 06:58:17 GMT; domain=.anaconda.org; HttpOnly; Secure; SameSite=None
< Strict-Transport-Security: max-age=31536000
< Vary: Accept-Encoding
< Connection: keep-alive
< Elapsed: 00:00.531916
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://conda.anaconda.org/ml4t/noarch/repodata.json'. Updating mtime and loading from disk
DEBUG urllib3.connectionpool:_make_request(456): https://repo.anaconda.com:443 "GET /pkgs/r/osx-arm64/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /pkgs/r/osx-arm64/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Fri, 19 Aug 2022 21:27:22 GMT
> If-None-Match: W/"bd18071599942dd824e1ec40e9d10873"
<<HTTPS 304 Not Modified
< Age: 70484
< Cache-Control: public, max-age=30
< CF-Cache-Status: HIT
< CF-RAY: 7729c306daf41899-EWR
< Date: Thu, 01 Dec 2022 06:28:17 GMT
< ETag: "bd18071599942dd824e1ec40e9d10873"
< Expires: Thu, 01 Dec 2022 06:28:47 GMT
< Last-Modified: Tue, 03 May 2022 07:57:20 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=JAZuB9kuZKjDvy1WXV.IHe1gCAnfEEZIs2uQ0YOh.nY-1669876097-0-AcbFb9BTBsrUintQD6w4DP0qheARYSHDdmj1IfpgfRRjTdJlAeFbjfAQhX/8gthx2K7VCEDYMRtjVnJGkgyCwUw=; path=/; expires=Thu, 01-Dec-22 06:58:17 GMT; domain=.anaconda.com; HttpOnly; Secure; SameSite=None
< Vary: Accept-Encoding
< x-amz-id-2: fY9HZBoI/58riYlxXBQEYfV8bKmFamLhAbhZ0J9i5X/O76LU6Xv7DmrLw/lA4gHYZlTeq3dMEDM=
< x-amz-request-id: YY7S26ZWVFSN8T0M
< x-amz-version-id: PxKW1ua_FXQgEcZyls93YYZW2aaplpSK
< Connection: keep-alive
< Elapsed: 00:00.524347
DEBUG urllib3.connectionpool:_make_request(456): https://repo.anaconda.com:443 "GET /pkgs/main/osx-arm64/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://repo.anaconda.com/pkgs/r/osx-arm64/repodata.json'. Updating mtime and loading from disk
DEBUG urllib3.connectionpool:_make_request(456): https://repo.anaconda.com:443 "GET /pkgs/main/noarch/repodata.json HTTP/1.1" 304 0
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/091140c5.json
DEBUG urllib3.connectionpool:_make_request(456): https://repo.anaconda.com:443 "GET /pkgs/r/noarch/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /pkgs/main/osx-arm64/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Wed, 30 Nov 2022 19:20:01 GMT
> If-None-Match: W/"1d4ef7661a7ed1933c0a6c41ba4cc425"
<<HTTPS 304 Not Modified
< Age: 39940
< Cache-Control: public, max-age=30
< CF-Cache-Status: HIT
< CF-RAY: 7729c306dadbc431-EWR
< Date: Thu, 01 Dec 2022 06:28:17 GMT
< ETag: "1d4ef7661a7ed1933c0a6c41ba4cc425"
< Expires: Thu, 01 Dec 2022 06:28:47 GMT
< Last-Modified: Wed, 30 Nov 2022 19:20:01 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=7x27GyPAJ_UqkTJ5ao1cZqqBeayN2Vq_70IaoJpxzR8-1669876097-0-ATY8FjtZs8mdSSsf4qFxF152kwLQLqkVqwVancCZTg2qapMhP1+FEa/52Z+AOF4oswA3GiYn7Uix0Aw73CW0GRs=; path=/; expires=Thu, 01-Dec-22 06:58:17 GMT; domain=.anaconda.com; HttpOnly; Secure; SameSite=None
< Vary: Accept-Encoding
< x-amz-id-2: Uish9rt+JimvRr8GdFZh7QAY41ytOYotp0TpctIyZ20CIAjj/6MuY/CWhjDJpjKlCv1rRqREnwY=
< x-amz-request-id: JVFF0K2E15ZN38V9
< x-amz-version-id: NpiUwg7Fl941vKA3jucFV5n6mUv51EJP
< Connection: keep-alive
< Elapsed: 00:00.524693
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/8bd55712.json
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /pkgs/main/noarch/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Tue, 29 Nov 2022 16:03:07 GMT
> If-None-Match: W/"6e04ba60f4112b8b66a702155b149789"
<<HTTPS 304 Not Modified
< Age: 138272
< Cache-Control: public, max-age=30
< CF-Cache-Status: HIT
< CF-RAY: 7729c306da4b8c45-EWR
< Date: Thu, 01 Dec 2022 06:28:17 GMT
< ETag: "6e04ba60f4112b8b66a702155b149789"
< Expires: Thu, 01 Dec 2022 06:28:47 GMT
< Last-Modified: Tue, 29 Nov 2022 16:03:07 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=8QKdusunJ3shgZum2CdhgDnvVSZar0.5gchEPAhnDBY-1669876097-0-AegybkAav3z1xItNVSkXgTOadb6BWGFIkf1h503nEQXjDZzXBwfpUPK6FUZ2NL6Lm1Vp5CzzYIbuW8VJDG2RDGo=; path=/; expires=Thu, 01-Dec-22 06:58:17 GMT; domain=.anaconda.com; HttpOnly; Secure; SameSite=None
< Vary: Accept-Encoding
< x-amz-id-2: XOcwXl6k5xoUe4CZu165pl5DxNRL491AX2Bo9oR0kKVB7C17o3jsWbDG9NiZYZJdTx5oBpaxcqA=
< x-amz-request-id: GVVB079XW40XCD4Q
< x-amz-version-id: Q4_RUh4DCA9G9p4t7FVjTf1kw3tFux..
< Connection: keep-alive
< Elapsed: 00:00.530062
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /pkgs/r/noarch/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Fri, 28 Oct 2022 15:33:23 GMT
> If-None-Match: W/"93476d5e7aa8d3f8bc0c04afafc94d26"
<<HTTPS 304 Not Modified
< Age: 485667
< Cache-Control: public, max-age=30
< CF-Cache-Status: HIT
< CF-RAY: 7729c306dc0918d0-EWR
< Date: Thu, 01 Dec 2022 06:28:17 GMT
< ETag: "93476d5e7aa8d3f8bc0c04afafc94d26"
< Expires: Thu, 01 Dec 2022 06:28:47 GMT
< Last-Modified: Fri, 28 Oct 2022 15:33:23 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=RY6dkW_AH.MOyDqWGMA8yJp41UzE7C0EjdUA6z.qv2E-1669876097-0-AX/HkmV1qRZQ5J/UH1Z0z4SbLecq+BzVhaoJGmrI2vgoIR/bJv2tfkoNqHeerl3ZI2S6oqtRb8P0Gav35+nOgOY=; path=/; expires=Thu, 01-Dec-22 06:58:17 GMT; domain=.anaconda.com; HttpOnly; Secure; SameSite=None
< Vary: Accept-Encoding
< x-amz-id-2: D6P8KXSXC8gI7KOzlv0g5TO90T3ZSLUoRW6bdyxr5QPE9G0npKKYCVCJxA2sG2SUDPMQvTjcbxg=
< x-amz-request-id: PRT6QH04241S05D7
< x-amz-version-id: gruUyeXEAuhL5g34laDjUOasClLQRFQz
< Connection: keep-alive
< Elapsed: 00:00.531401
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://repo.anaconda.com/pkgs/main/osx-arm64/repodata.json'. Updating mtime and loading from disk
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://repo.anaconda.com/pkgs/main/noarch/repodata.json'. Updating mtime and loading from disk
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/091140c5.q
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://repo.anaconda.com/pkgs/r/noarch/repodata.json'. Updating mtime and loading from disk
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/9e99ffaf.json
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/4ea078d6.json
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/3e39a7aa.json
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/8bd55712.q
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/4ea078d6.q
DEBUG urllib3.connectionpool:_make_request(456): https://conda.anaconda.org:443 "GET /ranaroussi/noarch/repodata.json HTTP/1.1" 304 0
DEBUG conda.core.subdir_data:fetch_repodata_remote_request(530):
>>GET /ranaroussi/noarch/repodata.json HTTPS
> User-Agent: conda/22.9.0 requests/2.28.1 CPython/3.9.15 Darwin/21.5.0 OSX/12.4
> Accept: application/json
> Accept-Encoding: gzip, deflate, compress, identity
> Connection: keep-alive
> If-Modified-Since: Sat, 10 Jul 2021 20:29:09 GMT
<<HTTPS 304 Not Modified
< CF-Cache-Status: DYNAMIC
< CF-Ray: 7729c306eae4c44f-EWR
< Date: Thu, 01 Dec 2022 06:28:17 GMT
< Server: cloudflare
< Set-Cookie: __cf_bm=z8IMtaIACkUQIrN4AAyFQZdV13R.rBlauiHJyaXMD84-1669876097-0-AeYOO899tSB0BSkyr1RX+7rzFGl8/m2XUWEw0WLe4gaVuzuEzaTXes5vpeUhvoSew0ZVOGdKRcf404U90fpX+srJDKTNNlvNf+wjflTXFgmU; path=/; expires=Thu, 01-Dec-22 06:58:17 GMT; domain=.anaconda.org; HttpOnly; Secure; SameSite=None
< Strict-Transport-Security: max-age=31536000
< Vary: Accept-Encoding
< Connection: keep-alive
< Elapsed: 00:00.645770
DEBUG conda.core.subdir_data:_load(292): 304 NOT MODIFIED for 'https://conda.anaconda.org/ranaroussi/noarch/repodata.json'. Updating mtime and loading from disk
TRACE conda.gateways.disk.update:touch(132): touching path /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/f2f1db2e.json
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/9e99ffaf.q
DEBUG conda.core.subdir_data:_read_pickled(375): Pickle load validation failed for https://repo.anaconda.com/pkgs/r/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/8bd55712.json.
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/3e39a7aa.q
DEBUG conda.core.subdir_data:_read_local_repdata(330): Loading raw json for https://repo.anaconda.com/pkgs/r/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/8bd55712.json
DEBUG conda.core.subdir_data:_read_pickled(357): found pickle file /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/f2f1db2e.q
DEBUG conda.core.subdir_data:_pickle_me(316): Saving pickled state for https://repo.anaconda.com/pkgs/r/osx-arm64/repodata.json at /opt/homebrew/Caskroom/miniforge/base/pkgs/cache/8bd55712.q
done
No match found for: zipline-reloaded. Search: *zipline-reloaded*
Traceback (most recent call last):
File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.9/site-packages/conda/exceptions.py", line 1129, in __call__
return func(*args, **kwargs)
File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.9/site-packages/conda/cli/main.py", line 86, in main_subshell
exit_code = do_call(args, p)
File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.9/site-packages/conda/cli/conda_argparse.py", line 93, in do_call
return getattr(module, func_name)(args, parser)
File "/opt/homebrew/Caskroom/miniforge/base/lib/python3.9/site-packages/conda/cli/main_search.py", line 89, in execute
raise PackagesNotFoundError((str(spec),), channels_urls)
conda.exceptions.PackagesNotFoundError: The following packages are not available from current channels:
</code></pre>
<p>This is a duplicate of <a href="https://stackoverflow.com/questions/64651410/conda-cannot-find-packages-to-install">this question</a>, but none of the solutions outlined there solve the issue.</p>
|
[
{
"answer_id": 74638800,
"author": "Will Holtz",
"author_id": 16596758,
"author_profile": "https://Stackoverflow.com/users/16596758",
"pm_score": 1,
"selected": false,
"text": "platform : osx-arm64 conda info osx-arm64"
},
{
"answer_id": 74650754,
"author": "sonny",
"author_id": 1933486,
"author_profile": "https://Stackoverflow.com/users/1933486",
"pm_score": 0,
"selected": false,
"text": "zipline-reloaded CONDA_SUBDIR=osx-64 conda create -n [environment] # create a new environment\nconda activate [environment]\nconda env config vars set CONDA_SUBDIR=osx-64 # subsequent commands use intel packages\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1933486/"
] |
74,637,867
|
<p>I'm trying to better understand how Python flow control works. Accordingly, I wrote a little script to understand how to make functional menus that include the ability to enter and leave sub-menus. The code below works as expected (no errors, it prints the expected output, etc). But when I enter option 4 "Exit" in the sub-menu "stage1" it accepts the input and re-prints the sub-menu. If I select option 4 again it exits the sub-menu and returns me to the main menu.</p>
<p>Why would it work after selecting the option twice?</p>
<p>I trimmed my code down to include the snippet for your review, and once I trimmed it down, it no longer requires I enter the "Exit" option twice. I'd like to have a menu with more than 1 option, so I'd love to get to the bottom of this.</p>
<pre><code>import time
import os
def stage1():
print("stage1")
time.sleep(1)
stage1_loop = 1
while stage1_loop == 1:
os.system('clear')
print("Sub Menu")
print("1. Stage 1")
print("4. Exit")
option = int(input("Please select a stage."))
if option == 1:
stage1()
elif option == 2:
stage2()
elif option == 3:
stage3()
elif option == 4:
print("Exit")
stage1_loop = 0
main_loop = 1
while main_loop == 1:
os.system('clear')
print("Main Menu")
print("1. Stage 1")
print("4. Exit")
option = int(input("Please select a stage."))
if option == 1:
stage1()
elif option == 2:
stage2()
elif option == 3:
stage3()
elif option == 4:
print("Exit")
main_loop = 0
##############################################################
print("Main Menu")
for stage in [1, 2, 3]:
print(f"{stage}. Stage {stage}")
print("4. Exit")
</code></pre>
<p>If I comment out the elif lines for stage 2 & 3 in the sub-menu then the issue disappears.</p>
<p>EDIT - after removing the recursive call to stage 1 I fixed my issue (see answers below. Pasted in the code snippet suggested by one of the answers to clean up my menu printing code. Cheers!</p>
|
[
{
"answer_id": 74638800,
"author": "Will Holtz",
"author_id": 16596758,
"author_profile": "https://Stackoverflow.com/users/16596758",
"pm_score": 1,
"selected": false,
"text": "platform : osx-arm64 conda info osx-arm64"
},
{
"answer_id": 74650754,
"author": "sonny",
"author_id": 1933486,
"author_profile": "https://Stackoverflow.com/users/1933486",
"pm_score": 0,
"selected": false,
"text": "zipline-reloaded CONDA_SUBDIR=osx-64 conda create -n [environment] # create a new environment\nconda activate [environment]\nconda env config vars set CONDA_SUBDIR=osx-64 # subsequent commands use intel packages\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653143/"
] |
74,637,896
|
<p>This is My Route</p>
<pre><code>Route::namespace("Core\Controller\Site")
->prefix("/")
->name("site.")
->group(function () {
Route::get("{slug}", "NewsController@index")->name("news.index");
Route::get("show/{slug}", "NewsController@show")->name("news.show");
Route::get("{slug}", "ArticleController@index")->name("article.index");
Route::get("show/{slug}", "ArticleController@show")->name("article.show");
Route::get("{slug}", "VideoController@index")->name("video.index");
});
</code></pre>
<p>This is My a href which is I used This Route</p>
<pre><code><a href="{{ route('site.news.show', $item->slug) }}"></a>
</code></pre>
<p>It gives Such Kind Of Error</p>
<pre><code>Route [site.news.show] not defined.
</code></pre>
|
[
{
"answer_id": 74637984,
"author": "Ruslan Nasrutdinov",
"author_id": 5599711,
"author_profile": "https://Stackoverflow.com/users/5599711",
"pm_score": 3,
"selected": true,
"text": "(show/{slug} and {slug})"
},
{
"answer_id": 74638008,
"author": "Bhargav Chudasama",
"author_id": 8165986,
"author_profile": "https://Stackoverflow.com/users/8165986",
"pm_score": 1,
"selected": false,
"text": "show_news and show_article Route::namespace(\"Core\\Controller\\Site\")\n ->prefix(\"/\")\n ->name(\"site.\")\n ->group(function () {\n Route::get(\"{slug}\", \"NewsController@index\")->name(\"news.index\");\n Route::get(\"show_news/{slug}\", \"NewsController@show\")->name(\"news.show\");\n Route::get(\"{slug}\", \"ArticleController@index\")->name(\"article.index\");\n Route::get(\"show_article/{slug}\", \"ArticleController@show\")->name(\"article.show\");\n Route::get(\"{slug}\", \"VideoController@index\")->name(\"video.index\"); \n});\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15826225/"
] |
74,637,918
|
<p>i have data string</p>
<pre><code>generate-image-scanID-60
generate-image-scanID-4
</code></pre>
<p>how to retrieve last digit with separator - ? in javascript</p>
<p>ouput :</p>
<ul>
<li>60</li>
<li>4</li>
</ul>
<p>thanks</p>
|
[
{
"answer_id": 74637929,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "String.split() Array.at() let datas =['generate-image-scanID-60','generate-image-scanID-4']\nconst getData = v => v.split('-').at(-1)\n\ndatas.forEach(d => {\n console.log(getData(d))\n})"
},
{
"answer_id": 74637998,
"author": "kennarddh",
"author_id": 14813577,
"author_profile": "https://Stackoverflow.com/users/14813577",
"pm_score": 0,
"selected": false,
"text": "const raw = ['generate-image-scanID-60', 'generate-image-scanID-4']\n\nconst result = raw.map(str => parseInt(str.split('-').at(-1), 10))\n\nconsole.log(result)"
},
{
"answer_id": 74638105,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 0,
"selected": false,
"text": "let arr = [\"generate-image-scanID-60\", \"generate-image-scanID-40\"];\n\nlet t = arr.map((x) => +x.match(/^.*-(\\d+)/)[1]);\n\nconsole.log(t);"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19550757/"
] |
74,637,964
|
<p>I have this dice game made in python for class, I am using functions for the scoring logic (which I believe is all working as desired). I have put these functions in a while loop so that when either player reaches 100 banked score the game ends. However, I cannot get this to work as intended.</p>
<pre><code>while int(player1Score) < 100 or int(player2Score) < 100:
player1()
player2()
</code></pre>
<p>Here is one of the functions (the other is the same with score added to player 2's variable and some output changes):</p>
<pre><code>def player1():
global player1Score #global score to reference outside of function
rTotal = 0 #running total - used when gamble
print("\nPlayer 1 turn!")
while 1==1:
d = diceThrow() #dicethrow output(s)
diceIndexer(d)
print(f"Dice 1: {dice1} \nDice 2: {dice2}")
if dice1 == '1' and dice2 == '1': #both die = 1 (banked & running = 0)
player1Score = 0
rTotal = 0
print("DOUBLE ONE! Banked total reset, Player 2's turn.")
break
elif dice1 == '1' or dice2 == '1': #either die = 1 (running = 0)
rTotal = 0
print("Rolled a single one. Player 2's turn!")
break
else: #normal dice roll - gamble or bank
choice = input("Gamble (G) or Bank (B): ")
choice = choice.upper() #incase lowercase letter given
if choice == 'G': #if Gamble chosen - reroll dice & add to running
rTotal += int(dice1) + int(dice2)
elif choice == 'B': #used to save score.
rTotal += int(dice1) + int(dice2)
player1Score += rTotal
print(f"\nPlayer 1 banked! Total: {player1Score}")
break
print("Turn over")
</code></pre>
<p>I have tried changing the 'or' in the while loop to an 'and'. While that did stop faster, it did not stop exactly as the other player achieved a score higher than 10.</p>
|
[
{
"answer_id": 74637929,
"author": "flyingfox",
"author_id": 3176419,
"author_profile": "https://Stackoverflow.com/users/3176419",
"pm_score": 2,
"selected": true,
"text": "String.split() Array.at() let datas =['generate-image-scanID-60','generate-image-scanID-4']\nconst getData = v => v.split('-').at(-1)\n\ndatas.forEach(d => {\n console.log(getData(d))\n})"
},
{
"answer_id": 74637998,
"author": "kennarddh",
"author_id": 14813577,
"author_profile": "https://Stackoverflow.com/users/14813577",
"pm_score": 0,
"selected": false,
"text": "const raw = ['generate-image-scanID-60', 'generate-image-scanID-4']\n\nconst result = raw.map(str => parseInt(str.split('-').at(-1), 10))\n\nconsole.log(result)"
},
{
"answer_id": 74638105,
"author": "jerry",
"author_id": 20493210,
"author_profile": "https://Stackoverflow.com/users/20493210",
"pm_score": 0,
"selected": false,
"text": "let arr = [\"generate-image-scanID-60\", \"generate-image-scanID-40\"];\n\nlet t = arr.map((x) => +x.match(/^.*-(\\d+)/)[1]);\n\nconsole.log(t);"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19147712/"
] |
74,637,992
|
<p>i want to make function to make from <code>1111 into 1 and 0000 into 0</code>.</p>
<p>for the example:</p>
<pre><code>Input:
['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000', '0000']
Desired output:
11011010010000000100110000101100
</code></pre>
<p>But i don't know how to make it or the algorithm. Can you help me?</p>
<p>My attempt so far:</p>
<pre class="lang-py prettyprint-override"><code>def bagiskalar(biner):
print(biner)
biner = str(biner)
n = 4
hasil = []
potong = [biner[i:i+n] for i in range(0, len(biner), n)]
for a in potong:
hasil = potong.append(a)
return hasil
</code></pre>
|
[
{
"answer_id": 74638039,
"author": "Abhinav Mathur",
"author_id": 9350720,
"author_profile": "https://Stackoverflow.com/users/9350720",
"pm_score": 2,
"selected": false,
"text": "join() lst = ['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000', '0000']\ns = ''.join(['1' if x == '1111' else '0' for x in lst ])\nprint(s)\n# prints 11011010010000000100110000101100\n"
},
{
"answer_id": 74638129,
"author": "Yaman Jain",
"author_id": 2756517,
"author_profile": "https://Stackoverflow.com/users/2756517",
"pm_score": 0,
"selected": false,
"text": "mapper = {'1111': '1', '0000': '0'} # can be extended for other maps if needed\n\ninput_data = ['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000', '0000']\n\noutput_data = ''.join([mapper.get(item) for item in input_data]) \n"
},
{
"answer_id": 74638201,
"author": "Exu",
"author_id": 1425438,
"author_profile": "https://Stackoverflow.com/users/1425438",
"pm_score": 0,
"selected": false,
"text": "def bagiskalar(biner):\n result = \"\"\n for b in biner:\n if b == '0000' or b == '1111':\n result = result + b[0]\n return result\n"
},
{
"answer_id": 74638605,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": false,
"text": "output = \"\".join([x[0] for x in input])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74637992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653332/"
] |
74,638,031
|
<pre><code>1 2
4 3
5 6
8 7
9 10
</code></pre>
<p>I want to print this pattern but don't know how to use swap with one value k</p>
<p>me trying this --</p>
<pre><code>cin >> n;
while (i <= n) {
int j = 1;
while (j <= 2) {
if (k % 2 == 0 || k == 1) {
cout << k;
}
else {
temp = k;
}
k++;
j++;
}
cout << "\n";
i++;
}
</code></pre>
|
[
{
"answer_id": 74638149,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n\nbool is_odd(int n)\n{\n return n%2;\n}\n\nint main()\n{\n int n;\n std::cin >> n; // assume n is even\n for (int row = 0; row < n/2; ++row)\n {\n if (is_odd(row))\n std::cout << 2*row+2 << ' ' << 2*row+1 << '\\n';\n else\n std::cout << 2*row+1 << ' ' << 2*row+2 << '\\n';\n }\n}\n n n n"
},
{
"answer_id": 74638190,
"author": "463035818_is_not_a_number",
"author_id": 4117728,
"author_profile": "https://Stackoverflow.com/users/4117728",
"pm_score": 0,
"selected": false,
"text": "n k i j temp for (int row = 0; row < nrows; ++row) {\n ...\n std::cout << (row+1)*2 - 1 << (row+1)*2 << \"\\n\";\n std::cout << (row+1)*2 << (row+1)*2 - 1 << \"\\n\";\n"
},
{
"answer_id": 74640383,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 0,
"selected": false,
"text": "inline void printPairs(std::ostream& os, std::uint64_t const n) {\n std::uint64_t offset = 0;\n for (std::uint64_t i = 1; i <= 2*n; i += 2) {\n std::uint64_t const next = !offset;\n os << i+offset << ' ' << i+next << '\\n';\n offset = next;\n }\n}\n\nint main() {\n std::uint64_t n;\n std::cin >> n;\n printPairs(std::cout, n);\n}\n n int"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16984696/"
] |
74,638,052
|
<p>In order to select address from Japan, what open next level when i checked on above level (eg: open cities if I check on prefecture, open area if I check on city). I found the <a href="https://vuetifyjs.com/en/components/treeview/#search-and-filter" rel="nofollow noreferrer">v-treeview component</a>, which can display data as I wanted. But i don't know how to pass my data to v-treeview item format. From DB, I have an areas array like this:</p>
<pre><code>const areas = [
{
"id": 1,
"name": "的場一丁目",
"city": "川越市",
"prefecture": "埼玉県"
},
{
"id": 2,
"name": "大字中野林",
"city": "さいたま市西区",
"prefecture": "埼玉県"
},
{
"id": 3,
"name": "大字中釘",
"city": "さいたま市西区",
"prefecture": "埼玉県"
},
{
"id": 4,
"name": "平和台1丁目",
"city": "練馬区",
"prefecture": "東京都"
},
{
"id": 5,
"name": "平和台2丁目",
"city": "練馬区",
"prefecture": "東京都"
},
{
"id": 6,
"name": "平和台3丁目",
"city": "練馬区",
"prefecture": "東京都"
}
]
</code></pre>
<p>I want to parse this array to below format base on prefecture and city field to pass it to <a href="https://vuetifyjs.com/en/components/treeview/#search-and-filter" rel="nofollow noreferrer">v-treeview component</a>, how can i do this? Thank for your support!</p>
<pre><code>items = [
{
name: '埼玉県',
id: '埼玉県',
children: [
{
name: '川越市',
id: '川越市',
children: [
{ id: 1, name: '大字三条町' }
]
},
{
name: 'さいたま市西区',
id: 'さいたま市西区',
children: [
{ id: 2, name: '大字中野林' },
{ id: 3, name: '大字中釘' }
]
}
]
},
{
name: '東京都',
id: '東京都',
children: [
{
name: '練馬区',
id: '練馬区',
children: [
{ id: 4, name: '平和台1丁目' },
{ id: 5, name: '平和台2丁目' },
{ id: 6, name: '平和台3丁目' }
]
}
]
}
]
</code></pre>
|
[
{
"answer_id": 74638149,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n\nbool is_odd(int n)\n{\n return n%2;\n}\n\nint main()\n{\n int n;\n std::cin >> n; // assume n is even\n for (int row = 0; row < n/2; ++row)\n {\n if (is_odd(row))\n std::cout << 2*row+2 << ' ' << 2*row+1 << '\\n';\n else\n std::cout << 2*row+1 << ' ' << 2*row+2 << '\\n';\n }\n}\n n n n"
},
{
"answer_id": 74638190,
"author": "463035818_is_not_a_number",
"author_id": 4117728,
"author_profile": "https://Stackoverflow.com/users/4117728",
"pm_score": 0,
"selected": false,
"text": "n k i j temp for (int row = 0; row < nrows; ++row) {\n ...\n std::cout << (row+1)*2 - 1 << (row+1)*2 << \"\\n\";\n std::cout << (row+1)*2 << (row+1)*2 - 1 << \"\\n\";\n"
},
{
"answer_id": 74640383,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 0,
"selected": false,
"text": "inline void printPairs(std::ostream& os, std::uint64_t const n) {\n std::uint64_t offset = 0;\n for (std::uint64_t i = 1; i <= 2*n; i += 2) {\n std::uint64_t const next = !offset;\n os << i+offset << ' ' << i+next << '\\n';\n offset = next;\n }\n}\n\nint main() {\n std::uint64_t n;\n std::cin >> n;\n printPairs(std::cout, n);\n}\n n int"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11123483/"
] |
74,638,078
|
<pre><code>[
{
"_id": "",
"at": IsoDate(2022-11-19 10:00:00),
"areaId": 3,
"data": [
{
"label": 1,
"name": "a",
"sec": 34,
"x": 10.3,
"y": 23.3
},
{
"label": 1,
"name": "a",
"sec": 36,
"x": 10.3,
"y": 23.3
}
]
},
{
"_id": "",
"at": IsoDate(2022-11-19 10:01:00),
"areaId": 4,
"data": [
{
"name": "a",
"label": 1,
"sec": 10,
"x": 10.3,
"y": 23.3
},
{
"label": 2,
"name": "b",
"sec": 12,
"x": 10.3,
"y": 23.3
}
]
}
]
</code></pre>
<p>I have a data like above and I want to get the data of only objects with label=1 from this data with the help of linq.</p>
<p>In other words, 2 data should come from the data field of the areaId=3 object and 1 data from the field of the areaId=4 object.</p>
<p>The return type will be the same.</p>
<p>How can I do this with LINQ?</p>
|
[
{
"answer_id": 74638149,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n\nbool is_odd(int n)\n{\n return n%2;\n}\n\nint main()\n{\n int n;\n std::cin >> n; // assume n is even\n for (int row = 0; row < n/2; ++row)\n {\n if (is_odd(row))\n std::cout << 2*row+2 << ' ' << 2*row+1 << '\\n';\n else\n std::cout << 2*row+1 << ' ' << 2*row+2 << '\\n';\n }\n}\n n n n"
},
{
"answer_id": 74638190,
"author": "463035818_is_not_a_number",
"author_id": 4117728,
"author_profile": "https://Stackoverflow.com/users/4117728",
"pm_score": 0,
"selected": false,
"text": "n k i j temp for (int row = 0; row < nrows; ++row) {\n ...\n std::cout << (row+1)*2 - 1 << (row+1)*2 << \"\\n\";\n std::cout << (row+1)*2 << (row+1)*2 - 1 << \"\\n\";\n"
},
{
"answer_id": 74640383,
"author": "bitmask",
"author_id": 430766,
"author_profile": "https://Stackoverflow.com/users/430766",
"pm_score": 0,
"selected": false,
"text": "inline void printPairs(std::ostream& os, std::uint64_t const n) {\n std::uint64_t offset = 0;\n for (std::uint64_t i = 1; i <= 2*n; i += 2) {\n std::uint64_t const next = !offset;\n os << i+offset << ' ' << i+next << '\\n';\n offset = next;\n }\n}\n\nint main() {\n std::uint64_t n;\n std::cin >> n;\n printPairs(std::cout, n);\n}\n n int"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10122164/"
] |
74,638,079
|
<p>I have a python string that consists of "0", "1" and "x". I would to know what is the bit location of x in the string. eg. string1= '0100xx11xxx0x1' and the output is [(4,5),(8,10),(12)]. x appears in bit locations 4 to 5, locations 8 to 10, and location 12. The following scripts are written in python; however, the results are not really as expected.</p>
<pre><code>string1= '0100xx11xxx0x1'
temparray=[]
trackarray=[]
i=0
for x in string1:
if x=="x":
#print('i: ',i)
temparray.append(i)
i=i+1
else:
if len(temparray)>1:
bitsRange= (temparray[0],temparray[-1])
trackarray.append(bitsRange)
temparray=[]
i=i+1
print(trackarray)
</code></pre>
|
[
{
"answer_id": 74638155,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 1,
"selected": false,
"text": "regex import re\nstring1= '0100xx11xxx0x1'\nmatches = []\nfor match in re.finditer(r'x+',string1): # iterates over re.Match object\n if match.start() == match.end()-1: matches.append(tuple([match.start()])) # if you want tuple else remove tuple() and []\n else: matches.append((match.start(), match.end()-1))\nprint(matches)\n string1= '0100xx11xxx0x1'\ntemparray=[]\ntrackarray=[]\ni = 0\nfor x in string1:\n if x == \"x\":\n temparray.append(i) \n elif len(temparray) > 1:\n trackarray.append((temparray[0],temparray[-1]))\n temparray = []\n elif len(temparray) == 1:\n trackarray.append(tuple(temparray)) # if you want in tuple else remove tuple()\n temparray = []\n i += 1 \n\nprint(trackarray)\n len 1 12"
},
{
"answer_id": 74638181,
"author": "Seiwon Park",
"author_id": 17320013,
"author_profile": "https://Stackoverflow.com/users/17320013",
"pm_score": 0,
"selected": false,
"text": "string1= '0100xx11xxx0x1'\n\ntemparray=[]\ntrackarray=[]\n\n# ------------------ modified ------------------\nfor i, x in enumerate(string1):\n if x == 'x':\n temparray.append(i)\n continue\n \n if len(temparray) > 1:\n trackarray.append((temparray[0], temparray[-1]))\n temparray = []\n elif len(temparray) == 1:\n trackarray.append((temparray[0],))\n temparray = []\n\nif len(temparray) == 1:\n trackarray.append((temparray[0],))\nelif len(temparray) > 1:\n trackarray.append((temparray[0], temparray[-1]))\n# ----------------------------------------------\n\nprint(trackarray)\n# [(4, 5), (8, 10), (12,)]\n"
},
{
"answer_id": 74642676,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "string1= '0100xx11xxx0x1'\n\nresult = []\nt = None\n\nfor i, c in enumerate(string1):\n if c == 'x':\n t = (t[0], i) if t else (i,)\n else:\n if t:\n t = result.append(t)\n\nif t: # final check needed in case last character in string is 'x'\n result.append(t)\n \nprint(result)\n [(4, 5), (8, 10), (12,)]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9960443/"
] |
74,638,117
|
<p>I want to convert HTML to PDF with the click of a button and download.
My js working perfectly only need the latest JavaScript CDN link.</p>
<p><strong>HTML</strong></p>
<pre><code><div id="pageprint">
<div id="reportbox">Hello World!!</div>
</div>
<button type="button" onclick="downloadCode();">Download HTML</button>
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code><script>
function generatePDF() {
const element = document.getElementById("pageprint");
document.getElementById("reportbox").style.display = "block";
document.getElementById("reportbox").style.marginTop = "0px";
document.getElementById("pageprint").style.border = "1px solid black";
html2pdf().from(element).save('download.pdf');
}
function downloadCode(){
var x = document.getElementById("reportbox");
generatePDF();
setTimeout(function() { window.location=window.location;},3000);}
</script>
</code></pre>
|
[
{
"answer_id": 74638155,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 1,
"selected": false,
"text": "regex import re\nstring1= '0100xx11xxx0x1'\nmatches = []\nfor match in re.finditer(r'x+',string1): # iterates over re.Match object\n if match.start() == match.end()-1: matches.append(tuple([match.start()])) # if you want tuple else remove tuple() and []\n else: matches.append((match.start(), match.end()-1))\nprint(matches)\n string1= '0100xx11xxx0x1'\ntemparray=[]\ntrackarray=[]\ni = 0\nfor x in string1:\n if x == \"x\":\n temparray.append(i) \n elif len(temparray) > 1:\n trackarray.append((temparray[0],temparray[-1]))\n temparray = []\n elif len(temparray) == 1:\n trackarray.append(tuple(temparray)) # if you want in tuple else remove tuple()\n temparray = []\n i += 1 \n\nprint(trackarray)\n len 1 12"
},
{
"answer_id": 74638181,
"author": "Seiwon Park",
"author_id": 17320013,
"author_profile": "https://Stackoverflow.com/users/17320013",
"pm_score": 0,
"selected": false,
"text": "string1= '0100xx11xxx0x1'\n\ntemparray=[]\ntrackarray=[]\n\n# ------------------ modified ------------------\nfor i, x in enumerate(string1):\n if x == 'x':\n temparray.append(i)\n continue\n \n if len(temparray) > 1:\n trackarray.append((temparray[0], temparray[-1]))\n temparray = []\n elif len(temparray) == 1:\n trackarray.append((temparray[0],))\n temparray = []\n\nif len(temparray) == 1:\n trackarray.append((temparray[0],))\nelif len(temparray) > 1:\n trackarray.append((temparray[0], temparray[-1]))\n# ----------------------------------------------\n\nprint(trackarray)\n# [(4, 5), (8, 10), (12,)]\n"
},
{
"answer_id": 74642676,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 0,
"selected": false,
"text": "string1= '0100xx11xxx0x1'\n\nresult = []\nt = None\n\nfor i, c in enumerate(string1):\n if c == 'x':\n t = (t[0], i) if t else (i,)\n else:\n if t:\n t = result.append(t)\n\nif t: # final check needed in case last character in string is 'x'\n result.append(t)\n \nprint(result)\n [(4, 5), (8, 10), (12,)]\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17263333/"
] |
74,638,121
|
<p>After I set the <code>setIsRunning(false)</code> in the else statement, it is supposed to go out <code>console.log('final call')</code>. but it keeps calling console.log('running'). anyone know what I am doing wrong here and how this can be fixed</p>
<pre><code> const [val, setval] = useState(0)
const [isRunning, setIsRunning] = useState(true)
useEffect(() => {
let intervalId
if (isRunning) {
intervalId = setInterval(() => {
if (val <= 100) {
setval((t) => t + 5)
} else {
console.log('call')
setIsRunning(false)
}
console.log('running') // This is being called continuously
}, 50)
} else {
console.log('final call')
}
return () => clearInterval(intervalId)
}, [isRunning])
</code></pre>
<p>Once the <code>val</code> reaches 100 I want the <code>setTimeout</code> to stop, but at the same time i dont want to use <code>val</code> in my dependency. I want the interval to be cleared so that it does not run anymore</p>
|
[
{
"answer_id": 74638229,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": " const [val, setval] = useState(0)\n // const [isRunning, setIsRunning] = useState(true)\n // use useRef if you dont want to react to changes in useEffect\n const isRunningRef = useRef(true)\n\n useEffect(() => {\n let intervalId\n if (isRunning.current) {\n intervalId = setInterval(() => {\n if (val <= 100) {\n setval((t) => t + 5)\n } else {\n console.log('call')\n isRunning.current = false;\n // stop the interval here if needed\n clearInterval(intervalId)\n }\n console.log('running') // This is being called continuously\n }, 50)\n } \n\n return () => {\n if (intervalId !== undefined) {\n // clear if only timer was set\n clearInterval(intervalId)\n }\n }\n\n }, []) // userRef varaibles not needed in depedency array\n"
},
{
"answer_id": 74638283,
"author": "Simba",
"author_id": 14177366,
"author_profile": "https://Stackoverflow.com/users/14177366",
"pm_score": 2,
"selected": true,
"text": " const [val, setval] = useState(0);\n const [isRunning, setIsRunning] = useState(true);\n\n useEffect(() => {\n let intervalId;\n if (isRunning) {\n intervalId = setInterval(() => {\n setval((t) => {\n if (t <= 100) {\n return (t += 5);\n } else {\n setIsRunning(false);\n clearInterval(intervalId);\n return t;\n }\n });\n console.log('running'); // This is being called continuously\n }, 50);\n } else {\n console.log('final call');\n }\n return () => clearInterval(intervalId);\n }, [isRunning]);\n"
},
{
"answer_id": 74638686,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "const valRef = useRef(0)\nconst isRunningRef = useRef(true);\n\nuseEffect(() => {\n let intervalId;\n intervalId = setInterval(() => {\n if (isRunningRef.current) {\n if (valRef.current <= 100) {\n valRef.current += 5;\n } else {\n console.log('call');\n isRunningRef.current = false;\n }\n console.log('running');\n } else {\n console.log('final call');\n clearInterval(intervalId);\n }\n }, 50)\n return () => clearInterval(intervalId)\n}, [])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9208673/"
] |
74,638,196
|
<p>Please refer to my code and Screen Shot below</p>
<p>Top two rows are build based on <code>MainAxisAlignment.spaceBetween</code> widget and a bottom row is on <code>MainAxisAlignment.spaceBetween</code>, respectively.</p>
<p>As you can see in Screen Shot,<code>MainAxisAlignment.spaceBetween</code> have no spaces like spacebetween, and I understood this is default behaviour of <code>MainAxisAlignment</code>.</p>
<p>However, I want keep same spaces between the items in 5 items, even if it consists of less than 5 items(like two items shown in Screen shot).
Is there any good ideas to implement this ?
thanks for your helpful advise.</p>
<pre><code> final List<String> _icon = [
"lock.png",
"cheer.png",
"map.png",
"stake.png",
"sushi.png",
"lock.png",
"cheer.png",
"map.png",
"stake.png",
"sushi.png",
"cheer.png",
"map.png"
];
var iconChunks = _icon.slices(5).toList();
Column(
children: iconChunks.map((e) => Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: Row(
mainAxisAlignment: e.length ==5 ? MainAxisAlignment.spaceBetween :MainAxisAlignment.start,
children: e.map((s) => selectIcon(id: 1, iconPass: s)
).toList(),
),
))
.toList()
),
</code></pre>
<p><a href="https://i.stack.imgur.com/EiZLO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EiZLO.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74638608,
"author": "Ahmed Saeed",
"author_id": 20607918,
"author_profile": "https://Stackoverflow.com/users/20607918",
"pm_score": 1,
"selected": false,
"text": "GridView.builder(\n shrinkWrap: true,\n physics: NeverScrollableScrollPhysics(),\n gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 5,\n mainAxisSpacing: 10,\n crossAxisSpacing: 10,\n ),\n itemCount: _icon.length,\n itemBuilder: ((context, index) => selectIcon(id: 1, iconPass: \n _icon[index])),\n ),\n"
},
{
"answer_id": 74639042,
"author": "Babul",
"author_id": 4353594,
"author_profile": "https://Stackoverflow.com/users/4353594",
"pm_score": 0,
"selected": false,
"text": "Gridview Column Spacebetween start Gridview return Container(\n // padding: const EdgeInsets.all(0.0),\n child: GridView.builder(\n physics: NeverScrollableScrollPhysics(),\n shrinkWrap: true,\n gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: lengthoflist,\n childAspectRatio: MediaQuery.of(context).size.width /\n (MediaQuery.of(context).size.height / 1.4),\n mainAxisSpacing: 10.0,\n crossAxisSpacing: 10.0,\n ),\n itemCount: snapshot.data.length,\n itemBuilder: (context, index) {\n Category category = snapshot.data[index];\n return Column(\n crossAxisAlignment: CrossAxisAlignment.center,\n mainAxisAlignment: MainAxisAlignment.start,\n children: <Widget>[\n Container(\n child: Image.network(\n category.image,\n fit: BoxFit.cover,\n ),\n decoration: BoxDecoration(\n border: Border.all(width: 1.0),\n ),\n ),\n Padding(\n padding: const EdgeInsets.only(\n top: 8.0,\n ),\n child: Text(\n category.name,\n textAlign: TextAlign.center,\n ),\n )\n ],\n );\n },\n ),\n );\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6843543/"
] |
74,638,199
|
<p>For some reason, I can't figure out, why when I run a <code>ggplot</code> loop to create multiple graphs I don't see them in the environment and hence can't further display the graphs.
Data sample.</p>
<pre><code>db = data.frame(exposure = sample(1:100, 100),
exposure2 = sample(-90:100,100),
outcome = sample(200:1000,100))
exposure_vector = c("exposure","exposure2")
exposure_title = c("Pesticide","Apple")
for (i in 1:length(exposure_vector)) {
current_exposure = db[[exposure_vector[i]]]
title = exposure_title[i]
graph_name = paste0(title,"_","Graph")
graph_name=ggplot(db,aes(x=current_exposure,y=outcome))+geom_smooth()+
theme_bw()+ylab("outcome")+xlab("exposure")+ggtitle(title)
print(graph_name)
}
</code></pre>
|
[
{
"answer_id": 74638318,
"author": "Nomad420",
"author_id": 12820897,
"author_profile": "https://Stackoverflow.com/users/12820897",
"pm_score": 0,
"selected": false,
"text": "graphname db = data.frame(exposure = sample(1:100, 100),\n exposure2 = sample(-90:100,100),\n outcome = sample(200:1000,100))\n\nexposure_vector = c(\"exposure\",\"exposure2\")\nexposure_title = c(\"Pesticide\",\"Apple\")\n\nplot <- list() #declare\nfor (i in 1:length(exposure_vector)) {\n current_exposure = db[[exposure_vector[i]]]\n title = exposure_title[i]\n graph_name = paste0(title,\"_\",\"Graph\")\n graph_name=ggplot(db,aes(x=current_exposure,y=outcome))+geom_smooth()+\n theme_bw()+ylab(\"outcome\")+xlab(\"exposure\")+ggtitle(title)\n \n plot[[i]] <- graph_name #write\n print(graph_name)\n \n \n}\n"
},
{
"answer_id": 74638654,
"author": "Stefano Barbi",
"author_id": 3207509,
"author_profile": "https://Stackoverflow.com/users/3207509",
"pm_score": 0,
"selected": false,
"text": "paste0(title, \"_\", \"Graph\") assign library(ggplot2)\n\ndb <- data.frame(exposure = sample(1:100, 100),\n exposure2 = sample(-90:100,100),\n outcome = sample(200:1000,100))\n\nexposure_vector <- c(\"exposure\",\"exposure2\")\nexposure_title <- c(\"Pesticide\",\"Apple\")\n\nfor (i in 1:length(exposure_vector)) {\n current_exposure <- db[[exposure_vector[i]]]\n title <- exposure_title[i]\n graph_name <- paste0(title,\"_\",\"Graph\")\n p <- ggplot(db,aes(x=current_exposure,y=outcome))+\n geom_smooth()+\n theme_bw()+\n ylab(\"outcome\")+\n xlab(\"exposure\")+\n ggtitle(title)\n \n assign(graph_name, p)\n print(p)\n}\n\nls()\n\n##> [1] \"Apple_Graph\" \"current_exposure\" \"db\" \"exposure_title\" \n##> [5] \"exposure_vector\" \"graph_name\" \"i\" \"p\" \n##> [9] \"Pesticide_Graph\" \"title\" \n"
},
{
"answer_id": 74639687,
"author": "George Savva",
"author_id": 12176280,
"author_profile": "https://Stackoverflow.com/users/12176280",
"pm_score": 2,
"selected": true,
"text": "mapply list graphs <- mapply(X=exposure_title,Y=exposure_vector, function(X,Y){\n \n ggplot(db,aes(x=.data[[Y]],y=outcome))+\n geom_smooth()+\n theme_bw()+\n ylab(\"outcome\")+\n xlab(\"exposure\")+\n ggtitle(X)\n\n}, SIMPLIFY = FALSE )\n graphs$Pesticide\n graphs$Apple\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18880691/"
] |
74,638,211
|
<p>I have a dataset which has empty cells, and also cells which contain only spaces (one or more). I want to convert all these cells into Null.</p>
<p>Sample dataset:</p>
<pre><code>data = [("", "CA", " "), ("Julia", "", None),("Robert", " ", None), ("Tom", "NJ", " ")]
df = spark.createDataFrame(data,["name", "state", "code"])
df.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/0cFPk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0cFPk.png" alt="enter image description here" /></a></p>
<p>I can convert empty cells by:</p>
<pre><code>df = df.select( [F.when(F.col(c)=="", None).otherwise(F.col(c)).alias(c) for c in df.columns] )
df.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/WPpcG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WPpcG.png" alt="enter image description here" /></a></p>
<p>And cells with one space:</p>
<pre><code>df = df.select( [F.when(F.col(c)==" ", None).otherwise(F.col(c)).alias(c) for c in df.columns] )
df.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/L4hxC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L4hxC.png" alt="enter image description here" /></a></p>
<p>But, I don't want to repeat the above codes for cells with 2, 3, or more spaces.</p>
<p>Is there any way I can convert those cells at once?</p>
|
[
{
"answer_id": 74638318,
"author": "Nomad420",
"author_id": 12820897,
"author_profile": "https://Stackoverflow.com/users/12820897",
"pm_score": 0,
"selected": false,
"text": "graphname db = data.frame(exposure = sample(1:100, 100),\n exposure2 = sample(-90:100,100),\n outcome = sample(200:1000,100))\n\nexposure_vector = c(\"exposure\",\"exposure2\")\nexposure_title = c(\"Pesticide\",\"Apple\")\n\nplot <- list() #declare\nfor (i in 1:length(exposure_vector)) {\n current_exposure = db[[exposure_vector[i]]]\n title = exposure_title[i]\n graph_name = paste0(title,\"_\",\"Graph\")\n graph_name=ggplot(db,aes(x=current_exposure,y=outcome))+geom_smooth()+\n theme_bw()+ylab(\"outcome\")+xlab(\"exposure\")+ggtitle(title)\n \n plot[[i]] <- graph_name #write\n print(graph_name)\n \n \n}\n"
},
{
"answer_id": 74638654,
"author": "Stefano Barbi",
"author_id": 3207509,
"author_profile": "https://Stackoverflow.com/users/3207509",
"pm_score": 0,
"selected": false,
"text": "paste0(title, \"_\", \"Graph\") assign library(ggplot2)\n\ndb <- data.frame(exposure = sample(1:100, 100),\n exposure2 = sample(-90:100,100),\n outcome = sample(200:1000,100))\n\nexposure_vector <- c(\"exposure\",\"exposure2\")\nexposure_title <- c(\"Pesticide\",\"Apple\")\n\nfor (i in 1:length(exposure_vector)) {\n current_exposure <- db[[exposure_vector[i]]]\n title <- exposure_title[i]\n graph_name <- paste0(title,\"_\",\"Graph\")\n p <- ggplot(db,aes(x=current_exposure,y=outcome))+\n geom_smooth()+\n theme_bw()+\n ylab(\"outcome\")+\n xlab(\"exposure\")+\n ggtitle(title)\n \n assign(graph_name, p)\n print(p)\n}\n\nls()\n\n##> [1] \"Apple_Graph\" \"current_exposure\" \"db\" \"exposure_title\" \n##> [5] \"exposure_vector\" \"graph_name\" \"i\" \"p\" \n##> [9] \"Pesticide_Graph\" \"title\" \n"
},
{
"answer_id": 74639687,
"author": "George Savva",
"author_id": 12176280,
"author_profile": "https://Stackoverflow.com/users/12176280",
"pm_score": 2,
"selected": true,
"text": "mapply list graphs <- mapply(X=exposure_title,Y=exposure_vector, function(X,Y){\n \n ggplot(db,aes(x=.data[[Y]],y=outcome))+\n geom_smooth()+\n theme_bw()+\n ylab(\"outcome\")+\n xlab(\"exposure\")+\n ggtitle(X)\n\n}, SIMPLIFY = FALSE )\n graphs$Pesticide\n graphs$Apple\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9668218/"
] |
74,638,216
|
<p>I have looked quite some time into output from angular, but everywhere I only find a way to emit events. In my case, I have a parent with a router inside, and I wish to change the title based on a value from the child. So when I load route 1 I was thinking to emit a string via ngOnInit, but this doesn't work. I get the feeling that the way I want to accomplish this is not how it's supposed to be done. Any advice? The data is static and won't change in the child. Should I do an ngIf in the parent instead and check for the route?</p>
<pre><code><div> here i want the title
<router-outlet> <router-outlet>
<div>
</code></pre>
|
[
{
"answer_id": 74638292,
"author": "Eli Porush",
"author_id": 14598976,
"author_profile": "https://Stackoverflow.com/users/14598976",
"pm_score": 0,
"selected": false,
"text": "behaviorSubject"
},
{
"answer_id": 74639468,
"author": "Antonio Vida",
"author_id": 3713193,
"author_profile": "https://Stackoverflow.com/users/3713193",
"pm_score": 1,
"selected": false,
"text": "Subject BehaviorSubject ...\n titleChanged$ = new Subject<string>();\n\n constructor() {}\n\n getTitleChanged$() {\n return this.titleChanged$.asObservable();\n }\n\n setTitle(title: string) {\n this.titleChanged$.next(title);\n }\n ...\n ...\n this.appService\n .getTitleChanged$()\n .pipe(delay(0))\n .subscribe((title) => {\n this.title = title;\n });\n ...\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19358592/"
] |
74,638,257
|
<p>I have a problem to compare two 2D arrays in javascript.
It should output "true" if the two 2D arrays are the same.</p>
<p>The code I tried:</p>
<p>`</p>
<pre><code>function check(){
if (data.every() === solution.every()){
alert("example");
} else {
console.log("Data Array: " + data);
console.log("Solution Array: " + solution);
}
}
</code></pre>
<p>`</p>
<p>I think my solution only works with two 1D arrays. I hope someone can help me and teach me something.</p>
<p>Note: I only use jquery and nativ js.</p>
<p>Thanks in advance.</p>
<p>~Luca</p>
|
[
{
"answer_id": 74638361,
"author": "Dani Pardo",
"author_id": 12197845,
"author_profile": "https://Stackoverflow.com/users/12197845",
"pm_score": -1,
"selected": false,
"text": "function check(){\n \n if ( JSON.stringify(data) === JSON.stringify(solution) ){\n alert(\"example\");\n } else {\n console.log(\"Data Array: \" + data);\n console.log(\"Solution Array: \" + solution);\n }\n}\n"
},
{
"answer_id": 74638362,
"author": "Emilien",
"author_id": 18143359,
"author_profile": "https://Stackoverflow.com/users/18143359",
"pm_score": 2,
"selected": true,
"text": "function test(array1, array2)\n{\n if(array1.length !== array2.length) return false;\n\nfor(let i=0;i<array1.length;i++)\n{\n if(array1[i].length !== array2[i].length) return false;\n for(let j=0;j<array1[i].length;j++)\n {\n if(array1[i][j] !== array2[i][j]) return false;\n }\n}\nreturn true;\n}\n"
},
{
"answer_id": 74638560,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 0,
"selected": false,
"text": "const random2dArray = (n,m) => Array(n).fill(0)\n .map(_=>Array(m).fill(0).map(_=>10*Math.random()|0))\n\nconst arrEq = (a,b) => Array.isArray(a) ?\n a.length===b.length && a.every((e,i)=>arrEq(e,b[i])) : a===b\n\nconst a = random2dArray(3,3)\nconst b = random2dArray(3,3)\nconst c = random2dArray(3,5)\nconst d = random2dArray(6,7)\nconst e = structuredClone(a)\n\nconsole.log(arrEq(a,b))\nconsole.log(arrEq(a,c))\nconsole.log(arrEq(a,d))\nconsole.log(arrEq(a,e))"
},
{
"answer_id": 74644019,
"author": "Rohìt Jíndal",
"author_id": 4116300,
"author_profile": "https://Stackoverflow.com/users/4116300",
"pm_score": 0,
"selected": false,
"text": "flatten Array.every() const data = [[1,2,3], [4,5]];\nconst solution = [[1,2,3], [4,5]];\n\nconst res = (data.flat().length === solution.flat().length) && data.flat().every((item, index) => item === solution.flat()[index]);\n\nconsole.log(res ? 'Both arrays are equal' : 'not equal');"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19928474/"
] |
74,638,267
|
<p>Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary</p>
<pre><code>reda.json file
[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
</code></pre>
<pre><code>import json
import collections
json_data = json.load(open('reda.json'))
if type(json_data) is dict:
json_data = [json_data]
d = collections.OrderedDict((json_data))
h = tuple(d.keys()).index('break')
print(h)
</code></pre>
<p>Also tried this</p>
<pre><code>j = 'break'
for i in json_data:
if j in i:
print(j.index('break'))
Result is 0
``
</code></pre>
|
[
{
"answer_id": 74638347,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 3,
"selected": true,
"text": "enumerate json_data = [{\"carl\": \"33\"}, {\"break\": \"55\"}, {\"user\": \"heake\"}]\nkey = 'break'\nfor index, record in enumerate(json_data):\n if key in record:\n print(index)\n 1"
},
{
"answer_id": 74638357,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 0,
"selected": false,
"text": "collections import json\n\njson_data = json.load(open('reda.json'))\njson_key_index = [key for key in json_data]\nprint(json_key_index.index(\"break\"))\n reda.json reda.json {\n \"carl\": \"33\", \n \"break\": \"55\", \n \"user\": \"heake\"\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19883274/"
] |
74,638,321
|
<p>I am developing my first Shopware 6 plugin and was wondering how to access snippets in the <code>Plugin</code> <code>class</code>. I checked the <a href="https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-translations" rel="nofollow noreferrer">Developer Guide</a> but could not make it work.<br />
I want to use the plugin translation as <code>label</code> in <code>customField</code> <code>select</code> <code>options</code>.</p>
<p><strong>myfirstplugin.en-GB.json</strong></p>
<pre class="lang-json prettyprint-override"><code>{
"myfirstplugin": {
"my_custom_field_option_1": "Option 1",
"my_custom_field_option_2": "Option 2",
}
}
</code></pre>
<p><strong>MyFirstPlugin.php</strong></p>
<pre class="lang-php prettyprint-override"><code>class MyFirstPlugin extends Plugin
{
// ....
private function createCustomFields(Context $context): void
{
if ($this->customFieldSetExists($context)) {
return;
}
$customFieldSetRepository = $this->container->get('custom_field_set.repository');
$customFieldSetRepository->create([
[
'id' => '294865e5c81b434d8349db9ea6b4e135',
'name' => 'my_custom_field_set',
'customFields' => [
[
'name' => 'my_custom_field',
'type' => CustomFieldTypes::SELECT,
'config' => [
'label' => [ 'en-GB' => 'My custom field'],
'options' => [
[
'value' => '294865e5c81b434d8349db9ea6b4e487',
// Access my_custom_field_option_1 of snippet myfirstplugin.en-GB.json
'label' => 'my_custom_field_option_1',
],
[
'value' => '1ce5abe719a04346930c7e43514ed4f1',
// Access my_custom_field_option_2 of snippet myfirstplugin.en-GB.json
'label' => 'my_custom_field_option_2',
],
],
'customFieldType' => 'select',
'componentName' => 'sw-single-select',
'customFieldPosition' => 1,
],
],
]
],
], $context);
}
}
</code></pre>
|
[
{
"answer_id": 74640517,
"author": "dneustadt",
"author_id": 8556259,
"author_profile": "https://Stackoverflow.com/users/8556259",
"pm_score": 0,
"selected": false,
"text": "'config' => [\n 'label' => ['en-GB' => 'Label english', 'de-DE' => 'Label german'],\n 'type' => CustomFieldTypes::SELECT,\n 'options' => [\n [\n 'value' => '294865e5c81b434d8349db9ea6b4e487',\n 'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'], \n ],\n [\n 'value' => '1ce5abe719a04346930c7e43514ed4f1',\n 'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'], \n ],\n ],\n],\n"
},
{
"answer_id": 74640535,
"author": "Stone Vo",
"author_id": 780427,
"author_profile": "https://Stackoverflow.com/users/780427",
"pm_score": 0,
"selected": false,
"text": "$sRepo = $this->container->get('snippet.repository');\n$labels = $sRepo->search((new Criteria())\n ->addFilter(\n new MultiFilter(\n MultiFilter::CONNECTION_OR,\n [\n new ContainsFilter('translationKey', 'my_custom_field_option_1'),\n new ContainsFilter('translationKey', 'my_custom_field_option_2')\n ]\n )\n ), $context)->getElements();\n"
},
{
"answer_id": 74666102,
"author": "Carsten Harnisch",
"author_id": 20139696,
"author_profile": "https://Stackoverflow.com/users/20139696",
"pm_score": 2,
"selected": true,
"text": "<argument type=\"service\" id=\"translator\"/>\n use Shopware\\Core\\Framework\\Adapter\\Translation\\Translator;\n\n/**\n * @var Translator\n */\nprivate $translator;\npublic function __construct($translator)\n{\n $this->translator = $translator;\n}\n $translated = $this->translator\n ->trans(\n 'myfirstplugin.product.detail.294865e5c81b434d8349db9ea6b4e487');\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7390885/"
] |
74,638,334
|
<p>I am trying to build the app after testing it and this error occurs</p>
<p><a href="https://i.stack.imgur.com/zt30E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zt30E.png" alt="enter image description here" /></a></p>
<p>I tried multiple methods shown in stack and other documentations but I am not very clear about the problem</p>
<p>Here is my code:</p>
<pre class="lang-js prettyprint-override"><code>type props = {
html: React.MutableRefObject<HTMLDivElement>;
data: any;
rows: any;
};
</code></pre>
|
[
{
"answer_id": 74640517,
"author": "dneustadt",
"author_id": 8556259,
"author_profile": "https://Stackoverflow.com/users/8556259",
"pm_score": 0,
"selected": false,
"text": "'config' => [\n 'label' => ['en-GB' => 'Label english', 'de-DE' => 'Label german'],\n 'type' => CustomFieldTypes::SELECT,\n 'options' => [\n [\n 'value' => '294865e5c81b434d8349db9ea6b4e487',\n 'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'], \n ],\n [\n 'value' => '1ce5abe719a04346930c7e43514ed4f1',\n 'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'], \n ],\n ],\n],\n"
},
{
"answer_id": 74640535,
"author": "Stone Vo",
"author_id": 780427,
"author_profile": "https://Stackoverflow.com/users/780427",
"pm_score": 0,
"selected": false,
"text": "$sRepo = $this->container->get('snippet.repository');\n$labels = $sRepo->search((new Criteria())\n ->addFilter(\n new MultiFilter(\n MultiFilter::CONNECTION_OR,\n [\n new ContainsFilter('translationKey', 'my_custom_field_option_1'),\n new ContainsFilter('translationKey', 'my_custom_field_option_2')\n ]\n )\n ), $context)->getElements();\n"
},
{
"answer_id": 74666102,
"author": "Carsten Harnisch",
"author_id": 20139696,
"author_profile": "https://Stackoverflow.com/users/20139696",
"pm_score": 2,
"selected": true,
"text": "<argument type=\"service\" id=\"translator\"/>\n use Shopware\\Core\\Framework\\Adapter\\Translation\\Translator;\n\n/**\n * @var Translator\n */\nprivate $translator;\npublic function __construct($translator)\n{\n $this->translator = $translator;\n}\n $translated = $this->translator\n ->trans(\n 'myfirstplugin.product.detail.294865e5c81b434d8349db9ea6b4e487');\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19043035/"
] |
74,638,392
|
<p>Actually i am sending a Form Data Which contains input text and input Files I am doing it like This but i am getting an empty object in response</p>
<p>Here is my Code</p>
<pre><code> const [ModelInfo,setModelInfo] = useState({
title:"",
description:"",
category:""
})
const [Modelfile,setModelfile] = useState({
file1:"",
file3:"",
file4:""
})
</code></pre>
<p>Here Is My Fuction To Handle Submit</p>
<pre><code> e.preventDefault();
const formData = new FormData();
// My Post Files Object
for(let key in Modelfile){
formData.append(key,Modelfile[key][0])
}
// My Post Text Object
for(let key in ModelInfo){
formData.append(key,ModelInfo[key])
}
fetch("http://192.168.10.8:8300/createpost",{
method:"POST",
body:formData
})
.then((resp)=>{
resp.json().then((data) => {
console.log(data)
})
})
</code></pre>
<pre><code>Payload :
file1: (binary)
file3: (binary)
file4: (binary)
title: test
description: test
category: test
Preview : {}
Getting Empty Obj in response
</code></pre>
<p><a href="https://i.stack.imgur.com/EYu6Y.jpg" rel="nofollow noreferrer">ScreenShot 1 Of Post Request</a></p>
<p><a href="https://i.stack.imgur.com/WvXRd.jpg" rel="nofollow noreferrer">ScreenShot 2 Of Post Request</a></p>
|
[
{
"answer_id": 74640517,
"author": "dneustadt",
"author_id": 8556259,
"author_profile": "https://Stackoverflow.com/users/8556259",
"pm_score": 0,
"selected": false,
"text": "'config' => [\n 'label' => ['en-GB' => 'Label english', 'de-DE' => 'Label german'],\n 'type' => CustomFieldTypes::SELECT,\n 'options' => [\n [\n 'value' => '294865e5c81b434d8349db9ea6b4e487',\n 'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'], \n ],\n [\n 'value' => '1ce5abe719a04346930c7e43514ed4f1',\n 'label' => ['en-GB' => 'Option english', 'de-DE' => 'Option german'], \n ],\n ],\n],\n"
},
{
"answer_id": 74640535,
"author": "Stone Vo",
"author_id": 780427,
"author_profile": "https://Stackoverflow.com/users/780427",
"pm_score": 0,
"selected": false,
"text": "$sRepo = $this->container->get('snippet.repository');\n$labels = $sRepo->search((new Criteria())\n ->addFilter(\n new MultiFilter(\n MultiFilter::CONNECTION_OR,\n [\n new ContainsFilter('translationKey', 'my_custom_field_option_1'),\n new ContainsFilter('translationKey', 'my_custom_field_option_2')\n ]\n )\n ), $context)->getElements();\n"
},
{
"answer_id": 74666102,
"author": "Carsten Harnisch",
"author_id": 20139696,
"author_profile": "https://Stackoverflow.com/users/20139696",
"pm_score": 2,
"selected": true,
"text": "<argument type=\"service\" id=\"translator\"/>\n use Shopware\\Core\\Framework\\Adapter\\Translation\\Translator;\n\n/**\n * @var Translator\n */\nprivate $translator;\npublic function __construct($translator)\n{\n $this->translator = $translator;\n}\n $translated = $this->translator\n ->trans(\n 'myfirstplugin.product.detail.294865e5c81b434d8349db9ea6b4e487');\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18259879/"
] |
74,638,417
|
<p>I have an array that has a list of 15 different country names. I have to create a function that finds the largest name and returns its index, and if there are more then one that have a maximum length equivalent to each other it only has to return 1 of the indexes to the names. (Example below).</p>
<p>I'll admit and say I'm quite new to c. But have tried using the strlen(), and the strcmp() functions. I know I'm probably missing something huge here, but any help would be better then where I'm at now. Thanks in advance!</p>
<p>Here's what I thought would work:</p>
<pre><code>int maxCountry(char countryNames[15][50]){
int i, x = 0, length, length2, returnVal;
char string[50], string2[50];
for(i = 0; i < 15; i++){
string = countryNames[i] ;
length = strlen(string);
string2 = countryNames[x];
length2 = strlen(string2);
if(length < length2){
returnVal = x;
x = i;
}
}
return returnVal;
}
</code></pre>
|
[
{
"answer_id": 74638736,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nint longest(const char **s, size_t n)\n{\n size_t maxlen = 0;\n int maxpos = -1;\n\n for (size_t i = 0; i < n; ++i)\n {\n const size_t len = strlen(s[i]);\n if (len > maxlen)\n {\n maxlen = len;\n maxpos = (int) i;\n }\n }\n return maxpos;\n}\n \nint main(void)\n{\n const char *s[] = { \"foo\", \"hello\", \"you\", \"monster\", \"test\" };\n printf(\"The longest is at %d\\n\", longest(s, sizeof s / sizeof *s));\n return 0;\n}\n The longest is at 3\n"
},
{
"answer_id": 74638758,
"author": "David Ranieri",
"author_id": 1606345,
"author_profile": "https://Stackoverflow.com/users/1606345",
"pm_score": 0,
"selected": false,
"text": "int maxCountry(char (*countryNames)[50], size_t countries)\n{\n size_t max_length = 0;\n int result = 0;\n\n for(size_t i = 0; i < countries; i++)\n {\n size_t length = strlen(countryNames[i]);\n\n if (length > max_length)\n {\n max_length = length;\n result = i;\n }\n }\n return result;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653586/"
] |
74,638,479
|
<p>Suppose that I have this architecture for my classes:</p>
<pre><code># abstracts.py
import abc
class AbstractReader(metaclass=abc.ABCMeta):
@classmethod
def get_reader_name(cl):
return cls._READER_NAME
@classmethod
@property
@abc.abstractmethod
def _READER_NAME(cls):
raise NotImplementedError
# concretes.py
from .abstracts import AbstractReader
class ReaderConcreteNumber1(AbstractReader):
_READER_NAME = "NAME1"
class ReaderConcreteNumber2(AbstractReader):
_READER_NAME = "NAME2"
</code></pre>
<p>Also I have a manager classes that find concrete classes by <code>_READER_NAME</code> variable. So I need to define unique <code>_READER_NAME</code> for each of my concrete classes.</p>
<p><em><strong>how do I check that <code>NAME1</code> and <code>NAME2</code> are unique when concrete classes are going to define?</strong></em></p>
|
[
{
"answer_id": 74638736,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <string.h>\n\nint longest(const char **s, size_t n)\n{\n size_t maxlen = 0;\n int maxpos = -1;\n\n for (size_t i = 0; i < n; ++i)\n {\n const size_t len = strlen(s[i]);\n if (len > maxlen)\n {\n maxlen = len;\n maxpos = (int) i;\n }\n }\n return maxpos;\n}\n \nint main(void)\n{\n const char *s[] = { \"foo\", \"hello\", \"you\", \"monster\", \"test\" };\n printf(\"The longest is at %d\\n\", longest(s, sizeof s / sizeof *s));\n return 0;\n}\n The longest is at 3\n"
},
{
"answer_id": 74638758,
"author": "David Ranieri",
"author_id": 1606345,
"author_profile": "https://Stackoverflow.com/users/1606345",
"pm_score": 0,
"selected": false,
"text": "int maxCountry(char (*countryNames)[50], size_t countries)\n{\n size_t max_length = 0;\n int result = 0;\n\n for(size_t i = 0; i < countries; i++)\n {\n size_t length = strlen(countryNames[i]);\n\n if (length > max_length)\n {\n max_length = length;\n result = i;\n }\n }\n return result;\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11274362/"
] |
74,638,498
|
<p>I have big model, that aggragates data for buisness entity.</p>
<pre><code>class BigObject
{
TypeA DataA { get;set; }
TypeB DataB { get;set; }
TypeC DataC { get;set; }
}
</code></pre>
<p>and have service, which fill fields of model from differents sources. Some data depends from another data</p>
<pre><code>class DataService
{
public BigObject GetModel()
{
var model = new BigObject();
model.DataA = sourceServiceA.GetData();
model.DataB = sourceServiceB.GetData(model.DataA.Id);
model.DataC = sourceServiceC.GetData();
}
}
</code></pre>
<p>In method <code>GetModel()</code> I need to configure, which fields should be filled, which should not. For example, I want to fill <code>DataA</code> property, but don't want fill others. First idea is pass in method object <code>BigObjectFilter</code></p>
<pre><code>public BigObject GetModel(BigObjectFilter filter)
</code></pre>
<pre><code>class BigObjectFilter
{
bool FillDataA { get; set; }
bool FillDataB { get; set; }
bool FillDataC { get; set; }
}
</code></pre>
<p>and initialize this object in DataService clients.
In <code>GetObject</code> method I was going to add conditions like</p>
<pre><code>if (filter.FillDataA)
{
model.DataA = sourceServiceA.GetData();
}
if (filter.FillDataC)
{
model.DataC = sourceServiceC.GetData();
}
</code></pre>
<p>I see, that this solution looks like bad practice. I would like to improve this construction. How can i improve it? I can't see, how to use builder pattern in this case, because i have requeired and optional data, one depends on the other.</p>
|
[
{
"answer_id": 74653519,
"author": "Peter Csala",
"author_id": 13268855,
"author_profile": "https://Stackoverflow.com/users/13268855",
"pm_score": 2,
"selected": false,
"text": "TypeA TypeB TypeC int? BigObject class BigObjectCommand\n{\n private readonly Func<BigObjectFilter, bool> canExecute;\n private readonly Action<BigObject>? executeWithoutParam;\n private readonly Action<int, BigObject>? executeWithParam;\n private readonly Expression<Func<BigObject, int?>>? dependsOn;\n\n public BigObjectCommand(Func<BigObjectFilter, bool> canExecute, Action<BigObject> execute)\n {\n this.canExecute = canExecute;\n this.executeWithoutParam = execute;\n }\n\n public BigObjectCommand(Func<BigObjectFilter, bool> canExecute, Action<int, BigObject> execute, Expression<Func<BigObject, int?>> dependsOn)\n {\n this.canExecute = canExecute;\n this.executeWithParam = execute;\n this.dependsOn = dependsOn;\n }\n}\n DataA DataC DataB Evaluate public void Evaluate(BigObjectFilter filter, BigObject context)\n{\n if (!canExecute(filter))\n return; //or throw exception\n\n if (executeWithoutParam is not null)\n {\n executeWithoutParam(context);\n return;\n }\n\n var input = dependsOn!.Compile()(context);\n if (!input.HasValue)\n return; //or throw exception\n\n executeWithParam!(input.Value, context);\n}\n GetModel private readonly List<BigObjectCommand> Commands;\n\npublic DataService()\n{\n Commands = new()\n {\n new (filter => filter.FillDataA, (m) => m.DataA = sourceServiceA.GetData()),\n new (filter => filter.FillDataB, (i, m) => m.DataB = sourceServiceB.GetData(i), m => m.DataA),\n new (filter => filter.FillDataC, (m) => m.DataC = sourceServiceC.GetData()),\n };\n}\n\npublic BigObject GetModel(BigObjectFilter filter)\n{\n var model = new BigObject();\n\n foreach (var command in Commands)\n {\n command.Evaluate(filter, model);\n }\n\n return model;\n}\n FillDataXYZ Evaluate"
},
{
"answer_id": 74666849,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 1,
"selected": false,
"text": "public class BigObject\n{\n public int A { get; set; }\n public int B { get; set; }\n public int C { get; set; }\n}\n public class BigObjectHandler\n{\n Dictionary<string, Action> _handlerByproperty = new ();\n BigObject _bigObject;\n\n public BigObjectHandler(BigObject bigObject)\n {\n _bigObject = bigObject;\n _handlerByproperty.Add(\"A\", GetDataA);\n _handlerByproperty.Add(\"B\", GetDataB);\n _handlerByproperty.Add(\"C\", GetDataC);\n }\n\n public void Handle(string propertyName) => \n _handlerByproperty[propertyName].Invoke();\n\n\n private void GetDataA()\n {\n _bigObject.A = 1; // sourceServiceA.GetData();\n } \n\n private void GetDataB()\n { \n _bigObject.B = 1; // sourceServiceA.GetData();\n }\n\n private void GetDataC() \n {\n _bigObject.C = 1; // sourceServiceA.GetData();\n }\n}\n IEnumerable<string> propertiesToFill = new List<string> { \"A\", \"B\" };\nBigObject bigObject = new ();\nBigObjectHandler bigObjectMapHandler = new (bigObject);\n\nforeach (var propertyToFill in propertiesToFill)\n{\n bigObjectMapHandler.Handle(propertyToFill);\n}\n A = 1\nB = 1\n if else public abstract class BigObjectHandler\n{\n private BigObjectHandler _nextBigObjectHandler;\n\n public void SetSuccessor(BigObjectHandler bigObjectHandler)\n {\n _nextBigObjectHandler = bigObjectHandler;\n }\n\n public virtual BigObject Execute(BigObject bigObject, \n BigObjectFilter parameter)\n {\n if (_nextBigObjectHandler != null)\n return _nextBigObjectHandler.Execute(bigObject, parameter);\n\n return null;\n }\n}\n sourceServiceX.GetData() public class BigObjectAHandler : BigObjectHandler\n{\n public override BigObject Execute(BigObject bigObject, BigObjectFilter filter)\n {\n if (filter.FillA)\n {\n bigObject.A = 1; // sourceServiceA.GetData();\n return bigObject;\n } \n\n return base.Execute(bigObject, filter);\n }\n}\n public class BigObjectBHandler : BigObjectHandler\n{\n public override BigObject Execute(BigObject bigObject, BigObjectFilter filter)\n {\n if (filter.FillB)\n {\n bigObject.B = 2; // sourceServiceB.GetData();\n return bigObject;\n }\n\n return base.Execute(bigObject, filter);\n }\n}\n public class BigObjectCHandler : BigObjectHandler\n{\n public override BigObject Execute(BigObject bigObject, BigObjectFilter filter)\n {\n if (filter.FillC)\n {\n bigObject.C = 3; // sourceServiceC.GetData();\n return bigObject;\n }\n\n return base.Execute(bigObject, filter);\n }\n}\n public class BigObject\n{\n public int A { get; set; }\n public int B { get; set; }\n public int C { get; set; }\n}\n public class BigObjectFilter\n{\n public bool FillA { get; set; } = true;\n public bool FillB { get; set; }\n public bool FillC { get; set; }\n}\n BigObjectHandler chain = new BigObjectAHandler();\nBigObjectHandler objectBHandler = new BigObjectBHandler();\nBigObjectHandler objectCHandler = new BigObjectCHandler();\n\nchain.SetSuccessor(objectBHandler);\nobjectBHandler.SetSuccessor(objectCHandler);\n\nBigObjectFilter bigObjectFilter = new BigObjectFilter();\nbigObjectFilter.FillA = true;\n\nBigObject vehicle = chain.Execute(new BigObject(), bigObjectFilter); // A = 1 \n A A = 1\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6721495/"
] |
74,638,506
|
<p>I'm trying to set Content-Type as <strong>"application/x.example.hr.employee.email+json;version=1"</strong> of an HttpClient request as required by the API I am calling. The API is of type <strong>GET</strong> and accepts a <strong>JSON body</strong> (containing list of emails).</p>
<p>I'm successfully able to set <strong>Accept</strong> header to <strong>"application/x.example.hr.employee+json;version=1"</strong>. In this case, both - Accept and Content-Type need to be set as mentioned, otherwise API throws a error of 400 (Bad request). I tried <a href="https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request">How do you set the Content-Type header for an HttpClient request?</a> and several other options but getting run time error when I try to set Content-Type other than <strong>"application/json"</strong>.</p>
<p>This type needs to be applied on the request content but not in the header Content-Type. Below is one of the code snippet I tried:</p>
<pre><code>_httpClient.BaseAddress = new Uri("http://example.com/");
_httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, "application/x.example.hr.employee+json;version=1");
//_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x.example.hr.employee.email+json;version=1"); // Throws exception
List<string> strEmail = new List<string>
{
employeeEmail
};
var jsonEmail = JsonConvert.SerializeObject(strEmail);
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri("http://example.com/employees"),
Content = new StringContent(jsonEmail, Encoding.UTF8, "application/x.example.hr.employee.email+json;version=1")
};
//var response = _httpClient.SendAsync(request).ConfigureAwait(false);
await _httpClient.SendAsync(request)
.ContinueWith(responseTask =>
{
var response = responseTask;
});
</code></pre>
|
[
{
"answer_id": 74653519,
"author": "Peter Csala",
"author_id": 13268855,
"author_profile": "https://Stackoverflow.com/users/13268855",
"pm_score": 2,
"selected": false,
"text": "TypeA TypeB TypeC int? BigObject class BigObjectCommand\n{\n private readonly Func<BigObjectFilter, bool> canExecute;\n private readonly Action<BigObject>? executeWithoutParam;\n private readonly Action<int, BigObject>? executeWithParam;\n private readonly Expression<Func<BigObject, int?>>? dependsOn;\n\n public BigObjectCommand(Func<BigObjectFilter, bool> canExecute, Action<BigObject> execute)\n {\n this.canExecute = canExecute;\n this.executeWithoutParam = execute;\n }\n\n public BigObjectCommand(Func<BigObjectFilter, bool> canExecute, Action<int, BigObject> execute, Expression<Func<BigObject, int?>> dependsOn)\n {\n this.canExecute = canExecute;\n this.executeWithParam = execute;\n this.dependsOn = dependsOn;\n }\n}\n DataA DataC DataB Evaluate public void Evaluate(BigObjectFilter filter, BigObject context)\n{\n if (!canExecute(filter))\n return; //or throw exception\n\n if (executeWithoutParam is not null)\n {\n executeWithoutParam(context);\n return;\n }\n\n var input = dependsOn!.Compile()(context);\n if (!input.HasValue)\n return; //or throw exception\n\n executeWithParam!(input.Value, context);\n}\n GetModel private readonly List<BigObjectCommand> Commands;\n\npublic DataService()\n{\n Commands = new()\n {\n new (filter => filter.FillDataA, (m) => m.DataA = sourceServiceA.GetData()),\n new (filter => filter.FillDataB, (i, m) => m.DataB = sourceServiceB.GetData(i), m => m.DataA),\n new (filter => filter.FillDataC, (m) => m.DataC = sourceServiceC.GetData()),\n };\n}\n\npublic BigObject GetModel(BigObjectFilter filter)\n{\n var model = new BigObject();\n\n foreach (var command in Commands)\n {\n command.Evaluate(filter, model);\n }\n\n return model;\n}\n FillDataXYZ Evaluate"
},
{
"answer_id": 74666849,
"author": "StepUp",
"author_id": 1646240,
"author_profile": "https://Stackoverflow.com/users/1646240",
"pm_score": 1,
"selected": false,
"text": "public class BigObject\n{\n public int A { get; set; }\n public int B { get; set; }\n public int C { get; set; }\n}\n public class BigObjectHandler\n{\n Dictionary<string, Action> _handlerByproperty = new ();\n BigObject _bigObject;\n\n public BigObjectHandler(BigObject bigObject)\n {\n _bigObject = bigObject;\n _handlerByproperty.Add(\"A\", GetDataA);\n _handlerByproperty.Add(\"B\", GetDataB);\n _handlerByproperty.Add(\"C\", GetDataC);\n }\n\n public void Handle(string propertyName) => \n _handlerByproperty[propertyName].Invoke();\n\n\n private void GetDataA()\n {\n _bigObject.A = 1; // sourceServiceA.GetData();\n } \n\n private void GetDataB()\n { \n _bigObject.B = 1; // sourceServiceA.GetData();\n }\n\n private void GetDataC() \n {\n _bigObject.C = 1; // sourceServiceA.GetData();\n }\n}\n IEnumerable<string> propertiesToFill = new List<string> { \"A\", \"B\" };\nBigObject bigObject = new ();\nBigObjectHandler bigObjectMapHandler = new (bigObject);\n\nforeach (var propertyToFill in propertiesToFill)\n{\n bigObjectMapHandler.Handle(propertyToFill);\n}\n A = 1\nB = 1\n if else public abstract class BigObjectHandler\n{\n private BigObjectHandler _nextBigObjectHandler;\n\n public void SetSuccessor(BigObjectHandler bigObjectHandler)\n {\n _nextBigObjectHandler = bigObjectHandler;\n }\n\n public virtual BigObject Execute(BigObject bigObject, \n BigObjectFilter parameter)\n {\n if (_nextBigObjectHandler != null)\n return _nextBigObjectHandler.Execute(bigObject, parameter);\n\n return null;\n }\n}\n sourceServiceX.GetData() public class BigObjectAHandler : BigObjectHandler\n{\n public override BigObject Execute(BigObject bigObject, BigObjectFilter filter)\n {\n if (filter.FillA)\n {\n bigObject.A = 1; // sourceServiceA.GetData();\n return bigObject;\n } \n\n return base.Execute(bigObject, filter);\n }\n}\n public class BigObjectBHandler : BigObjectHandler\n{\n public override BigObject Execute(BigObject bigObject, BigObjectFilter filter)\n {\n if (filter.FillB)\n {\n bigObject.B = 2; // sourceServiceB.GetData();\n return bigObject;\n }\n\n return base.Execute(bigObject, filter);\n }\n}\n public class BigObjectCHandler : BigObjectHandler\n{\n public override BigObject Execute(BigObject bigObject, BigObjectFilter filter)\n {\n if (filter.FillC)\n {\n bigObject.C = 3; // sourceServiceC.GetData();\n return bigObject;\n }\n\n return base.Execute(bigObject, filter);\n }\n}\n public class BigObject\n{\n public int A { get; set; }\n public int B { get; set; }\n public int C { get; set; }\n}\n public class BigObjectFilter\n{\n public bool FillA { get; set; } = true;\n public bool FillB { get; set; }\n public bool FillC { get; set; }\n}\n BigObjectHandler chain = new BigObjectAHandler();\nBigObjectHandler objectBHandler = new BigObjectBHandler();\nBigObjectHandler objectCHandler = new BigObjectCHandler();\n\nchain.SetSuccessor(objectBHandler);\nobjectBHandler.SetSuccessor(objectCHandler);\n\nBigObjectFilter bigObjectFilter = new BigObjectFilter();\nbigObjectFilter.FillA = true;\n\nBigObject vehicle = chain.Execute(new BigObject(), bigObjectFilter); // A = 1 \n A A = 1\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6748156/"
] |
74,638,521
|
<p>how do I achieve this in Python? Source file is a CSV file, and value of one column in that file is converted from numeric to day and month. Thank you very much in advance.</p>
<p>Example below:</p>
<p>Picture of the column:
<a href="https://i.stack.imgur.com/CPFSf.png" rel="nofollow noreferrer">room column</a></p>
<p>In my python script, value should look below:</p>
<pre><code>1-Feb ---> 2-1
2-Feb ---> 2-2
3-Mar ---> 3-3
4-Mar ---> 3-4
</code></pre>
<p>Here's my script.</p>
<pre><code>import os
import pandas as pd
directory = 'C:/Path'
ext = ('.csv')
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
if f.endswith(ext):
head_tail = os.path.split(f)
head_tail1 = 'C:/Path'
k =head_tail[1]
r=k.split(".")[0]
p=head_tail1 + "/" + r + " - Revised.csv"
mydata = pd.read_csv(f)
# to pull columns and values
new = mydata[["A","Room","C","D"]]
new = new.rename(columns={'D': 'Qty. of Parts'})
new['Qty. of Parts'] = 1
new.to_csv(p ,index=False)
#to merge columns and values
merge_columns = ['A', 'Room', 'C']
merged_col = ''.join(merge_columns).replace('ARoomC', 'F')
new[merged_col] = new[merge_columns].apply(lambda x: '.'.join(x), axis=1)
new.drop(merge_columns, axis=1, inplace=True)
new = new.groupby(merged_col).count().reset_index()
new.to_csv(p, index=False)
</code></pre>
|
[
{
"answer_id": 74638692,
"author": "Diego Torres Milano",
"author_id": 236465,
"author_profile": "https://Stackoverflow.com/users/236465",
"pm_score": 1,
"selected": false,
"text": "import datetime\n# datetime.datetime(1900, 2, 1, 0, 0)\nd = datetime.datetime.strptime(\"1-Feb\", \"%d-%b\")\nprint(f'{d.month}-{d.day}')\n 2-1\n"
},
{
"answer_id": 74651350,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": true,
"text": "pandas.to_datetime new[\"Room\"]= (\n pd.to_datetime(new[\"Room\"], format=\"%d-%b\", errors=\"coerce\")\n .dt.strftime(\"%#m-%#d\")\n .fillna(new[\"Room\"])\n )\n col\n0 1-Feb\n1 2-Feb\n2 3-Mar\n3 2-1\n col\n0 2-1\n1 2-2\n2 3-3\n3 2-1\n .csv"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20610995/"
] |
74,638,546
|
<pre><code>/**
* init array: [1, 2]
* Expect
* array per 1s: [1, 2, 3]
* array per 2s: [1, 2, 3, 4]
* array per (n)s: [1, 2, 3, 4, ..., n]
*/
const [countList, setCountList] = useState([]);
const counter = useRef(0);
useEffect(() => {
const interval = setInterval(() => {
counter.current = counter.current + 1;
setCountList([...countList, counter.current]);
}, 1000);
return () => clearInterval(interval);
});
return (
<>
<div>{countList.map((count) => count + ',')}</div>
</>
);
</code></pre>
<p>I want every second, the array to push 1 item and then display that on UI but the array only updates the last item. Exp [1, 2] => [1, 3] => [1, 4] ...</p>
|
[
{
"answer_id": 74638692,
"author": "Diego Torres Milano",
"author_id": 236465,
"author_profile": "https://Stackoverflow.com/users/236465",
"pm_score": 1,
"selected": false,
"text": "import datetime\n# datetime.datetime(1900, 2, 1, 0, 0)\nd = datetime.datetime.strptime(\"1-Feb\", \"%d-%b\")\nprint(f'{d.month}-{d.day}')\n 2-1\n"
},
{
"answer_id": 74651350,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": true,
"text": "pandas.to_datetime new[\"Room\"]= (\n pd.to_datetime(new[\"Room\"], format=\"%d-%b\", errors=\"coerce\")\n .dt.strftime(\"%#m-%#d\")\n .fillna(new[\"Room\"])\n )\n col\n0 1-Feb\n1 2-Feb\n2 3-Mar\n3 2-1\n col\n0 2-1\n1 2-2\n2 3-3\n3 2-1\n .csv"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6736894/"
] |
74,638,557
|
<pre class="lang-cs prettyprint-override"><code>public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpHeight =10.0f;
public float gravity = 1.0f;
//public float gravityScale = 1;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction= new Vector3(0, 0, 1);
Vector3 velocity= direction * speed;
if (player.isGrounded == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpHeight;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
</code></pre>
<p>I tried <code>Rigidbody</code> & much more script but my player doesn't jump if my player jump then my doesn't move left or right sometimes my player stocked in ground.. tell me the right way of script where I can use</p>
|
[
{
"answer_id": 74638692,
"author": "Diego Torres Milano",
"author_id": 236465,
"author_profile": "https://Stackoverflow.com/users/236465",
"pm_score": 1,
"selected": false,
"text": "import datetime\n# datetime.datetime(1900, 2, 1, 0, 0)\nd = datetime.datetime.strptime(\"1-Feb\", \"%d-%b\")\nprint(f'{d.month}-{d.day}')\n 2-1\n"
},
{
"answer_id": 74651350,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 1,
"selected": true,
"text": "pandas.to_datetime new[\"Room\"]= (\n pd.to_datetime(new[\"Room\"], format=\"%d-%b\", errors=\"coerce\")\n .dt.strftime(\"%#m-%#d\")\n .fillna(new[\"Room\"])\n )\n col\n0 1-Feb\n1 2-Feb\n2 3-Mar\n3 2-1\n col\n0 2-1\n1 2-2\n2 3-3\n3 2-1\n .csv"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653796/"
] |
74,638,580
|
<p>I'm trying to replace missing age values in one wave by adding 1 to the value from the previous wave. So, for instance:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: center;">Age</th>
<th style="text-align: right;">Wave</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">20</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">NA</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">61</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">NA</td>
<td style="text-align: right;">2</td>
</tr>
</tbody>
</table>
</div>
<p>would become</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: center;">Age</th>
<th style="text-align: right;">Wave</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">20</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: center;">21</td>
<td style="text-align: right;">2</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">61</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: center;">62</td>
<td style="text-align: right;">2</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74638660,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf %>% \n mutate(Age = case_when(is.na(Age) ~ lag(Age) + 1, \n TRUE ~ Age))\n\n# A tibble: 4 x 3\n ID Age Wave\n <dbl> <dbl> <dbl>\n1 1 20 1\n2 1 21 2\n3 2 61 1\n4 2 62 2\n"
},
{
"answer_id": 74638762,
"author": "user2974951",
"author_id": 2974951,
"author_profile": "https://Stackoverflow.com/users/2974951",
"pm_score": 1,
"selected": false,
"text": "> ave(df$Age,df$ID,FUN=function(x){x[1]+seq_along(x)-1})\n[1] 20 21 61 62\n"
},
{
"answer_id": 74638798,
"author": "Jan Z",
"author_id": 20477576,
"author_profile": "https://Stackoverflow.com/users/20477576",
"pm_score": 0,
"selected": false,
"text": "df library(tidyverse)\n\ndf %>% \n group_by(ID) %>% arrange(ID, Wave) %>%\n mutate(missing_grp = cumsum( (is.na(Age)!=is.na(lag(Age))) | !is.na(Age) )) %>%\n group_by(ID, missing_grp) %>%\n mutate(age_offset=cumsum(is.na(Age))) %>%\n group_by(ID) %>%\n fill(Age, .direction='down') %>%\n mutate(Age = Age + age_offset) %>%\n ungroup() %>% select(-missing_grp, -age_offset)\n df <- tribble(\n ~ID, ~Age, ~Wave,\n 1, 21, 1,\n 1, NA, 2,\n 2, 61, 1,\n 2, NA, 2,\n 2, NA, 3,\n 2, 70, 4,\n 2, NA, 5,\n )\n # A tibble: 7 × 3\n ID Age Wave\n <dbl> <dbl> <dbl>\n1 1 21 1\n2 1 22 2\n3 2 61 1\n4 2 62 2\n5 2 63 3\n6 2 70 4\n7 2 71 5\n"
},
{
"answer_id": 74639722,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 0,
"selected": false,
"text": "within(df, Age[is.na(Age)] <- Age[which(is.na(Age)) - 1] + 1)\n#> ID Age Wave\n#> 1 1 20 1\n#> 2 1 21 2\n#> 3 2 61 1\n#> 4 2 62 2\n"
},
{
"answer_id": 74640438,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyverse)\n\ndf |>\n group_by(ID) |>\n fill(Age) |>\n mutate(Age = Age + row_number() - 1) |>\n ungroup()\n # A tibble: 5 × 3\n ID Age Wave\n <dbl> <dbl> <dbl>\n1 1 21 1\n2 1 22 2\n3 2 61 1\n4 2 62 2\n5 2 63 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20188476/"
] |
74,638,591
|
<p>I use the following function for the connection with the Snowflake. For SQL injection prevention I use <code>paramstyle = "numeric"</code>.</p>
<pre><code>import snowflake.connector
def get_snowflake_connector(
user: str,
password: str,
account: str,
warehouse: str,
role: str,
):
params = {
"user": user,
"password": password,
"account": account,
"warehouse": warehouse,
"role": role,
}
snowflake.connector.paramstyle = "numeric"
conn = snowflake.connector.connect(**params)
return conn
</code></pre>
<p>So, when I use returned connection object <code>conn</code> I can execute queries over Snowflake. For example:</p>
<pre><code>conn.cursor().execute(query, params)
</code></pre>
<p>Where query is for example:</p>
<pre><code>query = """
SELECT *
FROM IDENTIFIER(:1)
LIMIT :2;
"""
</code></pre>
<p>and <code>params</code> are string replacements for places where we have <code>:1</code> and <code>:2</code>. In this case, for example, <code>params=("DATABASE_NAME.SCHEMA_NAME.TABLE_NAME", 100000)</code>.</p>
<p>So, the result is like this:</p>
<pre><code>conn.cursor().execute(
"SELECT * FROM IDENTIFIER(:1) LIMIT :2;", params=("DATABASE_NAME.SCHEMA_NAME.TABLE_NAME", 100000)
)
</code></pre>
<p>And this is working. I use <code>IDENTIFIER(:N)</code> for the objects and without it, I use <code>:N</code> for literals.
But the problem appears when I use <code>LIKE</code> keyword. For example, <code>query = "SHOW USERS LIKE 'some_user'</code>".
What should I use instead of <code>'some_user'</code>? <code>IDENTIFIER(:1)</code> doesn't work because it is not an object, but also <code>:1</code> doesn't work. And I wonder what is the solution to prevent this from SQL injection?</p>
|
[
{
"answer_id": 74638660,
"author": "Tom Hoel",
"author_id": 17213355,
"author_profile": "https://Stackoverflow.com/users/17213355",
"pm_score": 1,
"selected": false,
"text": "library(tidyverse)\n\ndf %>% \n mutate(Age = case_when(is.na(Age) ~ lag(Age) + 1, \n TRUE ~ Age))\n\n# A tibble: 4 x 3\n ID Age Wave\n <dbl> <dbl> <dbl>\n1 1 20 1\n2 1 21 2\n3 2 61 1\n4 2 62 2\n"
},
{
"answer_id": 74638762,
"author": "user2974951",
"author_id": 2974951,
"author_profile": "https://Stackoverflow.com/users/2974951",
"pm_score": 1,
"selected": false,
"text": "> ave(df$Age,df$ID,FUN=function(x){x[1]+seq_along(x)-1})\n[1] 20 21 61 62\n"
},
{
"answer_id": 74638798,
"author": "Jan Z",
"author_id": 20477576,
"author_profile": "https://Stackoverflow.com/users/20477576",
"pm_score": 0,
"selected": false,
"text": "df library(tidyverse)\n\ndf %>% \n group_by(ID) %>% arrange(ID, Wave) %>%\n mutate(missing_grp = cumsum( (is.na(Age)!=is.na(lag(Age))) | !is.na(Age) )) %>%\n group_by(ID, missing_grp) %>%\n mutate(age_offset=cumsum(is.na(Age))) %>%\n group_by(ID) %>%\n fill(Age, .direction='down') %>%\n mutate(Age = Age + age_offset) %>%\n ungroup() %>% select(-missing_grp, -age_offset)\n df <- tribble(\n ~ID, ~Age, ~Wave,\n 1, 21, 1,\n 1, NA, 2,\n 2, 61, 1,\n 2, NA, 2,\n 2, NA, 3,\n 2, 70, 4,\n 2, NA, 5,\n )\n # A tibble: 7 × 3\n ID Age Wave\n <dbl> <dbl> <dbl>\n1 1 21 1\n2 1 22 2\n3 2 61 1\n4 2 62 2\n5 2 63 3\n6 2 70 4\n7 2 71 5\n"
},
{
"answer_id": 74639722,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 0,
"selected": false,
"text": "within(df, Age[is.na(Age)] <- Age[which(is.na(Age)) - 1] + 1)\n#> ID Age Wave\n#> 1 1 20 1\n#> 2 1 21 2\n#> 3 2 61 1\n#> 4 2 62 2\n"
},
{
"answer_id": 74640438,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyverse)\n\ndf |>\n group_by(ID) |>\n fill(Age) |>\n mutate(Age = Age + row_number() - 1) |>\n ungroup()\n # A tibble: 5 × 3\n ID Age Wave\n <dbl> <dbl> <dbl>\n1 1 21 1\n2 1 22 2\n3 2 61 1\n4 2 62 2\n5 2 63 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10631916/"
] |
74,638,627
|
<pre><code>def my_function(df_1) :
df_1 = df_1.filter[['col_1','col_2','col_3']]
# Keeping only those records where col_1 == 'success'
df_1 = df_1[df_1['col_1'] == 'success']
# Checking if the df_1 shape is 0
if df_1.shape[0]==0:
print('No records found')
break
#further program
</code></pre>
<p>I am looking to break the execution of further program if the <strong>if</strong> condition is met.</p>
<p>is this the correct way to do so..? since break only ends the loop, but i want to end the function</p>
|
[
{
"answer_id": 74638659,
"author": "kingrazer",
"author_id": 12853476,
"author_profile": "https://Stackoverflow.com/users/12853476",
"pm_score": 3,
"selected": true,
"text": " if df_1.shape[0]==0:\n print('No records found')\n return \n"
},
{
"answer_id": 74638662,
"author": "Jeson Pun",
"author_id": 20026039,
"author_profile": "https://Stackoverflow.com/users/20026039",
"pm_score": 0,
"selected": false,
"text": "break return return def my_function(df_1) :\n \n df_1 = df_1.filter[['col_1','col_2','col_3']]\n \n # Keeping only those records where col_1 == 'success'\n df_1 = df_1[df_1['col_1'] == 'success']\n \n # Checking if the df_1 shape is 0\n if df_1.shape[0]==0:\n print('No records found')\n return\n\n #further program\n"
},
{
"answer_id": 74638728,
"author": "ljbkusters",
"author_id": 15322704,
"author_profile": "https://Stackoverflow.com/users/15322704",
"pm_score": 1,
"selected": false,
"text": "break for while return return None None return"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19303365/"
] |
74,638,638
|
<p>i want to validation 2 date using mat-datepicker
Here is my code :
file HTML:</p>
<pre><code>
<mat-form-field class="w-100-p">
<input matInput [matDatepicker]="st" formControlName="studyTime"
[(ngModel)]="item.studyTime" placeholder="{{'CertificateDegree.StudyTime' | translate}}">
<mat-datepicker-toggle matSuffix [for]="st"></mat-datepicker-toggle>
<mat-datepicker #st></mat-datepicker>
</mat-form-field>
</code></pre>
<pre><code> <mat-form-field class="w-100-p" >
<input matInput [matDatepicker]="gt" formControlName="grantTime"
[(ngModel)]="item.grantTime" placeholder="{{'CertificateDegree.GrantTime' | translate}}"
>
<mat-datepicker-toggle matSuffix [for]="gt" ></mat-datepicker-toggle>
<mat-datepicker #gt ></mat-datepicker>
<mat-error *ngIf="error.isError">
{{'CertificateDegree.Error.studyForm' | translate}}
</mat-error>
</mat-form-field>
</code></pre>
<p>Here is my ts file:</p>
<pre><code> @Component....
export class AddCertificatedegreeCompoment implements OnInit{
...
}
constructor(){
this.formError ={
granTime:{}
studyTime:{}
}
}
ngOnInit() {
this.form = this.formBuilder.group({
studyTime: new FormControl(this.item.studyTime,Validators.required),
grantTime: new FormControl(this.item.grantTime,Validators.required),
</code></pre>
<p>i want to validate when the user pick the studyTime > grantTime it put the error and cannot save .And it wil have a mat-error warning them they need to pick studyTime < grantTime to save.</p>
|
[
{
"answer_id": 74638659,
"author": "kingrazer",
"author_id": 12853476,
"author_profile": "https://Stackoverflow.com/users/12853476",
"pm_score": 3,
"selected": true,
"text": " if df_1.shape[0]==0:\n print('No records found')\n return \n"
},
{
"answer_id": 74638662,
"author": "Jeson Pun",
"author_id": 20026039,
"author_profile": "https://Stackoverflow.com/users/20026039",
"pm_score": 0,
"selected": false,
"text": "break return return def my_function(df_1) :\n \n df_1 = df_1.filter[['col_1','col_2','col_3']]\n \n # Keeping only those records where col_1 == 'success'\n df_1 = df_1[df_1['col_1'] == 'success']\n \n # Checking if the df_1 shape is 0\n if df_1.shape[0]==0:\n print('No records found')\n return\n\n #further program\n"
},
{
"answer_id": 74638728,
"author": "ljbkusters",
"author_id": 15322704,
"author_profile": "https://Stackoverflow.com/users/15322704",
"pm_score": 1,
"selected": false,
"text": "break for while return return None None return"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17675243/"
] |
74,638,679
|
<p>I'm writing controller tests with Rspec in a Rails 7 application and getting some unexpected behaviour when asserting against an assignment.</p>
<p>The controller action that I'm testing returns the instance variable <code>@prefectures</code>;</p>
<pre><code> def edit
@prefectures = Prefecture.all.order(:code)
@city = City.find(params[:id])
respond_to do |format|
format.html { render :edit, locals: { city: @city } }
end
end
</code></pre>
<p>In the tests I'm using FactoryBot to create a list of three <code>Prefectures</code> and then checking in the example that the assigned <code>@prefectures</code> matches those three.</p>
<pre><code>RSpec.describe 'Cities', type: :request do
let(:city) { create(:city) }
let(:prefecture_list) { create_list(:prefecture, 3) }
describe 'GET /edit' do
it 'succeeds' do
get edit_city_path(city)
expect(response).to be_successful
expect(response.status).to eq(200)
end
it 'assigns @prefectures' do
expected = prefecture_list.sort_by { |prefecture| prefecture.code }
get edit_city_path(city)
expect(assigns(:prefectures)).to eq(expected)
end
end
end
</code></pre>
<p>There are several actions on the controller that return an instance variable of <code>@prefectures</code>. There are also a number of tests in the test file that assert the assignment of <code>@prefectures</code> using the same FactoryBot list. In each instance FactoryBot instantiates a collection of three prefectures and the test confirms that the assigned '@prefectures' is that same collection of three <code>Prefectures</code>.</p>
<p>In the <code>'GET /edit'</code> tests, however, the test fails because for reasons I don't understand, the assigned <code>@prefectures</code> is a collection of 6 <code>Prefectures</code> rather than 3. Each time it runs it's a distinct collection of six so it's not as if three are somehow being saved between test runs and added to. It seems as though in this test instance FactoryBot is creating a list of 6 rather than three.</p>
<p>Any ideas on why this is happening?</p>
|
[
{
"answer_id": 74641667,
"author": "Lee Drum",
"author_id": 17457026,
"author_profile": "https://Stackoverflow.com/users/17457026",
"pm_score": 1,
"selected": false,
"text": "RSpec.configure do |config|\n\n config.before(:suite) do\n DatabaseCleaner.strategy = :transaction\n DatabaseCleaner.clean_with(:truncation)\n end\n\n config.around(:each) do |example|\n DatabaseCleaner.cleaning do\n example.run\n end\n end\n\nend\n"
},
{
"answer_id": 74649879,
"author": "DukeSmellington",
"author_id": 13309792,
"author_profile": "https://Stackoverflow.com/users/13309792",
"pm_score": 0,
"selected": false,
"text": "city_list let(:city_list) { create_list(:city, 3) }\nlet(:prefecture_list) { create_list(:prefecture, 3) }\n Prefecture Prefecture FactoryBot.define do\n factory :prefecture do\n name { Faker::Address.state }\n code { Faker::Number.number(digits: 3) }\n end\nend\n City City Prefecture FactoryBot.define do\n factory :city do\n prefecture { create(:prefecture) }\n name { Faker::Address.city }\n rating { Faker::Number.within(range: 0.0..5.0) }\n end\nend\n @prefectures city_list city_list prefecture_id city_list let(:prefecture_list) { create_list(:prefecture, 3) }\nlet(:city_list) { create_list(:city, 3, prefecture_id:prefecture_list[0].id) }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13309792/"
] |
74,638,704
|
<p>I am working with multiple parquet datasets that were written with nested structs (sometimes multiple levels deep). I need to output a flattened (no struct) schema. Right now the only way I can think to do that is to use for loops to iterate through the columns. Here is a simplified example where I'm for looping.</p>
<pre><code>while len([x.name for x in df if x.dtype == pl.Struct]) > 0:
for col in df:
if col.dtype == pl.Struct:
df = df.unnest(col.name)
</code></pre>
<p>This works, maybe that is the only way to do it, and if so it would be helpful to know that. But Polars is pretty neat and I'm wondering if there is a more functional way to do this without all the looping and reassigning the df to itself.</p>
|
[
{
"answer_id": 74641667,
"author": "Lee Drum",
"author_id": 17457026,
"author_profile": "https://Stackoverflow.com/users/17457026",
"pm_score": 1,
"selected": false,
"text": "RSpec.configure do |config|\n\n config.before(:suite) do\n DatabaseCleaner.strategy = :transaction\n DatabaseCleaner.clean_with(:truncation)\n end\n\n config.around(:each) do |example|\n DatabaseCleaner.cleaning do\n example.run\n end\n end\n\nend\n"
},
{
"answer_id": 74649879,
"author": "DukeSmellington",
"author_id": 13309792,
"author_profile": "https://Stackoverflow.com/users/13309792",
"pm_score": 0,
"selected": false,
"text": "city_list let(:city_list) { create_list(:city, 3) }\nlet(:prefecture_list) { create_list(:prefecture, 3) }\n Prefecture Prefecture FactoryBot.define do\n factory :prefecture do\n name { Faker::Address.state }\n code { Faker::Number.number(digits: 3) }\n end\nend\n City City Prefecture FactoryBot.define do\n factory :city do\n prefecture { create(:prefecture) }\n name { Faker::Address.city }\n rating { Faker::Number.within(range: 0.0..5.0) }\n end\nend\n @prefectures city_list city_list prefecture_id city_list let(:prefecture_list) { create_list(:prefecture, 3) }\nlet(:city_list) { create_list(:city, 3, prefecture_id:prefecture_list[0].id) }\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996021/"
] |
74,638,730
|
<p>How can I get all body of response without mapping?</p>
<p>When I try <code>response.getBody().toString()</code> it just show <code>Helper@214c265e</code>
but I need response of this api in String to show
(jsut example) {"test": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }} in string</p>
|
[
{
"answer_id": 74638931,
"author": "Nghia Hoang",
"author_id": 17003471,
"author_profile": "https://Stackoverflow.com/users/17003471",
"pm_score": 0,
"selected": false,
"text": "ResponseEntity<?> response = apiCall();\nresponse.getBody().toString();\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14176225/"
] |
74,638,754
|
<p>I created a custom invoice but now I am having trouble breaking the page when product lines are more than 30. I am trying to do this so it doesn't overlap with the total amount and payment terms (<a href="https://i.imgur.com/4aKT6Xr.png" rel="nofollow noreferrer">see image for the desired scenario</a>)</p>
<p>Update code snippet:
<a href="https://pastebin.com/WDr5uphK" rel="nofollow noreferrer">https://pastebin.com/WDr5uphK</a></p>
<p>I tried adding <code><div style="page-break-after: always;"/></code> using <code>foreach</code> but it breaks the whole table and moves to next page.</p>
|
[
{
"answer_id": 74638931,
"author": "Nghia Hoang",
"author_id": 17003471,
"author_profile": "https://Stackoverflow.com/users/17003471",
"pm_score": 0,
"selected": false,
"text": "ResponseEntity<?> response = apiCall();\nresponse.getBody().toString();\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646416/"
] |
74,638,766
|
<p>Same Id but multiple different product in SQL.
Data should be retrieved from SQL and Output should be shortened to one line for each ID using PHP.</p>
<p>EXAMPLE:</p>
<p>SQL</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Product</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>Laptop</td>
</tr>
<tr>
<td>001</td>
<td>Monitor</td>
</tr>
<tr>
<td>001</td>
<td>Speaker</td>
</tr>
<tr>
<td>002</td>
<td>Phone</td>
</tr>
<tr>
<td>003</td>
<td>Other Services</td>
</tr>
</tbody>
</table>
</div>
<p>Expected Output</p>
<p>PHP</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Product</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>Laptop, Monitor, Speaker</td>
</tr>
<tr>
<td>002</td>
<td>Phone, Case</td>
</tr>
<tr>
<td>003</td>
<td>Other Services</td>
</tr>
</tbody>
</table>
</div>
<p>MY CODE</p>
<pre><code>$sql = "SELECT id, product From Stock";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_array()){
$id[] = $row["id"];
$product[] = $row["product"];
}
$max_id = count($id);
$duplicate_id = array();
for($i=0; $i<$max_id;$i++){
$duplicate_m[$id[$i]] = $id[$i] = $product[$i];
}
print_r($duplicate_m);
</code></pre>
<p>CURRENT OUTPUT</p>
<pre><code>[001] => Laptop
[002] => Phone
[003] => Other Services
</code></pre>
|
[
{
"answer_id": 74638931,
"author": "Nghia Hoang",
"author_id": 17003471,
"author_profile": "https://Stackoverflow.com/users/17003471",
"pm_score": 0,
"selected": false,
"text": "ResponseEntity<?> response = apiCall();\nresponse.getBody().toString();\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20653783/"
] |
74,638,769
|
<pre><code>Pass=[0,20,40,60,80,100,120]
while True:
Pass_Input=int(input("Enter : "))
if Pass_Input in Pass[5:6]:
print("Progress")
elif Pass_Input in Pass[0:2]:
print("Progress Module Trailer")
elif Pass_Input in Pass[0]:
print("Exclude")
</code></pre>
<p>Input:</p>
<pre><code>Enter : 120
</code></pre>
<p>Output I get:</p>
<pre><code>Traceback (most recent call last):
File "E:\IIT\Python\CW_Python\1 st question 2nd try.py", line 8, in <module>
elif Pass_Input in Pass[0]:
TypeError: argument of type 'int' is not iterable
</code></pre>
<p>Output I expect:</p>
<pre><code>Progress
</code></pre>
|
[
{
"answer_id": 74638931,
"author": "Nghia Hoang",
"author_id": 17003471,
"author_profile": "https://Stackoverflow.com/users/17003471",
"pm_score": 0,
"selected": false,
"text": "ResponseEntity<?> response = apiCall();\nresponse.getBody().toString();\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17128896/"
] |
74,638,806
|
<p>I have a dataframe such as</p>
<pre><code>Names Values
A 0.20
A 1.30
A 1.2
B 0.30
B 0.40
C 1.2
D 0.70
E 0.12
E 1.3
F 0.90
F 0.78
F 0.88
</code></pre>
<p>And I would like to add to a <code>New_col</code> the number :</p>
<ul>
<li><code>1</code> where for each <code>Names</code> with at least one <code>Values > 0.75</code> <strong>and</strong> one <code>Values < 0.75</code></li>
<li><code>0</code> for each <code>Names</code> with only <code>Values > 0.75</code></li>
<li><code>2</code> for each <code>Names</code> with only <code>Values < 0.75</code></li>
</ul>
<p>I should then get:</p>
<pre><code>Names Values New_col
A 0.20 1
A 1.30 1
A 1.2 1
B 0.30 2
B 0.40 2
C 1.2 0
D 0.70 2
E 0.12 1
E 1.3 1
F 0.90 2
F 0.78 2
F 0.88 2
</code></pre>
|
[
{
"answer_id": 74639142,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "0.75 Names numpy.select m = df.Values > 0.75\n\ns1 = df.loc[m, 'Names'].unique()\ns2 = df.loc[~m, 'Names'].unique()\n\nm1 = df['Names'].isin(s1)\nm2 = df['Names'].isin(s2)\n\ndf['New_col'] = np.select([m1 & ~m2, ~m1 & m2], [0, 2], default=1)\nprint (df)\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n 0.75 print (df)\n Names Values\n0 A 0.20\n1 A 1.30\n2 A 1.20\n3 B 0.30\n4 B 0.40\n5 C 1.20\n6 D 0.70\n7 E 0.12\n8 E 1.30\n9 F 0.90\n10 F 0.78\n11 F 0.88\n12 G 0.75\n13 G 0.75\n\nm1 = df.Values > 0.75\nm2 = df.Values < 0.75\n\ns1 = df.loc[m1, 'Names'].unique()\ns2 = df.loc[m2, 'Names'].unique()\n\n\nm1 = df['Names'].isin(s1)\nm2 = df['Names'].isin(s2)\n\ndf['New_col'] = np.select([m1 & ~m2, ~m1 & m2, m1 & m2], \n [0, 2, 1], default=None)\n print (df)\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n12 G 0.75 None\n13 G 0.75 None\n"
},
{
"answer_id": 74639153,
"author": "Will",
"author_id": 12829151,
"author_profile": "https://Stackoverflow.com/users/12829151",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({\"Names\":['A','A','A','B','B','C','D','E','E','F','F','F'], \"Values\":[0.20,1.30,1.2,0.30,0.40,1.2,0.70,0.12,1.3,0.90,0.78,0.88]})\n\ndf[\"New_col\"] = None\nfor val in set(df.Names):\n flags = [True if x>0.75 else False for x in df[df['Names']==val].Values ]\n \n if sum(flags)==0: \n df.loc[ df['Names']==val, \"New_col\"] = 2\n \n elif sum(flags)==len(df[df['Names']==val]): \n df.loc[ df['Names']==val, \"New_col\"] = 0\n \n else:\n df.loc[ df['Names']==val, \"New_col\"] = 1\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n"
},
{
"answer_id": 74639731,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 1,
"selected": false,
"text": "groupby df = df.merge(df.groupby(by=\"Names\").apply(lambda x: 0 if all(x['Values']>0.75) else (2 if all(x['Values']<0.75) else 1)).reset_index())\n import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({ 'Names': ['A', 'A', 'A', 'B', 'B', 'C', 'D', 'E', 'E', 'F', 'F', 'F'],\n 'Values': [0.2, 1.3, 1.2, 0.3, 0.4, 1.2, 0.7, 0.12, 1.3, 0.9, 0.78, 0.88]})\n\ndf = df.merge(df.groupby(by=\"Names\").apply(lambda x: 0 if all(x['Values']>0.75) else (2 if all(x['Values']<0.75) else 1)).reset_index())\ndf.columns = ['Names', 'Values', 'New_col']\n\nprint(df)\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12559770/"
] |
74,638,813
|
<p>As the title suggests, I am trying to create a single array of strings:</p>
<pre><code>['string1', 'string2', 'string3', 'string4', 'string5', 'string6']
</code></pre>
<p>Out of an array of objects with arrays of strings within those objects:</p>
<pre><code>[
{
array_of_strings: ['string1', 'string2', 'string3']
},
{
array_of_strings: ['string1', 'string4', 'string5']
},
{
array_of_strings: ['string6', 'string3', 'string2']
}
]
</code></pre>
<p>As you can see there is a possibility that the nested arrays may contain the same strings as each other, and I am trying to de-duplicate at the same time. I got very lost in <code>map</code>, <code>filter</code> and <code>reduce</code>. But nothing really outputs the data as needed.</p>
<p>Any guidance would be appreciated.</p>
|
[
{
"answer_id": 74639142,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "0.75 Names numpy.select m = df.Values > 0.75\n\ns1 = df.loc[m, 'Names'].unique()\ns2 = df.loc[~m, 'Names'].unique()\n\nm1 = df['Names'].isin(s1)\nm2 = df['Names'].isin(s2)\n\ndf['New_col'] = np.select([m1 & ~m2, ~m1 & m2], [0, 2], default=1)\nprint (df)\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n 0.75 print (df)\n Names Values\n0 A 0.20\n1 A 1.30\n2 A 1.20\n3 B 0.30\n4 B 0.40\n5 C 1.20\n6 D 0.70\n7 E 0.12\n8 E 1.30\n9 F 0.90\n10 F 0.78\n11 F 0.88\n12 G 0.75\n13 G 0.75\n\nm1 = df.Values > 0.75\nm2 = df.Values < 0.75\n\ns1 = df.loc[m1, 'Names'].unique()\ns2 = df.loc[m2, 'Names'].unique()\n\n\nm1 = df['Names'].isin(s1)\nm2 = df['Names'].isin(s2)\n\ndf['New_col'] = np.select([m1 & ~m2, ~m1 & m2, m1 & m2], \n [0, 2, 1], default=None)\n print (df)\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n12 G 0.75 None\n13 G 0.75 None\n"
},
{
"answer_id": 74639153,
"author": "Will",
"author_id": 12829151,
"author_profile": "https://Stackoverflow.com/users/12829151",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({\"Names\":['A','A','A','B','B','C','D','E','E','F','F','F'], \"Values\":[0.20,1.30,1.2,0.30,0.40,1.2,0.70,0.12,1.3,0.90,0.78,0.88]})\n\ndf[\"New_col\"] = None\nfor val in set(df.Names):\n flags = [True if x>0.75 else False for x in df[df['Names']==val].Values ]\n \n if sum(flags)==0: \n df.loc[ df['Names']==val, \"New_col\"] = 2\n \n elif sum(flags)==len(df[df['Names']==val]): \n df.loc[ df['Names']==val, \"New_col\"] = 0\n \n else:\n df.loc[ df['Names']==val, \"New_col\"] = 1\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n"
},
{
"answer_id": 74639731,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 1,
"selected": false,
"text": "groupby df = df.merge(df.groupby(by=\"Names\").apply(lambda x: 0 if all(x['Values']>0.75) else (2 if all(x['Values']<0.75) else 1)).reset_index())\n import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({ 'Names': ['A', 'A', 'A', 'B', 'B', 'C', 'D', 'E', 'E', 'F', 'F', 'F'],\n 'Values': [0.2, 1.3, 1.2, 0.3, 0.4, 1.2, 0.7, 0.12, 1.3, 0.9, 0.78, 0.88]})\n\ndf = df.merge(df.groupby(by=\"Names\").apply(lambda x: 0 if all(x['Values']>0.75) else (2 if all(x['Values']<0.75) else 1)).reset_index())\ndf.columns = ['Names', 'Values', 'New_col']\n\nprint(df)\n Names Values New_col\n0 A 0.20 1\n1 A 1.30 1\n2 A 1.20 1\n3 B 0.30 2\n4 B 0.40 2\n5 C 1.20 0\n6 D 0.70 2\n7 E 0.12 1\n8 E 1.30 1\n9 F 0.90 0\n10 F 0.78 0\n11 F 0.88 0\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972399/"
] |
74,638,814
|
<p>I try to do following:</p>
<pre><code>import pandas as pd
d = {'col1': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df = pd.DataFrame(data=d)
out = df.query('col1 > col2')
out= col1 col2
1 7 4
3 6 1
</code></pre>
<p>This works OK. But when I modify column name <strong>col1</strong> --> <strong>col1:suf</strong></p>
<pre><code>d = {'col1:suf': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df = pd.DataFrame(data=d)
out = df.query('col1:suf > col2')
</code></pre>
<p>I get an error:</p>
<blockquote>
<p>'AnnAssign' nodes are not implemented</p>
</blockquote>
<p>Is there easy way to avoid this behavior? Or course renaming headers etc. is a workaround</p>
|
[
{
"answer_id": 74638901,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": true,
"text": ": out = df.query('`col1:suf` > col2')\n print(out)\n\n col1:suf col2\n1 7 4\n3 6 1\n"
},
{
"answer_id": 74639005,
"author": "Jason Lee",
"author_id": 15876496,
"author_profile": "https://Stackoverflow.com/users/15876496",
"pm_score": 0,
"selected": false,
"text": "df.query('`Column: Name`==value')\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15925357/"
] |
74,638,826
|
<p>I have a very simple static site, written in <code>HTML</code> and <code>CSS</code> style rules. A simplified form of the <code>HTML</code> code is:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My title</title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>My static site</h1>
<p>This is a simplified example for my static site.</p>
<p>I don't use PHP, JavaScript, or any other programming language</p>
<img style="width: 40%;" src="image.png" />
</body>
</code></pre>
<p>The fact is that, from <code>CSS</code> using <code>prefers-color-scheme: dark</code> I configure some rules in case the user has dark mode configured. I do it like this:</p>
<pre><code>body {
color: #000;
background-color: #fff;
font-family: monospace;
max-width: 130ex;
margin-left:auto;
margin-right:auto;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 80%;
}
@media (prefers-color-scheme: dark) {
body {
color: #fff;
background-color: #000;
}
}
</code></pre>
<p>As you can see, the content is very very simple. I usually try to place the images using transparencies so that they look good in both light and dark mode.</p>
<p>However, I can't do this with many images and they become hopelessly illegible in some of the ways. In these cases I can make a clone of the image as in the following example:</p>
<pre><code><img style="width: 40%;" src="image.png" />
<img style="width: 40%;" src="dark-image.png" />
</code></pre>
<p><a href="https://i.stack.imgur.com/QsDXn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QsDXn.png" alt="light image" /></a>
<a href="https://i.stack.imgur.com/pdIUs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pdIUs.png" alt="dark image" /></a></p>
<p>Is there a way to know, without using programming languages or cookies (maybe in <code>CSS</code>?) to tell the code which image to use?</p>
<p>Is there any other way than this to "darken" an image in <code>CSS</code> in case we find ourselves in dark mode?</p>
<p>Or maybe it's impossible and I must to implement a <code>javascript</code> script for it?</p>
|
[
{
"answer_id": 74638992,
"author": "Jonas Grumann",
"author_id": 1254917,
"author_profile": "https://Stackoverflow.com/users/1254917",
"pm_score": 3,
"selected": true,
"text": ".only-on-dark {\n display: none;\n}\n\n@media (prefers-color-scheme: dark) {\n .only-on-dark {\n display: block;\n }\n \n .only-on-light {\n display: none;\n }\n} <img class=\"only-on-dark\" src=\"//via.placeholder.com/200/000000/ffffff\" />\n<img class=\"only-on-light\" src=\"//via.placeholder.com/200/ffffff/000000\" />"
},
{
"answer_id": 74638998,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 1,
"selected": false,
"text": "img prefer-color-scheme background-color @media (prefers-color-scheme: dark) {\n .light {\n display: none;\n }\n .bg-container {\n background-image: url(\"https://placekitten.com/200/200\");\n }\n}\n\n@media (prefers-color-scheme: light) {\n .dark {\n display: none;\n }\n .bg-container {\n background-image: url(\"https://via.placeholder.com/200x200\");\n }\n}\n\n.bg-container {\n width: 200px;\n height: 200px;\n}\n\ndiv {\n display: inline-block;\n} <img src=\"https://placekitten.com/200/200\" alt=\"\" class=\"dark\">\n<img src=\"https://via.placeholder.com/200x200\" alt=\"\" class=\"light\">\n\n<div class=\"bg-container\"></div>"
},
{
"answer_id": 74639288,
"author": "erecodes",
"author_id": 18703252,
"author_profile": "https://Stackoverflow.com/users/18703252",
"pm_score": 1,
"selected": false,
"text": "<picture> html <source> media img media media=\"(max-width: 600px)\" <picture>\n <!-- User prefers light mode: -->\n <source srcset=\"light-image.jpg\" media=\"(prefers-color-scheme: light)\"/>\n\n <!-- User prefers dark mode: -->\n <source srcset=\"dark-image.jpg\" media=\"(prefers-color-scheme: dark)\"/>\n\n <!-- User has no preference: -->\n <!-- ( I use the light image here, it could be dark as well ) -->\n <img src=\"light-image.png\" />\n</picture>\n"
},
{
"answer_id": 74639542,
"author": "Fco Javier Balón",
"author_id": 12074079,
"author_profile": "https://Stackoverflow.com/users/12074079",
"pm_score": 1,
"selected": false,
"text": "<img class=\"color-invertible\" src=\"image.png\"/>\n prefers-color-scheme: dark .color-invertible {\n filter: invert(100%);\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12074079/"
] |
74,638,831
|
<p>(<a href="https://i.stack.imgur.com/J4v7h.png" rel="nofollow noreferrer">https://i.stack.imgur.com/J4v7h.png</a>)
I have installed both <strong>AutoMapper</strong> and <strong>AutoMapper.Extensions.Microsoft.DependencyInjection</strong></p>
<p>But still I am getting the same error</p>
|
[
{
"answer_id": 74638895,
"author": "amplifier",
"author_id": 1793353,
"author_profile": "https://Stackoverflow.com/users/1793353",
"pm_score": -1,
"selected": false,
"text": "builder.Services.AddAutoMapper(config =>\n{\n config.AddProfile(typeof(YourMappingProfile));\n});\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16014420/"
] |
74,638,856
|
<pre><code>from datetime import datetime
import pytz
# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)
</code></pre>
<p>This doesn't give me the required format i want</p>
<pre><code>2022-05-18T13:43:13
</code></pre>
<p>I wanted to get the time like '2022-12-01T09:13:45Z'</p>
|
[
{
"answer_id": 74639046,
"author": "Ftagliacarne",
"author_id": 4470987,
"author_profile": "https://Stackoverflow.com/users/4470987",
"pm_score": 0,
"selected": false,
"text": "current_datetime = datetime.now().replace(microsecond=0)\nprint(f'ISO Datetime: {current_datetime.strftime(\"%Y-%m-%dT%H:%M:%SZ\")}')\n"
},
{
"answer_id": 74639057,
"author": "louis joseph",
"author_id": 20652486,
"author_profile": "https://Stackoverflow.com/users/20652486",
"pm_score": 2,
"selected": true,
"text": "import datetime\nnow = datetime.datetime.now(datetime.timezone.utc)\nprint(now)\n #2022-12-01 10:07:06.552326+00:00\n import datetime\nnow = datetime.datetime.now(datetime.timezone.utc)\nnow = now.strftime('%Y-%m-%dT%H:%M:%S')+ now.strftime('.%f')[:4] + 'Z'\nprint(now)\n #2022-12-01T10:06:41.122Z\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17287470/"
] |
74,638,914
|
<p>Encoding Input Data: ABC - Output: ZBYX</p>
<p>The encoding happens such that the odd numbered letters of the English alphabet are replaced by their alphabetic opposite, even numbered letters are replaced by a combination of that same letter and it's alphabetic opposite (ie. as shown above 'B' is even numbered alphabet so it got replaced as 'BY', A is replaced by Z, C is replaced by X)</p>
<p>I need to <strong>decode</strong> the encoded output data to get the input (the reverse logic). I wrote the below function but it doesn't quite give me the expected output for all test cases. (eg: When the input is ZBYX, output comes up correctly as ABC, but in other cases such as:</p>
<ul>
<li>JQPLO (input) - output comes as QJKL (supposed to come as JKL)</li>
<li>NMLPK (input) - output comes as MNOP (supposed to come as NOP)</li>
</ul>
<p>)</p>
<p>How should I refactor the below code so that I get the expected output for all test cases?</p>
<pre><code>let alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
function decode(str){
let answer=""
for(let i=0;i<str.length;i++){
if(alpha.indexOf(answer[answer.length-1])%2==0){
if((alpha.indexOf(str[i])+1)%2==0){
continue
}
answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]
}else{
answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]
}
}
return answer
}
</code></pre>
|
[
{
"answer_id": 74639333,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 2,
"selected": false,
"text": "const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nconst decode = str => {\n str = str.split(\"\").reduce((p, c, i, arr) => {\n if (alphabet.indexOf(arr[i + 1]) % 2 !== 0)\n p += alphabet[25 - alphabet.indexOf(c)];\n\n return p\n }, \"\");\n\n return str;\n}\n\nconsole.log(decode(\"ZBYX\"));\nconsole.log(decode(\"JQPLO\"));\nconsole.log(decode(\"NMLPK\"));\n\nconst encode = str => {\n str = str.split(\"\").reduce((p, c) => {\n if (alphabet.indexOf(c) % 2 !== 0)\n p += c + alphabet[25 - alphabet.indexOf(c)];\n else\n p += alphabet[25 - alphabet.indexOf(c)];\n return p\n }, \"\");\n\n return str\n}\n\nconsole.log(encode(\"ABC\"));"
},
{
"answer_id": 74639336,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 3,
"selected": true,
"text": "l l l l let alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nfunction isEven(c) {\n return (alpha.indexOf(c) + 1) % 2 === 0;\n}\n\nfunction opposite(c) {\n return alpha[alpha.length - alpha.indexOf(c) - 1];\n}\n\nfunction encode(str) {\n let answer = \"\";\n for (let i = 0; i < str.length; i++) {\n if (!isEven(str[i])) {\n answer += opposite(str[i]);\n } else {\n answer += str[i];\n answer += opposite(str[i]);\n }\n }\n return answer;\n}\n\nfunction decode(str) {\n let answer = \"\";\n for (let i = 0; i < str.length; i++) {\n if (isEven(str[i]) && str[i + 1] === opposite(str[i])) {\n answer += str[i];\n i++;\n } else {\n answer += opposite(str[i]);\n }\n }\n return answer;\n}\n\nconsole.log(encode('ABC'));\nconsole.log(decode('ZBYX'));\nconsole.log(decode('NMLPK'));\nconsole.log(decode('JQPLO'));"
},
{
"answer_id": 74639508,
"author": "jumosbro",
"author_id": 17494908,
"author_profile": "https://Stackoverflow.com/users/17494908",
"pm_score": 0,
"selected": false,
"text": "function decode(str){\ntry{\n let answer=\"\"\n if(!(/^[A-Z]+$/).test(str)){\n throw Error(\"Input must only contain upper case letters\")\n }\n\n for(let i=0;i<str.length;i++){\n if(alpha.indexOf(answer[answer.length-1])%2==0){\n if((alpha.indexOf(str[i])+1)%2==0){\n continue\n }\n }else{\n if(str.length>4)answer=answer.slice(-1) \n }\n answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]\n\n }\n\n return answer\n} catch (err){\n console.log(err)\n}\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17494908/"
] |
74,638,944
|
<p>How to see if a user can be unbanned or not between 2 dates?</p>
<p>Hi, I have a given variable which is the date the user was unbanned as <code>end_banned</code> in the format <code>HH:mm:ss dd/MM/YYYY</code>.</p>
<p><code>val end_banned: String= "15:05:00 12/01/2022"</code></p>
<p>I want to calculate if at the current time they can be unbanned or not. I have tried with <code>SimpleDateFormat, Calendar, Date...</code> but still haven't found a solution.</p>
<ol>
<li>I've tried separating each element of <code>seconds, minutes, days...</code> and comparing them with if...else like this:</li>
</ol>
<pre><code>var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var _hours = cal.get(Calendar.HOUR)
var _minutes = cal.get(Calendar.MINUTE)
var _seconds = cal.get(Calendar.SECOND)
var _day = cal.get(Calendar.DAY_OF_MONTH)
var _month = cal.get(Calendar.MONTH) + 1
var _year = cal.get(Calendar.YEAR)
var hours = end_banned.toString().substring(0, 2).toInt()
var minutes = end_banned.toString().substring(3, 5).toInt()
var seconds = end_banned.toString().substring(6, 8).toInt()
var day = end_banned.toString().substring(9, 11).toInt()
var month = end_banned.toString().substring(12, 14).toInt()
var year = end_banned.toString().substring(15).toInt()
if (_year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes && _seconds >= seconds
|| _year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes
|| _year >= year && _month >= month && _day >= day && _hours >= hours
|| _year >= year && _month >= month && _day >= day
|| _year >= year && _month >= month
|| _year >= year) {
println("True")
} else {
println("False")
}
</code></pre>
<p>But it is only true for the first 3 conditions when there are hours, minutes and seconds.</p>
<ol start="2">
<li>I tried with SimpleDateFormat and Date like this:</li>
</ol>
<pre><code>var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var hours = cal.get(Calendar.HOUR)
var minutes = cal.get(Calendar.MINUTE)
var seconds = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var sdf_unbanned = sdf.parse(end_banned)
var sdf_now = sdf.parse("${hours}:${minutes}:${seconds} ${day}/${month}/${year}")
if (sdf_now.time - sdf_unbanned.time <= 0) {
println(true)
} else {
println(false)
}
</code></pre>
<p>But this condition always gives an incorrect number if I adjust the now and unbanned variables a few minutes apart (This makes it easier to spot)</p>
|
[
{
"answer_id": 74639333,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 2,
"selected": false,
"text": "const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nconst decode = str => {\n str = str.split(\"\").reduce((p, c, i, arr) => {\n if (alphabet.indexOf(arr[i + 1]) % 2 !== 0)\n p += alphabet[25 - alphabet.indexOf(c)];\n\n return p\n }, \"\");\n\n return str;\n}\n\nconsole.log(decode(\"ZBYX\"));\nconsole.log(decode(\"JQPLO\"));\nconsole.log(decode(\"NMLPK\"));\n\nconst encode = str => {\n str = str.split(\"\").reduce((p, c) => {\n if (alphabet.indexOf(c) % 2 !== 0)\n p += c + alphabet[25 - alphabet.indexOf(c)];\n else\n p += alphabet[25 - alphabet.indexOf(c)];\n return p\n }, \"\");\n\n return str\n}\n\nconsole.log(encode(\"ABC\"));"
},
{
"answer_id": 74639336,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 3,
"selected": true,
"text": "l l l l let alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nfunction isEven(c) {\n return (alpha.indexOf(c) + 1) % 2 === 0;\n}\n\nfunction opposite(c) {\n return alpha[alpha.length - alpha.indexOf(c) - 1];\n}\n\nfunction encode(str) {\n let answer = \"\";\n for (let i = 0; i < str.length; i++) {\n if (!isEven(str[i])) {\n answer += opposite(str[i]);\n } else {\n answer += str[i];\n answer += opposite(str[i]);\n }\n }\n return answer;\n}\n\nfunction decode(str) {\n let answer = \"\";\n for (let i = 0; i < str.length; i++) {\n if (isEven(str[i]) && str[i + 1] === opposite(str[i])) {\n answer += str[i];\n i++;\n } else {\n answer += opposite(str[i]);\n }\n }\n return answer;\n}\n\nconsole.log(encode('ABC'));\nconsole.log(decode('ZBYX'));\nconsole.log(decode('NMLPK'));\nconsole.log(decode('JQPLO'));"
},
{
"answer_id": 74639508,
"author": "jumosbro",
"author_id": 17494908,
"author_profile": "https://Stackoverflow.com/users/17494908",
"pm_score": 0,
"selected": false,
"text": "function decode(str){\ntry{\n let answer=\"\"\n if(!(/^[A-Z]+$/).test(str)){\n throw Error(\"Input must only contain upper case letters\")\n }\n\n for(let i=0;i<str.length;i++){\n if(alpha.indexOf(answer[answer.length-1])%2==0){\n if((alpha.indexOf(str[i])+1)%2==0){\n continue\n }\n }else{\n if(str.length>4)answer=answer.slice(-1) \n }\n answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]\n\n }\n\n return answer\n} catch (err){\n console.log(err)\n}\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19358095/"
] |
74,638,945
|
<p>I'm trying to scrape URLs of images over multiple pages but my code seems to only scrape the URLs belonging to the first page.</p>
<p>My goal is to manipulate the website URL such that it loops between pages 1 to 100 (after the "page=" portion) and the URL links are scraped accordingly!</p>
<p>Would appreciate some assistance! Thank you!</p>
<p>I've attached my code below;</p>
<pre><code>library("rvest")
library("ralger")
for(page_result in 1:100){
link = paste0("https://www.istockphoto.com/search/2/image?alloweduse=availableforalluses&mediatype=photography&phrase=man&page=", page_result)
male <- images_preview(link)
}
</code></pre>
|
[
{
"answer_id": 74639333,
"author": "Layhout",
"author_id": 17308201,
"author_profile": "https://Stackoverflow.com/users/17308201",
"pm_score": 2,
"selected": false,
"text": "const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nconst decode = str => {\n str = str.split(\"\").reduce((p, c, i, arr) => {\n if (alphabet.indexOf(arr[i + 1]) % 2 !== 0)\n p += alphabet[25 - alphabet.indexOf(c)];\n\n return p\n }, \"\");\n\n return str;\n}\n\nconsole.log(decode(\"ZBYX\"));\nconsole.log(decode(\"JQPLO\"));\nconsole.log(decode(\"NMLPK\"));\n\nconst encode = str => {\n str = str.split(\"\").reduce((p, c) => {\n if (alphabet.indexOf(c) % 2 !== 0)\n p += c + alphabet[25 - alphabet.indexOf(c)];\n else\n p += alphabet[25 - alphabet.indexOf(c)];\n return p\n }, \"\");\n\n return str\n}\n\nconsole.log(encode(\"ABC\"));"
},
{
"answer_id": 74639336,
"author": "kimbo",
"author_id": 9638991,
"author_profile": "https://Stackoverflow.com/users/9638991",
"pm_score": 3,
"selected": true,
"text": "l l l l let alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nfunction isEven(c) {\n return (alpha.indexOf(c) + 1) % 2 === 0;\n}\n\nfunction opposite(c) {\n return alpha[alpha.length - alpha.indexOf(c) - 1];\n}\n\nfunction encode(str) {\n let answer = \"\";\n for (let i = 0; i < str.length; i++) {\n if (!isEven(str[i])) {\n answer += opposite(str[i]);\n } else {\n answer += str[i];\n answer += opposite(str[i]);\n }\n }\n return answer;\n}\n\nfunction decode(str) {\n let answer = \"\";\n for (let i = 0; i < str.length; i++) {\n if (isEven(str[i]) && str[i + 1] === opposite(str[i])) {\n answer += str[i];\n i++;\n } else {\n answer += opposite(str[i]);\n }\n }\n return answer;\n}\n\nconsole.log(encode('ABC'));\nconsole.log(decode('ZBYX'));\nconsole.log(decode('NMLPK'));\nconsole.log(decode('JQPLO'));"
},
{
"answer_id": 74639508,
"author": "jumosbro",
"author_id": 17494908,
"author_profile": "https://Stackoverflow.com/users/17494908",
"pm_score": 0,
"selected": false,
"text": "function decode(str){\ntry{\n let answer=\"\"\n if(!(/^[A-Z]+$/).test(str)){\n throw Error(\"Input must only contain upper case letters\")\n }\n\n for(let i=0;i<str.length;i++){\n if(alpha.indexOf(answer[answer.length-1])%2==0){\n if((alpha.indexOf(str[i])+1)%2==0){\n continue\n }\n }else{\n if(str.length>4)answer=answer.slice(-1) \n }\n answer+=alpha[alpha.length-(alpha.indexOf(str[i])+1)]\n\n }\n\n return answer\n} catch (err){\n console.log(err)\n}\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654129/"
] |
74,638,985
|
<p>I have this variable called "number" with the range being the variables "a" and "b". These range variables are ranges themselves.</p>
<pre><code>from random import *
a = randint(1, 99)
b = randint(2, 100)
number = randint(a, b)
print(number)
</code></pre>
<p>When I try to enter this code, I occasionally receive an integer or get this error:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 6, in <module>
number = randint(a, b)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/random.py", line 248, in randint
return self.randrange(a, b+1)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/random.py", line 226, in randrange
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (17, 6, -11)
</code></pre>
|
[
{
"answer_id": 74639011,
"author": "Tim Stack",
"author_id": 10540017,
"author_profile": "https://Stackoverflow.com/users/10540017",
"pm_score": 0,
"selected": false,
"text": "randint b a b a from random import *\n\na = randint(1, 99)\nb = randint(a, 100)\n\nnumber = randint(a, b)\nprint(number)\n"
},
{
"answer_id": 74639053,
"author": "dev_master089",
"author_id": 20652510,
"author_profile": "https://Stackoverflow.com/users/20652510",
"pm_score": 1,
"selected": false,
"text": "a <= b\n a = randint(1, 50)\nb = randint(50, 100)\n"
},
{
"answer_id": 74639067,
"author": "Psykomentax",
"author_id": 20653615,
"author_profile": "https://Stackoverflow.com/users/20653615",
"pm_score": -1,
"selected": false,
"text": "import random\n\na = random.randint(1, 99)\nb = random.randint(2, 100)\n\nnumber = random.randint(a, b)\nprint(number)\n"
},
{
"answer_id": 74639132,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "from random import randint\n\na = randint(1, 99)\nb = randint(a, 100)\nnumber = randint(a, b)\nprint(number)\n from random import randint\n\nnumber = randint(1, 100)\nprint(number)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18208415/"
] |
74,638,990
|
<p>I am very new to Xcode and trying to fetch data from my WordPress website in SwiftUI using rest api. I have got code from internet , I have installed these pod's</p>
<pre><code>pod 'SwiftyJSON'
pod 'Alamofire'
pod 'SDWebImage'
</code></pre>
<p>Imported all pods in homeController and using this code to fetch data.</p>
<pre class="lang-swift prettyprint-override"><code>Alamofire.request("\(urlPage)\(page)").responseJSON { response in
if let data = response.result.value {
let json2 = JSON(data)
self.moreDataNum = json2["count"].intValue
if self.dataArray?.isEmpty == false {
self.dataArray.append(contentsOf: json2["posts"].arrayValue)
self.collectionView.reloadData()
// ...
</code></pre>
<p>I am getting this error..</p>
<p><a href="https://i.stack.imgur.com/HFCgE.png" rel="nofollow noreferrer">open image to see error</a></p>
<p>please help me ..</p>
|
[
{
"answer_id": 74639011,
"author": "Tim Stack",
"author_id": 10540017,
"author_profile": "https://Stackoverflow.com/users/10540017",
"pm_score": 0,
"selected": false,
"text": "randint b a b a from random import *\n\na = randint(1, 99)\nb = randint(a, 100)\n\nnumber = randint(a, b)\nprint(number)\n"
},
{
"answer_id": 74639053,
"author": "dev_master089",
"author_id": 20652510,
"author_profile": "https://Stackoverflow.com/users/20652510",
"pm_score": 1,
"selected": false,
"text": "a <= b\n a = randint(1, 50)\nb = randint(50, 100)\n"
},
{
"answer_id": 74639067,
"author": "Psykomentax",
"author_id": 20653615,
"author_profile": "https://Stackoverflow.com/users/20653615",
"pm_score": -1,
"selected": false,
"text": "import random\n\na = random.randint(1, 99)\nb = random.randint(2, 100)\n\nnumber = random.randint(a, b)\nprint(number)\n"
},
{
"answer_id": 74639132,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "from random import randint\n\na = randint(1, 99)\nb = randint(a, 100)\nnumber = randint(a, b)\nprint(number)\n from random import randint\n\nnumber = randint(1, 100)\nprint(number)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74638990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20501766/"
] |
74,639,012
|
<p>I have 2 arrays:</p>
<ul>
<li>$DatesToDelete()</li>
<li>$ArrayAllDates()</li>
</ul>
<p>$DatesToDelete() contains a list of dates, like this:</p>
<p>01/11/2022
02/11/2022
03/11/2022
04/11/2022
05/11/2022
06/11/2022
07/11/2022
08/11/2022
09/11/2022
10/11/2022
11/11/2022
12/11/2022
13/11/2022
14/11/2022
15/11/2022
16/11/2022
17/11/2022
18/11/2022
19/11/2022
20/11/2022
21/11/2022
22/11/2022
23/11/2022
24/11/2022
25/11/2022
26/11/2022
27/11/2022
28/11/2022
29/11/2022
30/11/2022</p>
<p>$ArrayAllDates() contains another list of dates, like this:</p>
<p>07/11/2022
07/11/2022
18/11/2022
17/11/2022
02/12/2022</p>
<p>**My goal is to find if dates coming from $DatesToDelete() are contained in $ArrayAllDates()
**</p>
<p>I'm not a PHP expert and I tried a lot of loops with foreach() without success :-(</p>
<p>Thank you</p>
<pre><code>foreach($ArrayAllDates as $d) {
foreach($DatesToDelete as $e) {
if(in_array($b,$arrayalldates)){
}
}
}
</code></pre>
|
[
{
"answer_id": 74639127,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 0,
"selected": false,
"text": "foreach($ArrayAllDates as $d){\n if(in_array($d, $DatesToDelete)){\n echo $d.\"<br>\";\n }\n}\n $containDates = array();\nforeach($ArrayAllDates as $d){\n if(in_array($d, $DatesToDelete)){\n array_push($containDates ,$d);\n }\n}\nprint_r($containDates);\n"
},
{
"answer_id": 74639712,
"author": "Ernesto Vladimir Pereda Díaz",
"author_id": 4471745,
"author_profile": "https://Stackoverflow.com/users/4471745",
"pm_score": 1,
"selected": false,
"text": "$datesToDelete = [\n '02/11/2022',\n '04/11/2022',\n '06/11/2022',\n '07/11/2022',\n '02/12/2022',\n];\n$allDates = [\n '07/11/2022',\n '07/11/2022',\n '18/11/2022',\n '17/11/2022',\n '02/12/2022',\n];\n$commonDates = array_intersect($allDates, $datesToDelete);\nprint_r($commonDates);\n/* it print this:\nArray\n(\n [0] => 07/11/2022\n [1] => 07/11/2022\n [4] => 02/12/2022\n)\nwhen the key is de key and value are of $allDates array\n*/\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8208116/"
] |
74,639,032
|
<p>For example i want to write <code>(rand%(MaxValue-MinValue+1))-MinValue</code> i don't want to write this line everytime i want to use it but is there a way to make Visual Studio auto write it when i just need to write <code>rand</code> or <code>R</code>.</p>
|
[
{
"answer_id": 74639127,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 0,
"selected": false,
"text": "foreach($ArrayAllDates as $d){\n if(in_array($d, $DatesToDelete)){\n echo $d.\"<br>\";\n }\n}\n $containDates = array();\nforeach($ArrayAllDates as $d){\n if(in_array($d, $DatesToDelete)){\n array_push($containDates ,$d);\n }\n}\nprint_r($containDates);\n"
},
{
"answer_id": 74639712,
"author": "Ernesto Vladimir Pereda Díaz",
"author_id": 4471745,
"author_profile": "https://Stackoverflow.com/users/4471745",
"pm_score": 1,
"selected": false,
"text": "$datesToDelete = [\n '02/11/2022',\n '04/11/2022',\n '06/11/2022',\n '07/11/2022',\n '02/12/2022',\n];\n$allDates = [\n '07/11/2022',\n '07/11/2022',\n '18/11/2022',\n '17/11/2022',\n '02/12/2022',\n];\n$commonDates = array_intersect($allDates, $datesToDelete);\nprint_r($commonDates);\n/* it print this:\nArray\n(\n [0] => 07/11/2022\n [1] => 07/11/2022\n [4] => 02/12/2022\n)\nwhen the key is de key and value are of $allDates array\n*/\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18519699/"
] |
74,639,063
|
<p>I have Data which indicates month of Order date and month of Shipment date. I want to convert the records which will show, in each month, what is the count of orders and in same month what is the count of shipments</p>
<p>Because I am a beginner to SQL I could not try any way but this is the expected table.</p>
<p>I want to make this happen with Select statement. Please refer the image for the data by clicking here <a href="https://i.stack.imgur.com/lQD39.png" rel="nofollow noreferrer">Data with expected result</a></p>
|
[
{
"answer_id": 74639127,
"author": "Danz",
"author_id": 19681705,
"author_profile": "https://Stackoverflow.com/users/19681705",
"pm_score": 0,
"selected": false,
"text": "foreach($ArrayAllDates as $d){\n if(in_array($d, $DatesToDelete)){\n echo $d.\"<br>\";\n }\n}\n $containDates = array();\nforeach($ArrayAllDates as $d){\n if(in_array($d, $DatesToDelete)){\n array_push($containDates ,$d);\n }\n}\nprint_r($containDates);\n"
},
{
"answer_id": 74639712,
"author": "Ernesto Vladimir Pereda Díaz",
"author_id": 4471745,
"author_profile": "https://Stackoverflow.com/users/4471745",
"pm_score": 1,
"selected": false,
"text": "$datesToDelete = [\n '02/11/2022',\n '04/11/2022',\n '06/11/2022',\n '07/11/2022',\n '02/12/2022',\n];\n$allDates = [\n '07/11/2022',\n '07/11/2022',\n '18/11/2022',\n '17/11/2022',\n '02/12/2022',\n];\n$commonDates = array_intersect($allDates, $datesToDelete);\nprint_r($commonDates);\n/* it print this:\nArray\n(\n [0] => 07/11/2022\n [1] => 07/11/2022\n [4] => 02/12/2022\n)\nwhen the key is de key and value are of $allDates array\n*/\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406488/"
] |
74,639,082
|
<p>I want to extract lines to create files for each chromosome. My source file is look like as below:</p>
<p><a href="https://i.stack.imgur.com/ygEb5.png" rel="nofollow noreferrer">BED file</a></p>
<p>I could run <code>awk '{OFS="\t"} {split($1, a, "r")} a[2]==1 {print $0}' MISA.bed > chr_1.bed</code>. This way take much time to do manually</p>
<p>I tried this and it did create correct list of files but they were all empty</p>
<p><code>for i in {1..22}; do awk '{OFS="\t"} $1=="chr${i}" {print $0}' MISA.bed > chr_${i}.bed; done</code></p>
|
[
{
"answer_id": 74640922,
"author": "Pierre",
"author_id": 58082,
"author_profile": "https://Stackoverflow.com/users/58082",
"pm_score": 0,
"selected": false,
"text": "awk -F '\\t' '{F=sprintf(\"chr_%s.bed\",$1); print >> F}' MISA.bed \n"
},
{
"answer_id": 74642902,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 2,
"selected": true,
"text": "i -v var=\"value\" $1 > MISA.bed .bed awk '{print $0 > $1\".bed\"}' MISA.bed\n fn=$1\".bed\"; print $0 > fn close(fn) MISA.bed chr1 10286 10321 6 AACCCC\nchr1 10386 10421 2 CT\nchr1 10486 10521 2 TC\nchr2 10186 10221 2 TC\nchr2 10286 10321 2 AT\nchr2 10486 10521 6 CCAACC\nchr3 10486 10521 2 TC\nchr3 10586 10621 2 AT\nchr3 10686 10721 6 CCAACC\n awk '{print $0 > $1\".bed\"}' MISA.bed\n > ls *.bed\n> chr1.bed chr2.bed chr3.bed MISA.bed\n\n> cat chr1.bed \nchr1 10286 10321 6 AACCCC\nchr1 10386 10421 2 CT\nchr1 10486 10521 2 TC\n\n> cat chr2.bed \nchr2 10186 10221 2 TC\nchr2 10286 10321 2 AT\nchr2 10486 10521 6 CCAACC\n\n> cat chr3.bed \nchr3 10486 10521 2 TC\nchr3 10586 10621 2 AT\nchr3 10686 10721 6 CCAACC\n\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19226179/"
] |
74,639,097
|
<p>I want my <code>text</code> and <code>button</code> at the top of the screen, but both the elements have a few gaps between, so I added <code>marginBottom</code> to my <code>text</code> and then that <code>text</code> went to the top. But I want that <code>button</code> to be at the top so I added <code>marginBottom</code> to the <code>button</code> too, but now it's not going to the top.</p>
<p>How can I position it to the top? Where is the style issue coming from? Please, explain my mistake as well.</p>
<pre><code>import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={{ margin: 16, marginBottom: '80%', backgroundColor: 'black' }}>Hello World</Text>
<View style={{ marginBottom: '80%' }}>
<Button title='Click me' />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
</code></pre>
|
[
{
"answer_id": 74639250,
"author": "Kay Angevare",
"author_id": 11787139,
"author_profile": "https://Stackoverflow.com/users/11787139",
"pm_score": 3,
"selected": true,
"text": "alignItems: 'center' justifyContent: 'center' container alignItems:center justifyContent:center Text marginBottom View Button marginBottom Text marginBottom Text container container:{ alignItems:'center', } marginTop Text"
},
{
"answer_id": 74639319,
"author": "Bugra Kucuk",
"author_id": 16260715,
"author_profile": "https://Stackoverflow.com/users/16260715",
"pm_score": 1,
"selected": false,
"text": " return (\n <View style={styles.container}>\n <Text\n style={{ margin: 16, marginBottom: \"auto\", backgroundColor: \"white\" }}\n >\n Hello World\n </Text>\n <View style={{ marginBottom: \"auto\" }}>\n <Button title=\"Click me\" />\n </View>\n </View>\n );\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,639,098
|
<p><a href="https://i.stack.imgur.com/XZpoi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XZpoi.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/GSE1P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GSE1P.png" alt="enter image description here" /></a></p>
<p>I'm Trying to capture onChanged property value which is comming from my TextField and use it inside my onPressed textButton but it's not working. I've read most of the related issues in stack overflow but none of it actually helping in the problem. Do you have any better suggestion that I should do.</p>
|
[
{
"answer_id": 74639250,
"author": "Kay Angevare",
"author_id": 11787139,
"author_profile": "https://Stackoverflow.com/users/11787139",
"pm_score": 3,
"selected": true,
"text": "alignItems: 'center' justifyContent: 'center' container alignItems:center justifyContent:center Text marginBottom View Button marginBottom Text marginBottom Text container container:{ alignItems:'center', } marginTop Text"
},
{
"answer_id": 74639319,
"author": "Bugra Kucuk",
"author_id": 16260715,
"author_profile": "https://Stackoverflow.com/users/16260715",
"pm_score": 1,
"selected": false,
"text": " return (\n <View style={styles.container}>\n <Text\n style={{ margin: 16, marginBottom: \"auto\", backgroundColor: \"white\" }}\n >\n Hello World\n </Text>\n <View style={{ marginBottom: \"auto\" }}>\n <Button title=\"Click me\" />\n </View>\n </View>\n );\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20635666/"
] |
74,639,165
|
<pre class="lang-py prettyprint-override"><code>class OrganizationUser(models.Model):
pass
class Feedback(models.Model):
teams_shared_with = models.ManyToManyField('team.Team', related_name="feedback")
class Team(models.Model):
leads = models.ManyToManyField('organizations.OrganizationUser', related_name='teams_lead_at')
members = models.ManyToManyField('organizations.OrganizationUser', related_name='teams_member_at', blank=True)
</code></pre>
<p>I have the above models, all the fields were not shown. I want to filter those feedback which are shared in any team where I am a member or an admin.</p>
<p>I would like to do something like:</p>
<pre class="lang-py prettyprint-override"><code>Feedback.objects.filter(teams_shared_with is a subset of organization_user.teams_lead_at.all()|organization_user.teams_member_at.all())
</code></pre>
<p>How would I do that?</p>
|
[
{
"answer_id": 74639250,
"author": "Kay Angevare",
"author_id": 11787139,
"author_profile": "https://Stackoverflow.com/users/11787139",
"pm_score": 3,
"selected": true,
"text": "alignItems: 'center' justifyContent: 'center' container alignItems:center justifyContent:center Text marginBottom View Button marginBottom Text marginBottom Text container container:{ alignItems:'center', } marginTop Text"
},
{
"answer_id": 74639319,
"author": "Bugra Kucuk",
"author_id": 16260715,
"author_profile": "https://Stackoverflow.com/users/16260715",
"pm_score": 1,
"selected": false,
"text": " return (\n <View style={styles.container}>\n <Text\n style={{ margin: 16, marginBottom: \"auto\", backgroundColor: \"white\" }}\n >\n Hello World\n </Text>\n <View style={{ marginBottom: \"auto\" }}>\n <Button title=\"Click me\" />\n </View>\n </View>\n );\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11144121/"
] |
74,639,181
|
<p>From what I understood, when I run <code>git clone</code>, then start to add/edit files on my local repo, I have actually 2 repos : <code>master</code> and <code>origin/master</code> -where the later points to the remote- , I am getting this intuition from what <code>git fetch</code> does, It actually gets the latest version from <code>remote</code> repo to <code>origin/master</code> repo without merging it with local <code>master</code>, it is only when I call <code>git merge</code> that these remote changes are merged to local <code>master</code></p>
<p>So first question: Am I understanding it correctly? I really have 2 repos on local</p>
<p>Second question: If this is the case, then why pushing a change to the remote server is a 2 step process (<code>git commit</code> then <code>git push</code>) , If I really have 2 local repos, I believe I will need to make 3 steps : commit to local <code>master</code> - merge to <code>origin/master</code> then push to <code>remote/master</code> ... how now this is only done via 2 steps, is there any implicit action that happens or am I getting something wrong?</p>
|
[
{
"answer_id": 74639470,
"author": "rutaka nashimo",
"author_id": 4953217,
"author_profile": "https://Stackoverflow.com/users/4953217",
"pm_score": 3,
"selected": false,
"text": "master origin/master master origin/master master origin"
},
{
"answer_id": 74642278,
"author": "IMSoP",
"author_id": 157957,
"author_profile": "https://Stackoverflow.com/users/157957",
"pm_score": 1,
"selected": false,
"text": "git clone git push git fetch git pull git fetch git pull master origin/master origin/master"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2866298/"
] |
74,639,184
|
<p>Do you know why the output of the program below is</p>
<pre><code>1000
2000
</code></pre>
<p>I am very grateful if you can help me!
Here is the program.</p>
<pre class="lang-c prettyprint-override"><code>int main()
{
int t[] = { 1, 2 };
char* p = (char*)t;
int i;
for (i = 0; i < sizeof(t); i++)
{
printf("%d", *(p + i));
if (i % sizeof(t[0]) == sizeof(t[0]) - 1) printf("\n");
}
return 0;
}
</code></pre>
|
[
{
"answer_id": 74639470,
"author": "rutaka nashimo",
"author_id": 4953217,
"author_profile": "https://Stackoverflow.com/users/4953217",
"pm_score": 3,
"selected": false,
"text": "master origin/master master origin/master master origin"
},
{
"answer_id": 74642278,
"author": "IMSoP",
"author_id": 157957,
"author_profile": "https://Stackoverflow.com/users/157957",
"pm_score": 1,
"selected": false,
"text": "git clone git push git fetch git pull git fetch git pull master origin/master origin/master"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654288/"
] |
74,639,186
|
<p>I am in home page everything is dispatched and works fine and when I go enter to next page which display detailed information and when I go back using <code>react-router-dom</code> <code><Link to='..'></code> back to home page the useEffect is not firing It will not dispatch the redux state which let to blank page and if I manually reload the home page it works. So how do make sure that useEffect re-renders when i navigate it back to home page. I am facing the same problem when I am navigating from any other page to home page or any other page.</p>
<p>Here is the navigation routes for these two documents.</p>
<pre><code>{/* Product Screen Design none Functionalities Complete% /}
<Route
path='/product/:id'
element={<ProductScreen />}
/>
{/ HomeScreen Screen Design complete Functionalities complete */}
<Route
path='/'
element={<HomeScreen />}
exact
/>
</code></pre>
<p>Here is my Code for homeScreen and <a href="https://i.stack.imgur.com/PDi02.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PDi02.png" alt="Snapshot of homescreen" /></a></p>
<pre><code>const HomeScreen = () => {
const dispatch = useDispatch()
const { keyword, pageNumber } = useParams()
const keywords = keyword
const pageNumbers = pageNumber || 1
const { products, page, pages, isLoading, isError, message } = useSelector(
(state) => state.products,
)
// console.log(products)
useEffect(() => {
if (isError) {
toast.error(message)
}
dispatch(getProduct(keywords, pageNumbers))
}, [isError, message, keywords, pageNumbers, dispatch])
</code></pre>
<p>Here on my first load two this page everything renders all list of product which is expected outcome</p>
<p>and when I visit to ProductDetails page and <a href="https://i.stack.imgur.com/6GJ2U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6GJ2U.png" alt="snapshot of productDetails" /></a> where in back button i have attached the link to go back</p>
<pre><code>const ProductScreen = () => {
const dispatch = useDispatch()
const navigate = useNavigate()
const { id } = useParams()
const [qty, setQty] = useState(1)
const [image, setImage] = useState(null)
const [formData, setFormData] = useState({
rating: '',
comment: '',
})
const { rating, comment } = formData
const { user } = useSelector((state) => state.auth)
const { products, isLoading, isError, message } = useSelector(
(state) => state.products,
)
useEffect(() => {
if (isError) {
toast.error(message)
}
dispatch(getProductById(id))
return () => {
dispatch(reset())
}
}, [dispatch, id, message, user, isError])
</code></pre>
<p>Inside this return I have link should redirects me to home page and dispatch the product data as expected but i am getting black screen and <strong>error I am getting is undefined in the products const which should have all the data to loop in the screen</strong></p>
<pre><code>return (
<>
<Link
to='..'
className='fa-2x my-3 float-left'
>
<IoIosArrowBack />
</Link>
</code></pre>
<p>I am expecting the home page renders whenever I use useNavigate hooks or link of react-router-dom</p>
<p>I tried to make <a href="https://codesandbox.io/s/codesandbox-forked-mz9si4?file=/src/ProductScreen.js" rel="nofollow noreferrer">codeSandbox</a> .</p>
|
[
{
"answer_id": 74639346,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "<Link to=\"..\" react-router-dom import {useHistory} from 'react-router-dom';\n\nconst App =()=>{\nconst history=useHistory()\nreturn(\n <IoIosArrowBack onClick={()=>history.goBack() }/>\n)\n}\n import {useNavigate} from 'react-router-dom';\n\nconst App =()=>{\nconst navigate=useNavigate()\nreturn(\n <IoIosArrowBack onClick={()=>navigate(-1) }/>\n)\n}\n"
},
{
"answer_id": 74639924,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": false,
"text": "import { useLocation } from 'react-router-dom';\n let location = useLocation();\n\nuseEffect(() => {\n if (isError) {\n toast.error(message)\n }\n\n dispatch(getProduct(keywords, pageNumbers))\n}, [isError, message, keywords, pageNumbers, dispatch, location.pathname])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11109926/"
] |
74,639,267
|
<p>I want to remove the type 'A' from the capital. How do I do it? Any code example will be appreciated. I am working on a react project.
<img src="https://i.stack.imgur.com/WfroF.png" alt="" /></p>
|
[
{
"answer_id": 74639346,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "<Link to=\"..\" react-router-dom import {useHistory} from 'react-router-dom';\n\nconst App =()=>{\nconst history=useHistory()\nreturn(\n <IoIosArrowBack onClick={()=>history.goBack() }/>\n)\n}\n import {useNavigate} from 'react-router-dom';\n\nconst App =()=>{\nconst navigate=useNavigate()\nreturn(\n <IoIosArrowBack onClick={()=>navigate(-1) }/>\n)\n}\n"
},
{
"answer_id": 74639924,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": false,
"text": "import { useLocation } from 'react-router-dom';\n let location = useLocation();\n\nuseEffect(() => {\n if (isError) {\n toast.error(message)\n }\n\n dispatch(getProduct(keywords, pageNumbers))\n}, [isError, message, keywords, pageNumbers, dispatch, location.pathname])\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17820997/"
] |
74,639,273
|
<p>I want to have a hover animation that disappears when hovering over the picture and another picture takes its place, but the back picture isn't disappearing</p>
<p>I tried to use opacity 1 to go to 0, and transition time 0.5sec but it's stuck in the old position</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>.Menu .mnpic {
transform: translateX(30%);
/* display: flex;
justify-content: center;
align-content: center; */
}
.mnovly {
position: absolute;
top: 0;
}
.mwhite{
/* position: relative; */
opacity: 1;
transition: 0.5s;
}
.mwhite:hover {
opacity: 0;
}
.mblack{
opacity: 0;
transition: 0.5s;
}
.mblack:hover{
opacity: 1;
height: 200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mnpic">
<img calss="mwhite" src="menuwhite.png" alt="" height="150px">
<div class="mnovly">
<img class="mblack" src="menublack.png" alt="" height="150px">
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74639619,
"author": "Pete Pearl",
"author_id": 14290361,
"author_profile": "https://Stackoverflow.com/users/14290361",
"pm_score": 1,
"selected": false,
"text": ".hover {\n width: 200px;\n height: 200px;\n background: url('https://picsum.photos/200') no-repeat center center;\n position: relative;\n}\n\n.hover:after{\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: url('https://picsum.photos/300') no-repeat center center;\n opacity: 0;\n transition: opacity .3s;\n}\n\n.hover:hover:after {\n opacity: 1;\n} <div class=\"hover\"></div>"
},
{
"answer_id": 74641320,
"author": "Gonzalo F S",
"author_id": 15928193,
"author_profile": "https://Stackoverflow.com/users/15928193",
"pm_score": 1,
"selected": true,
"text": ".mwhite:hover calss=\"mwhite\" class=\"mwhite\" .mwhite:hover + .mblack .Menu .mnpic {\n transform: translateX(30%);\n}\n\n.mwhite{\n opacity: 1;\n transition: 0.5s;\n border: 1px green solid;\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n}\n.mwhite:hover {\n opacity: 0;\n border: 1px blue solid;\n}\n.mblack{\n border: 1px red solid;\n opacity: 0;\n transition: 0.5s;\n}\n.mwhite:hover + .mblack{\n opacity: 1;\n height: 200px;\n} <div class=\"mnpic\">\n <img class=\"mwhite\" src='https://picsum.photos/200' alt=\"\" height=\"150px\">\n <img class=\"mblack\" src='https://picsum.photos/300' alt=\"\" height=\"150px\">\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654304/"
] |
74,639,276
|
<p>I'm following the <a href="https://learn.microsoft.com/en-us/windows/mixed-reality/develop/unity/tutorials/mr-learning-sharing-03" rel="nofollow noreferrer">tutorial</a> from Microsoft in order to create a multi-users experience in augmented reality between an Hololens and an Android app.</p>
<p>After installing the following packages :</p>
<ul>
<li><p>MRTK.HoloLens2.Unity.Tutorials.Assets.MultiUserCapabilities.2.7.2.unitypackage</p>
</li>
<li><p>MRTK.HoloLens2.Unity.Tutorials.Assets.GettingStarted.2.7.2.unitypackage</p>
</li>
<li><p>MRTK.HoloLens2.Unity.Tutorials.Assets.AzureSpatialAnchors.2.7.2.unitypackage</p>
</li>
</ul>
<p>and following the tutorial, I can launch the app in the Unity Editor with no issue and I can see a message indicating "number of players in the experience: 1".</p>
<p><strong>The problem</strong><br />
When I try to build the app in order to launch it on the Hololens, I get the following error which cause the build to fail :</p>
<pre><code>Library\PackageCache\com.microsoft.azure.object-anchors.runtime@f40a6f902078-1669719345205\Runtime\Core\ObjectAnchorsWorldManager.cs(151,29): error CS0234: The type or namespace name 'WindowsMR' does not exist in the namespace 'UnityEngine.XR' (are you missing an assembly reference?)
</code></pre>
<p><strong>What I've tried</strong><br />
I tried to re-import the XR Plug-in<br />
<a href="https://i.stack.imgur.com/jz4UR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jz4UR.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/IoKRW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IoKRW.png" alt="enter image description here" /></a></p>
<p>I use Unity 2019.4.36f1</p>
|
[
{
"answer_id": 74639619,
"author": "Pete Pearl",
"author_id": 14290361,
"author_profile": "https://Stackoverflow.com/users/14290361",
"pm_score": 1,
"selected": false,
"text": ".hover {\n width: 200px;\n height: 200px;\n background: url('https://picsum.photos/200') no-repeat center center;\n position: relative;\n}\n\n.hover:after{\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: url('https://picsum.photos/300') no-repeat center center;\n opacity: 0;\n transition: opacity .3s;\n}\n\n.hover:hover:after {\n opacity: 1;\n} <div class=\"hover\"></div>"
},
{
"answer_id": 74641320,
"author": "Gonzalo F S",
"author_id": 15928193,
"author_profile": "https://Stackoverflow.com/users/15928193",
"pm_score": 1,
"selected": true,
"text": ".mwhite:hover calss=\"mwhite\" class=\"mwhite\" .mwhite:hover + .mblack .Menu .mnpic {\n transform: translateX(30%);\n}\n\n.mwhite{\n opacity: 1;\n transition: 0.5s;\n border: 1px green solid;\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n}\n.mwhite:hover {\n opacity: 0;\n border: 1px blue solid;\n}\n.mblack{\n border: 1px red solid;\n opacity: 0;\n transition: 0.5s;\n}\n.mwhite:hover + .mblack{\n opacity: 1;\n height: 200px;\n} <div class=\"mnpic\">\n <img class=\"mwhite\" src='https://picsum.photos/200' alt=\"\" height=\"150px\">\n <img class=\"mblack\" src='https://picsum.photos/300' alt=\"\" height=\"150px\">\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20203445/"
] |
74,639,284
|
<p>I want to integrate square payment gateway for multi-vendor website.</p>
<p>I have done some research on this but not getting the exact answer that Does it providing multi-vendor support or not. Also does it supports, Split payment?</p>
<p>Can anyone please help?</p>
|
[
{
"answer_id": 74639619,
"author": "Pete Pearl",
"author_id": 14290361,
"author_profile": "https://Stackoverflow.com/users/14290361",
"pm_score": 1,
"selected": false,
"text": ".hover {\n width: 200px;\n height: 200px;\n background: url('https://picsum.photos/200') no-repeat center center;\n position: relative;\n}\n\n.hover:after{\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: url('https://picsum.photos/300') no-repeat center center;\n opacity: 0;\n transition: opacity .3s;\n}\n\n.hover:hover:after {\n opacity: 1;\n} <div class=\"hover\"></div>"
},
{
"answer_id": 74641320,
"author": "Gonzalo F S",
"author_id": 15928193,
"author_profile": "https://Stackoverflow.com/users/15928193",
"pm_score": 1,
"selected": true,
"text": ".mwhite:hover calss=\"mwhite\" class=\"mwhite\" .mwhite:hover + .mblack .Menu .mnpic {\n transform: translateX(30%);\n}\n\n.mwhite{\n opacity: 1;\n transition: 0.5s;\n border: 1px green solid;\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n}\n.mwhite:hover {\n opacity: 0;\n border: 1px blue solid;\n}\n.mblack{\n border: 1px red solid;\n opacity: 0;\n transition: 0.5s;\n}\n.mwhite:hover + .mblack{\n opacity: 1;\n height: 200px;\n} <div class=\"mnpic\">\n <img class=\"mwhite\" src='https://picsum.photos/200' alt=\"\" height=\"150px\">\n <img class=\"mblack\" src='https://picsum.photos/300' alt=\"\" height=\"150px\">\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8899521/"
] |
74,639,286
|
<p>How to calculate float value and then convert to uint8_t?
As below, the current progress is 50, but overall just 50% completed, the correct value is 25, but I got 0.</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
uint8_t remaining = 1;
uint8_t total = 2;
uint8_t progress=50;
float value=0;
value = (float)(total-remaining)/total;
progress = (uint8_t)value*progress;
cout<<"value:"<<value<<endl;
cout<<"progress:"<<(unsigned)progress<<endl;
return 0;
}
</code></pre>
<p>The result are:</p>
<pre class="lang-none prettyprint-override"><code>value:0.5
progress:0
</code></pre>
<p>How to get the correct 25?</p>
|
[
{
"answer_id": 74639619,
"author": "Pete Pearl",
"author_id": 14290361,
"author_profile": "https://Stackoverflow.com/users/14290361",
"pm_score": 1,
"selected": false,
"text": ".hover {\n width: 200px;\n height: 200px;\n background: url('https://picsum.photos/200') no-repeat center center;\n position: relative;\n}\n\n.hover:after{\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: url('https://picsum.photos/300') no-repeat center center;\n opacity: 0;\n transition: opacity .3s;\n}\n\n.hover:hover:after {\n opacity: 1;\n} <div class=\"hover\"></div>"
},
{
"answer_id": 74641320,
"author": "Gonzalo F S",
"author_id": 15928193,
"author_profile": "https://Stackoverflow.com/users/15928193",
"pm_score": 1,
"selected": true,
"text": ".mwhite:hover calss=\"mwhite\" class=\"mwhite\" .mwhite:hover + .mblack .Menu .mnpic {\n transform: translateX(30%);\n}\n\n.mwhite{\n opacity: 1;\n transition: 0.5s;\n border: 1px green solid;\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n}\n.mwhite:hover {\n opacity: 0;\n border: 1px blue solid;\n}\n.mblack{\n border: 1px red solid;\n opacity: 0;\n transition: 0.5s;\n}\n.mwhite:hover + .mblack{\n opacity: 1;\n height: 200px;\n} <div class=\"mnpic\">\n <img class=\"mwhite\" src='https://picsum.photos/200' alt=\"\" height=\"150px\">\n <img class=\"mblack\" src='https://picsum.photos/300' alt=\"\" height=\"150px\">\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10971265/"
] |
74,639,289
|
<pre><code>query user /server:$SERVER
</code></pre>
<p>how can I filter only active users, for send to each user in server msg</p>
<pre><code>$Session_Users = query user /server:$SERVER | Where-Object {$_ -match "Active"}
$Session_Users
ForEach ($user in $Session_Users){
$TheMessage = "X"
& msg $user /v /Time:120 $TheMessage
}
</code></pre>
<p>btw I cant do & msg * , due security issue in server I can only to active users that why I need to filter them.</p>
|
[
{
"answer_id": 74639619,
"author": "Pete Pearl",
"author_id": 14290361,
"author_profile": "https://Stackoverflow.com/users/14290361",
"pm_score": 1,
"selected": false,
"text": ".hover {\n width: 200px;\n height: 200px;\n background: url('https://picsum.photos/200') no-repeat center center;\n position: relative;\n}\n\n.hover:after{\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: url('https://picsum.photos/300') no-repeat center center;\n opacity: 0;\n transition: opacity .3s;\n}\n\n.hover:hover:after {\n opacity: 1;\n} <div class=\"hover\"></div>"
},
{
"answer_id": 74641320,
"author": "Gonzalo F S",
"author_id": 15928193,
"author_profile": "https://Stackoverflow.com/users/15928193",
"pm_score": 1,
"selected": true,
"text": ".mwhite:hover calss=\"mwhite\" class=\"mwhite\" .mwhite:hover + .mblack .Menu .mnpic {\n transform: translateX(30%);\n}\n\n.mwhite{\n opacity: 1;\n transition: 0.5s;\n border: 1px green solid;\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n}\n.mwhite:hover {\n opacity: 0;\n border: 1px blue solid;\n}\n.mblack{\n border: 1px red solid;\n opacity: 0;\n transition: 0.5s;\n}\n.mwhite:hover + .mblack{\n opacity: 1;\n height: 200px;\n} <div class=\"mnpic\">\n <img class=\"mwhite\" src='https://picsum.photos/200' alt=\"\" height=\"150px\">\n <img class=\"mblack\" src='https://picsum.photos/300' alt=\"\" height=\"150px\">\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20111374/"
] |
74,639,303
|
<p>I have a project from github and it has the recoil function. I'm trying <code>npm install</code> to run npm but it's not working:</p>
<p><img src="https://i.stack.imgur.com/yZdjQ.png" alt="enter image description here" /></p>
<p>Then I tried <code>npm install --legacy-peer-deps</code>, and got</p>
<pre><code>61 vulnerabilities (4 low, 5 moderate, 39 high, 13 critical)
</code></pre>
<p>If I write <code>npm start</code> I got</p>
<pre><code>Debugger attached.
> tgp-core-api@0.1.0 start
> PORT=3006 react-scripts start
'PORT' is not recognized as an internal or external command,
operable program or batch file.
Waiting for the debugger to disconnect...
</code></pre>
|
[
{
"answer_id": 74639619,
"author": "Pete Pearl",
"author_id": 14290361,
"author_profile": "https://Stackoverflow.com/users/14290361",
"pm_score": 1,
"selected": false,
"text": ".hover {\n width: 200px;\n height: 200px;\n background: url('https://picsum.photos/200') no-repeat center center;\n position: relative;\n}\n\n.hover:after{\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: url('https://picsum.photos/300') no-repeat center center;\n opacity: 0;\n transition: opacity .3s;\n}\n\n.hover:hover:after {\n opacity: 1;\n} <div class=\"hover\"></div>"
},
{
"answer_id": 74641320,
"author": "Gonzalo F S",
"author_id": 15928193,
"author_profile": "https://Stackoverflow.com/users/15928193",
"pm_score": 1,
"selected": true,
"text": ".mwhite:hover calss=\"mwhite\" class=\"mwhite\" .mwhite:hover + .mblack .Menu .mnpic {\n transform: translateX(30%);\n}\n\n.mwhite{\n opacity: 1;\n transition: 0.5s;\n border: 1px green solid;\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n}\n.mwhite:hover {\n opacity: 0;\n border: 1px blue solid;\n}\n.mblack{\n border: 1px red solid;\n opacity: 0;\n transition: 0.5s;\n}\n.mwhite:hover + .mblack{\n opacity: 1;\n height: 200px;\n} <div class=\"mnpic\">\n <img class=\"mwhite\" src='https://picsum.photos/200' alt=\"\" height=\"150px\">\n <img class=\"mblack\" src='https://picsum.photos/300' alt=\"\" height=\"150px\">\n</div>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18092344/"
] |
74,639,356
|
<p>I get a timeout when trying to connect to my newly set up amazon redshift database.
I tried telnet:</p>
<pre><code>telnet redshift-cluster-1.foobar.us-east-1.redshift.amazonaws.com 5439
</code></pre>
<p>With the same result.</p>
<p>I set the database configuration to "Publicly accessible".</p>
<p>Note that I am just experimenting. I have set up aws services for fun before, but don't have much knowledge of the network and security setup. So I expect it to be a simple mistake I make.</p>
<p>I want to keep it simple, so my goal is just to connect to the database from a local SQL client and I don't care about anything else at this stage :)</p>
<p>It would be great if you could give me some pointers for me to understand what the problem could be and what I should try next.</p>
<p><a href="https://i.stack.imgur.com/mkX7d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mkX7d.png" alt="subnets" /></a></p>
|
[
{
"answer_id": 74643400,
"author": "smac2020",
"author_id": 1435543,
"author_profile": "https://Stackoverflow.com/users/1435543",
"pm_score": 0,
"selected": false,
"text": " private static final String database = \"dev\";\n private static final String dbUser =\"awsuser\";\n private static final String clusterId = \"redshift-cluster-1\";\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2474025/"
] |
74,639,363
|
<p>I have a column <code>data$Floor</code> from a dataset imported from CSV that supposedly contains the floor of an apartment. Here is a sample data:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Floor</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ground out of 2</td>
</tr>
<tr>
<td>1 out of 3</td>
</tr>
</tbody>
</table>
</div>
<p>I wish to separate the data to have the floor and the total floors as following:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Floor</th>
<th>Total Floors</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ground</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>I have done <code>write(str_replace_all(data$Floor, "out of", " "), data)</code> with the intention of splitting the columns where the space is, then writing the changes to the dataset <code>data</code> but I have no idea how to do that.</p>
|
[
{
"answer_id": 74639427,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "tidyr::separate tidyr::separate(data, Floor, c('Floor', 'Total Floors'), sep = ' out of ')\n#> Floor Total Floors\n#> 1 Ground 2\n#> 2 1 3\n data <- data.frame(Floor = c(\"Ground out of 2\", \"1 out of 3\"))\n\ndata\n#> Floor\n#> 1 Ground out of 2\n#> 2 1 out of 3\n"
},
{
"answer_id": 74641124,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "strsplit strsplit(data$Floor, ' out of ') |> rbind.data.frame() |> setNames(c('Floor', 'Total Floors'))\n# Floor Total Floors\n# 1 Ground 1\n# 2 2 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19375357/"
] |
74,639,414
|
<p>I'm using the same exact code from an existing file practically and the data I'm trying to display using map is only showing 1 part of it. I'm trying to display a table of data but only the header is appearing. I know my database calls are not the problem because I can see the data in my state component "purchases".</p>
<pre><code>var navigate = useNavigate();
// refundable purchases
const [purchases, setPurchases] = useState([]);
// current balance
const [balance, setBalance] = useState(0);
const Purchase = (props) => {
// on click open interactive pop up confirming refund
<tr>
<td className='table-data'>{props.purchase.title}</td>
<td className='table-data'>{numberFormat(props.purchase.amount)}</td>
</tr>
};
useEffect(()=> {
async function fetchData(){
const purchaseResponse = await fetch(`http://localhost:4000/refund/`);
if (!purchaseResponse.ok){
window.alert(`An error occured: ${purchaseResponse.statusText}.`)
return;
}
const data = await purchaseResponse.json();
setPurchases(data);
}
fetchData();
return;
},[purchases.length]);
function makeTable(){
return purchases.map((element)=> {
console.log(element);
return (
<Purchase
purchase={element}
key = {element._id}
/>
);
});
}
return (
// Will Display
<section>
<div className='home'>
{/* Title */}
<h1 className='hometitle'>
Claim A Refund
</h1>
{/* Table of Clickable elements showing possilbe purchase refunds*/}
<div>
<table className='table' style={{marginTop:20}}>
<thead className='table-data'>
<tr>
<th className='table-header'>Title</th>
<th className='table-header'>Amount</th>
</tr>
</thead>
<tbody>{makeTable()}</tbody>
</table>
</div>
{/* On selection of specific purchase :
-> double check with user
-> diplay alert box containing "Refund for <transaction title> made" */}
</div>
</section>
);
</code></pre>
<p>I've been staring at this like a maniac and can't figure out why its not displaying.</p>
|
[
{
"answer_id": 74639427,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "tidyr::separate tidyr::separate(data, Floor, c('Floor', 'Total Floors'), sep = ' out of ')\n#> Floor Total Floors\n#> 1 Ground 2\n#> 2 1 3\n data <- data.frame(Floor = c(\"Ground out of 2\", \"1 out of 3\"))\n\ndata\n#> Floor\n#> 1 Ground out of 2\n#> 2 1 out of 3\n"
},
{
"answer_id": 74641124,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "strsplit strsplit(data$Floor, ' out of ') |> rbind.data.frame() |> setNames(c('Floor', 'Total Floors'))\n# Floor Total Floors\n# 1 Ground 1\n# 2 2 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19244659/"
] |
74,639,435
|
<p>How do I get only the total count in Microsoft Graph query search. Is there a request to get only the total count?</p>
<p>I'm implementing a custom solution that is using MS Graph query search to get the total count results when searching SharePoint online. MS Graph API returns the total count but I'm wondering is there a way to get only the total count without retrieving hits.</p>
<p>API Request: <a href="https://graph.microsoft.com/v1.0/search/query" rel="nofollow noreferrer">https://graph.microsoft.com/v1.0/search/query</a></p>
<pre><code>{
"value": [
{
"searchTerms": [
"covid"
],
"hitsContainers": [
{
"hits": [...
],
"total": 20,
"moreResultsAvailable": false
}
]
}
],
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.searchResponse)"
}
</code></pre>
<p>What I tried:</p>
<p>I used MS Graph Explorer and submitted this request
API Request: <a href="https://graph.microsoft.com/v1.0/search/query" rel="nofollow noreferrer">https://graph.microsoft.com/v1.0/search/query</a></p>
<p>This is the results from MS Graph Explorer:</p>
<pre><code>{
"value": [
{
"searchTerms": [
"covid"
],
"hitsContainers": [
{
"hits": [...
],
"total": 20,
"moreResultsAvailable": false
}
]
}
],
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.searchResponse)"
}
</code></pre>
|
[
{
"answer_id": 74639427,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "tidyr::separate tidyr::separate(data, Floor, c('Floor', 'Total Floors'), sep = ' out of ')\n#> Floor Total Floors\n#> 1 Ground 2\n#> 2 1 3\n data <- data.frame(Floor = c(\"Ground out of 2\", \"1 out of 3\"))\n\ndata\n#> Floor\n#> 1 Ground out of 2\n#> 2 1 out of 3\n"
},
{
"answer_id": 74641124,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "strsplit strsplit(data$Floor, ' out of ') |> rbind.data.frame() |> setNames(c('Floor', 'Total Floors'))\n# Floor Total Floors\n# 1 Ground 1\n# 2 2 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9673821/"
] |
74,639,520
|
<p>We have a big project with lots of repos where we would like to introduce a coding standard that is followed in all repos.</p>
<p>We do this by adding an identical .editorconfig file in all repos.</p>
<p>When doing this we also format all java files by Code -> Reformat Code and filtering out *.java files.</p>
<p>I just noticed that this operation is not stable and intellij keeps toggling some code sections.</p>
<p>E.g. this code section ...</p>
<pre><code> public CaasOrder toggles(final String caasOrderId, final String authHeader) {
final List<String> cardOrderIds = transactionTemplate.execute(status -> {
final Order order = getOrderWithInitiatedState(caasOrderId);
final List<String> ids = order.getCardOrders().stream().map(CardOrder::getId).collect(Collectors.toList());
return ids;
});
return transactionTemplate.execute(s -> ObjectConverter.convert(getOrderWithInitiatedState(caasOrderId)));
}
</code></pre>
<p>... keeps togling back and forth with this code section ...</p>
<pre><code> public CaasOrder toggles(final String caasOrderId, final String authHeader) {
final List<String> cardOrderIds = transactionTemplate.execute(status -> {
final Order order = getOrderWithInitiatedState(caasOrderId);
final List<String> ids = order
.getCardOrders()
.stream()
.map(CardOrder::getId)
.collect(Collectors.toList());
return ids;
});
return transactionTemplate.execute(s -> ObjectConverter.convert(getOrderWithInitiatedState(caasOrderId)));
}
</code></pre>
<p>This is really annoying and hinders us from enforcing a common coding standard in an easy way.</p>
<p>I.e. add our .editorconfig filen and reformat all java files and make a commit!</p>
<p>And here is the .editorconfig file</p>
<pre><code>[*]
charset = utf-8
end_of_line = crlf
indent_size = 4
indent_style = space
insert_final_newline = false
max_line_length = 120
tab_width = 4
ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = true
ij_smart_tabs = false
ij_visual_guides = none
ij_wrap_on_typing = false
[*.java]
ij_java_align_consecutive_assignments = false
ij_java_align_consecutive_variable_declarations = true
ij_java_align_group_field_declarations = true
ij_java_align_multiline_annotation_parameters = false
ij_java_align_multiline_array_initializer_expression = false
ij_java_align_multiline_assignment = false
ij_java_align_multiline_binary_operation = false
ij_java_align_multiline_chained_methods = false
ij_java_align_multiline_extends_list = false
ij_java_align_multiline_for = true
ij_java_align_multiline_method_parentheses = false
ij_java_align_multiline_parameters = true
ij_java_align_multiline_parameters_in_calls = false
ij_java_align_multiline_parenthesized_expression = false
ij_java_align_multiline_records = true
ij_java_align_multiline_resources = true
ij_java_align_multiline_ternary_operation = false
ij_java_align_multiline_text_blocks = false
ij_java_align_multiline_throws_list = false
ij_java_align_subsequent_simple_methods = false
ij_java_align_throws_keyword = false
ij_java_align_types_in_multi_catch = true
ij_java_annotation_parameter_wrap = off
ij_java_array_initializer_new_line_after_left_brace = false
ij_java_array_initializer_right_brace_on_new_line = false
ij_java_array_initializer_wrap = off
ij_java_assert_statement_colon_on_next_line = false
ij_java_assert_statement_wrap = off
ij_java_assignment_wrap = off
ij_java_binary_operation_sign_on_next_line = false
ij_java_binary_operation_wrap = off
ij_java_blank_lines_after_anonymous_class_header = 0
ij_java_blank_lines_after_class_header = 0
ij_java_blank_lines_after_imports = 1
ij_java_blank_lines_after_package = 1
ij_java_blank_lines_around_class = 1
ij_java_blank_lines_around_field = 0
ij_java_blank_lines_around_field_in_interface = 0
ij_java_blank_lines_around_initializer = 1
ij_java_blank_lines_around_method = 1
ij_java_blank_lines_around_method_in_interface = 1
ij_java_blank_lines_before_class_end = 0
ij_java_blank_lines_before_imports = 1
ij_java_blank_lines_before_method_body = 0
ij_java_blank_lines_before_package = 0
ij_java_block_brace_style = end_of_line
ij_java_block_comment_add_space = false
ij_java_block_comment_at_first_column = true
ij_java_builder_methods = none
ij_java_call_parameters_new_line_after_left_paren = false
ij_java_call_parameters_right_paren_on_new_line = false
ij_java_call_parameters_wrap = off
ij_java_case_statement_on_separate_line = true
ij_java_catch_on_new_line = false
ij_java_class_annotation_wrap = split_into_lines
ij_java_class_brace_style = end_of_line
ij_java_class_count_to_use_import_on_demand = 999
ij_java_class_names_in_javadoc = 1
ij_java_do_not_indent_top_level_class_members = false
ij_java_do_not_wrap_after_single_annotation = false
ij_java_do_not_wrap_after_single_annotation_in_parameter = false
ij_java_do_while_brace_force = never
ij_java_doc_add_blank_line_after_description = true
ij_java_doc_add_blank_line_after_param_comments = false
ij_java_doc_add_blank_line_after_return = false
ij_java_doc_add_p_tag_on_empty_lines = true
ij_java_doc_align_exception_comments = true
ij_java_doc_align_param_comments = true
ij_java_doc_do_not_wrap_if_one_line = false
ij_java_doc_enable_formatting = true
ij_java_doc_enable_leading_asterisks = true
ij_java_doc_indent_on_continuation = false
ij_java_doc_keep_empty_lines = true
ij_java_doc_keep_empty_parameter_tag = true
ij_java_doc_keep_empty_return_tag = true
ij_java_doc_keep_empty_throws_tag = true
ij_java_doc_keep_invalid_tags = true
ij_java_doc_param_description_on_new_line = false
ij_java_doc_preserve_line_breaks = false
ij_java_doc_use_throws_not_exception_tag = true
ij_java_else_on_new_line = false
ij_java_entity_dd_suffix = EJB
ij_java_entity_eb_suffix = Bean
ij_java_entity_hi_suffix = Home
ij_java_entity_lhi_prefix = Local
ij_java_entity_lhi_suffix = Home
ij_java_entity_li_prefix = Local
ij_java_entity_pk_class = java.lang.String
ij_java_entity_vo_suffix = VO
ij_java_enum_constants_wrap = off
ij_java_extends_keyword_wrap = off
ij_java_extends_list_wrap = off
ij_java_field_annotation_wrap = split_into_lines
ij_java_finally_on_new_line = false
ij_java_for_brace_force = never
ij_java_for_statement_new_line_after_left_paren = false
ij_java_for_statement_right_paren_on_new_line = false
ij_java_for_statement_wrap = off
ij_java_generate_final_locals = false
ij_java_generate_final_parameters = false
ij_java_if_brace_force = never
ij_java_imports_layout = *,|,javax.**,java.**,|,$*
ij_java_indent_case_from_switch = true
ij_java_insert_inner_class_imports = false
ij_java_insert_override_annotation = true
ij_java_keep_blank_lines_before_right_brace = 2
ij_java_keep_blank_lines_between_package_declaration_and_header = 2
ij_java_keep_blank_lines_in_code = 2
ij_java_keep_blank_lines_in_declarations = 2
ij_java_keep_builder_methods_indents = false
ij_java_keep_control_statement_in_one_line = true
ij_java_keep_first_column_comment = true
ij_java_keep_indents_on_empty_lines = false
ij_java_keep_line_breaks = false
ij_java_keep_multiple_expressions_in_one_line = false
ij_java_keep_simple_blocks_in_one_line = false
ij_java_keep_simple_classes_in_one_line = false
ij_java_keep_simple_lambdas_in_one_line = false
ij_java_keep_simple_methods_in_one_line = false
ij_java_label_indent_absolute = false
ij_java_label_indent_size = 0
ij_java_lambda_brace_style = end_of_line
ij_java_layout_static_imports_separately = true
ij_java_line_comment_add_space = false
ij_java_line_comment_add_space_on_reformat = false
ij_java_line_comment_at_first_column = true
ij_java_message_dd_suffix = EJB
ij_java_message_eb_suffix = Bean
ij_java_method_annotation_wrap = split_into_lines
ij_java_method_brace_style = end_of_line
ij_java_method_call_chain_wrap = on_every_item
ij_java_method_parameters_new_line_after_left_paren = false
ij_java_method_parameters_right_paren_on_new_line = false
ij_java_method_parameters_wrap = off
ij_java_modifier_list_wrap = false
ij_java_multi_catch_types_wrap = normal
ij_java_names_count_to_use_import_on_demand = 3
ij_java_new_line_after_lparen_in_annotation = false
ij_java_new_line_after_lparen_in_record_header = false
ij_java_packages_to_use_import_on_demand = java.awt.*,javax.swing.*
ij_java_parameter_annotation_wrap = off
ij_java_parentheses_expression_new_line_after_left_paren = false
ij_java_parentheses_expression_right_paren_on_new_line = false
ij_java_place_assignment_sign_on_next_line = false
ij_java_prefer_longer_names = true
ij_java_prefer_parameters_wrap = false
ij_java_record_components_wrap = normal
ij_java_repeat_synchronized = true
ij_java_replace_instanceof_and_cast = false
ij_java_replace_null_check = true
ij_java_replace_sum_lambda_with_method_ref = true
ij_java_resource_list_new_line_after_left_paren = false
ij_java_resource_list_right_paren_on_new_line = false
ij_java_resource_list_wrap = off
ij_java_rparen_on_new_line_in_annotation = false
ij_java_rparen_on_new_line_in_record_header = false
ij_java_session_dd_suffix = EJB
ij_java_session_eb_suffix = Bean
ij_java_session_hi_suffix = Home
ij_java_session_lhi_prefix = Local
ij_java_session_lhi_suffix = Home
ij_java_session_li_prefix = Local
ij_java_session_si_suffix = Service
ij_java_space_after_closing_angle_bracket_in_type_argument = false
ij_java_space_after_colon = true
ij_java_space_after_comma = true
ij_java_space_after_comma_in_type_arguments = true
ij_java_space_after_for_semicolon = true
ij_java_space_after_quest = true
ij_java_space_after_type_cast = true
ij_java_space_before_annotation_array_initializer_left_brace = false
ij_java_space_before_annotation_parameter_list = false
ij_java_space_before_array_initializer_left_brace = false
ij_java_space_before_catch_keyword = true
ij_java_space_before_catch_left_brace = true
ij_java_space_before_catch_parentheses = true
ij_java_space_before_class_left_brace = true
ij_java_space_before_colon = true
ij_java_space_before_colon_in_foreach = true
ij_java_space_before_comma = false
ij_java_space_before_do_left_brace = true
ij_java_space_before_else_keyword = true
ij_java_space_before_else_left_brace = true
ij_java_space_before_finally_keyword = true
ij_java_space_before_finally_left_brace = true
ij_java_space_before_for_left_brace = true
ij_java_space_before_for_parentheses = true
ij_java_space_before_for_semicolon = false
ij_java_space_before_if_left_brace = true
ij_java_space_before_if_parentheses = true
ij_java_space_before_method_call_parentheses = false
ij_java_space_before_method_left_brace = true
ij_java_space_before_method_parentheses = false
ij_java_space_before_opening_angle_bracket_in_type_parameter = false
ij_java_space_before_quest = true
ij_java_space_before_switch_left_brace = true
ij_java_space_before_switch_parentheses = true
ij_java_space_before_synchronized_left_brace = true
ij_java_space_before_synchronized_parentheses = true
ij_java_space_before_try_left_brace = true
ij_java_space_before_try_parentheses = true
ij_java_space_before_type_parameter_list = false
ij_java_space_before_while_keyword = true
ij_java_space_before_while_left_brace = true
ij_java_space_before_while_parentheses = true
ij_java_space_inside_one_line_enum_braces = false
ij_java_space_within_empty_array_initializer_braces = false
ij_java_space_within_empty_method_call_parentheses = false
ij_java_space_within_empty_method_parentheses = false
ij_java_spaces_around_additive_operators = true
ij_java_spaces_around_annotation_eq = true
ij_java_spaces_around_assignment_operators = true
ij_java_spaces_around_bitwise_operators = true
ij_java_spaces_around_equality_operators = true
ij_java_spaces_around_lambda_arrow = true
ij_java_spaces_around_logical_operators = true
ij_java_spaces_around_method_ref_dbl_colon = false
ij_java_spaces_around_multiplicative_operators = true
ij_java_spaces_around_relational_operators = true
ij_java_spaces_around_shift_operators = true
ij_java_spaces_around_type_bounds_in_type_parameters = true
ij_java_spaces_around_unary_operator = false
ij_java_spaces_within_angle_brackets = false
ij_java_spaces_within_annotation_parentheses = false
ij_java_spaces_within_array_initializer_braces = false
ij_java_spaces_within_braces = false
ij_java_spaces_within_brackets = false
ij_java_spaces_within_cast_parentheses = false
ij_java_spaces_within_catch_parentheses = false
ij_java_spaces_within_for_parentheses = false
ij_java_spaces_within_if_parentheses = false
ij_java_spaces_within_method_call_parentheses = false
ij_java_spaces_within_method_parentheses = false
ij_java_spaces_within_parentheses = false
ij_java_spaces_within_record_header = false
ij_java_spaces_within_switch_parentheses = false
ij_java_spaces_within_synchronized_parentheses = false
ij_java_spaces_within_try_parentheses = false
ij_java_spaces_within_while_parentheses = false
ij_java_special_else_if_treatment = true
ij_java_subclass_name_suffix = Impl
ij_java_ternary_operation_signs_on_next_line = false
ij_java_ternary_operation_wrap = off
ij_java_test_name_suffix = Test
ij_java_throws_keyword_wrap = off
ij_java_throws_list_wrap = off
ij_java_use_external_annotations = false
ij_java_use_fq_class_names = false
ij_java_use_relative_indents = false
ij_java_use_single_class_imports = true
ij_java_variable_annotation_wrap = off
ij_java_visibility = public
ij_java_while_brace_force = never
ij_java_while_on_new_line = false
ij_java_wrap_comments = false
ij_java_wrap_first_method_in_call_chain = true
ij_java_wrap_long_lines = true
wildcard_import_limit = 999
[.editorconfig]
ij_editorconfig_align_group_field_declarations = false
ij_editorconfig_space_after_colon = false
ij_editorconfig_space_after_comma = true
ij_editorconfig_space_before_colon = false
ij_editorconfig_space_before_comma = false
ij_editorconfig_spaces_around_assignment_operators = true
</code></pre>
|
[
{
"answer_id": 74639427,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "tidyr::separate tidyr::separate(data, Floor, c('Floor', 'Total Floors'), sep = ' out of ')\n#> Floor Total Floors\n#> 1 Ground 2\n#> 2 1 3\n data <- data.frame(Floor = c(\"Ground out of 2\", \"1 out of 3\"))\n\ndata\n#> Floor\n#> 1 Ground out of 2\n#> 2 1 out of 3\n"
},
{
"answer_id": 74641124,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "strsplit strsplit(data$Floor, ' out of ') |> rbind.data.frame() |> setNames(c('Floor', 'Total Floors'))\n# Floor Total Floors\n# 1 Ground 1\n# 2 2 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2276754/"
] |
74,639,543
|
<p>I'm trying to navigate via <code><Link href="/register">Register</Link></code> to my registration page, but when I click it I get an error/warning either saying that:</p>
<ul>
<li>NextJS failed to load my script:
<a href="https://i.stack.imgur.com/gxOUM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gxOUM.png" alt="enter image description here" /></a></li>
</ul>
<p>OR</p>
<ul>
<li>fast reload had to perform a full reload
<a href="https://i.stack.imgur.com/XvXI8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XvXI8.png" alt="enter image description here" /></a></li>
</ul>
<p>In both cases I get the same message in my terminal:
<a href="https://i.stack.imgur.com/WkGB7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WkGB7.png" alt="enter image description here" /></a></p>
<p>This is my register page component:</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 type { NextPage } from "next/types";
import type { FormEvent } from "react";
import { useRef } from "react";
import { createUser } from "../../helpers/helperFuncs";
import styles from "./styles.module.scss";
const Register: NextPage = (): JSX.Element => {
const emailInputRef = useRef<HTMLInputElement | null>(null);
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const submitHandler = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const enteredEmail = emailInputRef.current?.value ?? "";
const enteredPassword = passwordInputRef.current?.value ?? "";
// create a new user
try {
const createdUser = await createUser(enteredEmail, enteredPassword);
console.log("createdUser", createdUser);
} catch (err) {
console.log("err", err);
}
};
return (
<div className={styles.auth}>
<h1>{"Sign Up"}</h1>
<form onSubmit={submitHandler}>
<div className={styles.control}>
<label htmlFor="email">Your Email</label>
<input type="email" id="email" required ref={emailInputRef} />
</div>
<div className={styles.control}>
<label htmlFor="password">Your Password</label>
<input
type="password"
id="password"
required
ref={passwordInputRef}
/>
</div>
<div className={styles.actions}>
<button>{"Create Account"}</button>
</div>
</form>
</div>
);
};
export default Register;</code></pre>
</div>
</div>
</p>
<p>My createUser function that I'm importing:</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>async function createUser(email: string, password: string) {
const response = await fetch("/api/auth/register", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Something went wrong");
}
return data;
}
export { createUser };</code></pre>
</div>
</div>
</p>
<p>I don't understand why NextJS would be forcing full reloads, since I'm not using class components, and I don't think I'm editing anything outside of the React rendering tree.</p>
<p>The failed to load script error message is also beyond me, but I reckon it's got to do with webpack being weird, since it's asking for a .js file and that's also what the terminal message seems to imply. I'm stumped. Any help would be greatly appreciated.</p>
<p><strong>Edit1:</strong> I've figured out that it's the usage of <code>className={styles.<whatever>}</code> that's causing these errors and forced reloads. The questions still remains though - how can I use my styles.module.scss in the correct way then?</p>
|
[
{
"answer_id": 74639427,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "tidyr::separate tidyr::separate(data, Floor, c('Floor', 'Total Floors'), sep = ' out of ')\n#> Floor Total Floors\n#> 1 Ground 2\n#> 2 1 3\n data <- data.frame(Floor = c(\"Ground out of 2\", \"1 out of 3\"))\n\ndata\n#> Floor\n#> 1 Ground out of 2\n#> 2 1 out of 3\n"
},
{
"answer_id": 74641124,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "strsplit strsplit(data$Floor, ' out of ') |> rbind.data.frame() |> setNames(c('Floor', 'Total Floors'))\n# Floor Total Floors\n# 1 Ground 1\n# 2 2 3\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4852315/"
] |
74,639,555
|
<p>My project has a Selector element which is a native HTML <code>button</code> element under the hood. I am trying to replicate the behaviour of clicking a label and triggering an event on an input/select.</p>
<p>Using <code><label htmlFor="size"></code> produces a warning during testing in Jest.</p>
<blockquote>
<p>Found a label with the text of: Size, however the element associated with this label () is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a , you can use aria-label or aria-labelledby instead.</p>
</blockquote>
<p><code>aria-labelledby</code> + <code>id</code> combination will require 2 <code>onClick</code> I believe, right? Is there a more native way of doing it? What is the best practice to have a label for such element?</p>
|
[
{
"answer_id": 74640614,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": -1,
"selected": false,
"text": "<label for=\"my-input\">\n <span>Label text:</span>\n <input id=\"my-input\" type=\"SELECT|RADIO|SUBMIT|...\" />\n</label>\n"
},
{
"answer_id": 74649531,
"author": "slugolicious",
"author_id": 76714,
"author_profile": "https://Stackoverflow.com/users/76714",
"pm_score": 0,
"selected": false,
"text": "htmlFor for <label> htmlFor for <button> <label for=\"foo\">my label</label>\n<button id=\"foo\">button label</button>\n <label> <label> <button>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9559251/"
] |
74,639,567
|
<p>I an doing update using open query on progress database which is connected to sql server using lined server . below is the query when I print :</p>
<pre><code> UPDATE OPENQUERY(PROGRESSDB,'SELECT * FROM PUB.workitem where
act_emp= 73870 and wtype='B'')
SET start_time='81410',logonstat = '1',realstrttme ='81410'
</code></pre>
<p>It gives Incorrect syntax near 'B'. Any idea where it went wrong.</p>
|
[
{
"answer_id": 74640614,
"author": "dbonev",
"author_id": 4200334,
"author_profile": "https://Stackoverflow.com/users/4200334",
"pm_score": -1,
"selected": false,
"text": "<label for=\"my-input\">\n <span>Label text:</span>\n <input id=\"my-input\" type=\"SELECT|RADIO|SUBMIT|...\" />\n</label>\n"
},
{
"answer_id": 74649531,
"author": "slugolicious",
"author_id": 76714,
"author_profile": "https://Stackoverflow.com/users/76714",
"pm_score": 0,
"selected": false,
"text": "htmlFor for <label> htmlFor for <button> <label for=\"foo\">my label</label>\n<button id=\"foo\">button label</button>\n <label> <label> <button>"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433302/"
] |
74,639,579
|
<p>I have a dataset like this :</p>
<pre><code>TYPE count
TYPE1 50
TYPE2 20
TYPE1 10
TYPE2 30
</code></pre>
<p>i want to sum the distinct type in a same line :</p>
<pre><code>TYPE count
TYPE1 60
TYPE2 50
</code></pre>
<p>Can you help me please ?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74639629,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "SELECT TYPE, SUM(count) AS count\nFROM yourTable\nGROUP BY TYPE;\n"
},
{
"answer_id": 74639652,
"author": "Frederik Spang",
"author_id": 1009655,
"author_profile": "https://Stackoverflow.com/users/1009655",
"pm_score": 0,
"selected": false,
"text": "GROUP BY SUM() CREATE TABLE dataset(type varchar(50), cnt int);\n INSERT INTO dataset (type, cnt)\nVALUES\n ('TYPE1', 50),\n ('TYPE2', 20),\n ('TYPE1', 10),\n ('TYPE2', 30)\n SELECT type, SUM(cnt)\nFROM dataset\nGROUP BY type\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18814820/"
] |
74,639,602
|
<pre><code>fn main() {
//! First question
// C++: string* ptr1 = new string("hello");
// so ptr1 contains the address of string "hello" that is allocated on heap
let ptr1 = String::from("Hello");
// output: 0x66c96ff910
println!("{:p}", &ptr1);
// C++: ptr2 = ptr1
// so they should have now the same address
let ptr2 = ptr1;
// output: 0x66c96ff910
println!("{:p}", &ptr2);
// why ptr1 and ptr2 have different value ? (address of string on heap)
// Isn't it because they are fat pointers?
// Second question
let reference1 = String::from("Hello");
// output: 0x44fc6ff5f0
println!("{:p}", &reference1);
// C++: reference1 and referenc2 should point to the same address
let reference2 = &reference1;
// output: 0x44fc6ff650
println!("{:p}", &reference2);
// why reference1 and reference2 don't have the same address?
}
</code></pre>
<p>why ptr1 and ptr2 have different value ? (address of string on heap)</p>
<p>why reference1 and reference2 don't have the same address?</p>
|
[
{
"answer_id": 74639629,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "SELECT TYPE, SUM(count) AS count\nFROM yourTable\nGROUP BY TYPE;\n"
},
{
"answer_id": 74639652,
"author": "Frederik Spang",
"author_id": 1009655,
"author_profile": "https://Stackoverflow.com/users/1009655",
"pm_score": 0,
"selected": false,
"text": "GROUP BY SUM() CREATE TABLE dataset(type varchar(50), cnt int);\n INSERT INTO dataset (type, cnt)\nVALUES\n ('TYPE1', 50),\n ('TYPE2', 20),\n ('TYPE1', 10),\n ('TYPE2', 30)\n SELECT type, SUM(cnt)\nFROM dataset\nGROUP BY type\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19196249/"
] |
74,639,617
|
<p>There is one array for me. my array is as follows.</p>
<pre><code>var Array = [["Dog","0","A","eat"],["cat","1","B","eat"]]
</code></pre>
<p>I want to replace the value in some indexes in this array with other values.</p>
<p>for example, it should be like this.</p>
<pre><code>var newArray = [["Dog","big","house","eat"],["cat","small","forest","eat"]]
</code></pre>
<p>can be understood from the example, <strong>"0 = big, 1 = small" and "A=house, B=forest"</strong></p>
<p>how can I solve this both with the for loop and using C# Linq.</p>
|
[
{
"answer_id": 74640500,
"author": "Jostein S",
"author_id": 20106677,
"author_profile": "https://Stackoverflow.com/users/20106677",
"pm_score": 2,
"selected": false,
"text": "var Array = new string[][] {\n new string[] {\"Dog\", \"0\", \"A\", \"eat\" },\n new string[] {\"Cat\", \"1\", \"B\", \"eat\" }\n};\n//Array: [[\"Dog\",\"0\",\"A\",\"eat\"],[\"Cat\",\"1\",\"B\",\"eat\"]]\n\nvar TranslationDict = new Dictionary<string, string>() {\n { \"0\", \"big\" },\n { \"1\", \"small\" },\n { \"A\", \"house\" },\n { \"B\", \"forest\" },\n};\n\nfor (int y = 0; y < Array.Length; y++) {\n for (int x = 0; x < Array[y].Length; x++) {\n if(TranslationDict.ContainsKey(Array[y][x])) {\n Array[y][x] = TranslationDict[Array[y][x]];\n }\n }\n}\n\n//Array: [[\"Dog\",\"big\",\"house\",\"eat\"],[\"Cat\",\"small\",\"forest\",\"eat\"]]\n"
},
{
"answer_id": 74641006,
"author": "Hannes Füreder",
"author_id": 20649261,
"author_profile": "https://Stackoverflow.com/users/20649261",
"pm_score": 1,
"selected": false,
"text": "var testArray = array.\nSelect(x => x.\nSelect(y => y.Replace(\"0\", \"big\").Replace(\"1\",\"test\")).ToArray())\n.ToArray();\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17321009/"
] |
74,639,635
|
<p>When I was working on an open source project on GitHub Clone, there was a problem with executing Yarn Install, what caused it?</p>
<p><a href="https://i.stack.imgur.com/XuAOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XuAOk.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/bQgeH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bQgeH.png" alt="enter image description here" /></a></p>
<p>English is not my native language; please excuse typing errors.</p>
|
[
{
"answer_id": 74639795,
"author": "Ivneet Singh",
"author_id": 3418593,
"author_profile": "https://Stackoverflow.com/users/3418593",
"pm_score": 0,
"selected": false,
"text": "npm install"
},
{
"answer_id": 74640162,
"author": "Karl-Johan Sjögren",
"author_id": 547640,
"author_profile": "https://Stackoverflow.com/users/547640",
"pm_score": 2,
"selected": true,
"text": "\"@zeeis/velectron\": \"^17.0.0\""
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19706404/"
] |
74,639,717
|
<p>I have one table that contains customer id and start date and one table that contains customer id and end date.</p>
<p>table A</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>customer_id</th>
<th>start_date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-01-01</td>
</tr>
<tr>
<td>1</td>
<td>2022-04-01</td>
</tr>
<tr>
<td>1</td>
<td>2022-07-01</td>
</tr>
<tr>
<td>2</td>
<td>2022-01-15</td>
</tr>
<tr>
<td>2</td>
<td>2022-03-25</td>
</tr>
<tr>
<td>3</td>
<td>2022-04-01</td>
</tr>
<tr>
<td>3</td>
<td>2022-08-01</td>
</tr>
<tr>
<td>4</td>
<td>2022-09-01</td>
</tr>
</tbody>
</table>
</div>
<p>table B</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>customer_id</th>
<th>end_date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-01-25</td>
</tr>
<tr>
<td>1</td>
<td>2022-05-03</td>
</tr>
<tr>
<td>2</td>
<td>2022-03-24</td>
</tr>
<tr>
<td>2</td>
<td>2022-03-29</td>
</tr>
<tr>
<td>3</td>
<td>2022-04-15</td>
</tr>
</tbody>
</table>
</div>
<p>Is there a way that I can get an output that looks like below?</p>
<p>desired output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>customer_id</th>
<th>start_date</th>
<th>end_date</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2022-01-01</td>
<td>2022-01-25</td>
</tr>
<tr>
<td>1</td>
<td>2022-04-01</td>
<td>2022-05-03</td>
</tr>
<tr>
<td>1</td>
<td>2022-07-01</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>2022-01-15</td>
<td>2022-03-24</td>
</tr>
<tr>
<td>2</td>
<td>2022-03-25</td>
<td>2022-03-29</td>
</tr>
<tr>
<td>3</td>
<td>2022-04-01</td>
<td>2022-04-15</td>
</tr>
<tr>
<td>3</td>
<td>2022-08-01</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>2022-09-01</td>
<td></td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74639795,
"author": "Ivneet Singh",
"author_id": 3418593,
"author_profile": "https://Stackoverflow.com/users/3418593",
"pm_score": 0,
"selected": false,
"text": "npm install"
},
{
"answer_id": 74640162,
"author": "Karl-Johan Sjögren",
"author_id": 547640,
"author_profile": "https://Stackoverflow.com/users/547640",
"pm_score": 2,
"selected": true,
"text": "\"@zeeis/velectron\": \"^17.0.0\""
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14732194/"
] |
74,639,725
|
<p>I have the following string:</p>
<p><code>'- Submission GMV / return finance027110/06 Abdul Rahman -26,00- Submission GMV / return finance02432548/08 Michael Scott -56,47- GMV success. 452630/10/21 Lehazq998890/92 +60,00'</code></p>
<p>How can I return the values as:</p>
<pre><code>[['- Submission PVT / return finance027110/06 Abdul Rahman','-26,00'],
['- Submission LTD / return finance02432548/08 Michael Scott','-56,47'],
['- GMV success. 452630/10/21 Lehazq998890/92', '+60,00']]
</code></pre>
<p>I'm looping into multiple input. Hence, the count of output rows differs in each iteration. But the split pattern remains same.</p>
|
[
{
"answer_id": 74639795,
"author": "Ivneet Singh",
"author_id": 3418593,
"author_profile": "https://Stackoverflow.com/users/3418593",
"pm_score": 0,
"selected": false,
"text": "npm install"
},
{
"answer_id": 74640162,
"author": "Karl-Johan Sjögren",
"author_id": 547640,
"author_profile": "https://Stackoverflow.com/users/547640",
"pm_score": 2,
"selected": true,
"text": "\"@zeeis/velectron\": \"^17.0.0\""
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12446218/"
] |
74,639,727
|
<p>I am trying to generate a random string output from an array that's getting triggered at random times. The issue that I am facing now is, sometimes the same output comes out twice in a row, or even more than two times. I wanted the output to be different every single time it gets triggered. I don't want the next output to be the same as the very previous output. Please take a look at the code below. Thanks!</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>function randAnnouncement() {
var lastIndex, ann = ["one", "two", "three"];
let randomAnnouncement = ann[Math.floor(Math.random() * ann.length)];
//speakTTS(randomAnnouncement);
console.log(randomAnnouncement);
}
function init() {
var myFunction = function() {
randAnnouncement();
var rand = Math.round(Math.random() * (5000 - 1000)) + 500; // generate new time (between x sec and x + 500"s)
setTimeout(myFunction, rand);
}
myFunction();
}
init();</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74639795,
"author": "Ivneet Singh",
"author_id": 3418593,
"author_profile": "https://Stackoverflow.com/users/3418593",
"pm_score": 0,
"selected": false,
"text": "npm install"
},
{
"answer_id": 74640162,
"author": "Karl-Johan Sjögren",
"author_id": 547640,
"author_profile": "https://Stackoverflow.com/users/547640",
"pm_score": 2,
"selected": true,
"text": "\"@zeeis/velectron\": \"^17.0.0\""
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7676733/"
] |
74,639,783
|
<p>I'm attempting to create a clone of the windows 10 file explorer in python using tkinter and I cant work out how to get the name of the file type from its file extension <a href="https://i.stack.imgur.com/ZrvVm.png" rel="nofollow noreferrer">like file explorer does</a></p>
<p>I have already got a function to get the programs file extension and another to open it in the default application however nowhere online has a solution to my issue</p>
|
[
{
"answer_id": 74639868,
"author": "benicamera",
"author_id": 13826114,
"author_profile": "https://Stackoverflow.com/users/13826114",
"pm_score": 0,
"selected": false,
"text": "def get_file_type():\n extension_full_names = {\".txt\":\"Text file\", \".py\":\"Python file\"}\n\n file_extension = getFileExtension(file)\n \n if file_extension in extension_full_names.keys():\n return extension_full_names[file_extension]\n \n return f\"{file_extension} file\" # extension not in your dictionary\n"
},
{
"answer_id": 74640322,
"author": "Julien Sorin",
"author_id": 16552422,
"author_profile": "https://Stackoverflow.com/users/16552422",
"pm_score": 3,
"selected": true,
"text": "_HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\.py \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Python.File from typing import Tuple\nfrom winreg import HKEYType, ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx\n\n\nclass ExtensionQuery:\n def __init__(self):\n self.base: str = r\"SOFTWARE\\Classes\"\n self.reg: HKEYType = ConnectRegistry(None, HKEY_LOCAL_MACHINE)\n\n def _get_value_from_class(self, class_str: str) -> str:\n path: str = fr\"{self.base}\\{class_str}\"\n key: HKEYType = OpenKey(self.reg, path)\n value_tuple: Tuple[str, int] = QueryValueEx(key, \"\")\n return value_tuple[0]\n\n def get_application_name(self, ext: str) -> str:\n return self._get_value_from_class(self._get_value_from_class(ext))\n\n\nquery = ExtensionQuery()\nprint(query.get_application_name(\".py\"))\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17283029/"
] |
74,639,791
|
<p>Whenever I visit a page it should automatically fetch the API</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react'
const Component = () => {
fetch("api url").then((res) => console.log(res))
return (
<div>comp</div>
)
}
export default Component
</code></pre>
|
[
{
"answer_id": 74639844,
"author": "Itay Elkouby",
"author_id": 4134411,
"author_profile": "https://Stackoverflow.com/users/4134411",
"pm_score": 2,
"selected": false,
"text": "useEffect const Comp = () => {\n\n useEffect(() => {\n fetch(\"api url\").then((res)=>console.log(res))\n }, []);\n\n return (\n <div>comp</div>\n )\n}\n"
},
{
"answer_id": 74639852,
"author": "Shubham Yadav",
"author_id": 13034319,
"author_profile": "https://Stackoverflow.com/users/13034319",
"pm_score": 3,
"selected": true,
"text": "import React, { useEffect } from 'react'\n\nconst comp = () => {\nuseEffect(() => {\n fetch(\"api url\").then((res)=>console.log(res))\n}, [])\n\n\n return (\n <div>comp</div>\n )\n}\n\nexport default comp\n"
},
{
"answer_id": 74639919,
"author": "Zehan Khan",
"author_id": 16884475,
"author_profile": "https://Stackoverflow.com/users/16884475",
"pm_score": 0,
"selected": false,
"text": "import React, { useState, useEffect } from 'react'\n\nconst Comp = () => {\n\nconst [ data, setData ] = useState([]);\n\nconst getData = async () => {\n const res = await fetch(\"api url\");\n const data = await res.json();\n setData(data)\n} \n\nuseEffect(()=>{ getData() },[]);\n\n return (\n <>\n <div>comp</div>\n // dispaly your data here from data state \n </>\n )\n}\n\nexport default Comp;\n"
},
{
"answer_id": 74639925,
"author": "Thery",
"author_id": 17183643,
"author_profile": "https://Stackoverflow.com/users/17183643",
"pm_score": 1,
"selected": false,
"text": "import React, {useEffect} from 'react'\n\n\n useEffect(() => {\n\n fetch(\"api url\").then((res)=>console.log(res))\n\n }, []);\n\n"
},
{
"answer_id": 74639968,
"author": "Azzy",
"author_id": 2122822,
"author_profile": "https://Stackoverflow.com/users/2122822",
"pm_score": 0,
"selected": false,
"text": "const initialValue = {};\n\nconst comp = () => {\n\n const [data, setData] = useState(initialValue);\n\n useEffect(() => {\n\n let ignore = false;\n \n const fetchData = async () => {\n const res = fetch(\"api url\");\n if (ignore) { return; }\n setData(res.json())\n\n return () => {\n ignore = true;\n }\n }\n\n , [])\n\n\n return (\n <div>comp {data.prop}</div>\n )\n}\n"
},
{
"answer_id": 74640075,
"author": "Ahmad Faraz",
"author_id": 13567807,
"author_profile": "https://Stackoverflow.com/users/13567807",
"pm_score": 0,
"selected": false,
"text": "API useEffect import React, { useEffect, useState } from 'react'\n\nconst comp = () => {\n\n const [data, setData] = useState([]);\n\n useEffect(() => {\n fetch(\"api url\").then((res)=> {\n console.log(res)\n setData(res)\n } )\n }, [])\n\n\n return (\n // use data state to show the data here\n <div>comp</div>\n )\n}\n\nexport default comp;\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20248412/"
] |
74,639,813
|
<p>I want to scrape all pages of a website and get the <code>meta tag description</code> like</p>
<p><code><meta name="description" content="I want to get this description of this meta tag" /></code></p>
<p>similarly for all other pages I want to get their individual <code>meta description</code></p>
<p>Here is my code</p>
<pre><code>add_action('woocommerce_before_single_product', 'my_function_get_description');
function my_function_get_description($url) {
$the_html = file_get_contents('https://tipodense.dk/');
print_r($the_html)
}
</code></pre>
<p>This<code>print_r($the_html)</code> gives me the whole website, I don't know how to get the meta description of each page</p>
<p>Kindly guide me thanks</p>
|
[
{
"answer_id": 74639959,
"author": "Camille",
"author_id": 15282066,
"author_profile": "https://Stackoverflow.com/users/15282066",
"pm_score": 1,
"selected": false,
"text": "function my_function_get_description($url) {\n $the_html = file_get_contents('https://tipodense.dk/');\n preg_match('meta name=\"description\" content=\"([\\w\\s]+)\"', $the_html, $matches);\n print_r($matches);\n}\n $matches[0][1]"
},
{
"answer_id": 74639961,
"author": "Professor Abronsius",
"author_id": 3603681,
"author_profile": "https://Stackoverflow.com/users/3603681",
"pm_score": 1,
"selected": true,
"text": "DOMDocument DOMXPath $url='https://tipodense.dk/';\n\n# create the DOMDocument and load url\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n$dom->loadHTMLFile( $url );\nlibxml_clear_errors();\n\n# load XPath\n$xp=new DOMXPath( $dom );\n$expr='//meta[@name=\"description\"]';\n\n\n$col=$xp->query($expr);\nif( $col && $col->length > 0 ){\n foreach( $col as $node ){\n echo $node->getAttribute('content');\n }\n}\n Har du brug for at vide hvad der sker i Odense? Vores fokuspunkter er især events, mad, musik, kultur og nyheder. Hvis du vil vide mere så læs med på sitet.\n $url='https://tipodense.dk/';\n$sitemap='https://tipodense.dk/sitemap-pages.xml';\n\n$urls=array();\n\n\n# create the DOMDocument and load url\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n\n\n# read the sitemap & store urls\n$dom->load( $sitemap );\nlibxml_clear_errors();\n\n$col=$dom->getElementsByTagName('loc');\nforeach( $col as $node )$urls[]=$node->nodeValue;\n\n\n\nforeach( $urls as $url ){\n \n $dom->loadHTMLFile( $url );\n libxml_clear_errors();\n \n # load XPath\n $xp=new DOMXPath( $dom );\n $expr='//meta[@name=\"description\"]';\n \n \n $col=$xp->query( $expr );\n if( $col && $col->length > 0 ){\n foreach( $col as $node ){\n printf('<div>%s: %s</div>', $url, $node->getAttribute('content') );\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7014609/"
] |
74,639,879
|
<p>I have a json file (API.json) which looks like this:</p>
<pre class="lang-json prettyprint-override"><code>{"applist":{"apps":[{"appid":1234567,"name":"Test$: Number 1"},{"appid":7654321,"name":"Test- Number 2"},{"appid":7777777,"name":"Test & *(test)* Num. 3"}]}}
</code></pre>
<p>This is just the short version for testing.</p>
<p>I would like to know if it's possible to search for a "name" and view the related "appid" before that "name" via batch or any windows built-in commands.</p>
<p>E.g.</p>
<pre class="lang-bash prettyprint-override"><code>set /P name=Insert the name:
rem (Part of the name which matches exactly with the name)
if %name%=Test$: echo
Name: Test$: Number 1
App ID: 1234567
rem (Part of the name which matches with more than 1 name)
if %name%=Number echo
Name: Test$: Number 1
App ID: 1234567
Name: Test- Number 2
App ID: 7654321
</code></pre>
<p>As it is obvious, <code>Test</code> or <code>Number</code> might, or might not be, included in the name.</p>
<p>I have tried converting this to object via PowerShell (convertto-json) but without any success. I Don't know if that would help.</p>
|
[
{
"answer_id": 74639959,
"author": "Camille",
"author_id": 15282066,
"author_profile": "https://Stackoverflow.com/users/15282066",
"pm_score": 1,
"selected": false,
"text": "function my_function_get_description($url) {\n $the_html = file_get_contents('https://tipodense.dk/');\n preg_match('meta name=\"description\" content=\"([\\w\\s]+)\"', $the_html, $matches);\n print_r($matches);\n}\n $matches[0][1]"
},
{
"answer_id": 74639961,
"author": "Professor Abronsius",
"author_id": 3603681,
"author_profile": "https://Stackoverflow.com/users/3603681",
"pm_score": 1,
"selected": true,
"text": "DOMDocument DOMXPath $url='https://tipodense.dk/';\n\n# create the DOMDocument and load url\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n$dom->loadHTMLFile( $url );\nlibxml_clear_errors();\n\n# load XPath\n$xp=new DOMXPath( $dom );\n$expr='//meta[@name=\"description\"]';\n\n\n$col=$xp->query($expr);\nif( $col && $col->length > 0 ){\n foreach( $col as $node ){\n echo $node->getAttribute('content');\n }\n}\n Har du brug for at vide hvad der sker i Odense? Vores fokuspunkter er især events, mad, musik, kultur og nyheder. Hvis du vil vide mere så læs med på sitet.\n $url='https://tipodense.dk/';\n$sitemap='https://tipodense.dk/sitemap-pages.xml';\n\n$urls=array();\n\n\n# create the DOMDocument and load url\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n\n\n# read the sitemap & store urls\n$dom->load( $sitemap );\nlibxml_clear_errors();\n\n$col=$dom->getElementsByTagName('loc');\nforeach( $col as $node )$urls[]=$node->nodeValue;\n\n\n\nforeach( $urls as $url ){\n \n $dom->loadHTMLFile( $url );\n libxml_clear_errors();\n \n # load XPath\n $xp=new DOMXPath( $dom );\n $expr='//meta[@name=\"description\"]';\n \n \n $col=$xp->query( $expr );\n if( $col && $col->length > 0 ){\n foreach( $col as $node ){\n printf('<div>%s: %s</div>', $url, $node->getAttribute('content') );\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12261902/"
] |
74,639,911
|
<p>I want to use pyenv to create a virtual environment that accesses system packages (specifically wxPython).</p>
<p>I have tried</p>
<pre><code>pyenv virtualenv --system-site-packages 3.9.10 myenv
</code></pre>
<p>It creates the virtual env and <em>pyenv.cfg</em> contains the line</p>
<pre><code>include-system-site-packages = true
</code></pre>
<p>But it will not detect the system packages</p>
<p>I have tried creating it using</p>
<pre><code>pyenv virtualenv 3.9.10 myenv
</code></pre>
<p>and then editing <em>pyenv.cfg</em></p>
<p>but that does not work either</p>
<p>What can I do?</p>
<p>I have studied <a href="https://stackoverflow.com/questions/55600132/installing-local-packages-with-python-virtualenv-system-site-packages">this question and answers</a> but it doesn't seem to help</p>
|
[
{
"answer_id": 74639959,
"author": "Camille",
"author_id": 15282066,
"author_profile": "https://Stackoverflow.com/users/15282066",
"pm_score": 1,
"selected": false,
"text": "function my_function_get_description($url) {\n $the_html = file_get_contents('https://tipodense.dk/');\n preg_match('meta name=\"description\" content=\"([\\w\\s]+)\"', $the_html, $matches);\n print_r($matches);\n}\n $matches[0][1]"
},
{
"answer_id": 74639961,
"author": "Professor Abronsius",
"author_id": 3603681,
"author_profile": "https://Stackoverflow.com/users/3603681",
"pm_score": 1,
"selected": true,
"text": "DOMDocument DOMXPath $url='https://tipodense.dk/';\n\n# create the DOMDocument and load url\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n$dom->loadHTMLFile( $url );\nlibxml_clear_errors();\n\n# load XPath\n$xp=new DOMXPath( $dom );\n$expr='//meta[@name=\"description\"]';\n\n\n$col=$xp->query($expr);\nif( $col && $col->length > 0 ){\n foreach( $col as $node ){\n echo $node->getAttribute('content');\n }\n}\n Har du brug for at vide hvad der sker i Odense? Vores fokuspunkter er især events, mad, musik, kultur og nyheder. Hvis du vil vide mere så læs med på sitet.\n $url='https://tipodense.dk/';\n$sitemap='https://tipodense.dk/sitemap-pages.xml';\n\n$urls=array();\n\n\n# create the DOMDocument and load url\nlibxml_use_internal_errors( true );\n$dom=new DOMDocument;\n$dom->validateOnParse=false;\n$dom->strictErrorChecking=false;\n$dom->recover=true;\n\n\n# read the sitemap & store urls\n$dom->load( $sitemap );\nlibxml_clear_errors();\n\n$col=$dom->getElementsByTagName('loc');\nforeach( $col as $node )$urls[]=$node->nodeValue;\n\n\n\nforeach( $urls as $url ){\n \n $dom->loadHTMLFile( $url );\n libxml_clear_errors();\n \n # load XPath\n $xp=new DOMXPath( $dom );\n $expr='//meta[@name=\"description\"]';\n \n \n $col=$xp->query( $expr );\n if( $col && $col->length > 0 ){\n foreach( $col as $node ){\n printf('<div>%s: %s</div>', $url, $node->getAttribute('content') );\n }\n }\n}\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3070181/"
] |
74,639,946
|
<p>According to the official documentation, the playwright doesn't support chaining the actions you perform on a single selector like, alternatively, Cypress allows for.
As a result, your code file grows with repetitive expressions:</p>
<pre><code>await page.getByRole('textbox').click();
await page.getByRole('textbox').fill('test value in the text box');
await page.getByRole('textbox').press('Enter');
</code></pre>
<p>What I'm trying to achieve: is that after you perform a click, you can perform a fill and maybe a press, if it's programmatically possible, in a single expression. Without repeating
<code>await page.getByRole('textbox')</code></p>
<p>I'm relatively new to javascript and typescript. I'm reading the documentation but feeling overwhelmed. I would be grateful for any guidance concerning if, e.g., promises would solve this issue, with an example on the above code provided.</p>
<p>Using "@playwright/test": "^1.28.0"</p>
|
[
{
"answer_id": 74640181,
"author": "Basti",
"author_id": 16391362,
"author_profile": "https://Stackoverflow.com/users/16391362",
"pm_score": 2,
"selected": false,
"text": "const myTextbox = page.getByRole('textbox');\nawait myTextbox.click();\nawait myTextbox.fill('some text');\nawait myTextbox.press('Enter');\n"
},
{
"answer_id": 74641562,
"author": "geoffrey",
"author_id": 8225569,
"author_profile": "https://Stackoverflow.com/users/8225569",
"pm_score": 1,
"selected": false,
"text": "type ChainLocator = {\n [K in keyof Locator]: Locator[K] extends ((...args: any[]) => Promise<void>)\n ? (...args: Parameters<Locator[K]>) => ChainLocator : Locator[K]\n} & { run: () => Promise<void> }\n\n\nconst chain = (selector: Locator): ChainLocator => {\n const queue: ((...args: any[]) => Promise<void>)[] = [];\n const proxy = new Proxy(selector, {\n get: (target, key: keyof ChainLocator) => \n key === 'run' ? async () => {\n for (const f of queue) await f(selector)\n }\n \n : (typeof target[key] === 'function') ? (...args: any[]) => {\n queue.push(target[key].bind(target, args));\n return proxy;\n }\n\n : target[key]\n \n });\n return proxy;\n}\n\n\nchain(page.getByRole('textbox'))\n .click().fill('test value in the text box').press('Enter').run();\n const chain = (selector: Locator) =>\n async (...fs: ((a: Locator) => Promise<void>)[]) => {\n for (const f of fs) await f(selector);\n }\n\nchain(page.getByRole('textbox'))(\n s => s.click(),\n s => s.fill('test value in the text box'),\n s => s.press('Enter')\n)\n const { click, fill, press } = curryMethods(theLocatorClass);\n \nchain(page.getByRole('textbox'))(\n click(),\n fill('test value in the text box'),\n press('Enter')\n)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654763/"
] |
74,639,947
|
<p>The restrictions are that the elements can be appended to the front if they are greater than the element at the front and to the back if they are smaller than the back. It can also ignore elements (and there comes the difficulty).</p>
<p>Example:</p>
<p>Input:
<code>{6, 7, 3, 5, 4}</code></p>
<p>The longest sequence to that input is:</p>
<ul>
<li><p>Start with <code>{6}</code>.</p>
</li>
<li><p>Append 7 to the front because it is greater than 6. <code>{7, 6}</code></p>
</li>
<li><p>Ignore 3.</p>
</li>
<li><p>Append 5 to the back because it is smaller. <code>{7, 6, 5}</code></p>
</li>
<li><p>Append 4 to the back because it is smaller. <code>{7, 6, 5, 4}</code></p>
</li>
</ul>
<p>If we appended 3, the sequence would be smaller <code>{7, 6, 3}</code> because then we wouldn't be able to append 4.</p>
<p>I tried to adapt a LIS algorithm to solve it, but the results are totally wrong.</p>
<pre><code>int adapted_LIS(int input[], int n)
{
int score[n] = {};
score[0] = 1;
for (int i = 1; i < n; i++)
{
score[i] = 1;
int front = input[i];
int back = input[i];
for (int j = 0; j < i; j++)
{
if (input[j] > front)
{
front = input[j];
score[i] = std::max(score[i], score[j] + 1);
}
else if (input[j] < back)
{
back = input[j];
score[i] = std::max(score[i], score[j] + 1);
}
}
}
return *std::max_element(score, score + n);
}
</code></pre>
<p>How can I solve it using Dynamic Programming?</p>
|
[
{
"answer_id": 74672268,
"author": "David Eisenstat",
"author_id": 2144669,
"author_profile": "https://Stackoverflow.com/users/2144669",
"pm_score": 2,
"selected": false,
"text": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n\nstd::vector<int> PushFront(int x, std::vector<int> subsequence) {\n subsequence.insert(subsequence.begin(), x);\n return subsequence;\n}\n\nstd::vector<int> PushBack(std::vector<int> subsequence, int x) {\n subsequence.push_back(x);\n return subsequence;\n}\n\nvoid Consider(std::map<std::pair<int, int>, std::vector<int>> &table,\n std::vector<int> subsequence) {\n std::vector<int> &entry = table[{subsequence.front(), subsequence.back()}];\n if (subsequence.size() > entry.size()) {\n entry = std::move(subsequence);\n }\n}\n\nstd::vector<int> TwoSidedDecreasingSubsequence(const std::vector<int> &input) {\n if (input.empty()) {\n return {};\n }\n // Maps {front, back} to the longest known subsequence.\n std::map<std::pair<int, int>, std::vector<int>> table;\n for (int x : input) {\n auto table_copy = table;\n for (const auto &[front_back, subsequence] : table_copy) {\n auto [front, back] = front_back;\n if (x > front) {\n Consider(table, PushFront(x, subsequence));\n }\n if (back > x) {\n Consider(table, PushBack(subsequence, x));\n }\n }\n Consider(table, {x});\n }\n return std::max_element(\n table.begin(), table.end(),\n [&](const std::pair<std::pair<int, int>, std::vector<int>> &a,\n const std::pair<std::pair<int, int>, std::vector<int>> &b) {\n return a.second.size() < b.second.size();\n })\n ->second;\n}\n\nint main() {\n for (int x : TwoSidedDecreasingSubsequence({6, 7, 3, 5, 4})) {\n std::cout << ' ' << x;\n }\n std::cout << '\\n';\n}\n"
},
{
"answer_id": 74674510,
"author": "J. M. Arnold",
"author_id": 14852784,
"author_profile": "https://Stackoverflow.com/users/14852784",
"pm_score": 0,
"selected": false,
"text": "front back n i i front[i-1] front[i] front[i-1] + 1 i back[i-1] back[i] back[i-1] + 1 of front[n-1] back[n-1] int longest_sequence(int input[], int n)\n{\n // Initialize dynamic programming arrays\n int front[n];\n int back[n];\n\n // Set all elements of the arrays to 1\n for (int i = 0; i < n; i++)\n {\n front[i] = 1;\n back[i] = 1;\n }\n\n // Iterate over the input array from left to right\n for (int i = 1; i < n; i++)\n {\n // If the current element is smaller than the element at the front of the sequence,\n // append it to the front of the sequence by updating front[i]\n if (input[i] < input[front[i-1] - 1])\n {\n front[i] = front[i-1] + 1;\n }\n\n // If the current element is greater than the element at the back of the sequence,\n // append it to the back of the sequence by updating back[i]\n if (input[i] > input[back[i-1] + 1])\n {\n back[i] = back[i-1] + 1;\n }\n }\n\n // Return the maximum of front[n-1] and back[n-1]\n return std::max(front[n-1], back[n-1]);\n int input[] = {6, 7, 3, 5, 4};\nint n = 5;\n\nint result = longest_sequence(input, n);\n {7, 6, 5, 4} longest_sequence"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14833479/"
] |
74,639,957
|
<p>I am trying to connect to a mariadb-database on my local network. using Python.</p>
<pre><code>import mariadb
cursor = mariadb.connect(host='192.168.178.77', user='someuser', password='somepass', db='temps')
</code></pre>
<p>Output is:</p>
<pre><code>Traceback (most recent call last):
File "/Users/localuser/PycharmProjects/SQL/main.py", line 20, in <module>
cursor = mariadb.connect(host='192.168.178.77', user='someuser', password='somepass', db='temps')
File "/Users/user/.conda/envs/SQL/lib/python3.10/site-packages/mariadb/__init__.py", line 142, in connect
connection = connectionclass(*args, **kwargs)
File "/Users/localuser/.conda/envs/SQL/lib/python3.10/site-packages/mariadb/connections.py", line 86, in __init__
super().__init__(*args, **kwargs)
mariadb.OperationalError: Can't connect to server on '192.168.178.77' (60)
</code></pre>
<p>I can connect via Pycharms Database functionality and send SQL Statements.
I also can use DB management tools from that very host and use data without any issue.
It even works from my phone.</p>
<p>This code is the only place where I get an error.</p>
<p>OS is MacOS13.0.1</p>
<p>Thank You!</p>
|
[
{
"answer_id": 74640231,
"author": "Georg Richter",
"author_id": 6930501,
"author_profile": "https://Stackoverflow.com/users/6930501",
"pm_score": 0,
"selected": false,
"text": "brew update\nbrew upgrade mariadb-connector-c\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8978772/"
] |
74,639,988
|
<p>I am writing R ggplot, and I am arranging multiple plots with <code>grid.arrange</code>.</p>
<p>Is there a way to add some words in in between two plots?
I want the output to be like the red word.</p>
<p>Thank you for your help :)</p>
<pre><code>library(ggplot2)
library(gridExtra)
P1 <- ggplot(mtcars, aes(x = mpg)) +
geom_histogram()
P2 <- ggplot(mtcars, aes(x = wt)) +
geom_histogram()
grid.arrange(P1, *I want to add some information here*,P2, ncol = 1, nrow = 2)
</code></pre>
<p><a href="https://i.stack.imgur.com/uRwpc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uRwpc.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74640152,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "grid.text grid ### Libraries\nlibrary(grid)\nlibrary(ggplot2)\nlibrary(gridExtra)\n\n### Data\ndata(cars)\n\n### Initiating plots\nP1 <- ggplot(mtcars, aes(x = mpg)) +\n geom_histogram()\n\nP2 <- ggplot(mtcars, aes(x = wt)) +\n geom_histogram()\n\n### Display plots\ngrid.arrange(P1, P2, ncol = 1, nrow = 2)+\ngrid.text(\"I want to add some information here\", \n x=unit(0.25, \"npc\"), \n y=unit(.52, \"npc\"),\n gp=gpar(fontsize=20, col=\"red\"))\n"
},
{
"answer_id": 74640201,
"author": "Ronak Shah",
"author_id": 3962914,
"author_profile": "https://Stackoverflow.com/users/3962914",
"pm_score": 1,
"selected": false,
"text": "ggplot cowplot::plot_grid library(ggplot2)\n\nP1 <- ggplot(mtcars, aes(x = mpg)) + geom_histogram()\n\nP2 <- ggplot() + \n annotate(\"text\", x = 4, y = 25, size=8, \n label = \"This is some text in the middle\", color = \"red\") + \n theme_void() \n\nP3 <- ggplot(mtcars, aes(x = wt)) + geom_histogram()\n\ncowplot::plot_grid(P1, P2, P3, rel_heights = c(1/2, 1/12, 1/2), \n align = \"v\", nrow = 3)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16469595/"
] |
74,639,989
|
<p>I have files in one directory/folder named:</p>
<ol>
<li><code>2022-07-31_DATA_GVAX_ARPA_COMBINED.csv</code></li>
<li><code>2022-08-31_DATA_GVAX_ARPA_COMBINED.csv</code></li>
<li><code>2022-09-30_DATA_GVAX_ARPA_COMBINED.csv</code></li>
</ol>
<p>The folder will be updated with each month's file in the same format as above eg.:</p>
<ul>
<li><code>2022-10-31_DATA_GVAX_ARPA_COMBINED.csv</code></li>
<li><code>2022-11-30_DATA_GVAX_ARPA_COMBINED.csv</code></li>
</ul>
<p>I want to only load the most recent month's .csv into a pandas dataframe, not all the files. How can I do this (maybe using glob)?</p>
<p>I have seen this used for prefixes using:</p>
<pre><code>dir_files = r'/path/to/folder/*'
dico={}
for file in Path(dir_files).glob('DATA_GVAX_COMBINED_*.csv'):
dico[file.stem.split('_')[-1]] = file
max_date = max(dico)
</code></pre>
|
[
{
"answer_id": 74640152,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "grid.text grid ### Libraries\nlibrary(grid)\nlibrary(ggplot2)\nlibrary(gridExtra)\n\n### Data\ndata(cars)\n\n### Initiating plots\nP1 <- ggplot(mtcars, aes(x = mpg)) +\n geom_histogram()\n\nP2 <- ggplot(mtcars, aes(x = wt)) +\n geom_histogram()\n\n### Display plots\ngrid.arrange(P1, P2, ncol = 1, nrow = 2)+\ngrid.text(\"I want to add some information here\", \n x=unit(0.25, \"npc\"), \n y=unit(.52, \"npc\"),\n gp=gpar(fontsize=20, col=\"red\"))\n"
},
{
"answer_id": 74640201,
"author": "Ronak Shah",
"author_id": 3962914,
"author_profile": "https://Stackoverflow.com/users/3962914",
"pm_score": 1,
"selected": false,
"text": "ggplot cowplot::plot_grid library(ggplot2)\n\nP1 <- ggplot(mtcars, aes(x = mpg)) + geom_histogram()\n\nP2 <- ggplot() + \n annotate(\"text\", x = 4, y = 25, size=8, \n label = \"This is some text in the middle\", color = \"red\") + \n theme_void() \n\nP3 <- ggplot(mtcars, aes(x = wt)) + geom_histogram()\n\ncowplot::plot_grid(P1, P2, P3, rel_heights = c(1/2, 1/12, 1/2), \n align = \"v\", nrow = 3)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74639989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14739761/"
] |
74,640,003
|
<p><img src="https://i.stack.imgur.com/T0ijs.png" alt="enter image description here" />
How would you solve that question?
Background: beginner in C# who has only studied for a couple of days.</p>
<pre><code>int[] nums= new int[10];
for (int i = 0; i < nums.Length; i++)
{
{
Console.WriteLine("Enter number:");
string strnum = Console.ReadLine();
nums[i] = Convert.ToInt32(strnum);
}
}
sum(nums);
Biggest(nums);
...
Got stuck here while doing the above question
</code></pre>
|
[
{
"answer_id": 74640152,
"author": "Yacine Hajji",
"author_id": 17049772,
"author_profile": "https://Stackoverflow.com/users/17049772",
"pm_score": 2,
"selected": false,
"text": "grid.text grid ### Libraries\nlibrary(grid)\nlibrary(ggplot2)\nlibrary(gridExtra)\n\n### Data\ndata(cars)\n\n### Initiating plots\nP1 <- ggplot(mtcars, aes(x = mpg)) +\n geom_histogram()\n\nP2 <- ggplot(mtcars, aes(x = wt)) +\n geom_histogram()\n\n### Display plots\ngrid.arrange(P1, P2, ncol = 1, nrow = 2)+\ngrid.text(\"I want to add some information here\", \n x=unit(0.25, \"npc\"), \n y=unit(.52, \"npc\"),\n gp=gpar(fontsize=20, col=\"red\"))\n"
},
{
"answer_id": 74640201,
"author": "Ronak Shah",
"author_id": 3962914,
"author_profile": "https://Stackoverflow.com/users/3962914",
"pm_score": 1,
"selected": false,
"text": "ggplot cowplot::plot_grid library(ggplot2)\n\nP1 <- ggplot(mtcars, aes(x = mpg)) + geom_histogram()\n\nP2 <- ggplot() + \n annotate(\"text\", x = 4, y = 25, size=8, \n label = \"This is some text in the middle\", color = \"red\") + \n theme_void() \n\nP3 <- ggplot(mtcars, aes(x = wt)) + geom_histogram()\n\ncowplot::plot_grid(P1, P2, P3, rel_heights = c(1/2, 1/12, 1/2), \n align = \"v\", nrow = 3)\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654833/"
] |
74,640,047
|
<p>I'm trying to follow a small laravel tutorial.</p>
<p>In my application I have a controller called, HomeController.</p>
<p>In my HomeController, I have the followinf index function</p>
<pre><code>public function index()
{
try {
//get autheticated users selected organisation
$organisation = $this->getSelectedOrganisationByUser(Auth::user());
//set application timezone
$this->setApplicationTimezone($organisation);
$this->setSiteConnection($organisation);
$this->setGAConnection($organisation);
if ($organisation->disabled) {
Auth::logout();
return redirect(route('login'));
}
//sales today
$sum='23';
return view('dashboard.index')
->with('organisation',$organisation,'sum',$sum);
} catch (\Throwable $exception) {
\Sentry\captureException($exception);
}
}
</code></pre>
<p>Here I'm trying to send this $sum value to my blade and display it. But, Every time i tried to display this value on my blade I get $sum is undefined error.</p>
<p>I tried to echo this on my blade as follows,</p>
<pre><code>{{ $sum }}
</code></pre>
<p>What changes should I make, in order to display that on my blade.</p>
<p>I tried hard, but yet to figure out a solution</p>
|
[
{
"answer_id": 74640113,
"author": "Afif Zafri",
"author_id": 5784900,
"author_profile": "https://Stackoverflow.com/users/5784900",
"pm_score": 2,
"selected": false,
"text": "return view('dashboard.index', ['organisation' => $organisation, 'sum' => $sum]);\n compact() return view('dashboard.index', compact('organisation', 'sum'));\n"
},
{
"answer_id": 74640176,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 3,
"selected": true,
"text": "with() /Illuminate/View/View.php //Call with() for each variable\nreturn view('dashboard.index')\n ->with('organisation',$organisation)\n ->with('sum',$sum);\n//use an array as second parameter of view\nreturn view('dashboard.index', ['organisation' => $organisation,'sum' => $sum]);\n//use compact to create the array using the variable name\nreturn view('dashboard.index', compact('organisation', 'sum'));\n//use an array as first parameter in with (using compact or not)\nreturn view('dashboard.index')->with(compact('organisation', 'sum'));\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654572/"
] |
74,640,059
|
<p>I'm wondering if there is a way to force getting strings from the custom file? Let's say I would like to have testing strings set and use them in the debug mode. As far as I know, there is no possibility to create a custom Locale and use for example <code>values-test</code> folder. But maybe there is the possibility to override something and force getting strings from the assets folder file?</p>
|
[
{
"answer_id": 74640113,
"author": "Afif Zafri",
"author_id": 5784900,
"author_profile": "https://Stackoverflow.com/users/5784900",
"pm_score": 2,
"selected": false,
"text": "return view('dashboard.index', ['organisation' => $organisation, 'sum' => $sum]);\n compact() return view('dashboard.index', compact('organisation', 'sum'));\n"
},
{
"answer_id": 74640176,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 3,
"selected": true,
"text": "with() /Illuminate/View/View.php //Call with() for each variable\nreturn view('dashboard.index')\n ->with('organisation',$organisation)\n ->with('sum',$sum);\n//use an array as second parameter of view\nreturn view('dashboard.index', ['organisation' => $organisation,'sum' => $sum]);\n//use compact to create the array using the variable name\nreturn view('dashboard.index', compact('organisation', 'sum'));\n//use an array as first parameter in with (using compact or not)\nreturn view('dashboard.index')->with(compact('organisation', 'sum'));\n"
}
] |
2022/12/01
|
[
"https://Stackoverflow.com/questions/74640059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281821/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.