qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,552,043
<p>So I've built an API for movies <code>dataset</code> which contain following structure:</p> <p><strong>Models.py</strong></p> <pre><code>class Directors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'directors' ordering = ['-id'] class Movies(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) year = models.IntegerField(blank=True, null=True) rank = models.FloatField(blank=True, null=True) class Meta: db_table = 'movies' ordering = ['-id'] class Actors(models.Model): id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) gender = models.CharField(max_length=20, blank=True, null=True) class Meta: db_table = 'actors' ordering = ['-id'] class DirectorsGenres(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres') genre = models.CharField(max_length=100, blank=True, null=True) prob = models.FloatField(blank=True, null=True) class Meta: db_table = 'directors_genres' ordering = ['-director'] class MoviesDirectors(models.Model): director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors') class Meta: db_table = 'movies_directors' ordering = ['-director'] class MoviesGenres(models.Model): movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres') genre = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'movies_genres' ordering = ['-movie'] class Roles(models.Model): actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles') movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles') role = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'roles' ordering = ['-actor'] </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.urls import path, include from . import views from api.views import getMovies, getGenres, getActors urlpatterns = [ path('', views.getRoutes), path('movies/', getMovies.as_view(), name='movies'), path('movies/genres/', getGenres.as_view(), name='genres'), path('actor_stats/&lt;pk&gt;', getActors.as_view(), name='actor_stats'), ] </code></pre> <p><strong>serializer.py</strong></p> <pre><code>from rest_framework import serializers from movies.models import * class MoviesSerializer(serializers.ModelSerializer): class Meta: model = Movies fields = '__all__' class DirectorsSerializer(serializers.ModelSerializer): class Meta: model = Directors fields = '__all__' class ActorsSerializer(serializers.ModelSerializer): class Meta: model = Actors fields = '__all__' class DirectorsGenresSerializer(serializers.ModelSerializer): class Meta: model = DirectorsGenres fields = '__all__' class MoviesDirectorsSerializer(serializers.ModelSerializer): movie = MoviesSerializer(many = False) director = DirectorsSerializer(many = False) class Meta: model = MoviesDirectors fields = '__all__' class MoviesGenresSerializer(serializers.ModelSerializer): movie = MoviesSerializer(many = False) class Meta: model = MoviesGenres fields = '__all__' class RolesSerializer(serializers.ModelSerializer): movie = MoviesSerializer(many = False) actor = ActorsSerializer(many = False) class Meta: model = Roles fields = '__all__' </code></pre> <p><strong>views.py</strong></p> <pre><code>class getMovies(ListAPIView): directors = Directors.objects.all() queryset = MoviesDirectors.objects.filter(director__in=directors) serializer_class = MoviesDirectorsSerializer pagination_class = CustomPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['director__first_name', 'director__last_name'] class getGenres(ListAPIView): movies = Movies.objects.all() queryset = MoviesGenres.objects.filter(movie__in=movies).order_by('-genre') serializer_class = MoviesGenresSerializer pagination_class = CustomPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['genre'] class getActors(ListAPIView): queryset = Roles.objects.all() serializer_class = RolesSerializer pagination_class = CustomPagination def get_queryset(self): return super().get_queryset().filter( actor_id=self.kwargs['pk'] ) </code></pre> <p>Now I want to count number of movies by genre that actor with specific pk played in <code>getActors</code> class. Like the number of movies by genre that actor participated in. E.g. Drama: 2, Horror: 3 Right now I am getting the overall count of movies <code>count: 2</code>:</p> <pre><code>GET /api/actor_stats/17 HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { &quot;count&quot;: 2, &quot;next&quot;: null, &quot;previous&quot;: null, &quot;results&quot;: [ { &quot;id&quot;: 800480, &quot;movie&quot;: { &quot;id&quot;: 105231, &quot;name&quot;: &quot;Everybody's Business&quot;, &quot;year&quot;: 1993, &quot;rank&quot;: null }, &quot;actor&quot;: { &quot;id&quot;: 17, &quot;first_name&quot;: &quot;Luis Roberto&quot;, &quot;last_name&quot;: &quot;Formiga&quot;, &quot;gender&quot;: &quot;M&quot; }, &quot;role&quot;: &quot;Grandfather&quot; }, { &quot;id&quot;: 800481, &quot;movie&quot;: { &quot;id&quot;: 242453, &quot;name&quot;: &quot;OP Pro 88 - Barra Rio&quot;, &quot;year&quot;: 1988, &quot;rank&quot;: null }, &quot;actor&quot;: { &quot;id&quot;: 17, &quot;first_name&quot;: &quot;Luis Roberto&quot;, &quot;last_name&quot;: &quot;Formiga&quot;, &quot;gender&quot;: &quot;M&quot; }, &quot;role&quot;: &quot;Himself&quot; } ] } </code></pre> <p>What is the optimized way of achieving the following:</p> <ul> <li>number_of_movies_by_genre</li> <li>Drama: 2</li> <li>Horror: 3</li> </ul> <p><strong>UPDATE</strong></p> <pre><code>class RolesSerializer(serializers.Serializer): id = serializers.SerializerMethodField() name = serializers.SerializerMethodField() top_genre = serializers.SerializerMethodField() number_of_movies = serializers.SerializerMethodField() number_of_movies_by_genre = serializers.SerializerMethodField() most_frequent_partner = serializers.SerializerMethodField() class Meta: model = Roles fields = '__all__' def get_id(self, obj): return obj.actor.id def get_name(self, obj): return f'{obj.actor.first_name} {obj.actor.last_name}' def get_top_genre(self, obj): number_by_genre = Roles.objects.filter(actor = obj.actor.id ).values('movie__movies_genres__genre').annotate( genre = F('movie__movies_genres__genre'), number_of_movies=Count('movie__movies_genres__genre'), ) data = [s['number_of_movies'] for s in number_by_genre] highest = max(data) result = [s for s in data if s == highest] return result def get_number_of_movies(self, obj): number_of_movies = Roles.objects.filter(actor = obj.actor.id ).values('movie__name').count() return number_of_movies def get_number_of_movies_by_genre(self, obj): number_of_movies_by_genre = Roles.objects.filter(actor = obj.actor.id ).values('movie__movies_genres__genre').annotate( genre=F('movie__movies_genres__genre'), number_of_movies=Count('movie__movies_genres__genre'), ).values('genre', 'number_of_movies') return number_of_movies_by_genre def get_most_frequent_partner(self, obj): partners = Roles.objects.filter(actor = obj.actor.id ).values('movie__id') result = Roles.objects.filter(movie__in = partners ).values('actor').exclude(actor=obj.actor.id).annotate( partner_actor_id = F('actor'), partner_actor_name = Concat(F('actor__first_name'), Value(' '), F('actor__last_name')), number_of_shared_movies =Count('actor'), ).values('partner_actor_id', 'partner_actor_name', 'number_of_shared_movies') return result </code></pre> <p>The problem with that code is: It repeats the results by the number of movies. For instance if the actor have 5 movies the results will be repeated 5 times. Another issue is: in order to get <code>top_genre</code> and <code>most_frequent_partner</code> I'm using <code>max()</code> but then I just get the numbers and not the actual name of genre in (<code>top_genre</code>) and actor name in (<code>most_frequent_partner</code>). Since I use <code>max()</code> in a way to get more than one value. For instance in the <code>top_genre</code>: If the actor have <code>3 Drama, 3 Comedy, 1 Horror, 1 Documentary</code>, I get the max in that way: <code>[3,3]</code>, but how can I get the actual names out of these results? Same goes to <code>most_frequent_partner</code>.</p> <p>Results looks like this so far:</p> <pre><code>{ &quot;next&quot;: null, &quot;previous&quot;: null, &quot;count&quot;: 4, &quot;pagenum&quot;: null, &quot;results&quot;: [ { &quot;id&quot;: 36, &quot;name&quot;: &quot;Benjamin 2X&quot;, &quot;top_genre&quot;: [ 2, 2 ], &quot;number_of_movies&quot;: 4, &quot;number_of_movies_by_genre&quot;: [ { &quot;movie__movies_genres__genre&quot;: null, &quot;genre&quot;: null, &quot;number_of_movies&quot;: 0 }, { &quot;movie__movies_genres__genre&quot;: &quot;Documentary&quot;, &quot;genre&quot;: &quot;Documentary&quot;, &quot;number_of_movies&quot;: 2 }, { &quot;movie__movies_genres__genre&quot;: &quot;Music&quot;, &quot;genre&quot;: &quot;Music&quot;, &quot;number_of_movies&quot;: 2 } ], &quot;most_frequent_partner&quot;: [] }, { &quot;id&quot;: 36, &quot;name&quot;: &quot;Benjamin 2X&quot;, &quot;top_genre&quot;: [ 2, 2 ], &quot;number_of_movies&quot;: 4, &quot;number_of_movies_by_genre&quot;: [ { &quot;movie__movies_genres__genre&quot;: null, &quot;genre&quot;: null, &quot;number_of_movies&quot;: 0 }, { &quot;movie__movies_genres__genre&quot;: &quot;Documentary&quot;, &quot;genre&quot;: &quot;Documentary&quot;, &quot;number_of_movies&quot;: 2 }, { &quot;movie__movies_genres__genre&quot;: &quot;Music&quot;, &quot;genre&quot;: &quot;Music&quot;, &quot;number_of_movies&quot;: 2 } ], &quot;most_frequent_partner&quot;: [] }, { &quot;id&quot;: 36, &quot;name&quot;: &quot;Benjamin 2X&quot;, &quot;top_genre&quot;: [ 2, 2 ], &quot;number_of_movies&quot;: 4, &quot;number_of_movies_by_genre&quot;: [ { &quot;movie__movies_genres__genre&quot;: null, &quot;genre&quot;: null, &quot;number_of_movies&quot;: 0 }, { &quot;movie__movies_genres__genre&quot;: &quot;Documentary&quot;, &quot;genre&quot;: &quot;Documentary&quot;, &quot;number_of_movies&quot;: 2 }, { &quot;movie__movies_genres__genre&quot;: &quot;Music&quot;, &quot;genre&quot;: &quot;Music&quot;, &quot;number_of_movies&quot;: 2 } ], &quot;most_frequent_partner&quot;: [] }, { &quot;id&quot;: 36, &quot;name&quot;: &quot;Benjamin 2X&quot;, &quot;top_genre&quot;: [ 2, 2 ], &quot;number_of_movies&quot;: 4, &quot;number_of_movies_by_genre&quot;: [ { &quot;movie__movies_genres__genre&quot;: null, &quot;genre&quot;: null, &quot;number_of_movies&quot;: 0 }, { &quot;movie__movies_genres__genre&quot;: &quot;Documentary&quot;, &quot;genre&quot;: &quot;Documentary&quot;, &quot;number_of_movies&quot;: 2 }, { &quot;movie__movies_genres__genre&quot;: &quot;Music&quot;, &quot;genre&quot;: &quot;Music&quot;, &quot;number_of_movies&quot;: 2 } ], &quot;most_frequent_partner&quot;: [] } ] } </code></pre> <p>What I want to see in the end:</p> <pre><code>{ &quot;next&quot;: null, &quot;previous&quot;: null, &quot;count&quot;: 2, &quot;results&quot;: [ { &quot;id&quot;: 18 (actor_id), &quot;name&quot;: Bruce Buffer (actor_name), &quot;number of movies&quot;: 2, &quot;top genre&quot;: Drama, Documentary, &quot;number of movies by genre&quot;: Drama: 1, Documentary: 1, &quot;most frequent partner&quot;: partner_actor_id, partner_actor_name, number_of_shared_movies, } ] } </code></pre>
[ { "answer_id": 74584870, "author": "k4anubhav", "author_id": 14312439, "author_profile": "https://Stackoverflow.com/users/14312439", "pm_score": 2, "selected": true, "text": "number of movies genre return Roles.objects.filter(\n actor_id=self.kwargs['pk']\n ).values('movie__movies_genres__genre').annotate(\n no_of_movies=Count('movie__movies_genres__genre'),\n genre=F('movie__movies_genres__genre'),\n )\n genre count genre SerializerMethodField" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17602275/" ]
74,552,058
<p>I currently have a method that recursively enumerates all the files on my desktop and returns them as an <code>IEnumerable&lt;string&gt;</code>. What I am trying to now do is create a method that takes that <code>IEnumerable&lt;string&gt;</code> as the parameter and uses LINQ to group/order them by their file type. I am having trouble getting the file types. After experimenting, I have gotten this:</p> <pre><code>foreach(string file in files){ FileInfo f = new FileInfo(file); Console.WriteLine(f.Extension); } </code></pre> <p>I am able to get the extensions of all files, but cannot figure out how to get that information using a LINQ query</p>
[ { "answer_id": 74584870, "author": "k4anubhav", "author_id": 14312439, "author_profile": "https://Stackoverflow.com/users/14312439", "pm_score": 2, "selected": true, "text": "number of movies genre return Roles.objects.filter(\n actor_id=self.kwargs['pk']\n ).values('movie__movies_genres__genre').annotate(\n no_of_movies=Count('movie__movies_genres__genre'),\n genre=F('movie__movies_genres__genre'),\n )\n genre count genre SerializerMethodField" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8768617/" ]
74,552,089
<p>I'm trying to create a array which contains a bunch of objects like this and insert them upon different actions:</p> <pre><code>[ {price: 'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1}, {price: 'price_1M73OzI4545W1JretwretkAHa', quantity: 3}, {price: 'price_1M73OzIRkO4545twr45kAHa', quantity:2} ] </code></pre> <p>However I cant seem to add in a third object it just overwrittes the second one.</p> <pre><code>const [allPlans, setAllPlans] = useState([]); setAllPlans([{...allPlans, price:'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1}]); </code></pre> <p>Thank you for the help!</p> <p>update: Early in the code I do do this to update the quanity on the orginal entry. Could this be creating the issue?</p> <pre><code>setAllPlans({...allPlans,&quot;quantity&quot;: userAmount}); </code></pre> <p>Update: Here is a link to a working example of the problem corrected: <a href="https://codesandbox.io/s/priceless-ully-594ihs?file=/src/App.js:280-287" rel="nofollow noreferrer">https://codesandbox.io/s/priceless-ully-594ihs?file=/src/App.js:280-287</a></p>
[ { "answer_id": 74552113, "author": "Sean", "author_id": 11726149, "author_profile": "https://Stackoverflow.com/users/11726149", "pm_score": 3, "selected": true, "text": "setAllPlans(allplans => [...allplans, {price:'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1}]);\n" }, { "answer_id": 74552678, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "push prevPlans setAllPlans((prevPlans) => [\n prevPlans.push({\n price: \"i'm new here\",\n quantity: 1\n })\n ]);\n const {\n useState\n} = React;\n\nconst App = () => {\n const [allPlans, setAllPlans] = useState([{\n price: \"price_1M73OzIRkO5W1JretwretkAHa\",\n quantity: 1\n },\n {\n price: \"price_1M73OzI4545W1JretwretkAHa\",\n quantity: 3\n },\n {\n price: \"price_1M73OzIRkO4545twr45kAHa\",\n quantity: 2\n }\n ]);\n\n const addtoArray = () => {\n //prevPlans is your actual array and you push new object inside it and set your state\n setAllPlans((prevPlans) => [\n prevPlans.push({\n price: \"i'm new here\",\n quantity: 1\n })\n ]);\n console.log(allPlans);\n };\n\n return ( <\n div >\n <\n button onClick = {\n () => addtoArray()\n } > Click me < /button> <\n /div>\n );\n\n}\n\n\n// Render it\nReactDOM.createRoot(\n document.getElementById(\"root\")\n).render( <\n App / >\n); <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js\"></script>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827252/" ]
74,552,123
<p>I have two programs, one in go and one in python that I am trying to characterize. For this, I'd like to measure the CPU usage and Memory Usage by regularly measuring the amounts consumed by the two programs at regular intervals (say, every 0.1 seconds) for some given amount of time. I have been looking everywhere for any sort of solution to this problem, but I can't find any.</p> <p>Does a good solution to this exist? If so, what?</p>
[ { "answer_id": 74552113, "author": "Sean", "author_id": 11726149, "author_profile": "https://Stackoverflow.com/users/11726149", "pm_score": 3, "selected": true, "text": "setAllPlans(allplans => [...allplans, {price:'price_1M73OzIRkO5W1JretwretkAHa', quantity: 1}]);\n" }, { "answer_id": 74552678, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "push prevPlans setAllPlans((prevPlans) => [\n prevPlans.push({\n price: \"i'm new here\",\n quantity: 1\n })\n ]);\n const {\n useState\n} = React;\n\nconst App = () => {\n const [allPlans, setAllPlans] = useState([{\n price: \"price_1M73OzIRkO5W1JretwretkAHa\",\n quantity: 1\n },\n {\n price: \"price_1M73OzI4545W1JretwretkAHa\",\n quantity: 3\n },\n {\n price: \"price_1M73OzIRkO4545twr45kAHa\",\n quantity: 2\n }\n ]);\n\n const addtoArray = () => {\n //prevPlans is your actual array and you push new object inside it and set your state\n setAllPlans((prevPlans) => [\n prevPlans.push({\n price: \"i'm new here\",\n quantity: 1\n })\n ]);\n console.log(allPlans);\n };\n\n return ( <\n div >\n <\n button onClick = {\n () => addtoArray()\n } > Click me < /button> <\n /div>\n );\n\n}\n\n\n// Render it\nReactDOM.createRoot(\n document.getElementById(\"root\")\n).render( <\n App / >\n); <div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js\"></script>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17420895/" ]
74,552,131
<p>Im having a trouble with editing a txt file on python.</p> <p>Hi guys,</p> <p>Im having a trouble with editing a txt file on python.</p> <p>Here is the first few lines of the txt file</p> <pre><code>m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['comedy', 'romance'] m1 +++$+++ 1492: conquest of paradise +++$+++ 1992 +++$+++ 6.20 +++$+++ 10421 +++$+++ ['adventure', 'biography', 'drama', 'history'] </code></pre> <p>here is my code:</p> <pre class="lang-py prettyprint-override"><code>import re file = open('datasets/movie_titles_metadata.txt') def extract_categories(file): for line in file: line: str = line.rstrip() if re.search(&quot; &quot;, line): line = re.sub(r&quot;[0-9]&quot;, &quot;&quot;, line) line = re.sub(r&quot;[$ + : . ]&quot;, &quot;&quot;, line) return line extract_categories(file) </code></pre> <p>i need to get an out put that looks like this:</p> <p><code>['action', 'comedy', 'crime', 'drama', 'thriller']</code> can someone help?</p>
[ { "answer_id": 74552203, "author": "C.Nivs", "author_id": 7867968, "author_profile": "https://Stackoverflow.com/users/7867968", "pm_score": 1, "selected": false, "text": "str.rsplit from io import StringIO\nimport ast\n\ncontent = \"\"\"m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['comedy', 'romance']\nm1 +++$+++ 1492: conquest of paradise +++$+++ 1992 +++$+++ 6.20 +++$+++ 10421 +++$+++ ['adventure', 'biography', 'drama', 'history']\"\"\"\n\n# this is a mock file-handle, use your file instead here\nwith StringIO(content) as fh:\n genres = []\n\n for line in fh:\n # the 1 means that only 1 split occurs\n _, lst = line.rsplit('+++$+++', 1)\n\n # use ast to convert the string representation\n # to a python list\n lst = ast.literal_eval(lst.strip())\n\n # extend your result list\n genres.extend(lst)\n\nprint(genres)\n['comedy', 'romance', 'adventure', 'biography', 'drama', 'history']\n" }, { "answer_id": 74552419, "author": "Dash", "author_id": 11542834, "author_profile": "https://Stackoverflow.com/users/11542834", "pm_score": 0, "selected": false, "text": "def extract_categories(file):\n categories = []\n\n for line in file:\n _, line = line.rsplit('+++$+++', 1)\n if re.search(r\"\\['[a-z]+\", line):\n res = re.findall(r\"'([a-z]+)'\", line)\n categories.extend(res)\n\n return categories\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585013/" ]
74,552,134
<p>Whenever I create a zip package of my laravel application it stalls for perhaps 10 seconds on a particular file in the .git/objects/1c folder</p> <pre><code>-r--r--r-- 1 root root 267 Sep 3 03:51 2594ce9a9da03d6809e24073d6d108825d5742 -r--r--r-- 1 root root 666746290 Sep 15 17:11 3132aadcdf726d34029ea4cfebd0c4be1da404 -r--r--r-- 1 root root 2394 Nov 17 09:36 3b6e5ba61c50d8c98efa06f0e81d9092510aac </code></pre> <p>This = diskspace quite a bit. I would like to know if it will cause any issues with the application or issues when I do a git push if I delete that file?</p>
[ { "answer_id": 74552282, "author": "acran", "author_id": 11932806, "author_profile": "https://Stackoverflow.com/users/11932806", "pm_score": 1, "selected": false, "text": "git .git/objects/ git .git/objects/ git gc git archive git zip .git/ git" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4001619/" ]
74,552,142
<p>I can use a <code>for</code> loop to loop over two byte sequences and return the index at the first difference of course:</p> <pre><code>bytes1 = b'12345' bytes2 = b'1F345' for index, pair in enumerate(zip(bytes1, bytes2)): if pair[0] != pair[1]: print(index) break </code></pre> <p>But I don't think that's a smart and fast way to do it. I would hope a native method exists that I can call to get this done. Is there something that can help me here? I can also use numpy if it helps.</p> <p>I also want to clarify that this will run many times, with medium sequences. Approximately 300MB is expected, chunked by 100kB. I might be able to change that for larger if it helps significantly.</p>
[ { "answer_id": 74552289, "author": "Ahmed AEK", "author_id": 15649230, "author_profile": "https://Stackoverflow.com/users/15649230", "pm_score": 2, "selected": false, "text": "import numpy as np\nbytes1 = b'12345'\nbytes2 = b'1F345'\nbytes3 = np.frombuffer(bytes1,dtype=np.uint8)\nbytes4 = np.frombuffer(bytes2,dtype=np.uint8)\nmax_loc = np.flatnonzero(bytes3 ^ bytes4)[0]\nprint(max_loc)\n 1\n argmax flatnonzero indexError" }, { "answer_id": 74552780, "author": "dankal444", "author_id": 4601890, "author_profile": "https://Stackoverflow.com/users/4601890", "pm_score": 1, "selected": false, "text": "import numba\n@numba.jit()\ndef method2(bytes1, bytes2):\n idx = 0\n while idx < len(bytes1):\n if bytes1[idx] != bytes2[idx]:\n return idx\n idx += 1\n return idx\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607407/" ]
74,552,158
<p>I have the following SQL query:</p> <pre><code>SELECT `NeighbourhoodName`, count(NAME) as `Number of Parks`, sum(CASE WHEN `parks`.`Advisories` = 'Y' THEN 1 ELSE 0 END) as Advisories, FROM parks GROUP BY `NeighbourhoodName`; </code></pre> <p>In the second line of the code, I create a column called &quot;Number of Parks&quot;. I would like all the values in the next column (Advisories) to be divided by the values in &quot;Number of parks&quot;. However, when I try to insert the division statement after the column like this:</p> <pre><code>SELECT `NeighbourhoodName`, count(NAME) as `Number of Parks`, sum(CASE WHEN `parks`.`Advisories` = 'Y' THEN 1 ELSE 0 END)/`Number of Parks` as Advisories FROM parks GROUP BY `NeighbourhoodName`; </code></pre> <p>I get the following error:</p> <pre><code>Unknown column, `Number of Parks` in field list. </code></pre> <p>How can I perform this division while still keeping it in one query?</p>
[ { "answer_id": 74552202, "author": "Ergest Basha", "author_id": 16461952, "author_profile": "https://Stackoverflow.com/users/16461952", "pm_score": 2, "selected": true, "text": "SELECT `NeighbourhoodName`,\n `Number of Parks`,\n Advisories/`Number of Parks` as Advisories\nFROM ( SELECT `NeighbourhoodName`,\n count(NAME) as `Number of Parks`,\n sum( CASE WHEN `parks`.`Advisories` = 'Y' THEN 1 ELSE 0 END ) as Advisories\n FROM parks\n GROUP BY `NeighbourhoodName`\n ) as tbl;\n" }, { "answer_id": 74552948, "author": "JHH", "author_id": 20127235, "author_profile": "https://Stackoverflow.com/users/20127235", "pm_score": 0, "selected": false, "text": "count(Name) Number of Parks select NeighbourhoodName,\n count(Name) as `Number of Parks`,\n sum(case when Advisories='Y' then 1 else 0 end)\n /count(Name) as Advisories\n from parks\n group by NeighbourhoodName;\n\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18183846/" ]
74,552,180
<p>I am trying to build vectors by checking the values of the data frame. I think I am running into issues checking for the NA condition. What I am trying to accomplish:</p> <p>If index i at vectorA is not NA and index i at vectorB is also not NA then store those values in vectors xp and yp. Else if index i at vectorA is NA but index i at vectorB has a value (and vice versa) then store the values in vectors 3 and 4. When the loop is done I should have 4 vectors xp, yp with complete values. xu will store values where index i in vectorA was not empty but index i at vectorB was empty. yu will store values where index i in vectorA was empty but index i at vectorB was not empty. Essentially xp and yp are paired complete data while xu and yu are incomplete paired data.</p> <p>In the code below I get the following error message, missing value where TRUE/FALSE needed.</p> <pre><code>xp = numeric() yp = numeric() xu = numeric() yu = numeric() m = length(df$Q15) for( i in 1:m) { if(df$Q15[i]!= NA &amp; df$QA[i]!= NA) xp1[i]=df$Q15[i] yp1[i]=df$QA[i] } else{ If(df$Q15[i] != NA &amp; df$QA[i] == NA) xu[i]=df$Q15[i] If(df$Q15i] == NA &amp; df$QA[i] != NA) yu[i]=df$QA[i] } </code></pre> <pre><code>Error in if (df$Q15[i] != NA &amp; df$QA[i] != NA) xp1[i] = df$Q15[i] : missing value where TRUE/FALSE needed </code></pre>
[ { "answer_id": 74552311, "author": "margusl", "author_id": 646761, "author_profile": "https://Stackoverflow.com/users/646761", "pm_score": 2, "selected": false, "text": "NA NA TRUE FALSE if() NA is.na() 123 * NA\n#> [1] NA\nNA == NA\n#> [1] NA\nNA != NA\n#> [1] NA\nNA == TRUE\n#> [1] NA\nNA == FALSE\n#> [1] NA\n\nis.na(NA)\n#> [1] TRUE\n!is.na(NA)\n#> [1] FALSE\n\nis.na(FALSE)\n#> [1] FALSE\n!is.na(FALSE)\n#> [1] TRUE\n" }, { "answer_id": 74552457, "author": "FactOREO", "author_id": 20462305, "author_profile": "https://Stackoverflow.com/users/20462305", "pm_score": 2, "selected": true, "text": "df <- data.frame(QA = sample(c(0L,1L,NA_integer_), size = 15, replace = TRUE, prob = c(0.4,0.4,0.2)),\n Q15= sample(c(0L,1L,NA_integer_), size = 15, replace = TRUE, prob = c(0.2,0.4,0.4)))\n\nxp <- numeric()\nyp <- numeric()\nxu <- numeric()\nyu <- numeric()\n\n# don't do this\n# m = length(df$Q15)\n\nfor( i in seq_along(df$QA)){\n \n ### use is.na() instead of == NA\n if( !is.na(df$Q15[[i]]) & !is.na(df$QA[[i]]) ){\n ### inserted missing brackets\n xp <- c(xp,df$Q15[[i]])\n yp <- c(yp,df$QA[[i]])\n }\n \n if( !is.na(df$Q15[[i]]) & is.na(df$QA[[i]]) ) xu <- c(xu,df$Q15[[i]])\n \n if( !is.na(df$QA[[i]]) & is.na(df$Q15[[i]]) ) yu <- c(yu,df$QA[[i]])\n \n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18980222/" ]
74,552,191
<p>I was trying to copy a repaint() and a paintComponent() method from a tutorial. After I copied the two methods my paintComponent did not get called and so the rectangle is not being showed. Here is my code:</p> <pre><code>public class Main { GameWindow gw; Main() { gw = new GameWindow(); } void start() { gw.setWindow(); } public static void main(String[] args) { new Main().start(); } } import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; public class GameWindow extends JPanel implements Runnable { final int ORIGINAL_TILE_SIZE = 16; final int SCALE = 3; final int TILE_SIZE = ORIGINAL_TILE_SIZE * SCALE; final int MAX_SCREEN_COLUMNS = 16; final int MAX_SCREEN_ROWS = 12; final int SCREEN_WIDTH = TILE_SIZE * MAX_SCREEN_COLUMNS; final int SCREEN_HEIGHT = TILE_SIZE * MAX_SCREEN_ROWS; Thread animation; void setWindow() { JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setResizable(false); window.setTitle(&quot;Avontuur&quot;); window.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); window.getContentPane().setBackground(Color.black); ImageIcon icon = new ImageIcon(&quot;C:\\Users\\Rick\\Desktop\\Star.png&quot;); window.setIconImage(icon.getImage()); window.pack(); window.setLocationRelativeTo(null); window.setVisible(true); startAnimation(); } void startAnimation() { animation = new Thread(this); animation.start(); } @Override public void run() { while (animation != null) { update(); repaint(); } } public void update() { } public void paintComponent(final Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.white); g2.fillRect(100, 100, TILE_SIZE, TILE_SIZE); g2.dispose(); } } </code></pre> <p>I already tried some solutions from stackOverflow, but they did not work or they were not relevant to my problem. Now the code above is what I tried myself using the video, but after using a println in the method I saw it was not getting called. I expected it to work after watching the tutorial, but it didn't. Does anyone know how I can fix this? Thanks in advance!</p>
[ { "answer_id": 74552470, "author": "Kaneda", "author_id": 9411636, "author_profile": "https://Stackoverflow.com/users/9411636", "pm_score": -1, "selected": false, "text": "void setWindow() {\n JFrame window = new JFrame();\n\n window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n window.setResizable(false);\n\n window.setTitle(\"Avontuur\");\n window.add(GameWindow.this);\n window.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));\n window.getContentPane().setBackground(Color.black);\n\n ImageIcon icon = new ImageIcon(\"C:\\\\Users\\\\Rick\\\\Desktop\\\\Star.png\");\n window.setIconImage(icon.getImage());\n window.pack();\n\n window.setLocationRelativeTo(null);\n window.setVisible(true);\n\n startAnimation();\n}\n" }, { "answer_id": 74552944, "author": "MadProgrammer", "author_id": 992484, "author_profile": "https://Stackoverflow.com/users/992484", "pm_score": 1, "selected": false, "text": "Timer import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.EventQueue;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.Timer;\n\npublic class Main {\n\n public static void main(String[] args) {\n new Main();\n }\n\n public Main() {\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n JFrame frame = new JFrame();\n frame.add(new GamePane());\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n });\n }\n\n public class GamePane extends JPanel {\n final int ORIGINAL_TILE_SIZE = 16;\n final int SCALE = 3;\n final int TILE_SIZE = ORIGINAL_TILE_SIZE * SCALE;\n\n final int MAX_SCREEN_COLUMNS = 16;\n final int MAX_SCREEN_ROWS = 12;\n final int SCREEN_WIDTH = TILE_SIZE * MAX_SCREEN_COLUMNS;\n final int SCREEN_HEIGHT = TILE_SIZE * MAX_SCREEN_ROWS;\n\n private Timer timer;\n\n @Override\n public Dimension getPreferredSize() {\n return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);\n }\n\n @Override\n public void addNotify() {\n super.addNotify();\n if (timer != null) {\n timer.stop();\n }\n\n timer = new Timer(5, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n update();\n }\n });\n timer.start();\n }\n\n @Override\n public void removeNotify() {\n super.removeNotify();\n if (timer != null) {\n timer.stop();\n }\n\n }\n\n public void update() {\n System.out.println(\"Updatey update\");\n repaint();\n }\n\n public void paintComponent(final Graphics g) {\n super.paintComponent(g);\n\n System.out.println(\"Painty paint paint\");\n\n Graphics2D g2 = (Graphics2D) g.create();\n\n g2.setColor(Color.white);\n g2.fillRect(100, 100, TILE_SIZE, TILE_SIZE);\n g2.dispose();\n }\n }\n}\n JPanel static" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20583558/" ]
74,552,196
<p>I'm currently working on an ASP.NET Core MVC project.</p> <p>I have a view model which contains a list as:</p> <pre><code>public class CampaignViewModel { public IList&lt;Agency&gt; Agencies { get; set; } } </code></pre> <p>In the controller, I assign that list like this:</p> <pre><code>[HttpGet] public async Task&lt;IActionResult&gt; Create() { var agencies = await _agenciesService.GetAgenciesAsync(); var model = new CampaignViewModel { Agencies = agencies }; } </code></pre> <p><code>GetAgenciesAsync</code> method:</p> <pre><code>public async Task&lt;IList&lt;Agency&gt;&gt; GetAgenciesAsync() { return await _db.Agencies .Include(a =&gt; a.Address) .Include(pc =&gt; pc.PrimaryContact) .Include(ac =&gt; ac.AlternateContact) .ToListAsync(); } </code></pre> <p>Agency model class:</p> <pre><code>public class Agency { public int AgencyId { get; set; } public string Name { get; set; } = string.Empty; ... } </code></pre> <p>Then in my razor view, I want to render it as:</p> <pre><code> @model Lib.ViewModels.Campaigns.CampaignViewModel &lt;select asp-for=&quot;Agencies&quot; asp-items=&quot;Model.Agencies&quot; class=&quot;form-select&quot;&gt;&lt;/select&gt; </code></pre> <p>When I try to run the project, I get an error:</p> <blockquote> <p>Cannot implicitly convert type 'System.Collections.Generic.IEnumerable&lt;Project.Lib.Models.Agency&gt;' to 'System.Collections.Generic.IEnumerable&lt;Microsoft.AspNetCore.Mvc.Rendering.SelectListItem&gt;'. An explicit conversion exists (are you missing a cast?)</p> </blockquote> <p>How can I solve that? Regards</p>
[ { "answer_id": 74553044, "author": "Akin D.", "author_id": 8908754, "author_profile": "https://Stackoverflow.com/users/8908754", "pm_score": 0, "selected": false, "text": "@model CampaignViewModel" }, { "answer_id": 74554922, "author": "Ruikai Feng", "author_id": 18177989, "author_profile": "https://Stackoverflow.com/users/18177989", "pm_score": 2, "selected": true, "text": "IEnumerable<SelectListItem> IEnumerable<Agency> <select asp-for=\"Agencies\" asp-items=\"Model.Agencies.Select(x=>new SelectListItem() { Text=x.Name,Value=x.AgencyId.ToString()})\" class=\"form-select\"></select>\n var vm = new CampaignViewModel() { Agencies = new List<Agency>() { new Agency() { AgencyId = 1, Name = \"SomeName\" }, new Agency() { AgencyId = 2, Name = \"AnotherName\" } } };\n Cannot resolve symbol 'Select' ViewBag.Select = vm.Agencies.Select(x => new SelectListItem() { Text = x.Name, Value = x.AgencyId.ToString() }).ToList();\n asp-items=\"(List<SelectListItem>)ViewBag.Select\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20286048/" ]
74,552,220
<p>I wanted to make two commands that alternate exactly for the specified number of percentages.</p> <p>How to do a command in <code>while</code> that will do only a few percent and if not do a different command.</p> <hr /> <p>I'm trying to create a program to which you give the total number of characters, how many characters it should return and the percentage that determines the ratio between two characters. e.g.</p> <pre class="lang-cs prettyprint-override"><code>decimal r = (decimal)1 / 3 * 100 //r = 33,33...% string output = &quot;&quot;; for (int i = 0; i &lt; 10; i++) { if (r) //go in only on r % { output += &quot;T &quot;; //return 'T' } else { output += &quot;F &quot;; //return 'F' } } Console.WriteLine(output); </code></pre> <p>Output:</p> <pre><code>F F T F F T F F T F </code></pre>
[ { "answer_id": 74552671, "author": "Rufus L", "author_id": 2052655, "author_profile": "https://Stackoverflow.com/users/2052655", "pm_score": 3, "selected": true, "text": "% \"T\" i numChars \\ percent \"T\" 100 33% 100 / 33 == 3 3 \"T\" public static void PrintResults(int numChars, int percentage)\n{\n // In this implementation, 'percentage' is a whole number, like 33\n // Here we determine what the percentage of numChars is\n var percent = numChars * percentage / 100;\n\n // And now we can divide numChars by percent to find out\n // how often we need to display the alternate character\n var occurrence = numChars / percent;\n\n for(int i = 1; i <= numChars; i++)\n {\n // Here we use the remainder operator to determine if this is an \n // occurrence where we should display the alternate character\n if (i % occurrence == 0) Console.Write(\"T \");\n else Console.Write(\"F \");\n }\n\n Console.WriteLine();\n}\n PrintResults(10, 33);\n F F T F F T F F T F \n" }, { "answer_id": 74555159, "author": "Enigmativity", "author_id": 259769, "author_profile": "https://Stackoverflow.com/users/259769", "pm_score": 0, "selected": false, "text": "T F public IEnumerable<char> Pattern(int fs, int ts)\n{\n while (true)\n {\n for (var f = 0; f < fs; f++) yield return 'F';\n for (var t = 0; t < ts; t++) yield return 'T';\n }\n}\n //2 F for every 1 T and take 10 in total.\nstring output = String.Join(\" \", Pattern(2, 1).Take(10));\n F F T F F T F F T F\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15590025/" ]
74,552,265
<p>please refer to the image, when I click on the link on the left partial table, instead of having the values display on a separate partial table view as shown, I'd like the values to be autofilled in the bottom 2 textboxes to avoid having to click and drag the values and to have the date formatted to 01312000 format</p> <p>index.cshtml</p> <pre><code>@page &quot;{id?}&quot; @model IndexModel @{ViewData[&quot;Title&quot;] = &quot;Test&quot;;} &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;text-center&quot;&gt; &lt;h1 class=&quot;display-4&quot;&gt;@Model.PageTitle&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; &lt;form class=&quot;mt-0&quot; method=&quot;get&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-3 offset-1&quot; id=&quot;ApplicationResult&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-4&quot; id=&quot;ApplicationOwnerResult&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-3&quot; id=&quot;ApplicationDmvResult&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; &lt;form class=&quot;mt-0&quot; method=&quot;post&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;label class=&quot;col-2 offset-4 col-form-label&quot;&gt;Date of Birth:&lt;/label&gt; &lt;div class=&quot;col-2&quot;&gt; &lt;input class=&quot;form-control&quot; title=&quot;Date of birth&quot; oninput=&quot;validate()&quot; asp-for=&quot;DateOfBirth&quot;&gt; &lt;span asp-validation-for=&quot;DateOfBirth&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;div class=&quot;row&quot;&gt; &lt;label class=&quot;col-2 offset-4 col-form-label&quot;&gt;Driver's License Number:&lt;/label&gt; &lt;div class=&quot;col-2&quot;&gt; &lt;input class=&quot;form-control&quot; title=&quot;Driver's license number&quot; oninput=&quot;validate()&quot; asp-for=&quot;DriversLicenseNumber&quot;&gt; &lt;span asp-validation-for=&quot;DriversLicenseNumber&quot;&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;div class=&quot;row&quot;&gt; &lt;button class=&quot;btn btn-outline-dark col-1 offset-5&quot; type=&quot;submit&quot; id=&quot;Submit&quot; disabled asp-page-handler=&quot;Submit&quot;&gt;Submit&lt;/button&gt; &amp;nbsp; &lt;button class=&quot;btn btn-outline-dark col-1&quot; type=&quot;button&quot; id=&quot;Reset&quot; onclick=&quot;clearAll()&quot;&gt;Reset&lt;/button&gt; &lt;/div&gt; &lt;br&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; @section Scripts { &lt;script&gt; // Any exemption applications found will be displayed when the page initially loads. On POST request GET form will be hidden $(document).ready(function () { if (&quot;@Model.Exist&quot; == &quot;DivIsVisible&quot;) { $.ajax({ url: &quot;Index/?handler=Display&quot;, type: &quot;GET&quot;, data: { value: @Model.Id }, headers: { RequestVerificationToken: $('input:hidden[name=&quot;__RequestVerificationToken&quot;]').val() }, success: function (data) { $(&quot;#ApplicationResult&quot;).html(data); } }); } else { $(&quot;#ApplicationResult&quot;).hide(); } }); &lt;/script&gt; } </code></pre> <p>index.cshtml.cs</p> <pre><code>using DMVServiceReference; using DMV.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Net.Http; using System.Runtime.Serialization; using System.Threading.Tasks; namespace DMV.Pages { public class IndexModel : PageModel { public Assess50Context _context; // Id property refers to checking the PropertyId value for the URL [BindProperty(SupportsGet = true)] public int Id { get; set; } // Exist property refers to checking if GetDivs exist on POST request [BindProperty] public string PageTitle { get; set; } = &quot;Residency Check&quot;; public ResidencyCheckCriteria CheckCriteria { get; set; } [BindProperty, DataMember, MaxLength(8, ErrorMessage = &quot; &quot;), MinLength(8, ErrorMessage = &quot; &quot;), RegularExpression(@&quot;^([0-9]{8}$)&quot;, ErrorMessage = &quot; &quot;), Required(ErrorMessage = &quot; &quot;)] public string DateOfBirth { get =&gt; CheckCriteria.DateOfBirth; set =&gt; CheckCriteria.DateOfBirth = value; } [BindProperty, DataMember, MaxLength(13, ErrorMessage = &quot; &quot;), MinLength(13, ErrorMessage = &quot; &quot;), RegularExpression(@&quot;^([A-Za-z0-9]{13}$)&quot;, ErrorMessage = &quot; &quot;), Required(ErrorMessage = &quot; &quot;)] public string DriversLicenseNumber { get =&gt; CheckCriteria.DriverLicenseNumber; set =&gt; CheckCriteria.DriverLicenseNumber = value; } [BindProperty(SupportsGet = true)] public string Exist { get; set; } = &quot;DivIsVisible&quot;; public IndexModel(Assess50Context context) { _context = context; CheckCriteria = new ResidencyCheckCriteria(); } // Reads all exemption application table information by property id public PartialViewResult OnGetDisplay(int value) =&gt; Partial(&quot;_DisplayApplicationPartial&quot;, _context.ExemptionApplications.Where(x =&gt; x.PropertyId == value).ToList()); // Reads all exemption application owner information by exemption application id public PartialViewResult OnGetDisplayOwner(int value) =&gt; Partial(&quot;_DisplayOwnerPartial&quot;, _context.ExemptionApplicationOwners.Where(x =&gt; x.ExemptionApplicationId == value).GroupBy(x =&gt; x.ExemptionApplicationOwnerId).Select(x =&gt; x.First()).ToList()); // Reads the dmv information by application owner ID public PartialViewResult OnGetDisplayOwnerInfo(int value) =&gt; Partial(&quot;_DisplayDMVPartial&quot;, _context.ExemptionApplicationDmvinformations.Where(x =&gt; x.ExemptionApplicationOwnerId == value).ToList()); </code></pre> <p>DbContext.cs</p> <pre><code>using Microsoft.EntityFrameworkCore; namespace DMV.Models { public partial class Assess50Context : DbContext { public virtual DbSet&lt;ExemptionApplication&gt; ExemptionApplications { get; set; } = null!; public virtual DbSet&lt;ExemptionApplicationDmvinformation&gt; ExemptionApplicationDmvinformations { get; set; } = null!; public virtual DbSet&lt;ExemptionApplicationOwner&gt; ExemptionApplicationOwners { get; set; } = null!; public Assess50Context() {} public Assess50Context(DbContextOptions&lt;Assess50Context&gt; options) : base(options) {} protected override void OnModelCreating(ModelBuilder modelBuilder) { } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } } </code></pre> <p>Application.cs model</p> <pre><code>using System; using System.ComponentModel.DataAnnotations; namespace DMV.Models { public partial class ExemptionApplication { public int PropertyId { get; set; } [Display(Name = &quot;Year&quot;)] public short YearId { get; set; } [Display(Name = &quot;App ID&quot;)] public int ExemptionApplicationId { get; set; } [Display(Name = &quot;Reference Number&quot;)] public string? ApplicationReference { get; set; } } } </code></pre> <p>Owner.cs model</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DMV.Models { public partial class ExemptionApplicationOwner { public int PropertyId { get; set; } public int ExemptionApplicationId { get; set; } [Display(Name = &quot;Application Owner ID&quot;)] public int ExemptionApplicationOwnerId { get; set; } [Display(Name = &quot;Owner ID&quot;)] public int? OwnerId { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } [Display(Name = &quot;Name&quot;)]public string? AssessProName { get; set; } } } </code></pre> <p>DmvInformation.cs model</p> <pre><code>using SoapCore.ServiceModel; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DMV.Models { public partial class ExemptionApplicationDmvinformation { public int PropertyId { get; set; } public int ExemptionApplicationId { get; set; } public int ExemptionApplicationOwnerId { get; set; } [Display(Name = &quot;DOB&quot;)] public DateTime? DmvDob { get; set; } [Display(Name = &quot;Driver's License #&quot;)] public string? DriverLicense { get; set; } } } </code></pre> <p>_DisplayApplicationPartial.cshtml</p> <pre><code>@model IEnumerable&lt;Models.ExemptionApplication&gt; @if (Model.Count() != 0) { &lt;div id=&quot;ExemptionApplicationNav&quot;&gt; &lt;table class=&quot;PartialTable&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class=&quot;PartialTableRowData&quot; colspan=&quot;3&quot;&gt;Exemption Applications&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class=&quot;PartialTableRowCategoryData&quot;&gt;@Html.DisplayNameFor(m =&gt; m.YearId)&lt;/td&gt; &lt;td class=&quot;PartialTableRowCategoryData&quot;&gt;@Html.DisplayNameFor(m =&gt; m.ApplicationReference)&lt;/td&gt; &lt;td class=&quot;PartialTableRowCategoryData&quot;&gt;@Html.DisplayNameFor(m =&gt; m.ExemptionApplicationId)&lt;/td&gt; &lt;/tr&gt; @foreach (Models.ExemptionApplication item in Model) { &lt;tr&gt; &lt;td class=&quot;PartialTableRowData&quot;&gt;@item.YearId&lt;/td&gt; &lt;td class=&quot;PartialTableRowData&quot;&gt;@item.ApplicationReference&lt;/td&gt; &lt;td class=&quot;PartialTableRowData&quot;&gt; &lt;a class=&quot;DMVLabelsTexts&quot; href=&quot;Index/?handler=DisplayOwner&amp;value=@item.ExemptionApplicationId&quot;&gt;@item.ExemptionApplicationId&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; } else { &lt;p&gt;No exemption applications found for this Property ID&lt;/p&gt; } &lt;script&gt; $('#ExemptionApplicationNav a').click(function (e) { $('#ApplicationOwnerResult').hide().load($(this).attr('href'), function () { $('#ApplicationOwnerResult').show() }) return false }) &lt;/script&gt; </code></pre> <p>_DisplayOwnerPartial.cshtml</p> <pre><code>@model IEnumerable&lt;Models.ExemptionApplicationOwner&gt; @if (Model.Count() != 0) { &lt;div id=&quot;OwnerNav&quot;&gt; &lt;table class=&quot;PartialTable&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class=&quot;PartialTableRowData&quot; colspan=&quot;3&quot;&gt;Owner Information&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class=&quot;PartialTableRowCategoryData&quot;&gt;@Html.DisplayNameFor(m =&gt; m.ExemptionApplicationOwnerId)&lt;/td&gt; &lt;td class=&quot;PartialTableRowCategoryData&quot; colspan=&quot;2&quot;&gt;@Html.DisplayNameFor(m =&gt; m.AssessProName)&lt;/td&gt; &lt;/tr&gt; @foreach (Models.ExemptionApplicationOwner item in Model) { &lt;tr&gt; &lt;td class=&quot;PartialTableRowData&quot;&gt; &lt;a class=&quot;DMVLabelsTexts&quot; href=&quot;Index/?handler=DisplayOwnerInfo&amp;value=@item.ExemptionApplicationOwnerId&quot;&gt;@item.ExemptionApplicationOwnerId&lt;/a&gt; &lt;/td&gt; &lt;td class=&quot;PartialTableRowMultipleData&quot;&gt;@item.FirstName&lt;/td&gt; &lt;td class=&quot;PartialTableRowMultipleData&quot;&gt;@item.LastName&lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; } else { &lt;p&gt;No owner data available&lt;/p&gt; } &lt;script&gt; $('#OwnerNav a').click(function (e) { $('#ApplicationDmvResult').hide().load($(this).attr('href'), function () { $('#ApplicationDmvResult').show() }) return false }) &lt;/script&gt; </code></pre> <p>_DisplayDMVPartial.cshtml</p> <pre><code>@model IEnumerable&lt;Models.ExemptionApplicationDmvinformation&gt; @if (Model.Count() != 0) { &lt;div id=&quot;DmvNav&quot;&gt; &lt;table style=&quot; border: 1px solid black;&quot;&gt; &lt;thead&gt; &lt;tr&gt; &lt;th colspan=&quot;2&quot; style=&quot;border: 1px solid black; text-align: center;&quot;&gt;DMV Information&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style=&quot;border: 1px solid black; font-weight: bold; text-align: center;&quot;&gt;@Html.DisplayNameFor(m =&gt; m.DmvDob)&lt;/td&gt; &lt;td style=&quot;border: 1px solid black; font-weight: bold; text-align: center;&quot;&gt;@Html.DisplayNameFor(m =&gt; m.DriverLicense)&lt;/td&gt; &lt;/tr&gt; @foreach (Models.ExemptionApplicationDmvinformation item in Model) { &lt;tr&gt; &lt;!-- &lt;td style=&quot;border: 1px solid black; text-align: center;&quot;&gt;item.DmvDob.Value.ToString(&quot;MMddyyyy&quot;)&lt;/td&gt; --&gt; &lt;td style=&quot;border: 1px solid black; text-align: center;&quot;&gt;@item.DmvDob&lt;/td&gt; &lt;td style=&quot;border: 1px solid black; text-align: center;&quot;&gt;@item.DriverLicense&lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; } else { &lt;p&gt;No owner data available&lt;/p&gt; } </code></pre> <p><a href="https://i.stack.imgur.com/wQOiS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wQOiS.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74552671, "author": "Rufus L", "author_id": 2052655, "author_profile": "https://Stackoverflow.com/users/2052655", "pm_score": 3, "selected": true, "text": "% \"T\" i numChars \\ percent \"T\" 100 33% 100 / 33 == 3 3 \"T\" public static void PrintResults(int numChars, int percentage)\n{\n // In this implementation, 'percentage' is a whole number, like 33\n // Here we determine what the percentage of numChars is\n var percent = numChars * percentage / 100;\n\n // And now we can divide numChars by percent to find out\n // how often we need to display the alternate character\n var occurrence = numChars / percent;\n\n for(int i = 1; i <= numChars; i++)\n {\n // Here we use the remainder operator to determine if this is an \n // occurrence where we should display the alternate character\n if (i % occurrence == 0) Console.Write(\"T \");\n else Console.Write(\"F \");\n }\n\n Console.WriteLine();\n}\n PrintResults(10, 33);\n F F T F F T F F T F \n" }, { "answer_id": 74555159, "author": "Enigmativity", "author_id": 259769, "author_profile": "https://Stackoverflow.com/users/259769", "pm_score": 0, "selected": false, "text": "T F public IEnumerable<char> Pattern(int fs, int ts)\n{\n while (true)\n {\n for (var f = 0; f < fs; f++) yield return 'F';\n for (var t = 0; t < ts; t++) yield return 'T';\n }\n}\n //2 F for every 1 T and take 10 in total.\nstring output = String.Join(\" \", Pattern(2, 1).Take(10));\n F F T F F T F F T F\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9748930/" ]
74,552,268
<p>Imagine you have the following data set:</p> <pre><code> df = data.frame(ID = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20), gender= c(1,2,1,2,2,2,2,1,1,2,1,2,1,2,2,2,2,1,1,2), PID = c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10)) </code></pre> <p>how can I write a code that removes the rows in the df whose gender and PID are the same (see picture). Please imagine that the code is over 1000 rows long (so it should be a solution that automatically searches for the right values to exclude).</p> <p><img src="https://i.stack.imgur.com/ERFbS.png" alt="enter image description here" /></p>
[ { "answer_id": 74552294, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "df[ave(rep(TRUE, nrow(df)), df[,c(\"gender\",\"paar\")], FUN = function(z) !any(duplicated(z))),]\n# ID gender paar\n# 1 1 1 1\n# 2 2 2 1\n# 3 3 1 2\n# 4 4 2 2\n# 7 7 2 4\n# 8 8 1 4\n# 9 9 1 5\n# 10 10 2 5\n# 11 11 1 6\n# 12 12 2 6\n# 13 13 1 7\n# 14 14 2 7\n# 17 17 2 9\n# 18 18 1 9\n# 19 19 1 10\n# 20 20 2 10\n library(dplyr)\ndf %>%\n group_by(gender, paar) %>%\n filter(!any(duplicated(cbind(gender, paar)))) %>%\n ungroup()\n" }, { "answer_id": 74552297, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "base R subset subset(df, ave(seq_along(gender), gender, paar, FUN = length) == 1)\n duplicated df[!(duplicated(df[-1])|duplicated(df[-1], fromLast = TRUE)),]\n ID gender paar\n1 1 1 1\n2 2 2 1\n3 3 1 2\n4 4 2 2\n7 7 2 4\n8 8 1 4\n9 9 1 5\n10 10 2 5\n11 11 1 6\n12 12 2 6\n13 13 1 7\n14 14 2 7\n17 17 2 9\n18 18 1 9\n19 19 1 10\n20 20 2 10\n" }, { "answer_id": 74552334, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "aggregate na.omit(aggregate(. ~ gender + PID, df, function(x) \n ifelse(length(x) == 1, x, NA)))\n gender PID ID\n1 1 1 1\n2 2 1 2\n3 1 2 3\n4 2 2 4\n6 1 4 8\n7 2 4 7\n8 1 5 9\n9 2 5 10\n10 1 6 11\n11 2 6 12\n12 1 7 13\n13 2 7 14\n15 1 9 18\n16 2 9 17\n17 1 10 19\n18 2 10 20\n dplyr library(dplyr)\n\ndf %>% \n group_by(gender, PID) %>% \n filter(n() == 1) %>% \n ungroup()\n# A tibble: 16 × 3\n ID gender PID\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 2 2 1\n 3 3 1 2\n 4 4 2 2\n 5 7 2 4\n 6 8 1 4\n 7 9 1 5\n 8 10 2 5\n 9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n" }, { "answer_id": 74552406, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 1, "selected": false, "text": "dplyr df %>%\n filter(with(rle(paste0(gender, PID)), rep(lengths == 1, lengths)))\n\n ID gender PID\n1 1 1 1\n2 2 2 1\n3 3 1 2\n4 4 2 2\n5 7 2 4\n6 8 1 4\n7 9 1 5\n8 10 2 5\n9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n df %>%\n arrange(gender, PID) %>%\n filter(with(rle(paste0(gender, PID)), rep(lengths == 1, lengths)))\n" }, { "answer_id": 74552446, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndf %>%\n group_by(gender, PID) %>% \n filter(is.na(ifelse(n()>1, 1, NA))) \n ID gender PID\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 2 2 1\n 3 3 1 2\n 4 4 2 2\n 5 7 2 4\n 6 8 1 4\n 7 9 1 5\n 8 10 2 5\n 9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19743239/" ]
74,552,274
<p>I receive a syntax error for the following:</p> <pre><code>CREATE OR REPLACE FUNCTION my_function(old_num INTEGER) returns INTEGER language plpgsql AS $$ DECLARE new_num INTEGER; BEGIN CASE WHEN (old_num IN (1, 2, 3, 4)) THEN new_num = 10 WHEN (old_num IN (5, 6, 7, 8)) THEN new_num = 20 ELSE new_num = 0 END; RETURN new_num; END; $$; </code></pre> <p>The error points to the second WHEN. I've tried using all kinds of combinations of parenthesis. What is wrong with this syntax??</p>
[ { "answer_id": 74552294, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "df[ave(rep(TRUE, nrow(df)), df[,c(\"gender\",\"paar\")], FUN = function(z) !any(duplicated(z))),]\n# ID gender paar\n# 1 1 1 1\n# 2 2 2 1\n# 3 3 1 2\n# 4 4 2 2\n# 7 7 2 4\n# 8 8 1 4\n# 9 9 1 5\n# 10 10 2 5\n# 11 11 1 6\n# 12 12 2 6\n# 13 13 1 7\n# 14 14 2 7\n# 17 17 2 9\n# 18 18 1 9\n# 19 19 1 10\n# 20 20 2 10\n library(dplyr)\ndf %>%\n group_by(gender, paar) %>%\n filter(!any(duplicated(cbind(gender, paar)))) %>%\n ungroup()\n" }, { "answer_id": 74552297, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "base R subset subset(df, ave(seq_along(gender), gender, paar, FUN = length) == 1)\n duplicated df[!(duplicated(df[-1])|duplicated(df[-1], fromLast = TRUE)),]\n ID gender paar\n1 1 1 1\n2 2 2 1\n3 3 1 2\n4 4 2 2\n7 7 2 4\n8 8 1 4\n9 9 1 5\n10 10 2 5\n11 11 1 6\n12 12 2 6\n13 13 1 7\n14 14 2 7\n17 17 2 9\n18 18 1 9\n19 19 1 10\n20 20 2 10\n" }, { "answer_id": 74552334, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "aggregate na.omit(aggregate(. ~ gender + PID, df, function(x) \n ifelse(length(x) == 1, x, NA)))\n gender PID ID\n1 1 1 1\n2 2 1 2\n3 1 2 3\n4 2 2 4\n6 1 4 8\n7 2 4 7\n8 1 5 9\n9 2 5 10\n10 1 6 11\n11 2 6 12\n12 1 7 13\n13 2 7 14\n15 1 9 18\n16 2 9 17\n17 1 10 19\n18 2 10 20\n dplyr library(dplyr)\n\ndf %>% \n group_by(gender, PID) %>% \n filter(n() == 1) %>% \n ungroup()\n# A tibble: 16 × 3\n ID gender PID\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 2 2 1\n 3 3 1 2\n 4 4 2 2\n 5 7 2 4\n 6 8 1 4\n 7 9 1 5\n 8 10 2 5\n 9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n" }, { "answer_id": 74552406, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 1, "selected": false, "text": "dplyr df %>%\n filter(with(rle(paste0(gender, PID)), rep(lengths == 1, lengths)))\n\n ID gender PID\n1 1 1 1\n2 2 2 1\n3 3 1 2\n4 4 2 2\n5 7 2 4\n6 8 1 4\n7 9 1 5\n8 10 2 5\n9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n df %>%\n arrange(gender, PID) %>%\n filter(with(rle(paste0(gender, PID)), rep(lengths == 1, lengths)))\n" }, { "answer_id": 74552446, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndf %>%\n group_by(gender, PID) %>% \n filter(is.na(ifelse(n()>1, 1, NA))) \n ID gender PID\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 2 2 1\n 3 3 1 2\n 4 4 2 2\n 5 7 2 4\n 6 8 1 4\n 7 9 1 5\n 8 10 2 5\n 9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18774863/" ]
74,552,292
<p>I would want to get the stdout of the python file into shell script. I initially used print and it worked fine but it is not working for logging.</p> <p>ab.py</p> <pre><code>import logging logger = logging.getLogger() logging.basicConfig(level=logging.INFO) logging.info('2222222222222') print(&quot;111111111111&quot;) </code></pre> <p>cd.sh</p> <pre><code>#/bin/bash set -e set -x communities=$(python3 ab.py) echo $communities </code></pre> <p>The output of executing cd.sh I am getting the output only as 111111111111 and not 2222222222222</p>
[ { "answer_id": 74552294, "author": "r2evans - GO NAVY BEAT ARMY", "author_id": 3358272, "author_profile": "https://Stackoverflow.com/users/3358272", "pm_score": 2, "selected": false, "text": "df[ave(rep(TRUE, nrow(df)), df[,c(\"gender\",\"paar\")], FUN = function(z) !any(duplicated(z))),]\n# ID gender paar\n# 1 1 1 1\n# 2 2 2 1\n# 3 3 1 2\n# 4 4 2 2\n# 7 7 2 4\n# 8 8 1 4\n# 9 9 1 5\n# 10 10 2 5\n# 11 11 1 6\n# 12 12 2 6\n# 13 13 1 7\n# 14 14 2 7\n# 17 17 2 9\n# 18 18 1 9\n# 19 19 1 10\n# 20 20 2 10\n library(dplyr)\ndf %>%\n group_by(gender, paar) %>%\n filter(!any(duplicated(cbind(gender, paar)))) %>%\n ungroup()\n" }, { "answer_id": 74552297, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 1, "selected": false, "text": "base R subset subset(df, ave(seq_along(gender), gender, paar, FUN = length) == 1)\n duplicated df[!(duplicated(df[-1])|duplicated(df[-1], fromLast = TRUE)),]\n ID gender paar\n1 1 1 1\n2 2 2 1\n3 3 1 2\n4 4 2 2\n7 7 2 4\n8 8 1 4\n9 9 1 5\n10 10 2 5\n11 11 1 6\n12 12 2 6\n13 13 1 7\n14 14 2 7\n17 17 2 9\n18 18 1 9\n19 19 1 10\n20 20 2 10\n" }, { "answer_id": 74552334, "author": "Andre Wildberg", "author_id": 9462095, "author_profile": "https://Stackoverflow.com/users/9462095", "pm_score": 1, "selected": false, "text": "aggregate na.omit(aggregate(. ~ gender + PID, df, function(x) \n ifelse(length(x) == 1, x, NA)))\n gender PID ID\n1 1 1 1\n2 2 1 2\n3 1 2 3\n4 2 2 4\n6 1 4 8\n7 2 4 7\n8 1 5 9\n9 2 5 10\n10 1 6 11\n11 2 6 12\n12 1 7 13\n13 2 7 14\n15 1 9 18\n16 2 9 17\n17 1 10 19\n18 2 10 20\n dplyr library(dplyr)\n\ndf %>% \n group_by(gender, PID) %>% \n filter(n() == 1) %>% \n ungroup()\n# A tibble: 16 × 3\n ID gender PID\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 2 2 1\n 3 3 1 2\n 4 4 2 2\n 5 7 2 4\n 6 8 1 4\n 7 9 1 5\n 8 10 2 5\n 9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n" }, { "answer_id": 74552406, "author": "tmfmnk", "author_id": 5964557, "author_profile": "https://Stackoverflow.com/users/5964557", "pm_score": 1, "selected": false, "text": "dplyr df %>%\n filter(with(rle(paste0(gender, PID)), rep(lengths == 1, lengths)))\n\n ID gender PID\n1 1 1 1\n2 2 2 1\n3 3 1 2\n4 4 2 2\n5 7 2 4\n6 8 1 4\n7 9 1 5\n8 10 2 5\n9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n df %>%\n arrange(gender, PID) %>%\n filter(with(rle(paste0(gender, PID)), rep(lengths == 1, lengths)))\n" }, { "answer_id": 74552446, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 1, "selected": false, "text": "library(dplyr)\ndf %>%\n group_by(gender, PID) %>% \n filter(is.na(ifelse(n()>1, 1, NA))) \n ID gender PID\n <dbl> <dbl> <dbl>\n 1 1 1 1\n 2 2 2 1\n 3 3 1 2\n 4 4 2 2\n 5 7 2 4\n 6 8 1 4\n 7 9 1 5\n 8 10 2 5\n 9 11 1 6\n10 12 2 6\n11 13 1 7\n12 14 2 7\n13 17 2 9\n14 18 1 9\n15 19 1 10\n16 20 2 10\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7802216/" ]
74,552,491
<p>I have a dataset where the columns are different sites and the latitude and longitude values are provided in the first two rows. I want to transpose this data, so that each site is now a row with the latitude and longitude values in the columns.</p> <p>I'm trying to do this with <code>pivot_longer</code>, but have not been successful to date, as I'm unclear from the examples how to indicate which fields should be the new rows and columns.</p> <pre><code>df &lt;- data.frame( sites = c(&quot;lat&quot;, &quot;lon&quot;), A = c(10, 20), B = c(12, 18), C = c(14, 17), D = c(21, 12), E = c(3, 23)) %&gt;% # transpose with sites in 1st column (A-E on different rows) and lat/lon values in seperate columns pivot_longer(cols = c(2:6), names_to = c(&quot;lat&quot;, &quot;lon&quot;), values_to = &quot;sites&quot;) Error in `build_longer_spec()`: ! If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`. Run `rlang::last_error()` to see where the error occurred. </code></pre>
[ { "answer_id": 74552522, "author": "akrun", "author_id": 3732271, "author_profile": "https://Stackoverflow.com/users/3732271", "pm_score": 4, "selected": true, "text": "transpose library(data.table)\ndata.table::transpose(setDT(df), make.names = \"sites\")\n lat lon\n <num> <num>\n1: 10 20\n2: 12 18\n3: 14 17\n4: 21 12\n5: 3 23\n data.table::transpose(setDT(df), make.names = \"sites\", keep.names = \"grp\")\n grp lat lon\n <char> <num> <num>\n1: A 10 20\n2: B 12 18\n3: C 14 17\n4: D 21 12\n5: E 3 23\n tidyverse pivot_wider library(dplyr)\nlibrary(tidyr)\ndf %>% \n pivot_longer(cols = -sites, names_to = 'grp') %>% \n pivot_wider(names_from = sites, values_from = value)\n# A tibble: 5 × 3\n grp lat lon\n <chr> <dbl> <dbl>\n1 A 10 20\n2 B 12 18\n3 C 14 17\n4 D 21 12\n5 E 3 23\n" }, { "answer_id": 74552592, "author": "TarJae", "author_id": 13321647, "author_profile": "https://Stackoverflow.com/users/13321647", "pm_score": 2, "selected": false, "text": "dplyr janitor row_to_names library(janitor)\nlibrary(dplyr)\n\ndf %>% \n t() %>% \n row_to_names(row_number = 1) %>% \n type.convert(as.is=TRUE)\n lat lon\nA 10 20\nB 12 18\nC 14 17\nD 21 12\nE 3 23\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3220999/" ]
74,552,511
<p>The three-digit number changes first, then the letters from right to left. So, first plate is AA 000 AA, followed by AA 001 AA...AA 999 AA, then AA 000 AB to AA 999 AZ, then AA 000 BA to AA 999 ZZ, then AB 000 AA to AZ 999 ZZ, then BA 000 AA to ZZ 999 ZZ.</p>
[ { "answer_id": 74552825, "author": "Mark", "author_id": 2203038, "author_profile": "https://Stackoverflow.com/users/2203038", "pm_score": -1, "selected": false, "text": "digits = [ \n # value, init, count, suffix, order \n [ 'A', 'A', 26 , '', 6], \n [ 'A', 'A', 26 , ' ', 5], \n [ '0', '0', 10, '', 2 ], \n [ '0', '0', 10, '', 1 ], \n [ '0', '0', 10, ' ', 0 ], \n [ 'A', 'A', 26 , '', 4], \n [ 'A', 'A', 26 , '', 3], \n]\n\ndef plate(digits):\n out = []\n for item in digits:\n out.append( item[0] )\n out.append( item[3] )\n\n return ''.join(out)\n\ndef increment(digits):\n digits = sorted(digits, key = lambda x : x[-1] )\n for item in digits:\n v = ord(item[0]) + 1 \n item[0] = chr(v) \n if v < ord(item[1]) + item[2]:\n break\n item[0] = item[1]\n \n \n \n \n\nvalue = plate( digits ) \nwhile value != 'ZZ 999 ZZ':\n print(value)\n increment(digits)\n value = plate( digits ) \nprint(value)\n" }, { "answer_id": 74552921, "author": "Yevhen Kuzmovych", "author_id": 4727702, "author_profile": "https://Stackoverflow.com/users/4727702", "pm_score": 1, "selected": true, "text": "for from string import ascii_uppercase as letters\n\nfor l1 in letters:\n for l2 in letters:\n for l3 in letters:\n for l4 in letters:\n for i in range(1000):\n print(f'{l1}{l2} {i:03d} {l3}{l4}')\n" }, { "answer_id": 74553099, "author": "treuss", "author_id": 19838568, "author_profile": "https://Stackoverflow.com/users/19838568", "pm_score": 0, "selected": false, "text": "def numberplate(i):\n chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" # Remove invalid ones\n c = len(chars)\n return chars[i//1000//c**3] + chars[(i//1000%c**3)//c**2] + \"{:03d}\".format(i%1000) + chars[(i//1000%c**2)//c] + chars[i//(1000)%c**1]\n\nprint(numberplate(0))\nprint(numberplate(456))\nprint(numberplate(1000))\nprint(numberplate(1335))\nprint(numberplate(1000*26**4-1))\n\n# The below will run for a while...\nfor i in range(1000*26**4):\n print(numberplate(i))\n ascii_uppercase" }, { "answer_id": 74553499, "author": "0x0fba", "author_id": 20339407, "author_profile": "https://Stackoverflow.com/users/20339407", "pm_score": 1, "selected": false, "text": "from string import ascii_uppercase\nfrom itertools import product\n\nplate_gen = (f\"{l1}{l2} {n:03d} {l3}{l4}\" for l1, l2, n, l3, l4 in product(ascii_uppercase, ascii_uppercase, range(1000), ascii_uppercase, ascii_uppercase))\n for plate in plate_gen:\n print(plate)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20581749/" ]
74,552,516
<p>I need for the navbar to show when the user logs into homepage/site in ReactJS?</p> <p>I tried to use a turnary method but it did not work successfully.</p> <p>take a look at my code in github: <a href="https://github.com/Brian-Tech-20s/Music-Essentials.git" rel="nofollow noreferrer">https://github.com/Brian-Tech-20s/Music-Essentials.git</a> (components/navbar.jsx)</p>
[ { "answer_id": 74552575, "author": "Finn", "author_id": 16952372, "author_profile": "https://Stackoverflow.com/users/16952372", "pm_score": -1, "selected": false, "text": "&& export default function App() {\n return (\n <div className=\"App\">\n {isLoggedIn && <Navbar/>}\n </div>\n );\n}\n export default function Navbar(props) {\n /* ... */\n return (\n <div className=\"navabar\">\n {isLoggedIn ? loginButton() : logoutButton()}</div>\n </div>\n );\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12713469/" ]
74,552,533
<p>I am trying to manipulate my list through the append function.</p> <p>Here is what i got:</p> <pre><code>list_all = [] list_gen = ['male', 'DEAN', 'SAM', 'JASON'] list_all.append(list_gen) list_gen = ['female', 'LARA', 'SUSI'] list_all.append(list_gen) a_list = [] b_list = [] for x in list_all: a_list.append(x[:1]) a_list.append(x[1:]) b_list.append(a_list) a_list.clear() print(b_list) </code></pre> <p>Result: [[], []]</p> <p>What i want: [[['male'], ['DEAN', 'SAM', 'JASON']], [['female'], ['LARA', 'SUSI']]]</p> <p>what am i doing wrong?</p>
[ { "answer_id": 74552575, "author": "Finn", "author_id": 16952372, "author_profile": "https://Stackoverflow.com/users/16952372", "pm_score": -1, "selected": false, "text": "&& export default function App() {\n return (\n <div className=\"App\">\n {isLoggedIn && <Navbar/>}\n </div>\n );\n}\n export default function Navbar(props) {\n /* ... */\n return (\n <div className=\"navabar\">\n {isLoggedIn ? loginButton() : logoutButton()}</div>\n </div>\n );\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585206/" ]
74,552,543
<pre><code>function sendEmails() { const sheet = getSpreadsheetApp() const sheetData = getSpreadsheetData(sheet).getValues(); const subjectline = &quot;Weekly Breakdown for the week of - &quot; var subjectDate = Browser.inputBox('Please enter the date range for e-mail subject.', Browser.Buttons.OK_CANCEL); if(Browser.Buttons.CANCEL = true) { Browser.msgBox('The operation has been cancelled') return; } const subject = subjectline + subjectDate </code></pre> <p>In the below code, even if I'm clicking OK by inputting the details to the input box,It gives me the same message box and stops running the script.</p>
[ { "answer_id": 74552575, "author": "Finn", "author_id": 16952372, "author_profile": "https://Stackoverflow.com/users/16952372", "pm_score": -1, "selected": false, "text": "&& export default function App() {\n return (\n <div className=\"App\">\n {isLoggedIn && <Navbar/>}\n </div>\n );\n}\n export default function Navbar(props) {\n /* ... */\n return (\n <div className=\"navabar\">\n {isLoggedIn ? loginButton() : logoutButton()}</div>\n </div>\n );\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20372911/" ]
74,552,547
<p>In K8s i'm practising the example <em>6.1. A pod with two containers sharing the same volume: fortune-pod.yaml</em> from the book <strong>kubernetes in Action</strong>. In volumes concept where my pod contain 2 containers, one of the containers is not running, Please guide me where i'm doing wrong. to run the pod successfully. on checking the logs of the container i'm getting the below error:</p> <pre><code>Defaulted container &quot;fortune-cont&quot; out of: fortune-cont, web-server </code></pre> <p>But where as in pod description events it looks like this.</p> <pre><code>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 40m default-scheduler Successfully assigned book/vol-1-fd556f5dc-8ggj6 to minikube Normal Pulled 40m kubelet Container image &quot;nginx:alpine&quot; already present on machine Normal Created 40m kubelet Created container web-server Normal Started 40m kubelet Started container web-server Normal Created 39m (x4 over 40m) kubelet Created container fortune-cont Normal Started 39m (x4 over 40m) kubelet Started container fortune-cont Normal Pulled 38m (x5 over 40m) kubelet Container image &quot;xxxx/fortune:v1&quot; already present on machine Warning BackOff 25s (x188 over 40m) kubelet Back-off restarting failed container </code></pre> <p>here is my deployment file</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: vol-1 namespace: book spec: replicas: 1 selector: matchLabels: name: fortune-vol-1 type: volume template: metadata: labels: name: fortune-vol-1 type: volume spec: containers: - image: ****/fortune:v1 name: fortune-cont volumeMounts: - name: html mountPath: /var/htdocs - image: nginx:alpine name: web-server volumeMounts: - name: html mountPath: /usr/share/nginx/html readOnly: true ports: - containerPort: 80 protocol: TCP volumes: - name: html emptyDir: {} </code></pre> <p>Here is my pod description for containers.</p> <pre><code>Containers: fortune-cont: Container ID: docker://3959e47a761b670ee826b2824efed09d8f5d6dfd6451c4c9840eebff018a3586 Image: prav33n/fortune:v1 Image ID: docker-pullable://prav33n/fortune@sha256:671257f6387a1ef81a293f8aef27ad7217e4281e30b777a7124b1f6017a330f8 Port: &lt;none&gt; Host Port: &lt;none&gt; State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Thu, 24 Nov 2022 02:05:26 +0530 Finished: Thu, 24 Nov 2022 02:05:26 +0530 Ready: False Restart Count: 17 Environment: &lt;none&gt; Mounts: /var/htdocs from html (rw) /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-spdq4 (ro) web-server: Container ID: docker://37d831a2f7e97abadb548a21ecb20b5c784b5b3d6102cf8f939f2c13cdfd08c0 Image: nginx:alpine Image ID: docker-pullable://nginx@sha256:455c39afebd4d98ef26dd70284aa86e6810b0485af5f4f222b19b89758cabf1e Port: 80/TCP Host Port: 0/TCP State: Running Started: Thu, 24 Nov 2022 01:02:55 +0530 Ready: True Restart Count: 0 Environment: &lt;none&gt; Mounts: /usr/share/nginx/html from html (ro) /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-spdq4 (ro) Conditions: Type Status Initialized True Ready False ContainersReady False PodScheduled True Volumes: html: Type: EmptyDir (a temporary directory that shares a pod's lifetime) Medium: SizeLimit: &lt;unset&gt; kube-api-access-spdq4: Type: Projected (a volume that contains injected data from multiple sources) TokenExpirationSeconds: 3607 ConfigMapName: kube-root-ca.crt ConfigMapOptional: &lt;nil&gt; DownwardAPI: true QoS Class: BestEffort Node-Selectors: &lt;none&gt; Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s node.kubernetes.io/unreachable:NoExecute op=Exists for 300s Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning BackOff 4m20s (x281 over 64m) kubelet Back-off restarting failed container </code></pre>
[ { "answer_id": 74552575, "author": "Finn", "author_id": 16952372, "author_profile": "https://Stackoverflow.com/users/16952372", "pm_score": -1, "selected": false, "text": "&& export default function App() {\n return (\n <div className=\"App\">\n {isLoggedIn && <Navbar/>}\n </div>\n );\n}\n export default function Navbar(props) {\n /* ... */\n return (\n <div className=\"navabar\">\n {isLoggedIn ? loginButton() : logoutButton()}</div>\n </div>\n );\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12569410/" ]
74,552,549
<p>I'd like to have a variable that can be either a React component or a string, like this:</p> <pre><code>function MyComponent(): JSX.Element { let icon: JSX.Element | string = &quot;/example.png&quot;; // (simplified) return &lt;div&gt;{typeof icon === &quot;JSX.Element&quot; ? icon : &lt;img src={icon} /&gt;}&lt;/div&gt;; } </code></pre> <p>however TS complains about my condition saying:</p> <blockquote> <p>TS2367: This condition will always return 'false' since the types '&quot;string&quot; | &quot;number&quot; | &quot;bigint&quot; | &quot;boolean&quot; | &quot;symbol&quot; | &quot;undefined&quot; | &quot;object&quot; | &quot;function&quot;' and '&quot;JSX.Element&quot;' have no overlap.</p> </blockquote> <p>What should I do?</p>
[ { "answer_id": 74552689, "author": "Alex Wayne", "author_id": 62076, "author_profile": "https://Stackoverflow.com/users/62076", "pm_score": 4, "selected": true, "text": "typeof \"JSX.Element\" \"string\" | \"number\" | \"bigint\" | \"boolean\" | \"symbol\" | \"undefined\" | \"object\" | \"function\"\n \"string\" function MyComponent(): JSX.Element {\n let icon: JSX.Element | string = \"/example.png\";\n \n return <div>{typeof icon === \"string\" ? <img src={icon} /> : icon }</div>;\n}\n" }, { "answer_id": 74552889, "author": "Garrett", "author_id": 2223706, "author_profile": "https://Stackoverflow.com/users/2223706", "pm_score": 1, "selected": false, "text": "string React.isValidElement JSX.Element ReactElement function MyComponent(): JSX.Element {\n let icon: ReactElement | string = \"/example.png\"; // (simplified)\n\n return <div>{React.isValidElement(icon) ? icon : <img src={icon} />}</div>;\n}\n JSX.Element JSX.Element" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2223706/" ]
74,552,553
<p>I would like to compute a missing value by way of taking the average of the lead and lag rows, for a specific row. In this example, year 2001.</p> <pre><code>df = data.frame(year = c(2000, 2001, 2002), A = c(2, NA, 3), B = c(2, 2, 3), C = c(3, NA, 2)) </code></pre> <p>have tried <code>case_when(year == 2001, is.na(.) ~ (lead(.) + lag(.) )/ 2)</code> but cant figure out how to change or mutate all of the 2001 rows in place for all instances of NA. Imagine many columns, some filled, some not!</p> <p>Thoughts? And thanks!</p>
[ { "answer_id": 74552738, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 2, "selected": false, "text": "library(dplyr)\n\ndf %>% \n mutate(across(A:C, ~case_when( is.na(.x) ~ (lead(.x) + lag(.x) )/ 2,\n TRUE ~ .x)))\n year A B C\n1 2000 2.0 2 3.0\n2 2001 2.5 2 2.5\n3 2002 3.0 3 2.0\n" }, { "answer_id": 74552743, "author": "denis", "author_id": 8053817, "author_profile": "https://Stackoverflow.com/users/8053817", "pm_score": 1, "selected": false, "text": "transpose data.table df2 <- data.table::transpose(df,make.names = \"year\",keep.names = \"name\")\n\n name 2000 2001 2002\n1 A 2 NA 3\n2 B 2 2 3\n3 C 3 NA 2\n df2$`2001` <- ifelse(is.na(df2$`2001`),(df2$`2000`+df2$`2002`)/2,df2$`2000`)\n data.table::transpose(df2,keep.names = \"year\",make.names = \"name\")\n\n year A B C\n1 2000 2.0 2 3.0\n2 2001 2.5 2 2.5\n3 2002 3.0 3 2.0\n data.table df %>% setDT()\n\ndf[,lapply(.SD,function(x){\n fifelse(year == 2001 & is.na(x),(lead(x) + lag(x))/2,x)\n}),.SDcols = c(\"A\",\"B\",\"C\")]\n\n A B C\n1: 2.0 2 3.0\n2: 2.5 2 2.5\n3: 3.0 3 2.0\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18048351/" ]
74,552,582
<p>Here is a sample dataframe:</p> <pre><code>df &lt;- tibble(variable =c(&quot;gdp&quot;, &quot;gdp_ppp&quot;), value = c(1000, 2000), variable_label=c(&quot;GDP&quot;, &quot;GDP_PPP&quot;)) </code></pre> <p>I would like to make variable_label an expression or text element of some sort because I want to use it as a title for a series of plots that I have generated using a loop. I could manually type the title using text elements but that would require me to generate each plot independently, as far as I know. For example, I want the &quot;PPP&quot; in &quot;GDP_PPP&quot; to be a subscript when it shows up in the title. Is this possible? Thanks!</p>
[ { "answer_id": 74552738, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 2, "selected": false, "text": "library(dplyr)\n\ndf %>% \n mutate(across(A:C, ~case_when( is.na(.x) ~ (lead(.x) + lag(.x) )/ 2,\n TRUE ~ .x)))\n year A B C\n1 2000 2.0 2 3.0\n2 2001 2.5 2 2.5\n3 2002 3.0 3 2.0\n" }, { "answer_id": 74552743, "author": "denis", "author_id": 8053817, "author_profile": "https://Stackoverflow.com/users/8053817", "pm_score": 1, "selected": false, "text": "transpose data.table df2 <- data.table::transpose(df,make.names = \"year\",keep.names = \"name\")\n\n name 2000 2001 2002\n1 A 2 NA 3\n2 B 2 2 3\n3 C 3 NA 2\n df2$`2001` <- ifelse(is.na(df2$`2001`),(df2$`2000`+df2$`2002`)/2,df2$`2000`)\n data.table::transpose(df2,keep.names = \"year\",make.names = \"name\")\n\n year A B C\n1 2000 2.0 2 3.0\n2 2001 2.5 2 2.5\n3 2002 3.0 3 2.0\n data.table df %>% setDT()\n\ndf[,lapply(.SD,function(x){\n fifelse(year == 2001 & is.na(x),(lead(x) + lag(x))/2,x)\n}),.SDcols = c(\"A\",\"B\",\"C\")]\n\n A B C\n1: 2.0 2 3.0\n2: 2.5 2 2.5\n3: 3.0 3 2.0\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15911106/" ]
74,552,586
<p>I didnt open new html file when onclick on button</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://thymeleaf.org"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Sign up Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Welcome to Getir Library&lt;/h1&gt; &lt;br&gt; &lt;hr&gt; &lt;form th:action="@{/Main}" method="post"&gt; &lt;div class = "header"&gt; &lt;h1&gt;Menu&lt;/h1&gt; &lt;button type="submit" th:onclick="|window.location.href='/CustomerLogin'|" &gt;Customer Login Page&lt;/button&gt;</code></pre> </div> </div> </p> <p>Also This is my Controller Class.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>@RequestMapping(value = "/CustomerLogin") String getCustomerLoginPage(){ return "CustomerLogin"; }</code></pre> </div> </div> </p> <p>[![enter image description here][1]][1]</p> <p>This is my html files in the javaspring project [1]: <a href="https://i.stack.imgur.com/iv7aq.png" rel="nofollow noreferrer">https://i.stack.imgur.com/iv7aq.png</a></p>
[ { "answer_id": 74565476, "author": "Kaushal", "author_id": 20593455, "author_profile": "https://Stackoverflow.com/users/20593455", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html xmlns:th=\"http://thymeleaf.org\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Sign up Page</title>\n</head>\n<body>\n<h1>Welcome to Getir Library</h1>\n<br>\n<hr>\n<form th:action=\"@{/Main}\" method=\"post\">\n <div class = \"header\">\n <h1>Menu</h1>\n <button type=\"button\" th:onclick=\"|window.location.href='/CustomerLogin'|\" >Customer Login Page</button>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13249946/" ]
74,552,594
<p>I am writing UI Test for my App using Espresso. The screen shows a <code>Recyclerview</code> with list of shops that have status <code>OPEN</code> or <code>CLOSED</code>. Depending upon the data the <code>openTextView</code> or <code>closedTextview</code> is shown and are hidden by default.</p> <p><strong>Below is my test case scenario:</strong></p> <ul> <li>Check if screen is visible</li> <li>Check if Recyclerview is visible</li> <li>Check if Recyclerview has atleast one shop with <code>OPEN</code> status</li> <li>Click on first found <code>OPEN</code> shop</li> <li>Check if details screen shows up</li> </ul> <p><strong>ISSUE:</strong></p> <p>I tried to click the first <code>OPEN</code> status item but it is throwing Exception.</p> <p>Below is the code</p> <pre><code>@Test fun openShopTest() { onView(withText(“Shops&quot;)).check(matches(isDisplayed())) onView(withId(R.id.rvShops)).check(matches(isDisplayed())) //There is at least one open shop visible onView(withId(R.id.rvShops)) .perform(RecyclerViewActions.scrollToHolder(first(withOpenText()))) //User clicks on open shop onView(allOf(withId(R.id.rvShops), isDisplayed())) .perform(actionOnItem&lt;ListAdapter.ListViewHolder&gt;(withChild(withText(“Open”)), click())) //Screen with details appear onView(withText(&quot;Details”)).check(matches(isDisplayed())) } fun withOpenText(): Matcher&lt;RecyclerView.ViewHolder&gt; { return object : BoundedMatcher&lt;RecyclerView.ViewHolder, ListAdapter.ListViewHolder&gt;( ListAdapter.ListViewHolder::class.java ) { override fun describeTo(description: Description) { description.appendText(&quot;No ViewHolder found with Open Status Visible&quot;) } override fun matchesSafely(item: ListAdapter.ListViewHolder): Boolean { val openTextView = item.itemView.findViewById(R.id.openTextView) as TextView return openTextView.isVisible } } } </code></pre> <p>Below is the exception:</p> <pre><code>androidx.test.espresso.PerformException: Error performing 'performing ViewAction: single click on item matching: holder with view: has child: with text: is &quot;Open&quot;' on view '(with id: mypackagename:id/rvShops and is displayed on the screen to the user)'. at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82) at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:79) at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:51) at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:312) at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:173) at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:114) at mypackagename.MyUITest.openShopTest(MyUITest.kt:77) ... 32 trimmed Caused by: androidx.test.espresso.PerformException: Error performing 'scroll RecyclerView to: holder with view: has child: with text: is &quot;Open&quot;' on view 'RecyclerView{id=2131231032, res-name=rvShops, visibility=VISIBLE, width=1080, height=2047, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@295fec9, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=12}'. at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82) at androidx.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:381) at androidx.test.espresso.contrib.RecyclerViewActions$ActionOnItemViewAction.perform(RecyclerViewActions.java:221) at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:356) at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:248) at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:63) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:153) at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:150) at java.util.concurrent.FutureTask.run(FutureTask.java:264) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8751) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135) Caused by: java.lang.RuntimeException: Found 0 items matching holder with view: has child: with text: is &quot;Open&quot;, but position -1 was requested. at androidx.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:361) </code></pre> <p><strong>What i have tried?</strong></p> <ul> <li><p>I had an idea that maybe <code>openTextView</code> or <code>closedTextview</code> are not always visible so that might be causing the problem. I tried by making both always visible as well.</p> </li> <li><p>I followed the steps mentioned in answers of <a href="https://stackoverflow.com/questions/62600556/espresso-preform-click-on-item-inside-recyclerview-that-has-specified-text">this question</a> but the same excpetion shows up.</p> </li> </ul> <p><strong>What is required?</strong></p> <ul> <li>Click on Recyclerview row where <code>openTextView</code> is visible</li> <li>Get position of row where <code>openTextView</code> is visible; so that i can use <code>atPosition</code> function and click the row.</li> </ul> <p>Can somebody please help me out with this?</p> <p>Any help will be appreciated.</p> <p>Thanks</p>
[ { "answer_id": 74565476, "author": "Kaushal", "author_id": 20593455, "author_profile": "https://Stackoverflow.com/users/20593455", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html xmlns:th=\"http://thymeleaf.org\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Sign up Page</title>\n</head>\n<body>\n<h1>Welcome to Getir Library</h1>\n<br>\n<hr>\n<form th:action=\"@{/Main}\" method=\"post\">\n <div class = \"header\">\n <h1>Menu</h1>\n <button type=\"button\" th:onclick=\"|window.location.href='/CustomerLogin'|\" >Customer Login Page</button>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14834877/" ]
74,552,649
<p>So I have five nav tabs and when someone clicks for example on a shop tab, I want it font to be 'bold' so you can see what tab is currently active. I have Home active when someone enters the site but it's hard coded. Meaning that when I click on a shop tab, 'bold' font on home tab still is there. `</p> <pre><code>function Header() { const [tabState, setActiveTab] = useState ({ activeObject: null, objects: [{id:1}, {id:2}, {id:3}, {id:4}, {id:5}] }); function activateTab(index) { setActiveTab({...tabState, activeObject: tabState.objects[index]}) } function activateTabStyles(index) { if (tabState.objects[index] === tabState.activeObject) { return 'activeTab' } else { return '' } } return ( &lt;header className='siteHeader'&gt; &lt;div className='headerWrapper'&gt; &lt;div className='logoWrapper'&gt; &lt;Link to=&quot;/&quot; className='link'&gt; &lt;img src={logo} alt='logo'&gt;&lt;/img&gt; &lt;/Link&gt; &lt;/div&gt; &lt;nav className='navBar'&gt; &lt;ul&gt; &lt;li className='activeTab' onClick={() =&gt; {activateTab(1)}} key={1}&gt; &lt;Link to=&quot;/&quot; className='link'&gt;Home&lt;/Link&gt; &lt;/li&gt; &lt;li className={activateTabStyles(2)} onClick={() =&gt; {activateTab(2)}} key={2}&gt; &lt;Link to=&quot;/Shop&quot; className='link'&gt;Shop&lt;/Link&gt; &lt;/li&gt; &lt;li className={activateTabStyles(3)} onClick={() =&gt; {activateTab(3)}} key={3}&gt; &lt;Link to=&quot;/Contact&quot; className='link'&gt;Contact&lt;/Link&gt; &lt;/li&gt; &lt;li className={activateTabStyles(4)} onClick={() =&gt; {activateTab(4)}} key={4}&gt; &lt;Link to=&quot;/TermsInfo&quot; className='link'&gt;Terms &amp; Info&lt;/Link&gt; &lt;/li&gt; &lt;li className={activateTabStyles(5)} onClick={() =&gt; {activateTab(5)}} key={5}&gt; &lt;Link to=&quot;/Cart&quot; className='link'&gt;Cart&lt;/Link&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/header&gt; ) } export default Header </code></pre> <p>`</p> <p>I hard coded a class 'activeTab' inside the home tab thinking that I could do something inside activateTab function to remove this class when I click on the other tabs. I wanted to try refs but I heard that I'm not supposed to use this. I tried creating another function with a style only for the home tab but I didn't know how to call that function inside the activateTab so I deleted it.</p>
[ { "answer_id": 74565476, "author": "Kaushal", "author_id": 20593455, "author_profile": "https://Stackoverflow.com/users/20593455", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n<html xmlns:th=\"http://thymeleaf.org\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Sign up Page</title>\n</head>\n<body>\n<h1>Welcome to Getir Library</h1>\n<br>\n<hr>\n<form th:action=\"@{/Main}\" method=\"post\">\n <div class = \"header\">\n <h1>Menu</h1>\n <button type=\"button\" th:onclick=\"|window.location.href='/CustomerLogin'|\" >Customer Login Page</button>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585267/" ]
74,552,683
<pre class="lang-bash prettyprint-override"><code>python -c &quot;import numpy as np; print(np.sum([-np.Inf, +np.Inf]))&quot; </code></pre> <p>gives</p> <pre><code>numpy\core\fromnumeric.py:86: RuntimeWarning: invalid value encountered in reduce return ufunc.reduce(obj, axis, dtype, out, **passkwargs) nan </code></pre> <p>I wonder why that is:</p> <ol> <li><p>There is no warning in</p> <pre class="lang-bash prettyprint-override"><code>python -c &quot;import numpy as np; print(np.sum([-np.Inf, -np.Inf]))&quot; </code></pre> <p>nor in</p> <pre class="lang-bash prettyprint-override"><code>python -c &quot;import numpy as np; print(np.sum([+np.Inf, +np.Inf]))&quot; </code></pre> <p>so it can't be the <code>Inf</code>s.</p> </li> <li><p>There is no warning in</p> <pre class="lang-bash prettyprint-override"><code>python -c &quot;import numpy as np; print(np.sum([np.nan, np.nan]))&quot; </code></pre> <p>so it can't be the <code>NaN</code> result.</p> </li> </ol> <p>What is it, then, and how can I avoid it? I actually like getting <code>NaN</code> as a result, I just want to avoid the warning.</p>
[ { "answer_id": 74552893, "author": "Carlos Horn", "author_id": 18205911, "author_profile": "https://Stackoverflow.com/users/18205911", "pm_score": 3, "selected": true, "text": "Inf - Inf import warnings\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n res = np.sum([-np.Inf, np.Inf])\n" }, { "answer_id": 74570324, "author": "bers", "author_id": 880783, "author_profile": "https://Stackoverflow.com/users/880783", "pm_score": 1, "selected": false, "text": "Inf NaN Inf - Inf NaN + NaN np.nan Inf + Inf np.inf - np.inf with np.errstate(invalid=\"ignore\"): ..." } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880783/" ]
74,552,712
<p>I've got this piece of code:</p> <pre><code>SELECT t1.sku_id, t1.putaway_group, t1.shortage, t4.location_id, t4.qty_on_hand FROM (WHERE clauses)t1 LEFT JOIN ( SELECT * FROM ( SELECT location_id, sku_id, qty_on_hand, DENSE_RANK() OVER ( PARTITION BY sku_id ORDER BY qty_on_hand DESC ) AS rnk FROM inventory WHERE substr(zone_1,1,5) IN ('TOTEB','TOTEC') ) WHERE rnk = 1 ORDER BY 2 DESC )t4 ON t3.sku_id = t4.sku_id </code></pre> <p>Where the output is:</p> <p><a href="https://i.stack.imgur.com/nTE9S.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nTE9S.jpg" alt="enter image description here" /></a></p> <p>What i want to achieve is to return as many rows from location_id as shortage require. For example if shortage is -84 THEN as an output for SKU: 02295441 i want to return 6 rows because (6*16 = 96) which will cover my shortage. Not really sure if it's possible or if yes then how to write a where/having clause to limit output rows. Currently I'm just doing it through power query in excel, but just wondering if it's possible straight from sql. Thanks in advance.</p>
[ { "answer_id": 74552822, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "row_number SQL> with data (sku_id, shortage, location_id, qty_on_hand) as\n 2 (select 1, -84, 3, 16 from dual union all\n 3 select 1, -84, 2, 16 from dual union all\n 4 select 1, -84, 5, 16 from dual union all\n 5 select 1, -84, 5, 16 from dual union all\n 6 select 1, -84, 5, 16 from dual union all\n 7 select 1, -84, 6, 16 from dual union all\n 8 select 1, -84, 1, 16 from dual union all\n 9 select 1, -84, 2, 16 from dual union all\n 10 select 1, -84, 1, 16 from dual union all\n 11 select 1, -84, 2, 16 from dual union all\n 12 --\n 13 select 2, -20, 1, 10 from dual\n 14 ),\n 15 temp as\n 16 (select d.*,\n 17 row_number() over (partition by sku_id order by qty_on_hand) rnk\n 18 from data d\n 19 )\n 20 select *\n 21 from temp\n 22 where rnk <= ceil(abs(shortage) / qty_on_hand);\n\n SKU_ID SHORTAGE LOCATION_ID QTY_ON_HAND RNK\n---------- ---------- ----------- ----------- ----------\n 1 -84 3 16 1 --> SKU_ID = 1 begins here\n 1 -84 2 16 2\n 1 -84 5 16 3\n 1 -84 5 16 4\n 1 -84 5 16 5\n 1 -84 6 16 6 --> SKU_ID = 1 ends here; 6 rows\n 2 -20 1 10 1\n\n7 rows selected.\n\nSQL>\n" }, { "answer_id": 74553102, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 3, "selected": true, "text": "SUM SELECT t1.sku_id,\n t1.putaway_group,\n t1.shortage,\n t4.location_id,\n t4.qty_on_hand\nFROM /*(WHERE clauses)*/ t1\n LEFT JOIN (\n SELECT location_id,\n sku_id,\n qty_on_hand,\n SUM(qty_on_hand) OVER (\n PARTITION BY sku_id\n ORDER BY qty_on_hand DESC, ROWNUM\n ) AS total_qty\n FROM inventory\n WHERE zone_1 LIKE 'TOTEB%'\n OR zone_1 LIKE 'TOTEC%'\n ) t4\n ON ( t1.sku_id = t4.sku_id\n AND -t1.shortage > t4.total_qty - t4.qty_on_hand )\n CREATE TABLE t1 (sku_id, putaway_group, shortage) AS\nSELECT 'SKU1', 'TEXTILES', -84 FROM DUAL UNION ALL\nSELECT 'SKU2', 'PLASTICS', -13 FROM DUAL;\n\nCREATE TABLE inventory(location_id, sku_id, qty_on_hand, zone_1) AS\nSELECT LEVEL, 'SKU1', LEAST(LEVEL * 4, 16), 'TOTEB' || CHR(64 + LEVEL) FROM DUAL CONNECT BY LEVEL <= 10\nUNION ALL\nSELECT LEVEL, 'SKU2', LEVEL, 'TOTEC' || CHR(64 + LEVEL) FROM DUAL CONNECT BY LEVEL <= 6;\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16004228/" ]
74,552,713
<p>I have set up the Workload Identity on a GKE cluster, and now I am using a Kubernetes SA linked to an IAM SA with appropriate permissions. I checked that when I use the IAM SA key file, it gets the access I need.</p> <p>However, it gets weird even when following the <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity" rel="nofollow noreferrer">docs</a>.</p> <p>The first suggested check is to run this command to check the metadata server response:</p> <pre><code>$ curl -H &quot;Metadata-Flavor: Google&quot; http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/email &lt;sa_name&gt;@&lt;project_id&gt;.iam.gserviceaccount.com </code></pre> <p>So far, so good. The next paragraph that describes using the Quota Project option suggests using another command, which should return the identity token. And it fails:</p> <pre><code>$ curl -H &quot;Metadata-Flavor: Google&quot; http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token Unable to generate access token; IAM returned 404 Not Found: Not found; Gaia id not found for email &lt;sa_name&gt;@&lt;project_id&gt;.iam.gserviceaccount.com </code></pre> <p>The same happens when I use the .NET SDK and call this:</p> <pre><code>var oidcToken1 = await cc.GetOidcTokenAsync( OidcTokenOptions.FromTargetAudience(_serviceUrl), cancellationToken ); _addToken = async (request, token) =&gt; { request.Headers.Authorization = new AuthenticationHeaderValue( &quot;Bearer&quot;, await oidcToken1.GetAccessTokenAsync(cancellationToken: token) ); }; </code></pre> <p>The code works fine when I use the IAM SA JSON key, but when it runs in the pod that uses the Workload Identity, I get the same message as before:</p> <pre><code>Google.Apis.Auth.OAuth2.ServiceCredential Token has expired, trying to get a new one. Google.Apis.Http.ConfigurableMessageHandler Request[00000001] (triesRemaining=3) URI: 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://&lt;service_url&gt;&amp;format=full' Google.Apis.Http.ConfigurableMessageHandler Response[00000001] Response status: NotFound 'Not Found' Google.Apis.Http.ConfigurableMessageHandler Response[00000001] An abnormal response wasn't handled. Status code is NotFound </code></pre> <p>The same happens when I use <code>gcloud auth application-default print-access-token</code> from the Workload Identity test pod:</p> <blockquote> <p>ERROR: (gcloud.auth.application-default.print-access-token) There was a problem refreshing your current auth tokens: (&quot;Failed to retrieve <a href="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/" rel="nofollow noreferrer">http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/</a>&lt;sa_name&gt;@&lt;project_id&gt;.iam.gserviceaccount.com/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform from the Google Compute Engine metadata service. Status: 404 Response:\nb'Unable to generate access token; IAM returned 404 Not Found: Not found; Gaia id not found for email &lt;sa_name&gt;@&lt;project_id&gt;.iam.gserviceaccount.com\n'&quot;, &lt;google.auth.transport.requests._Response object at 0x7feabe712910&gt;)</p> </blockquote> <p>I am not sure what else can be done; it seems like the whole thing just doesn't work.</p>
[ { "answer_id": 74552822, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "row_number SQL> with data (sku_id, shortage, location_id, qty_on_hand) as\n 2 (select 1, -84, 3, 16 from dual union all\n 3 select 1, -84, 2, 16 from dual union all\n 4 select 1, -84, 5, 16 from dual union all\n 5 select 1, -84, 5, 16 from dual union all\n 6 select 1, -84, 5, 16 from dual union all\n 7 select 1, -84, 6, 16 from dual union all\n 8 select 1, -84, 1, 16 from dual union all\n 9 select 1, -84, 2, 16 from dual union all\n 10 select 1, -84, 1, 16 from dual union all\n 11 select 1, -84, 2, 16 from dual union all\n 12 --\n 13 select 2, -20, 1, 10 from dual\n 14 ),\n 15 temp as\n 16 (select d.*,\n 17 row_number() over (partition by sku_id order by qty_on_hand) rnk\n 18 from data d\n 19 )\n 20 select *\n 21 from temp\n 22 where rnk <= ceil(abs(shortage) / qty_on_hand);\n\n SKU_ID SHORTAGE LOCATION_ID QTY_ON_HAND RNK\n---------- ---------- ----------- ----------- ----------\n 1 -84 3 16 1 --> SKU_ID = 1 begins here\n 1 -84 2 16 2\n 1 -84 5 16 3\n 1 -84 5 16 4\n 1 -84 5 16 5\n 1 -84 6 16 6 --> SKU_ID = 1 ends here; 6 rows\n 2 -20 1 10 1\n\n7 rows selected.\n\nSQL>\n" }, { "answer_id": 74553102, "author": "MT0", "author_id": 1509264, "author_profile": "https://Stackoverflow.com/users/1509264", "pm_score": 3, "selected": true, "text": "SUM SELECT t1.sku_id,\n t1.putaway_group,\n t1.shortage,\n t4.location_id,\n t4.qty_on_hand\nFROM /*(WHERE clauses)*/ t1\n LEFT JOIN (\n SELECT location_id,\n sku_id,\n qty_on_hand,\n SUM(qty_on_hand) OVER (\n PARTITION BY sku_id\n ORDER BY qty_on_hand DESC, ROWNUM\n ) AS total_qty\n FROM inventory\n WHERE zone_1 LIKE 'TOTEB%'\n OR zone_1 LIKE 'TOTEC%'\n ) t4\n ON ( t1.sku_id = t4.sku_id\n AND -t1.shortage > t4.total_qty - t4.qty_on_hand )\n CREATE TABLE t1 (sku_id, putaway_group, shortage) AS\nSELECT 'SKU1', 'TEXTILES', -84 FROM DUAL UNION ALL\nSELECT 'SKU2', 'PLASTICS', -13 FROM DUAL;\n\nCREATE TABLE inventory(location_id, sku_id, qty_on_hand, zone_1) AS\nSELECT LEVEL, 'SKU1', LEAST(LEVEL * 4, 16), 'TOTEB' || CHR(64 + LEVEL) FROM DUAL CONNECT BY LEVEL <= 10\nUNION ALL\nSELECT LEVEL, 'SKU2', LEVEL, 'TOTEC' || CHR(64 + LEVEL) FROM DUAL CONNECT BY LEVEL <= 6;\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484041/" ]
74,552,732
<p>I need some advice on how to list only words from <code>Text</code> branches in this code I have programmed.</p> <pre><code>data Article = Text String | Section String [Article] deriving (Show) myArticle :: Article myArticle = Section &quot;Document&quot; [ Section &quot;Introduction&quot; [ Text &quot;My intoduction&quot;, Section &quot;Notation&quot; [Text &quot;alpha beta gamma&quot;]], Section &quot;Methods&quot; [ Section &quot;Functional Programming&quot; [Text &quot;FPR&quot;], Section &quot;Logical Programming&quot; [Text &quot;LPR&quot;]], Section &quot;Results&quot; [Text &quot;All is great&quot;]] tex :: Article -&gt; [String] tex (Text x) = [x] tex (Section x (l:ls)) = tex l </code></pre> <p>I tried to call ls in the <code>tex</code> function, but it throws me an error. I don't know how to proceed.</p>
[ { "answer_id": 74552766, "author": "Joseph Sible-Reinstate Monica", "author_id": 7509065, "author_profile": "https://Stackoverflow.com/users/7509065", "pm_score": 4, "selected": true, "text": "concatMap : tex (Section x ls) = concatMap tex ls\n tex myArticle [\"My intoduction\",\"alpha beta gamma\",\"FPR\",\"LPR\",\"All is great\"]" }, { "answer_id": 74552777, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": false, "text": "(l:ls) l Article Text Section String tex :: Article -> [String]\ntex (Text x) = [x]\ntex (Section _ ls) = … ls" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538688/" ]
74,552,754
<p>Can be possible to store a file uploaded to a related table? <em>Scenario:</em> I have a <code>usres</code> table in database and another one <code>pictures</code>. <strong>Users Model</strong> have the following function</p> <pre><code>public function picture() { return $this-&gt;hasOne(Picture::class); } </code></pre> <p>And the <strong>Picture Model</strong> have the following function.</p> <pre><code>public function user_picture() { return $this-&gt;belongsTo(User::class, 'user_id', 'id'); } </code></pre> <p>Is possible to store the picture in <code>pictures</code> database table <code>(id, user_id, img_path)</code> from the <strong>UserCrudController</strong> <code>store()</code> function?</p>
[ { "answer_id": 74552766, "author": "Joseph Sible-Reinstate Monica", "author_id": 7509065, "author_profile": "https://Stackoverflow.com/users/7509065", "pm_score": 4, "selected": true, "text": "concatMap : tex (Section x ls) = concatMap tex ls\n tex myArticle [\"My intoduction\",\"alpha beta gamma\",\"FPR\",\"LPR\",\"All is great\"]" }, { "answer_id": 74552777, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": false, "text": "(l:ls) l Article Text Section String tex :: Article -> [String]\ntex (Text x) = [x]\ntex (Section _ ls) = … ls" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1262099/" ]
74,552,765
<p>I am trying to calculate some function results using predefined parameters that are generated before and stored in lists.</p> <p>But I need to recode this solution to save all results to a dataframe of appropriate structure, where each row contain next parameters:</p> <pre><code>E | number_of_iteration | result </code></pre> <p>The actual mapping is like this:</p> <pre><code>E -&gt; newenergy_grid[i] number_of_iteration -&gt; [j] result -&gt; gaus_res_ij </code></pre> <p>Here is the code which is running now and collects all data to the &quot;list of lists&quot; object. I have tried to get all data into a dataframe (code commented after list generation) - but it works very slowly.</p> <p>It's about 10000 points in a list and about 10000 in a offset list.</p> <p>I understand that I need to optimize solution to collect and store all the data into single dataframe. How to do it right?</p> <p>Maybe I can use numpy for efficient calculation and after - just save the resulting ndarray into one dataframe? I understand the idea but I don't really get how to realize it..</p> <pre><code># TODO: IMPORTANT(!) it's much easier to work with dataframes... # here I want to have such structure of resulting dataframe # E | number_of_iteration | result # results_df = pd.DataFrame() all_res = [] #global list of lists - each list for one energy level for i in range(0, len(newenergy_grid)): # res_for_one_E = np.empty(len(energy_grid)) #iterating through the energy grid list_for_one_E = [] for j in range(0, len(doffset)): #iterating through the seeding steps # selection of parameters for function calculation - they are stored in the lists p = [ damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j] ] gaus_res_ij = _3gaussian(newenergy_grid[i], *p) # for the i-th energy level and for j-th realization of a curve list_for_one_E.append(gaus_res_ij) &quot;&quot;&quot; #dataframes for future analysis # too slow solution... how to speed up it or use numpy? temp = pd.DataFrame({ &quot;E&quot;: newenergy_grid[i], &quot;step_number&quot;: j, &quot;res&quot;: res_for_one_E }, index=[j]) results_df = pd.concat([results_df, temp]) &quot;&quot;&quot; all_res.append(list_for_one_E) #appending the calculated list to the 'list of lists' </code></pre> <p><strong>UPDATE</strong> - providing some data for understanding.</p> <p><code>newenergy_grid [135.11618653 135.12066818 135.12514984 ... 179.91929833 179.92377998 179.92826164]</code> - about 10000 points which represent energy coordinates for a function under test. The number of points depends on data obtained for observation, in my case 100...100000 points on the energy axis.</p> <p>in the middle of the code I have p - list of parameters for the function <code>_3gaussian(newenergy_grid[i], *p)</code> - which calculates the resulting value I need to save for the point with coordinates (newenergy_grid[i], j). So it's the function f(x,y*) that calculates the value at the x = newenergy_grid[i], and y* stands for set of parameters, each element of a set is dependent on iteration number j and is already calculated - so on the each step ij I am only selecting the parameters y using j, and calculating the value of a function f(x[i], y*[j]).</p> <p>List p is constructed on each step j using pregenerated lists (damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j])</p> <p>j - is the index of a point in the lists of parameters, it can be iterated from 0 to len(offset). Each of the parameters of a p list has about 10000 elements, so j changes from 0 to len(doffset)</p> <ul> <li>damp1 [19.85128939 19.32065201 ... 19.50304656]</li> <li>dsigma1 [0.07900404 0.0798217 ... 0.08074941]</li> <li>...</li> </ul>
[ { "answer_id": 74552766, "author": "Joseph Sible-Reinstate Monica", "author_id": 7509065, "author_profile": "https://Stackoverflow.com/users/7509065", "pm_score": 4, "selected": true, "text": "concatMap : tex (Section x ls) = concatMap tex ls\n tex myArticle [\"My intoduction\",\"alpha beta gamma\",\"FPR\",\"LPR\",\"All is great\"]" }, { "answer_id": 74552777, "author": "Willem Van Onsem", "author_id": 67579, "author_profile": "https://Stackoverflow.com/users/67579", "pm_score": 2, "selected": false, "text": "(l:ls) l Article Text Section String tex :: Article -> [String]\ntex (Text x) = [x]\ntex (Section _ ls) = … ls" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7267480/" ]
74,552,785
<p>I need to convert some element in jsonb column to array</p> <p>What I have:</p> <pre><code>{&quot;a&quot;: { &quot;b&quot;: &quot;2022-11-03&quot;, &quot;c&quot;: &quot;321321&quot;, &quot;d&quot;: &quot;213321&quot; } } </code></pre> <p>What I need: `</p> <pre><code>{&quot;a&quot;: [ { &quot;b&quot;: &quot;2022-11-03&quot;, &quot;c&quot;: &quot;321321&quot;, &quot;d&quot;: &quot;213321&quot; } ] } </code></pre>
[ { "answer_id": 74553075, "author": "Mitko Keckaroski", "author_id": 12041280, "author_profile": "https://Stackoverflow.com/users/12041280", "pm_score": 0, "selected": false, "text": "select json_agg(DATA) from table_json\n" }, { "answer_id": 74553743, "author": "Adrian Klaver", "author_id": 7070613, "author_profile": "https://Stackoverflow.com/users/7070613", "pm_score": 0, "selected": false, "text": "SELECT\n jsonb_build_object(\n (jsonb_path_query_array('{\"a\": {\"b\": \"2022-11-03\",\"c\": \"321321\",\"d\": \"213321\"}}', '$.keyvalue()') -> 0 -> 'key') ->> 0, \n (jsonb_path_query_array('{\"a\": {\"b\": \"2022-11-03\",\"c\": \"321321\",\"d\": \"213321\"}}', '$.keyvalue()') -> 0 -> 'value' \n || '[]'::jsonb));\n\njsonb_build_object \n------------------------------------------------------------\n {\"a\": [{\"b\": \"2022-11-03\", \"c\": \"321321\", \"d\": \"213321\"}]}\n\n" }, { "answer_id": 74553781, "author": "a_horse_with_no_name", "author_id": 330315, "author_profile": "https://Stackoverflow.com/users/330315", "pm_score": 2, "selected": true, "text": "jsonb_set() SELECT jsonb_set(the_column, '{a}', jsonb_build_array(the_column -> 'a'))\nFROM the_table\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585419/" ]
74,552,793
<p>I have components <code>&lt;Parent&gt;</code> and <code>&lt;Child&gt;</code>, and <code>&lt;Parent&gt;</code> accesses a Redux state prop called <code>prop1</code> using <code>mapStateToProps()</code>. <code>&lt;Child&gt;</code> needs to access <code>prop1</code> as well.</p> <p>What's the difference between passing it to <code>&lt;Child&gt;</code> as a prop like <code>&lt;Child prop1={this.props.prop1}&gt;</code> vs having <code>&lt;Child&gt;</code> get it via <code>mapStateToProps()</code>? Is one way better than the other?</p>
[ { "answer_id": 74553385, "author": "fgkolf", "author_id": 13168083, "author_profile": "https://Stackoverflow.com/users/13168083", "pm_score": 3, "selected": true, "text": "mapStateToProps Child prop1 Child prop1 Child Parent Parent Child" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10864356/" ]
74,552,855
<p>I have the following single column DataFrame:</p> <p>df:</p> <p><a href="https://i.stack.imgur.com/5YpXY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5YpXY.png" alt="enter image description here" /></a></p> <pre><code>data = {'YEAR': [2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030], } df = pd.DataFrame(data) df </code></pre> <p>How can I create an empty square Dataframe from df like the following DatFrame:</p> <p><a href="https://i.stack.imgur.com/2t1fz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2t1fz.png" alt="enter image description here" /></a></p> <p>I´m kinda new to Python. I have tried converting the original Dataframme to list and the create a new dataframe from there without success. I also tried to do somekind concatenation but it does not work either.</p> <p>I guess that its not as hard, but I dont know how to do that.</p>
[ { "answer_id": 74552900, "author": "Psidom", "author_id": 4983450, "author_profile": "https://Stackoverflow.com/users/4983450", "pm_score": 1, "selected": false, "text": "index columns df = pd.DataFrame([], index=data['YEAR'], columns=data['YEAR'])\ndf\n 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2022 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2023 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2024 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2025 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2026 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2027 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2028 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2029 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2030 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n" }, { "answer_id": 74552904, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 1, "selected": false, "text": "df.dot replace df.set_index('YEAR').dot(df.set_index('YEAR').T).replace({0:''})\n" }, { "answer_id": 74552917, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "reindex df.reindex(columns=df.columns.union(df['YEAR']))\n YEAR 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n0 2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n1 2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2 2022 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n3 2023 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n4 2024 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n5 2025 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n6 2026 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n7 2027 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n8 2028 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n9 2029 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n10 2030 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n" }, { "answer_id": 74552925, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 0, "selected": false, "text": "pandas.DataFrame.loc df.loc[:, df.set_index(\"YEAR\").index.tolist()]= np.NaN #or \"\"\n print(df)\n\n YEAR 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n0 2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n1 2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2 2022 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n3 2023 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n4 2024 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n5 2025 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n6 2026 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n7 2027 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n8 2028 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n9 2029 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n10 2030 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11789082/" ]
74,552,879
<p>The code in question (below) reads much faster (30x), tahn regular: MemoryMappedViewAccessor.ReadArray() I'm trying to modify the code to be able to read from <strong>long</strong> offset, <strong>not int</strong> (!)</p> <pre><code> public unsafe byte[] ReadBytes(int offset, int num) { byte[] arr = new byte[num]; byte *ptr = (byte*)0; this._view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr); Marshal.Copy(IntPtr.Add(new IntPtr(ptr), offset), arr, 0, num); this._view.SafeMemoryMappedViewHandle.ReleasePointer(); return arr; } </code></pre> <p>original code is here: <a href="https://stackoverflow.com/questions/7956167/how-can-i-quickly-read-bytes-from-a-memory-mapped-file-in-net#_=">How can I quickly read bytes from a memory mapped file in .NET?</a>_</p> <p>I need to adjust IntPtr.Add and Marshal.Copy to correctly work with <strong>long offset</strong> Thank you in advance!</p>
[ { "answer_id": 74552900, "author": "Psidom", "author_id": 4983450, "author_profile": "https://Stackoverflow.com/users/4983450", "pm_score": 1, "selected": false, "text": "index columns df = pd.DataFrame([], index=data['YEAR'], columns=data['YEAR'])\ndf\n 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2022 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2023 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2024 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2025 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2026 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2027 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2028 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2029 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2030 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n" }, { "answer_id": 74552904, "author": "Nuri Taş", "author_id": 19255749, "author_profile": "https://Stackoverflow.com/users/19255749", "pm_score": 1, "selected": false, "text": "df.dot replace df.set_index('YEAR').dot(df.set_index('YEAR').T).replace({0:''})\n" }, { "answer_id": 74552917, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 1, "selected": false, "text": "reindex df.reindex(columns=df.columns.union(df['YEAR']))\n YEAR 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n0 2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n1 2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2 2022 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n3 2023 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n4 2024 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n5 2025 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n6 2026 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n7 2027 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n8 2028 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n9 2029 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n10 2030 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n" }, { "answer_id": 74552925, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 0, "selected": false, "text": "pandas.DataFrame.loc df.loc[:, df.set_index(\"YEAR\").index.tolist()]= np.NaN #or \"\"\n print(df)\n\n YEAR 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n0 2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n1 2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2 2022 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n3 2023 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n4 2024 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n5 2025 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n6 2026 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n7 2027 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n8 2028 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n9 2029 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n10 2030 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9152518/" ]
74,552,886
<p>Whenever I run <code>${__timeShift(HH:mm,,PT30M,,)}</code> from the Function Helper, it gives me the time in CST (my local timezone)</p> <p>I'm having trouble figuring out how to use timeShift to evaluate the HH:mm value <strong>without automatically converting it to CST time.</strong> Is there a simple way to do this, or will I need to use to use a JSR223 process to calculate the UTC value and vars.put it as a variable?</p> <p>The ultimate goal is to use this value in an HTTP Sampler.</p> <p>I've tried various combinations of parameters from the <a href="https://www.perfmatrix.com/jmeter-timestamp/" rel="nofollow noreferrer">https://www.perfmatrix.com/jmeter-timestamp/</a></p> <p>Also tried some basic time conversions in a JSR223 process. I am extremely new to both Java and JMeter though, so I haven't had much success.</p>
[ { "answer_id": 74556382, "author": "Charles Pannell", "author_id": 15125248, "author_profile": "https://Stackoverflow.com/users/15125248", "pm_score": 1, "selected": true, "text": "TimeZone.setDefault(TimeZone.getTimeZone('UTC')) def theTime = ${__timeShift(\"HH:mm\",,PT30M,,)}" }, { "answer_id": 74558944, "author": "Dmitri T", "author_id": 2897748, "author_profile": "https://Stackoverflow.com/users/2897748", "pm_score": 2, "selected": false, "text": "${__groovy(java.time.ZonedDateTime.now(java.time.ZoneId.of(\"UTC\")).plusMinutes(30).format(java.time.format.DateTimeFormatter.ofPattern(\"HH:mm\")),)}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15125248/" ]
74,552,896
<p>I'm learning Typescript and I'm trying to run method in a class. I have a Class Person, and two classes which extends the Person Class: Man and Woman.</p> <p>I also have an array of persons, and I need returns hello man! or hello woman! if person is a man or if is a woman.</p> <p>This is my code:</p> <pre><code>abstract class Person { static population: number = 0; constructor() { Person.population ++ ; } } class Man extends Person { age!: number; constructor(age: number) { super(); this.age = age; } public helloMan() { console.log('Hello Man!'); } } class Woman extends Person { age!: number; constructor(age: number) { super(); this.age = age; } public helloWoman() { console.log('Hello Woman!'); } } let persons: Person[] = []; persons.push(new Man(24)); persons.push(new Woman(27)); persons.push(new Man(42)); persons.push(new Woman(35)); for(let person of persons){ let typeOfPerson = Object.getPrototypeOf(person).constructor.name; switch (typeOfPerson) { case &quot;Man&quot;: // run helloMan method break; case &quot;Woman&quot;: // run helloWoman method break; default: break; } } </code></pre> <p>¿How I can run the method of each gender?</p> <p>expected result:</p> <pre><code>Hello Man! Hello Woman! Hello Man! Hello Woman! </code></pre>
[ { "answer_id": 74552945, "author": "Hammerbot", "author_id": 4547701, "author_profile": "https://Stackoverflow.com/users/4547701", "pm_score": 1, "selected": true, "text": "instanceof if (person instanceof Man) {\n person.helloMan()\n} else if (person instanceof Woman) {\n person.helloWoman()\n}\n" }, { "answer_id": 74566061, "author": "Peter Seliger", "author_id": 2627243, "author_profile": "https://Stackoverflow.com/users/2627243", "pm_score": 1, "selected": false, "text": "Person Person helloWoman helloMan Woman Man Person hello instanceof Person population // also see ... typescriptlang.org ... TypeScript Playground\n// [https://www.typescriptlang.org/play?target=99#code/PTAEGMHsFcDsBdQEsDOoAOAnS8Cm48ATUAIwE9QBbSQ6AG11BSnVwFgAoBxdSdegIbwkkWAGEYCAFyhY0SiVyZQAXlAAGANydOAkiniYBBCHQEo0ABSUpRoAN46OoUAGIA5rliElMg5iRYd21nNwFPGTkFJRCXVxQBOmh4IRFYP0NA4KcXKFh-aAJITAAKR1CXT28lVVAAclgcDGwANyQfQjqAGk4XF3DGNQBaAEYeiqZE5NS7NTqACVw6OkgAQm7e0ABfAEoHTZdefjNhUQk4eABqS5CD0HgAC1QAOg8vH2U1Ko-YvseX1wDWpAgB8anUoAA-KAgTJRr8XP8UK8EkkUqdYLVUdMMb8tptPIhvkoSjsMgEgvsJphcPBoJhMUjXsTMHiCbSYZ5SZF5IpMAAfOTLKl9UA0ukM+5PZGAzygMEaKFSgGw2T0Ohs0IPJYrUDc0AtSDtEV9PK2BjPFbuEpM+JTdFpHaalwgUBDWS4JCPGoCUAAA2smFssD9yHyKVg4EYjWU3v9geDfs2rtyZgsyHgKCWADMmA8YHRiNncEJ6YxfVg+Ep4BRismwC5KLT80XiqBcAAPXgoLJSxhHQQYiCSeDPetuvugE54ZQlnt0CjgASYxQw8BPXAtXDEcgw2Dj-qEQhetKJBftrvFIigbNwAhpYBNx40MccfEcTjgNNoADqkEoy4Xng3hWDYdjlLkogFEUpT2JygxumMkxojMmJzIsyyQKAf4AbA6zbHsEF9Cg0CsLBoAsjIdTFgBDDdP0nhdMhOJpARmrvl+5hoAAsoBnbAYQoFBuBmxmoYhTwMUZTwbUoxMdiDqzPUGG6rxeF1ARJouCRZHSZR9S0bg9EDPJ9qoWxmzvu+n5QTwYH5LUADamywLgADu2H-su0kDDIADMACsBHjC4rkeTh3lwb5oAAEwAOzBS57mgGpPkRKAAAsMWJaEYUpZF8EyDFGU5QAuiEZqQBaVrSRgfCDmk5wIBZH4cNmbYlGJGD2aAkC5mRwYoIRmwDaIzzaphpK-JV1WQNazmtaK0k0YkuBURFsAADp1Cg9GGVRanbbtuyOaNsDPCypVQtCdQJqIR0bBMdRAqgj2imdzwmTkoClc8ABWRqwCUGl1DsOycFsQA]\n\n// count is protected by module scope\nlet populationCount/*: number*/ = 0;\n\n/*abstract */class Person {\n\n #gender/*: string*/;\n #age/*: number*/;\n #salutation/*: string*/;\n\n constructor({\n gender = 'not provided',\n age = -1,\n salutation = 'Hello!',\n }) {\n populationCount++;\n\n this.#gender = gender;\n this.#age = age >= 0 ? age : -1;\n this.#salutation = salutation;\n }\n get gender()/*: string*/ {\n return this.#gender;\n }\n get age()/*: number|null*/ {\n return this.#age >= 0 ? this.#age : null;\n }\n hello ()/*: void*/ {\n console.log(this.#salutation);\n }\n // - neither a `Person` instance nor the `Person`\n // class itself should feature a property or\n // method for exposing the population count.\n // - the latter easily can be achieved by an\n // additionally exported function/method.\n}\n\nclass Woman extends Person {\n constructor({ age = -1, salutation = 'Hello Woman!' }) {\n super({ gender: 'female', age, salutation });\n }\n}\nclass Man extends Person {\n constructor({ age = -1, salutation = 'Hello Man!' }) {\n super({ gender: 'male', age, salutation });\n }\n}\n\nconst persons = [\n new Woman({ age: 35 }),\n new Woman({ age: 27 }),\n new Man({ age: 42 }),\n new Man({ age: 24 }),\n];\nconsole.log({ populationCount });\n\nfor (const person of persons) {\n person.hello();\n console.log([\n\n ({ female: 'Woman\\'s', male: 'Man\\'s'})[person.gender] ?? 'Person\\'s',\n 'age is',\n person.age,\n\n ].join(' '))\n} .as-console-wrapper { min-height: 100%!important; top: 0; }" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5718903/" ]
74,552,914
<p>I am currently trying to make a method that will create a query in C# LINQ that will give me the file type, the combined size of the file type, and the total amount of files of that type. I am struggling to get multiple columns and to have the query gather the file size. It seems to only work if I get the file size separately, but still can't seem to sum them up....</p> <p>This one works getting the file size alone:</p> <pre><code> var size = from f in files select (new FileInfo(f).Length); </code></pre> <p>but does not work here and I can't get the file count either:</p> <pre><code> var all = from f in files group Path.GetExtension(f) by Path.GetExtension(f).ToLower() into fileGroup select new { Ext = fileGroup, Byt = new FileInfo(fileGroup).Length }; </code></pre> <p>EDIT:</p> <p>I was able to group by type &amp; count, but still can't figure out how to add up the file sizes by their type:</p> <pre><code> var info = files.Select(f =&gt; Path.GetExtension(f).ToLower()).GroupBy(x =&gt; x, (t, c) =&gt; new { Extension = t, Count = c.Count(), Size = new FileInfo(x).Length </code></pre> <p>I am getting an error for the x</p>
[ { "answer_id": 74552990, "author": "mzm", "author_id": 20564950, "author_profile": "https://Stackoverflow.com/users/20564950", "pm_score": -1, "selected": false, "text": " var size = from f in files\n select (new FileInfo(f).Length);\n" }, { "answer_id": 74553055, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 3, "selected": true, "text": "filePaths FileInfo var fileDataByExtension = filePaths\n .Select(fp => new FileInfo(fp))\n .GroupBy(f => f.Extension)\n .Select(group => new\n {\n Extension = group.Key,\n TotalBytes = group.Sum(f => f.Length),\n TotalFiles = group.Count()\n });\n filePaths FileInfo" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8768617/" ]
74,552,923
<p>I'm having a lot of fun with C#, recently I created a simple &quot;statistics calculator&quot;. It takes in data and calculates the mean, standard deviation etc.</p> <p>However, I want to add something visual to my console apps. For example a diagram showing the data, or a graph (I also want to try coding something with function graphing).</p> <p>How can I do that?</p>
[ { "answer_id": 74552990, "author": "mzm", "author_id": 20564950, "author_profile": "https://Stackoverflow.com/users/20564950", "pm_score": -1, "selected": false, "text": " var size = from f in files\n select (new FileInfo(f).Length);\n" }, { "answer_id": 74553055, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 3, "selected": true, "text": "filePaths FileInfo var fileDataByExtension = filePaths\n .Select(fp => new FileInfo(fp))\n .GroupBy(f => f.Extension)\n .Select(group => new\n {\n Extension = group.Key,\n TotalBytes = group.Sum(f => f.Length),\n TotalFiles = group.Count()\n });\n filePaths FileInfo" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15323416/" ]
74,552,932
<p>I am given a list of old exe files where the original source code are lost.</p> <p>While i am able to extract code from some of the exe files using tools like DotPeek or ILSpy or JustDecompile.</p> <p>I see a couple of them failed to decompile. I am getting the below similar error</p> <p><a href="https://i.stack.imgur.com/kMyBD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kMyBD.png" alt="enter image description here" /></a></p> <p>What would be the next step I need to do to extract code or do reverse engineer?</p> <p>kindly let me know.</p>
[ { "answer_id": 74552990, "author": "mzm", "author_id": 20564950, "author_profile": "https://Stackoverflow.com/users/20564950", "pm_score": -1, "selected": false, "text": " var size = from f in files\n select (new FileInfo(f).Length);\n" }, { "answer_id": 74553055, "author": "gunr2171", "author_id": 1043380, "author_profile": "https://Stackoverflow.com/users/1043380", "pm_score": 3, "selected": true, "text": "filePaths FileInfo var fileDataByExtension = filePaths\n .Select(fp => new FileInfo(fp))\n .GroupBy(f => f.Extension)\n .Select(group => new\n {\n Extension = group.Key,\n TotalBytes = group.Sum(f => f.Length),\n TotalFiles = group.Count()\n });\n filePaths FileInfo" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3895221/" ]
74,552,937
<p>I am executing a command line program from Delphi.</p> <p>I am using CreateProcess as I need to capture the output and display it in a memo.</p> <p>My problem now is that the program I am executing needs to run &quot;as administrator&quot; to work properly. If I run it in an &quot;as administrator&quot; command prompt it executes fine.</p> <p>How do I tell the CreateProcess to run as administrator? I see ShellExecute has an lpVerb parameter that can be set to 'runas' for this to work, but I need CreateProcess to be able to capture the command line output and display it.</p> <p>I thought if I run my exe as administrator those rights would be passed down to the CreateProcess cmd, but it does not look like that happens.</p> <p>Any ideas on how I can tell CreateProcess I want to run the process elevated?</p> <p>Here is the working code now that launches a command line fine (just not as admin)</p> <pre><code>var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; Handle: Boolean; begin with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0); try with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; Handle := CreateProcess(nil, PWideChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil, PWideChar(WorkDir), SI, PI); </code></pre>
[ { "answer_id": 74554583, "author": "Remy Lebeau", "author_id": 65863, "author_profile": "https://Stackoverflow.com/users/65863", "pm_score": 2, "selected": true, "text": "requestedExecutionLevel requireAdministrator CreateProcess() ERROR_ELEVATION_REQUIRED CreateProcess() ShellExecute/Ex() \"runas\" ShellExecute/Ex(\"runas\") CreateProcess() CreateProcess CreateProcessElevated()" }, { "answer_id": 74556736, "author": "fisi-pjm", "author_id": 9868828, "author_profile": "https://Stackoverflow.com/users/9868828", "pm_score": 0, "selected": false, "text": "function RunAsAdmin(hWnd: hWnd; filename: string; Parameters: string; Visible: Boolean = true): Boolean;\n{\n See Step 3: Redesign for UAC Compatibility (UAC)\n http://msdn.microsoft.com/en-us/library/bb756922.aspx\n This code is released into the public domain. No attribution required.\n}\nvar\n sei: TShellExecuteInfo;\nbegin\n ZeroMemory(@sei, SizeOf(sei));\n sei.cbSize := SizeOf(TShellExecuteInfo);\n sei.Wnd := hWnd;\n sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI;\n sei.lpVerb := PChar('runas');\n sei.lpFile := PChar(filename); // PAnsiChar;\n if Parameters <> '' then\n sei.lpParameters := PChar(Parameters); // PAnsiChar;\n if Visible then\n sei.nShow := SW_SHOWNORMAL // Integer;\n else\n sei.nShow := SW_HIDE;\n\n Result := ShellExecuteEx(@sei);\nend;\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4237309/" ]
74,552,950
<p>I have a large numpy array whNumPylements I individually want to multiply with other indexes and then sum up. My current code is relatively slow, does anyone have an idea how I could make it faster:</p> <pre><code>result = 0 n = 1 int_array = np.array((3,16,3,29,36)) for i in int_array: result += int(i) * n n *= 10 </code></pre>
[ { "answer_id": 74552986, "author": "lemmgua", "author_id": 20281146, "author_profile": "https://Stackoverflow.com/users/20281146", "pm_score": -1, "selected": false, "text": "n n i i" }, { "answer_id": 74553004, "author": "I'mahdi", "author_id": 1740577, "author_profile": "https://Stackoverflow.com/users/1740577", "pm_score": 3, "selected": true, "text": "10 * prev(10 * ...) 10 ^ [0, 1, 2, ...] = [1, 10, 100, ...] numpy.power [1*int_arr[0], 10*int_arr[1], ...] numpy.sum() res = (np.power(10, np.arange(int_array.shape[0])) * int_array).sum()\n\nprint(res)\n 389463\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74552950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13216239/" ]
74,553,012
<pre><code>(define (iterate list) (cond ((null? list) '()) </code></pre> <p>So far all I have is that it checks if it is a null list. If it is then it passes the empty list. What I am trying to do is I want to iterate through the list until I find the last element. I want to loop the list cdr until cdr shows up as null. I understand the logic but not the syntax.</p> <p>For a list (1 2 3 4) I want to be able to see that 4 is the last element.</p>
[ { "answer_id": 74553788, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 0, "selected": false, "text": "null? (iterate (cdr list))\n iterate(...) iterate" }, { "answer_id": 74562535, "author": "Little Helper", "author_id": 3341241, "author_profile": "https://Stackoverflow.com/users/3341241", "pm_score": 2, "selected": false, "text": "get-last (define (get-last list)\n (cond\n [(null? list) (raise 'empty-list)]\n [(null? (cdr list)) (car list)]\n [else (get-last (cdr list))]\n))\n [] cond () (get-last '(1 2 3 4))" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18340746/" ]
74,553,018
<p>I have a hard time wrapping my head around some aspects of RxJS operators. I have some code here (in a component):</p> <pre><code>extendedOrders$ = this.salesService.getOrders().pipe( switchMap(orders =&gt; { return forkJoin(orders.map(order =&gt; { return this.salesService.getOrderCustomers(order.id).pipe( map(customer =&gt; ({ ...order, customerName: customer.name })), ); })); }), ); </code></pre> <p>It is possibile extend it and do more then one call inside the forkJoin? For example, another call to another getById service and merge the response in the same object?</p> <p><strong>UPDATE</strong></p> <p>My first try:</p> <pre><code>this.salesService.getOrders().pipe( switchMap(orders =&gt; { return forkJoin( orders.map(order =&gt; { return { ...order, idAttr1: this.service1.method1(order.idAttr1).pipe( map(result =&gt; result.name) ), idAttr2: this.service2.method2(order.idAttr2).pipe( map(result =&gt; result.name) ), }; }) ); }) ) .subscribe((result) =&gt; { console.log(result); }); </code></pre>
[ { "answer_id": 74553788, "author": "Sylwester", "author_id": 1565698, "author_profile": "https://Stackoverflow.com/users/1565698", "pm_score": 0, "selected": false, "text": "null? (iterate (cdr list))\n iterate(...) iterate" }, { "answer_id": 74562535, "author": "Little Helper", "author_id": 3341241, "author_profile": "https://Stackoverflow.com/users/3341241", "pm_score": 2, "selected": false, "text": "get-last (define (get-last list)\n (cond\n [(null? list) (raise 'empty-list)]\n [(null? (cdr list)) (car list)]\n [else (get-last (cdr list))]\n))\n [] cond () (get-last '(1 2 3 4))" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064283/" ]
74,553,030
<p>How can I find the most recently modified *.ipynb files in the subtree starting from the current directory? Ideally I would like a sorted list with the most recently modified ones shown first.</p> <p>I am using Ubuntu 22.04 and am happy to use GNU tools.</p>
[ { "answer_id": 74553052, "author": "Gilles Quenot", "author_id": 465183, "author_profile": "https://Stackoverflow.com/users/465183", "pm_score": 2, "selected": false, "text": "(shopt -s globstar; ls -lt **/*.ipynb)\n" }, { "answer_id": 74554176, "author": "Maximilian Ballard", "author_id": 6060841, "author_profile": "https://Stackoverflow.com/users/6060841", "pm_score": 0, "selected": false, "text": "find stat sort find . -type f -iname '*.ipynb' -exec stat --format=\"%y %n\" {} \\; | sort\n 2022-08-24 05:53:38.525297805 -0400 ./Desktop/fileone.pynb\n2022-11-04 01:51:18.894946451 -0400 ./.local/filetwo.pynb\n2022-11-13 20:26:53.897667918 -0500 ./go/pkg/mod/github.com/filethree.pynb\n" }, { "answer_id": 74555899, "author": "Rachel", "author_id": 20516968, "author_profile": "https://Stackoverflow.com/users/20516968", "pm_score": 0, "selected": false, "text": "find . -type f -newermt \"-24 hours\" \n find . -type f -newermt \"-10 minutes\" \nfind . -type f -newermt \"1 day ago\" \nfind . -type f -newermt \"yesterday\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473517/" ]
74,553,095
<p>I've data like below:</p> <pre><code>ID Task Time 1 X started T1 2 X ended T2 3 X started T3 [wrong entry in data] 4 X started T4 5 X ended T5 6 Y started T6 [wrong entry in data] 7 Y started T7 8 Y ended T8 </code></pre> <p>And, I need to get the data from above in started/ended fashion, but in case of wrong entry I need to pickup the latest one [as T4&gt;T3 and T7&gt;T6]. How can I write SQL on above dataset to get below result ?</p> <pre><code>ID Task Time 1 X started T1 2 X ended T2 4 X started T4 5 X ended T5 7 Y started T7 8 Y ended T8 </code></pre>
[ { "answer_id": 74553409, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "row_number() select max(ID), Task, max(Time) Time\nfrom\n(\n select *,\n row_number() over (order by Time) -\n row_number() over (partition by Task order by Time) grp\n from table_name\n) T\ngroup by Task, grp\norder by max(Time)\n set @gr=0;\nset @ts=null;\n\nselect max(ID), Task, max(Time) \nTime\nfrom\n(\n select *,\n if(@ts<>Task, @gr:=@gr+1, \n@gr) grp,\n @ts:=Task\n from table_name\n order by Time\n) T\ngroup by Task, grp\norder by max(Time)\n" }, { "answer_id": 74553819, "author": "Clint", "author_id": 7879634, "author_profile": "https://Stackoverflow.com/users/7879634", "pm_score": 0, "selected": false, "text": "SELECT * FROM `mytable` p1 \nwhere id = (select id from `mytable` p2 \n where p2.task= p1.task\n order by id DESC limit 1); \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10227815/" ]
74,553,126
<p>I´m trying write a function that returns a list with the positions for each capital letter it doesn’t work with when the capital letter in the string is repeated.</p> <pre><code>def capital_indexes(word): cap = [] for i in word: if i == i.upper(): cap.append(word.index(i)) return cap </code></pre> <pre><code>print(capital_indexes(&quot;HelloWorld&quot;)) [0, 5] </code></pre> <pre><code>print(capital_indexes(&quot;HoHoHoHo&quot;)) [0, 0, 0, 0] </code></pre>
[ { "answer_id": 74553409, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "row_number() select max(ID), Task, max(Time) Time\nfrom\n(\n select *,\n row_number() over (order by Time) -\n row_number() over (partition by Task order by Time) grp\n from table_name\n) T\ngroup by Task, grp\norder by max(Time)\n set @gr=0;\nset @ts=null;\n\nselect max(ID), Task, max(Time) \nTime\nfrom\n(\n select *,\n if(@ts<>Task, @gr:=@gr+1, \n@gr) grp,\n @ts:=Task\n from table_name\n order by Time\n) T\ngroup by Task, grp\norder by max(Time)\n" }, { "answer_id": 74553819, "author": "Clint", "author_id": 7879634, "author_profile": "https://Stackoverflow.com/users/7879634", "pm_score": 0, "selected": false, "text": "SELECT * FROM `mytable` p1 \nwhere id = (select id from `mytable` p2 \n where p2.task= p1.task\n order by id DESC limit 1); \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19699716/" ]
74,553,128
<p>I have a list of lists that make up a tree, similar to a top level directory with a recursive listing of directories and files. I want to visualize this as a printed tree.</p> <p><strong>How can a see a list of lists printed as a tree?</strong></p> <h2>Data</h2> <pre><code>tree = [ ['Main University'], ['Main University', 'Academic Affairs'], ['Main University', 'Academic Affairs', 'College of Health Sciences'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Biology'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Chemistry/Physics'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Chemistry/Physics', 'Physics'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Biology', 'Biochemistry &amp; Molecular Bio'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Biology', 'Earth Sciences'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Biology', 'Environmental Studies'], ['Main University', 'Academic Affairs', 'College of Health Sciences', 'Social Work'], ['Main University', 'Academic Affairs', 'College of Arts &amp; Science', 'Chemistry/Physics', 'Chemistry'], ['Main University', 'Academic Affairs', 'College of Health Sciences', 'Health Sciences'], ['Main University', 'Academic Affairs', 'College of Health Sciences', 'Occupational Therapy'] ] </code></pre> <h2>Desired Output (or similar; i.e., glyphs like <code>¦--</code>, <code>°--</code>, etc. don't matter)</h2> <pre><code>Main University °--Academic Affairs ¦--College of Arts &amp; Science ¦ ¦--Chemistry/Physics ¦ ¦ ¦--Physics ¦ ¦ °--Chemistry ¦ °--Biology ¦ ¦--Biochemistry &amp; Molecular Bio ¦ ¦--Earth Sciences ¦ °--Environmental Studies °--College of Health Sciences ¦--Health Sciences ¦--Occupational Therapy °--Social Work </code></pre>
[ { "answer_id": 74553409, "author": "ahmed", "author_id": 12705912, "author_profile": "https://Stackoverflow.com/users/12705912", "pm_score": 2, "selected": true, "text": "row_number() select max(ID), Task, max(Time) Time\nfrom\n(\n select *,\n row_number() over (order by Time) -\n row_number() over (partition by Task order by Time) grp\n from table_name\n) T\ngroup by Task, grp\norder by max(Time)\n set @gr=0;\nset @ts=null;\n\nselect max(ID), Task, max(Time) \nTime\nfrom\n(\n select *,\n if(@ts<>Task, @gr:=@gr+1, \n@gr) grp,\n @ts:=Task\n from table_name\n order by Time\n) T\ngroup by Task, grp\norder by max(Time)\n" }, { "answer_id": 74553819, "author": "Clint", "author_id": 7879634, "author_profile": "https://Stackoverflow.com/users/7879634", "pm_score": 0, "selected": false, "text": "SELECT * FROM `mytable` p1 \nwhere id = (select id from `mytable` p2 \n where p2.task= p1.task\n order by id DESC limit 1); \n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000343/" ]
74,553,131
<p>I have started using VSCode and was wondering what the <code>/</code> meant when I click on a file (see attached screenshot). Is it simply the full path of the file that I've clicked on? Thanks!</p> <p><a href="https://i.stack.imgur.com/SFQmL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SFQmL.png" alt="Screenshot" /></a></p>
[ { "answer_id": 74554360, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 0, "selected": false, "text": "X/\n├─ a/\n│ ├─ a1/\n│ │ └- a1.txt\n│ └- a2/\n│ └- a2.txt\n└ b/\n └- b1/\n └- b1.txt\n b1 b b b1" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8897159/" ]
74,553,149
<p>What to do I'm doing a project with a friend and I'm throwing him the project files, he opens the project and shows this error in Unity Hub, this did not happen before, and after one moment it began to appear, I don't have such an error, the Internet is almost empty about it. What to do?</p> <p><a href="https://i.stack.imgur.com/Z9tWJ.png" rel="nofollow noreferrer">nice error</a></p> <p>I solved the problem, I just needed to create a new folder for projects</p>
[ { "answer_id": 74554360, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 0, "selected": false, "text": "X/\n├─ a/\n│ ├─ a1/\n│ │ └- a1.txt\n│ └- a2/\n│ └- a2.txt\n└ b/\n └- b1/\n └- b1.txt\n b1 b b b1" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585577/" ]
74,553,157
<p>Hello I am trying to change the color of icon using dom. When I do that changing icon to h6 and instead of icon-exclamation use the text ! it works. How to apply it on the icon. Html code which do it:</p> <pre><code>&lt;div class =&quot;indicator&quot;&gt; &lt;i id =&quot;exclamation&quot; class = &quot;icon-exclamation&quot;&gt;&lt;/i&gt; &lt;h6 id = &quot;pinfo&quot; class =&quot;passwordinfo&quot; &gt;dupa&lt;/h6&gt; &lt;/div&gt; &lt;script&gt; var pass = document.getElementById(&quot;password&quot;); var pinfo =document.getElementById(&quot;pinfo&quot;); var exc = document.getElementById(&quot;exclamation&quot;); console.log(exc[0]) pass.addEventListener('input', ()=&gt; { if (pass.value.length === 0) { pinfo.innerHTML = &quot;Waiting for your password&quot; } else if (pass.value.length &lt;=4) { pinfo.style.visibility = &quot;visible&quot;; exc.style.color = &quot;blue&quot;; exc.style.display = &quot;block&quot;; // exc.style.display = 'block'; pinfo.innerHTML = &quot;Password is weak&quot;; pinfo.style.color = &quot;#ff0000&quot; } else if (pass.value.length &gt;=4 &amp;&amp; pass.value.length &lt;8) { pinfo.innerHTML = &quot;Password is medium&quot;; pinfo.style.color =&quot;#ff8000&quot;; } else { pinfo.innerHTML = &quot;Password is strong&quot;; pinfo.style.color = &quot;#00ff00&quot;; } }) &lt;/script&gt; </code></pre> <p>Why this code doesn't work and how to change the color of the icon dynamically?</p>
[ { "answer_id": 74553433, "author": "Dream Bold", "author_id": 12743692, "author_profile": "https://Stackoverflow.com/users/12743692", "pm_score": 1, "selected": false, "text": "https://codesandbox.io/s/mutable-sea-fl3320?file=/src/index.js fontawesome fontello fontawesome fontawesome <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n\n<div class=\"indicator\">\n <input id=\"password\" />\n <input id=\"pinfo\" />\n\n<!-- <i class=\"icon-exclamation\"></i> -->\n <i id=\"exclamation\" class=\"fa fa-exclamation-circle fa-2x\"></i>\n <h6 id=\"pinfo\" class=\"passwordinfo\">dupa</h6>\n</div>\n" }, { "answer_id": 74553630, "author": "El Captus", "author_id": 20584650, "author_profile": "https://Stackoverflow.com/users/20584650", "pm_score": 0, "selected": false, "text": "pass.addEventListener('input', () => {\n if (pass.value.length === 0)\n {\n pinfo.innerHTML = \"Waiting for your password\"\n }\n else if (pass.value.length <=4)\n {\n pinfo.style.visibility = \"visible\";\n exc.style.color = \"blue\";\n exc.style.display = \"block\";\n\n pinfo.innerHTML = \"Password is weak\";\n pinfo.style.color = \"#ff0000\"\n }\n else if (pass.value.length >=4 && pass.value.length <8)\n {\n pinfo.innerHTML = \"Password is medium\";\n pinfo.style.color =\"#ff8000\";\n exc.style.color = \"orange\";\n }\n else\n {\n pinfo.innerHTML = \"Password is strong\";\n pinfo.style.color = \"#00ff00\";\n exc.style.color = \"yellow\";\n }\n\n })\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17575080/" ]
74,553,160
<p>i want for loop to create symbolic link for All the files under <code>/root/Desktop/match/jars/44a65820/*</code> to be under this path <code>/root/Desktop/match/jars/</code> as symbolic link without version 44a65820 for example</p> <pre><code>match@match:~/Desktop/match/jars# ls -ll total 4 /root/Desktop/match/jars/match-five.jar -&gt; /root/Desktop/match/jars/44a65820/match-five-44a65820.jar /root/Desktop/match/jars/match-four.jar -&gt; /root/Desktop/match/jars/44a65820/match-four-44a65820.jar /root/Desktop/match/jars/match-one.jar -&gt; /root/Desktop/match/jars/44a65820/match-one-44a65820.jar /root/Desktop/match/jars/match-three.jar -&gt; /root/Desktop/match/jars/44a65820/match-three-44a65820.jar /root/Desktop/match/jars/match-two.jar -&gt; /root/Desktop/match/jars/44a65820/match-two-44a65820.jar root/Desktop/match/jars/match-six.jar -&gt; /root/Desktop/match/jars/44a65820/match-six-44a65820.jar </code></pre> <p>i don't know how to do?</p>
[ { "answer_id": 74553231, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "for f in /root/Desktop/match/jars/44a65820/*; do\n link=\"${f%-44a65820.jar}.jar\";\n ln -s \"$f\" \"/root/Desktop/match/jars/${link##*/}\";\ndone\n" }, { "answer_id": 74557029, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 0, "selected": false, "text": "shell> tree /tmp/match\n/tmp/match\n└── jars\n └── 44a65820\n ├── one.jar\n ├── three.jar\n └── two.jar\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n match_files:\n - /tmp/match/jars/44a65820/two.jar\n - /tmp/match/jars/44a65820/one.jar\n - /tmp/match/jars/44a65820/three.jar\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n shell> tree /tmp/match\n/tmp/match\n└── jars\n ├── 44a65820\n │   ├── one.jar\n │   ├── three.jar\n │   └── two.jar\n ├── one.jar -> /tmp/match/jars/44a65820/one.jar\n ├── three.jar -> /tmp/match/jars/44a65820/three.jar\n └── two.jar -> /tmp/match/jars/44a65820/two.jar\n - hosts: localhost\n\n vars:\n\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n\n tasks:\n\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n - debug:\n var: match_files\n\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12040472/" ]
74,553,173
<p>I am iterating through a list of dictionaries. I need to update the values for one specific key in all the dictionaries and I have the new values stored in a list. The list of new values is ordered so that the 1st new value belongs to a key in the 1st dictionary, 2nd new value to a key in the 2nd dictionary, etc.</p> <p>My data looks something like this:</p> <pre><code>dict_list = [{'person':'Tom', 'job':'student'}, {'person':'John', 'job':'teacher'}, {'person':'Mary', 'job':'manager'}] new_jobs = ['lecturer', 'cook', 'driver'] </code></pre> <p>And I want to transform the list of dictionaries using the list of new jobs according to my description into this:</p> <pre><code>dict_list = [{'person':'Tom', 'job':'lecturer'}, {'person':'John', 'job':'cook'}, {'person':'Mary', 'job':'driver'}] </code></pre> <p>As I have a very long list of dictionaries I would like to define a function that would do this automatically but I am struggling how to do it with for loops and zip(), any suggestions?</p> <p>I tried the for loop below. I guess the following code could work if it was possible to index the dictionaries like this <code>dictionary['job'][i]</code> Unfortunately dictionaries don't work like this as far as I know.</p> <pre><code>def update_dic_list(): for dictionary in dict_list: for i in range(len(new_jobs)): dictionary['job'] = new_jobs[i] print(dict_list) </code></pre> <p>The output the code above gave me was this:</p> <pre><code>[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'teacher'}, {'person': 'Mary', 'job': 'manager'}] [{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'manager'}] [{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'driver'}] </code></pre>
[ { "answer_id": 74553231, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "for f in /root/Desktop/match/jars/44a65820/*; do\n link=\"${f%-44a65820.jar}.jar\";\n ln -s \"$f\" \"/root/Desktop/match/jars/${link##*/}\";\ndone\n" }, { "answer_id": 74557029, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 0, "selected": false, "text": "shell> tree /tmp/match\n/tmp/match\n└── jars\n └── 44a65820\n ├── one.jar\n ├── three.jar\n └── two.jar\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n match_files:\n - /tmp/match/jars/44a65820/two.jar\n - /tmp/match/jars/44a65820/one.jar\n - /tmp/match/jars/44a65820/three.jar\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n shell> tree /tmp/match\n/tmp/match\n└── jars\n ├── 44a65820\n │   ├── one.jar\n │   ├── three.jar\n │   └── two.jar\n ├── one.jar -> /tmp/match/jars/44a65820/one.jar\n ├── three.jar -> /tmp/match/jars/44a65820/three.jar\n └── two.jar -> /tmp/match/jars/44a65820/two.jar\n - hosts: localhost\n\n vars:\n\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n\n tasks:\n\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n - debug:\n var: match_files\n\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15238944/" ]
74,553,190
<p>Im trying to make a complex queryset and I want to include my <code>ForeignKeys</code> names instead of pk. I'm using ajax to get a live feed from user inputs and print the results on a <code>DataTable</code> but I want to print the names instead of the pk. Im getting a queryset and when I <code>console.log</code> it, <code>sensor_name</code> is not in there. My models are like this:</p> <pre><code>class TreeSensor(models.Model): class Meta: verbose_name_plural = &quot;Tree Sensors&quot; field = models.ForeignKey(Field, on_delete=models.CASCADE) sensor_name = models.CharField(max_length=200, blank=True) datetime = models.DateTimeField(blank=True, null=True, default=now) longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) class TreeSensorMeasurement(models.Model): class Meta: verbose_name_plural = &quot;Tree Sensor Measurements&quot; sensor = models.ForeignKey(TreeSensor, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=None) soil_moisture_depth_1 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_2 = models.DecimalField(max_digits=15, decimal_places=2) soil_moisture_depth_1_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_moisture_depth_2_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) soil_temperature = models.DecimalField(max_digits=15, decimal_places=2) </code></pre> <p>And my view looks like this(I've omitted the non-essential code):</p> <pre><code>field_list = Field.objects.filter(user=request.user) tree_sensors = TreeSensor.objects.filter(field_id__in=field_list.values_list('id', flat=True)) statSensors = (TreeSensorMeasurement.objects .filter(sensor_id__in=tree_sensors.values_list('id', flat=True)) .filter(datetime__date__lte=To_T[0]).filter(datetime__date__gte=From_T[0]) .filter(soil_moisture_depth_1__lte=To_T[1]).filter(soil_moisture_depth_1__gte=From_T[1]) .filter(soil_moisture_depth_2__lte=To_T[2]).filter(soil_moisture_depth_2__gte=From_T[2]) .filter(soil_temperature__lte=To_T[3]).filter(soil_temperature__gte=From_T[3]) .order_by('sensor', 'datetime')) TreeData = serializers.serialize('json', statSensors) </code></pre> <p>The code above works correctly but I cant figure out the twist I need to do to get the <code>TreeSensors</code> name instead of pk in the frontend. An example of how I receive one instance in the frontend:</p> <pre><code>datetime: &quot;2022-11-20T13:28:45.901Z&quot; ​​​sensor: 2 ​​​soil_moisture_depth_1: &quot;166.00&quot; ​​​soil_moisture_depth_1_filtered: &quot;31.00&quot; ​​​soil_moisture_depth_2: &quot;171.00&quot; ​​​soil_moisture_depth_2_filtered: &quot;197.00&quot; soil_temperature: &quot;11.00&quot; </code></pre>
[ { "answer_id": 74553231, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "for f in /root/Desktop/match/jars/44a65820/*; do\n link=\"${f%-44a65820.jar}.jar\";\n ln -s \"$f\" \"/root/Desktop/match/jars/${link##*/}\";\ndone\n" }, { "answer_id": 74557029, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 0, "selected": false, "text": "shell> tree /tmp/match\n/tmp/match\n└── jars\n └── 44a65820\n ├── one.jar\n ├── three.jar\n └── two.jar\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n match_files:\n - /tmp/match/jars/44a65820/two.jar\n - /tmp/match/jars/44a65820/one.jar\n - /tmp/match/jars/44a65820/three.jar\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n shell> tree /tmp/match\n/tmp/match\n└── jars\n ├── 44a65820\n │   ├── one.jar\n │   ├── three.jar\n │   └── two.jar\n ├── one.jar -> /tmp/match/jars/44a65820/one.jar\n ├── three.jar -> /tmp/match/jars/44a65820/three.jar\n └── two.jar -> /tmp/match/jars/44a65820/two.jar\n - hosts: localhost\n\n vars:\n\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n\n tasks:\n\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n - debug:\n var: match_files\n\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,553,221
<p>I have a very simple test written, which only checks whether some text is displayed on screen. But it gives an error saying <code>useNavigate() may be used only in the context of a &lt;Router&gt; component.</code>, which is located in <code>LoginButton.js</code>.</p> <pre><code>useNavigate() may be used only in the context of a &lt;Router&gt; component. 10 | const service = new AccountService(); 11 | const value = useContext(userContext); &gt; 12 | const navigate = useNavigate(); | ^ 13 | 14 | function handleLogin(user){ 15 | value.userLogin(user); </code></pre> <p>index.js</p> <pre><code>const root = ReactDOM.createRoot(document.getElementById('root')); root.render( &lt;BrowserRouter&gt; &lt;App /&gt; &lt;/BrowserRouter&gt; ); </code></pre> <p>App.js</p> <pre><code>export default function App() { const service = new AccountService(); const [stateUser, setStateUser] = useState(null); const navigate = useNavigate(); let user; // some extra code... return ( &lt;div className=&quot;App&quot;&gt; &lt;userContext.Provider value={value}&gt; &lt;Navbar/&gt; &lt;Routes&gt; &lt;Route path='/' element={&lt;Posts/&gt;}/&gt; &lt;Route path='/login' element={&lt;Login/&gt;}/&gt; &lt;Route path='/posts' element={&lt;Posts/&gt;}/&gt; &lt;/Routes&gt; &lt;/userContext.Provider&gt; &lt;/div&gt; ); } </code></pre> <p>Login.js</p> <pre><code>export default function Login() { const value = useContext(userContext); return ( &lt;&gt; &lt;div className='w-full h-[80vh] flex justify-center items-center'&gt; &lt;GoogleOAuthProvider clientId={process.env.REACT_APP_CLIENT_ID}&gt; &lt;LoginButton value={value}/&gt; &lt;/GoogleOAuthProvider&gt; &lt;/div&gt; &lt;/&gt; ) } </code></pre> <p>LoginButton.js</p> <pre><code>export const LoginButton = () =&gt; { const service = new AccountService(); const value = useContext(userContext); const navigate = useNavigate(); function handleLogin(user){ value.userLogin(user); service.setUserSession(JSON.stringify(user)); navigate('/posts'); } const googleLogin = useGoogleLogin({ onSuccess: async (tokenResponse) =&gt; { console.log(tokenResponse); const userInfo = await axios.get( &quot;https://www.googleapis.com/oauth2/v3/userinfo&quot;, { headers: { Authorization: 'Bearer ' + tokenResponse.access_token } } ); handleLogin(userInfo.data); }, onError: (errorResponse) =&gt; console.log(errorResponse), }); return &lt;GoogleButton onClick={googleLogin}&gt;Login&lt;/GoogleButton&gt;; }; </code></pre> <p>The test:</p> <pre><code>import { render, screen } from '@testing-library/react'; import App from './App'; import Login from './Pages/Login'; test('renders login in nav', () =&gt; { render(&lt;Login /&gt;); const linkElement = screen.getByText(/Login/i); expect(linkElement).toBeInTheDocument(); }); </code></pre>
[ { "answer_id": 74553231, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "for f in /root/Desktop/match/jars/44a65820/*; do\n link=\"${f%-44a65820.jar}.jar\";\n ln -s \"$f\" \"/root/Desktop/match/jars/${link##*/}\";\ndone\n" }, { "answer_id": 74557029, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 0, "selected": false, "text": "shell> tree /tmp/match\n/tmp/match\n└── jars\n └── 44a65820\n ├── one.jar\n ├── three.jar\n └── two.jar\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n match_files:\n - /tmp/match/jars/44a65820/two.jar\n - /tmp/match/jars/44a65820/one.jar\n - /tmp/match/jars/44a65820/three.jar\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n shell> tree /tmp/match\n/tmp/match\n└── jars\n ├── 44a65820\n │   ├── one.jar\n │   ├── three.jar\n │   └── two.jar\n ├── one.jar -> /tmp/match/jars/44a65820/one.jar\n ├── three.jar -> /tmp/match/jars/44a65820/three.jar\n └── two.jar -> /tmp/match/jars/44a65820/two.jar\n - hosts: localhost\n\n vars:\n\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n\n tasks:\n\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n - debug:\n var: match_files\n\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19163958/" ]
74,553,238
<p>I have a 26MB JSON file containing UN/LOCODE data that I want to restructure and remove some data from so that it takes less space in my app's binary package.</p> <p>The JSON contains an array of objects like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;Change&quot;: null, &quot;Coordinates&quot;: &quot;4234N 00135E&quot;, &quot;Country&quot;: &quot;AD&quot;, &quot;Date&quot;: &quot;0307&quot;, &quot;Function&quot;: &quot;--3-----&quot;, &quot;IATA&quot;: null, &quot;Location&quot;: &quot;CAN&quot;, &quot;Name&quot;: &quot;Canillo&quot;, &quot;NameWoDiacritics&quot;: &quot;Canillo&quot;, &quot;Remarks&quot;: null, &quot;Status&quot;: &quot;RL&quot;, &quot;Subdivision&quot;: null } </code></pre> <p>The desired structure is an object rather than an array, keyed on the concatenation of the Country and Location fields, but the only nested fields that I am interested in are &quot;Name&quot; and &quot;Coordinates&quot;.</p> <p>I have been able to accomplish the first step with:</p> <pre><code>jq 'INDEX(&quot;\(.Country)-\(.Location)&quot;)' </code></pre> <p>giving me:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;AD-CAN&quot;: { &quot;Change&quot;: null, &quot;Coordinates&quot;: &quot;4234N 00135E&quot;, &quot;Country&quot;: &quot;AD&quot;, &quot;Date&quot;: &quot;0307&quot;, &quot;Function&quot;: &quot;--3-----&quot;, &quot;IATA&quot;: null, &quot;Location&quot;: &quot;CAN&quot;, &quot;Name&quot;: &quot;Canillo&quot;, &quot;NameWoDiacritics&quot;: &quot;Canillo&quot;, &quot;Remarks&quot;: null, &quot;Status&quot;: &quot;RL&quot;, &quot;Subdivision&quot;: null }, ... } </code></pre> <p>but I cannot figure out how to get only the desired keys from the nested objects inside the new top-level object.</p> <p>If this can't be done with <code>jq</code> I'll have to resort to a custom script to do it.</p>
[ { "answer_id": 74553231, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 2, "selected": true, "text": "for f in /root/Desktop/match/jars/44a65820/*; do\n link=\"${f%-44a65820.jar}.jar\";\n ln -s \"$f\" \"/root/Desktop/match/jars/${link##*/}\";\ndone\n" }, { "answer_id": 74557029, "author": "Vladimir Botka", "author_id": 6482561, "author_profile": "https://Stackoverflow.com/users/6482561", "pm_score": 0, "selected": false, "text": "shell> tree /tmp/match\n/tmp/match\n└── jars\n └── 44a65820\n ├── one.jar\n ├── three.jar\n └── two.jar\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n match_files:\n - /tmp/match/jars/44a65820/two.jar\n - /tmp/match/jars/44a65820/one.jar\n - /tmp/match/jars/44a65820/three.jar\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n shell> tree /tmp/match\n/tmp/match\n└── jars\n ├── 44a65820\n │   ├── one.jar\n │   ├── three.jar\n │   └── two.jar\n ├── one.jar -> /tmp/match/jars/44a65820/one.jar\n ├── three.jar -> /tmp/match/jars/44a65820/three.jar\n └── two.jar -> /tmp/match/jars/44a65820/two.jar\n - hosts: localhost\n\n vars:\n\n match_files: \"{{ st.files|map(attribute='path')|list }}\"\n\n tasks:\n\n - find:\n path: /tmp/match\n file_type: file\n patterns: '*.jar'\n recurse: true\n register: st\n - debug:\n var: match_files\n\n - file:\n state: link\n src: \"{{ item }}\"\n dest: \"{{ path }}/{{ file }}\"\n loop: \"{{ match_files }}\"\n vars:\n arr: \"{{ item.split('/') }}\"\n path: \"{{ arr[:-2]|join('/') }}\"\n file: \"{{ arr[-1] }}\"\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6782/" ]
74,553,270
<p>I have a record <code>AuthResult</code> with a class object <code>User</code> in it:</p> <pre><code>public record AuthResult( User User, string Token); public class User { public Guid Id { get; set; } = Guid.NewGuid(); public string UserName { get; set; } = null!; public string Email { get; set; } = null!; public string Password { get; set; } = null!; } </code></pre> <p>Which I want to map to a flat record <code>AuthResponse</code>:</p> <pre><code>public record AuthResponse( Guid Id, string UserName, string Email, string Token); </code></pre> <p>Mapping:</p> <pre><code>_mapper.Map&lt;AuthResponse&gt;(authResult) </code></pre> <p>Configurations I tried:</p> <pre><code>CreateMap&lt;User, AuthResponse&gt;(); // Gives &quot;AuthResponse does not have a matching constructor with a parameter named 'Token'&quot; exception CreateMap&lt;AuthResult, AuthResponse&gt;() .ForCtorParam(ctorParamName: nameof(AuthResponse.Token), opt =&gt; opt.MapFrom(src =&gt; src.Token)) .AfterMap((src, dest, context) =&gt; context.Mapper.Map(src.User, dest)); // Gives &quot;AuthResponse needs to have a constructor with 0 args or only optional args.&quot; CreateMap&lt;AuthResult, AuthResponse&gt;().IncludeMembers(src =&gt; src.User); // Gives &quot;AuthResponse needs to have a constructor with 0 args or only optional args.&quot; CreateMap&lt;AuthResult, AuthResponse&gt;() .ConvertUsing((wrapper, destination, context) =&gt; context.Mapper.Map&lt;AuthResponse&gt;(wrapper.User)); </code></pre> <p>Am I missing something or that impossible to do with the AutoMapper?</p>
[ { "answer_id": 74553682, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "IConfigurationProvider configuration = new MapperConfiguration(cfg =>\n cfg.CreateMap<AuthResult, AuthResponse>()\n .ForCtorParam(ctorParamName: nameof(AuthResponse.Id), m => m.MapFrom(s => s.User.Id))\n .ForCtorParam(ctorParamName: nameof(AuthResponse.UserName), m => m.MapFrom(s => s.User.UserName))\n .ForCtorParam(ctorParamName: nameof(AuthResponse.Email), m => m.MapFrom(s => s.User.Email)));\n\nvar mapper = configuration.CreateMapper();\n\nvar result = mapper.Map<AuthResponse>(new AuthResult(new User { UserName = \"Test\", Email = \"sas\" }, \"token\"));\n" }, { "answer_id": 74555743, "author": "NPras", "author_id": 5623232, "author_profile": "https://Stackoverflow.com/users/5623232", "pm_score": 2, "selected": true, "text": "record // Include the word 'User' to reflect the nested AuthResult.User\npublic record AuthResponse(\n Guid UserId, \n string UserUserName,\n string UserEmail,\n string Token);\n\n// This makes the mapping extremely straightforward:\ncfg.CreateMap<AuthResult, AuthResponse>();\n record public record AuthResponse(\n Guid Id = default,\n string UserName = default!,\n string Email = default!,\n string Token = default!);\n\n// This allows you to use the following\ncfg.CreateMap<User, AuthResponse>();\ncfg.CreateMap<AuthResult, AuthResponse>()\n .IncludeMember(src => src.User);\n /* If the above doesn't work, try instead: */\n //.AfterMap((src, dest, context) => context.Mapper.Map(src.User, dest));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11278567/" ]
74,553,277
<p>how I can run this command in powershell to all users in the server?</p> <pre><code>powerShell -sta -file 'E:\Script-Popup\Popup-Message - Done.ps1' </code></pre> <p>that on every user who is currently connected to the server, this command will run.</p>
[ { "answer_id": 74553682, "author": "Charles Han", "author_id": 11514907, "author_profile": "https://Stackoverflow.com/users/11514907", "pm_score": 0, "selected": false, "text": "IConfigurationProvider configuration = new MapperConfiguration(cfg =>\n cfg.CreateMap<AuthResult, AuthResponse>()\n .ForCtorParam(ctorParamName: nameof(AuthResponse.Id), m => m.MapFrom(s => s.User.Id))\n .ForCtorParam(ctorParamName: nameof(AuthResponse.UserName), m => m.MapFrom(s => s.User.UserName))\n .ForCtorParam(ctorParamName: nameof(AuthResponse.Email), m => m.MapFrom(s => s.User.Email)));\n\nvar mapper = configuration.CreateMapper();\n\nvar result = mapper.Map<AuthResponse>(new AuthResult(new User { UserName = \"Test\", Email = \"sas\" }, \"token\"));\n" }, { "answer_id": 74555743, "author": "NPras", "author_id": 5623232, "author_profile": "https://Stackoverflow.com/users/5623232", "pm_score": 2, "selected": true, "text": "record // Include the word 'User' to reflect the nested AuthResult.User\npublic record AuthResponse(\n Guid UserId, \n string UserUserName,\n string UserEmail,\n string Token);\n\n// This makes the mapping extremely straightforward:\ncfg.CreateMap<AuthResult, AuthResponse>();\n record public record AuthResponse(\n Guid Id = default,\n string UserName = default!,\n string Email = default!,\n string Token = default!);\n\n// This allows you to use the following\ncfg.CreateMap<User, AuthResponse>();\ncfg.CreateMap<AuthResult, AuthResponse>()\n .IncludeMember(src => src.User);\n /* If the above doesn't work, try instead: */\n //.AfterMap((src, dest, context) => context.Mapper.Map(src.User, dest));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20111374/" ]
74,553,292
<p>Is it possible to do something like this in c#, where we are trying to call a different method as a part of a conditional statement that uses the &quot;?&quot; operator?</p> <p><strong>Sample Code</strong></p> <pre><code> private bool myTenStepMethodVersion() { var stepPassed = false; stepPassed = StepOne(reportDate); stepPassed = (stepPassed) ? StepTwo() : RecordTimeAndLogFailure(timer,reportDate,&quot;Step2&quot;); stepPassed = (stepPassed) ? StepThree() : RecordTimeAndLogFailure(timer,reportDate,&quot;Step3&quot;); etc. } private bool StepOne(DateTime someDate) { //do stuff return true; } private bool StepTwo() { //do stuff return true; } private bool RecordTimeAndLogFailure(timer,someDate) { //write to a log the step where we failed, timer and date. } </code></pre> <p>The idea was to avoid having 10 different if / then combos for a 10 step process.</p> <p>This type of an approach kinda works until: a) step3 needs some data created by step 2? aka. I want to return something other than a bool? I guess we can create private global variables in the class and have each step check it? is there another way?</p> <p>b) After we run RecordTimeAndLogFailure(), we need to actually just exit the entire method. How can we do that if we follow this type of an approach?</p> <p>Overall, the goal is to make the code more readable. The current code has multiple if / then statements and over 60 lines in the main method</p>
[ { "answer_id": 74553347, "author": "knittl", "author_id": 112968, "author_profile": "https://Stackoverflow.com/users/112968", "pm_score": 3, "selected": true, "text": " class StepException : Exception {\n public string Step { get; }\n public StepException(string step) {\n this.Step = step;\n }\n }\n\n private bool myTenStepMethodVersion2()\n {\n try\n {\n stepOne(reportDate);\n var data = stepTwo();\n stepThree(data);\n // …\n return true;\n } catch (StepException ex) {\n RecordTimeAndLogFailure(timer, reportDate, ex.Step);\n return false;\n }\n }\n\n private void StepOne(DateTime reportDate)\n {\n if (error) { throw new StepException(\"Step2\"); }\n // do stuff …\n }\n\n private StepTwoResult StepTwo()\n {\n var result = new StepTwoResult();\n // do stuff ...\n if (error) { throw new StepException(\"Step2\"); }\n return result;\n }\n\n private RecordTimeAndLogFailure(timer,reportDate)\n {\n //write to serilog the step where we failed, timer and date. \n }\n" }, { "answer_id": 74553661, "author": "Filip Cordas", "author_id": 6330636, "author_profile": "https://Stackoverflow.com/users/6330636", "pm_score": 1, "selected": false, "text": " //Probably want the result of the pipleine to be somthing other then an array \n//This will run all the steps and record faliers\nPipeline().Select(RunAndRecordFailure).ToArray();\n\n//this will run untill first fails\nPipeline().TakeWhile(RunAndRecordFailure).ToArray();\n\nstatic bool RunAndRecordFailure((string name, Func<bool> step) step) => step.step() ? true : RecordTimeAndLogFailure(step.name);\n\nstatic IEnumerable<(string name, Func<bool> step)> Pipeline()\n{\n yield return (nameof(Step1), () => Step1(DateTime.Now));\n yield return (nameof(Step2), Step2);\n yield return (nameof(Step3), Step3);\n}\n\nstatic bool Step1(DateTime dateTime) => true;\nstatic bool Step2() => true;\nstatic bool Step3() => true;\n\nstatic bool RecordTimeAndLogFailure(string step) => false;\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078009/" ]
74,553,298
<p>In C++23, the ranges (sub)library has gained <a href="https://en.cppreference.com/w/cpp/ranges/zip_view" rel="nofollow noreferrer"><code>std::ranges::zip</code></a>, which zips multiple ranges into a single range of <code>std::tuple</code>'s (or pairs). This is nice, and precludes requiring implementing this ourselves, using <code>boost::zip_iterator</code> or resorting to <a href="https://stackoverflow.com/a/70482642/1593077">this kind of a hack</a><sup>*</sup>.</p> <p>However, we also get <code>std::ranges::zip_transform</code>. Why do we need it? After all , we can apply a <a href="https://en.cppreference.com/w/cpp/ranges/transform_view" rel="nofollow noreferrer"><code>ranges::views::transform</code></a> to a zipped range, can't we? So, isn't <code>zip_transform</code> redundant?</p> <hr /> <p>* - that hack works well in C++11, and doesn't require tens of thousands of lines of code with concepts...</p>
[ { "answer_id": 74553299, "author": "einpoklum", "author_id": 1593077, "author_profile": "https://Stackoverflow.com/users/1593077", "pm_score": 3, "selected": false, "text": "std::ranges::zip_transform std::tuple auto add = [](std::tuple t) { \n return std::get<0>(t) + std::get<1>(t) + std::get<2>(t); \n};\nauto elementwise_sum = \n std::views::zip(v1, v2, v3) | std::views::transform(add);\n auto add = [](auto a, auto b, auto c) { return a + b + c; };\nauto elementwise_sum = std::views::zip_transform(add, v1, v2, v3);\n" }, { "answer_id": 74555282, "author": "Ranoiaetep", "author_id": 12861639, "author_profile": "https://Stackoverflow.com/users/12861639", "pm_score": 1, "selected": false, "text": "zip_transform zip_transform zip | transform std::vector<int> v1, v2;\nauto func = [](std::tuple<int, int> t){ return double{}; };\n\nviews::zip(v1, v2) | views::transform(func); // ok\n\n// views::zip_transform(func, v1, v2); // this will not work\n views::adjacent views::adjacent_transform pairwise zip zip_transform" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
74,553,312
<p>I am trying to use powershell to find the users that has been newly added to an Active directory group. I export the membership of the groups daily into a csv and is now trying to get the newly added group members by comparing the previous day's and the current day's csv file.</p> <p>Here is the function I use to check if the a user from the current day's csv does not exist on the previous day's csv (which means that they are newly added).</p> <pre><code>$file1 = Import-Csv -path &quot;C:\test\members_previous.csv&quot; $file2 = Import-Csv -path &quot;C:\test\members_Current.csv&quot; foreach ($Item in $file2.samaccountname) { if ($Item -in $file1.samaccountname) { $true } else { $item } } export-csv -path &quot;C:\test|result.csv&quot; -NoTypeInformation </code></pre> <p>The csv file from the export does not contain anything inside.</p> <p>I'm not sure how I can export only the results of the else statement into a csv. The &quot;$item&quot; value in the else statement contains the samaccountname of the user.</p> <p>I think the solution might be simple, but I can't figure it out.</p> <p>Thank you in advance for any suggestion!</p>
[ { "answer_id": 74553387, "author": "Santiago Squarzon", "author_id": 15339544, "author_profile": "https://Stackoverflow.com/users/15339544", "pm_score": 2, "selected": false, "text": "Export-Csv Where-Object samaccountname $ref = Import-Csv \"C:\\test\\members_previous.csv\" \n\nImport-Csv \"C:\\test\\members_Current.csv\" |\n Where-Object { $_.samaccountname -notin $ref.samaccountname } |\n Export-Csv C:\\test\\result.csv -NoTypeInformation\n $ref = Import-Csv \"C:\\test\\members_previous.csv\" |\n Group-Object samaccountname -NoElement -AsHashTable -AsString\n\nImport-Csv \"C:\\test\\members_Current.csv\" |\n Where-Object { -not $ref.ContainsKey($_.samaccountname) } |\n Export-Csv C:\\test\\result.csv -NoTypeInformation\n" }, { "answer_id": 74556258, "author": "Dilly B", "author_id": 2670623, "author_profile": "https://Stackoverflow.com/users/2670623", "pm_score": 0, "selected": false, "text": "# Create output file\n$outFile = \"c:\\test\\report.csv\"\n\n$outData = New-Object -TypeName System.Text.StringBuilder\n[void]$outData.AppendLine(\"samAccountName,Status\")\n\n# Create the dictionary based on the previous members results\n$content = Import-CSV -Path c:\\test\\members_previous.csv\n$lookup = $content | Group-Object -AsHashTable -AsString -Property samAccountName\n\n$count = 0\n\n# Start cycling through the master list\nImport-Csv -Path c:\\test\\members_current.csv | foreach {\n $samAccountname = $PSItem.samaccountname\n $found = $lookup[$samAccountname]\n if ($found)\n {\n $status = \"Match\"\n }\n else\n {\n $status = \"No Match\"\n $count++\n }\n [void]$outData.AppendLine(\"`\"$samAccountName`\",`\"$status`\"\")\n}\n\n# Write the output to a file\n$outData.ToString() | Out-File -FilePath $outFile -Encoding ascii\nWrite-Host \"Found $count unmatched systems\" -ForegroundColor Yellow\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585603/" ]
74,553,316
<p>I have a spreadsheet which looks like this,</p> <pre><code>Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, Monday, Tuesday, ... 13-Nov-2022, 14-Nov-2022, 15-Nov-2022, 16-Nov-2022, 17-Nov-2022, ... 1:00, 2:05, 0:30, 2:00, 1:00, 0:05, 0:10, 1:20, 0:14 </code></pre> <p>I want to find the day which has the maximum sum, that is here, Sunday has 2:20 so I want a column where I mention Sunday. Currently, I have done something like this,</p> <pre><code>MAX(SUMIFS(range_of_time_spent, range_of_days, a_particular_day), SUMIFS(range_of_time_spent, range_of_days, a_particular_day), ...) # seven SUMIFS inside MAX for 7 different days </code></pre> <p>but this gives me 2:20, not the day</p>
[ { "answer_id": 74553765, "author": "Scott Craner", "author_id": 4851590, "author_profile": "https://Stackoverflow.com/users/4851590", "pm_score": 3, "selected": true, "text": "=TEXT(INDEX({1,2,3,4,5,6,7},MATCH(MAX(SUMIFS(range_of_time_spent,range_of_days,TEXT({1,2,3,4,5,6,7},\"dddd\"))),SUMIFS(range_of_time_spent,range_of_days,TEXT({1,2,3,4,5,6,7},\"dddd\")),0)),\"dddd\")\n" }, { "answer_id": 74555345, "author": "David Leal", "author_id": 6237093, "author_profile": "https://Stackoverflow.com/users/6237093", "pm_score": 0, "selected": false, "text": "MMULT A6 =INDEX(TEXT(SEQUENCE(7,1), \"dddd\"),\n MATCH(MAX(MMULT(IF(A1:O1=TEXT(SEQUENCE(7,1), \"dddd\"), A3:O3,0),\n TRANSPOSE(COLUMN(A1:O1)^0))),\n MMULT(IF(A1:O1=TEXT(SEQUENCE(7,1), \"dddd\"), A3:O3,0),\n TRANSPOSE(COLUMN(A1:O1)^0)),0))\n MMULT A3:O3 LOG10(A3:O3) TEXT 1 1/1/1900 7 1/7/1900 LET =LET(wkdays, TEXT(SEQUENCE(7,1), \"dddd\"), days, A1:O1, times, A3:O3,\n matrix, IF(days=wkdays, times,0), ones, TRANSPOSE(COLUMN(days)^0),\n totals, MMULT(matrix, ones),INDEX(wkdays, XMATCH(MAX(totals), totals))\n)\n matrix IF(a = b, c, 0)\n a 1xm b nx1 c a nxm b a c 0 IF({1,2,3,1,2,3}={1;2;3},{10,20,30,40,50,60},0)\n 10 0 0 10 0 0\n0 20 0 0 20 0\n0 0 30 0 0 30\n MMULT(matrix, {1;1;1;1;1;1}) wkdays b days a ones days times c matrix IF(days=wkdays, times,0) totals MMULT(matrix, ones) times wkdays totals MATCH/XMATCH INDEX" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10855529/" ]
74,553,319
<p>I'm beginning to use Bevy. I went to their website and started the set up thing, but when I went to compile wouldn't.</p> <p>It keeps returning this error.</p> <pre><code>error[E0658]: `let...else` statements are unstable --&gt; C:\Users\drew0\.cargo\registry\src\github.com-1ecc6299db9ec823\bevy_render_macros-0.9.0\src\as_bind_group.rs:119:13 | 119 | / let Some(attr_ident) = attr.path.get_ident() else { 120 | | continue; 121 | | }; | |______________^ | = note: see issue #87335 &lt;https://github.com/rust-lang/rust/issues/87335&gt; for more information For more information about this error, try `rustc --explain E0658`. error: could not compile `bevy_render_macros` due to previous error warning: build failed, waiting for other jobs to finish... error[E0658]: `let...else` statements are unstable --&gt; C:\Users\drew0\.cargo\registry\src\github.com-1ecc6299db9ec823\bevy_reflect_derive-0.9.0\src\container_attributes.rs:140:21 | 140 | / let Some(segment) = path.segments.iter().next() else { 141 | | continue; 142 | | }; | |______________________^ | = note: see issue #87335 &lt;https://github.com/rust-lang/rust/issues/87335&gt; for more information error[E0658]: `let...else` statements are unstable --&gt; C:\Users\drew0\.cargo\registry\src\github.com-1ecc6299db9ec823\bevy_reflect_derive-0.9.0\src\container_attributes.rs:174:21 | 174 | / let Some(segment) = list.path.segments.iter().next() else { 175 | | continue; 176 | | }; | |______________________^ | = note: see issue #87335 &lt;https://github.com/rust-lang/rust/issues/87335&gt; for more information error[E0658]: `let...else` statements are unstable --&gt; C:\Users\drew0\.cargo\registry\src\github.com-1ecc6299db9ec823\bevy_reflect_derive-0.9.0\src\type_uuid.rs:27:9 | 27 | / let Meta::NameValue(name_value) = attribute else { 28 | | continue; 29 | | }; | |__________^ | = note: see issue #87335 &lt;https://github.com/rust-lang/rust/issues/87335&gt; for more information error: could not compile `bevy_reflect_derive` due to 3 previous errors </code></pre> <p>I have open the files in vscode and have removed the semicolons, but it still wouldn't compile and told me to put them back. I'm really want to use Bevy and make games in rust, but this is stopping me.</p>
[ { "answer_id": 74559928, "author": "cameron1024", "author_id": 9186783, "author_profile": "https://Stackoverflow.com/users/9186783", "pm_score": 1, "selected": false, "text": "let-else rustup update" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20144756/" ]
74,553,336
<p>The following code is supposed to add an <code>&lt;h1&gt;</code> for every page in PDF output. Basically, it steps through the YAML file that defines my guide and, if the URL of the current page matches the URL in the YAML block, it places the <code>title</code> key of the parent block within an <code>&lt;h1&gt;</code> tag.</p> <pre><code>{% assign sidebar = site.data.sidebars[page.sidebar].entries %} {% for entry in sidebar %} {% for folder in entry.folders %} {% if folder.title and folder.type != &quot;navi&quot; and folder.type != &quot;frontmatter&quot; %} {% for folderitem in folder.folderitems %} {% if folderitem.url == page.url %} &lt;h1 class=&quot;post-title-main&quot; id=&quot;{{page.permalink | replace: '/', '' }}&quot;&gt;{{ folder.title }}&lt;/h1&gt; {% endif %} {% endfor %} {% endif %} {% endfor %} {% endfor %} </code></pre> <p>The problem is that the current code does this for <em>every</em> page, like this:</p> <pre><code>&lt;h1&gt;The Title I Want to Put in the H1&lt;/h1&gt; &lt;h2&gt;The Title of the Page Which I *Do* Want the &lt;H1&gt; to Appear Above&lt;/h2&gt; . . . &lt;h1&gt;The Title I Want to Put in the H1&lt;/h1&gt; &lt;h2&gt;The Title of the Page Which I *Don't* Want the &lt;H1&gt; to Appear Above&lt;/h2&gt; </code></pre> <p>I need another conditional check, something like &quot;if <code>folderitem</code> is the first one&quot; that would let the rest of the conditional logic proceed <em>only</em> if the item is the first in the list, resulting in:</p> <pre><code>&lt;h1&gt;The Title I Want to Put in the H1&lt;/h1&gt; &lt;h2&gt;The Title of the Page Which I *Do* Want the &lt;H1&gt; to Appear Above&lt;/h2&gt; </code></pre> <p>What is the syntax for selecting the first item? <code>first</code> appears to be for <em>returning</em> the first item of an array, which doesn't seem to apply to <em>checking</em> if the current item is the first item in the YAML data structure that I'm working with.</p> <p>Here's an example YAML structure:</p> <pre class="lang-yaml prettyprint-override"><code>entries: - title: pdftitle: foobar.pdf product: version: folders: - title: output: pdf type: frontmatter folderitems: - title: url: /titlepage.html output: pdf type: frontmatter - title: My Amazing Guide output: web type: navi folderitems: - title: Home url: /index.html output: web - title: The Title I Want to Put in the H1 url: /section/page/index.html output: web, pdf folderitems: - title: The Title of the Page Which I *Do* Want the &lt;H1&gt; to Appear Above url: /section/page/some-page.html output: web, pdf - title: The Title of the Page, Which I *Don't* Want the &lt;H1&gt; to Appear Above url: /section/page/another-page.html output: web, pdf </code></pre>
[ { "answer_id": 74559928, "author": "cameron1024", "author_id": 9186783, "author_profile": "https://Stackoverflow.com/users/9186783", "pm_score": 1, "selected": false, "text": "let-else rustup update" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7273897/" ]
74,553,445
<p>I have a plot using emmip and I have been successful of modifying the labels of the panels and the x axis label but I have been unsuccessful changing the labels and the order of the legend, any suggestions?</p> <p>It should be Phonemes by Cognate Status</p> <p>and the label /k/ - Cognate, /k/ Noncognate, ....</p> <p>This is the code for this plot.</p> <p><a href="https://i.stack.imgur.com/WYxxa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WYxxa.png" alt="enter image description here" /></a></p> <pre><code>###{r HS in CS interaction plot with pre switch syllable count vs phoneme } (mylist &lt;- list( Syl_Pre_Switch = seq(7,12,by=1), phoneTxtGrid=c(&quot;p&quot;,&quot;t&quot;,&quot;k&quot;), CogStatus=c(&quot;Cog&quot;, &quot;Cag&quot;))) emmip(modelHSCSwithDistance, phonemeTxtGrid*CogStatus ~ Syl_Pre_Switch, at=mylist, CIs = TRUE) + ggplot2::facet_grid(~factor(phonemeTxtGrid, levels=c('p', 't', 'k'))) + xlab(&quot;Syllables After Cognate&quot;) + labs(fill = &quot;Stops by Cognate Status&quot;) </code></pre> <p>I tried this suggestion from this post <a href="https://stackoverflow.com/questions/56586983/is-there-a-way-to-change-the-legend-of-graph-in-emmeans">is there a way to change the Legend of graph in emmeans?</a></p> <p>Adding</p> <pre><code> scale_color_discrete() </code></pre> <p>but I have been unsuccessful in changing the label name.</p>
[ { "answer_id": 74583803, "author": "Russ Lenth", "author_id": 3961566, "author_profile": "https://Stackoverflow.com/users/3961566", "pm_score": 0, "selected": false, "text": "plot.data <- emmip(<your emmip arguments>, plotit = FALSE)\n ? emmip ggplot()" }, { "answer_id": 74592434, "author": "Hernán Rosario", "author_id": 19607817, "author_profile": "https://Stackoverflow.com/users/19607817", "pm_score": -1, "selected": false, "text": " (mylist222 <- list(Sylb_PostCog=seq(2,5,by = 1),phoneTxtGrid=c(\"p\",\"t\",\"k\"), CogStatus=c(\"Cog\", \"Cag\")))\nemmip(modelHSvsL2CSwithDistancePostCogToSwitch, phonemeTxtGrid*CogStatus*SpeakGroup ~ Sylb_PostCog, at=mylist222, CIs = TRUE) + ggplot2::facet_grid(SpeakGroup~factor(phonemeTxtGrid, levels = c(\"p\", \"t\", \"k\"))) + labs(x = \"Syllables Post Cognate\", colour = \"Stops by Cognate Status and Speaker Group\") + scale_color_hue(labels = c(\"/k/ Cognate HS\", \"/p/ Cognate HS\", \"/t/ Cognate HS\", \"/k/ Noncognate HS\", \"/p/ Noncognate HS\", \"/t/ Noncognate HS\", \"/k/ Cognate L2\", \"/p/ Cognate L2\", \"/t/ Cognate L2\", \"/k/ Noncognate L2\", \"/p/ Noncognate L2\", \"/t/ Noncognate L2\"))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19607817/" ]
74,553,450
<p>I have a block of code that I am iterating through a dictionary looking for keywords found and the number of times each is found. The if statement works and returns the expected output if keywords are found. However, the else statement is not working when no keywords are found it should return &quot;No keywords found&quot;. This seems simple enough but I just can't put my finger on why this is not working. I'm fairly new to coding, so I apologize if this seems extremely basic.</p> <p>Here is the code block I'm using:</p> <pre><code> with open(keyword_file_path, 'r') as file: data = file.read() kw_found = {} for keyword in keywords: found = re.findall(keyword, data, re.I) if found: kw_found[keyword] = len(found) for key in kw_found.keys(): if key in kw_found.keys(): width = max(len(x) for x in key) output_fp.write(&quot;{0:&lt;{1}} : {2}\n&quot;.format(key, width, kw_found[key])) else: output_fp.write(&quot;No Keywords Found\n&quot;) </code></pre> <p>The if statement works and we get the following output if it does find the predefined keywords:</p> <p>dog : 5</p> <p>cat : 2</p> <p>bird : 100</p> <p>What should happen when it does not find the keywords is return &quot;No Keywords Found&quot;; however, it just doesn't return anything. No errors are reported, so it seems it just never sees the else statement as True if I'm understanding it correctly.</p> <p>Any advice to get this to work would be greatly appreciated! Thank you in advanced!</p>
[ { "answer_id": 74583803, "author": "Russ Lenth", "author_id": 3961566, "author_profile": "https://Stackoverflow.com/users/3961566", "pm_score": 0, "selected": false, "text": "plot.data <- emmip(<your emmip arguments>, plotit = FALSE)\n ? emmip ggplot()" }, { "answer_id": 74592434, "author": "Hernán Rosario", "author_id": 19607817, "author_profile": "https://Stackoverflow.com/users/19607817", "pm_score": -1, "selected": false, "text": " (mylist222 <- list(Sylb_PostCog=seq(2,5,by = 1),phoneTxtGrid=c(\"p\",\"t\",\"k\"), CogStatus=c(\"Cog\", \"Cag\")))\nemmip(modelHSvsL2CSwithDistancePostCogToSwitch, phonemeTxtGrid*CogStatus*SpeakGroup ~ Sylb_PostCog, at=mylist222, CIs = TRUE) + ggplot2::facet_grid(SpeakGroup~factor(phonemeTxtGrid, levels = c(\"p\", \"t\", \"k\"))) + labs(x = \"Syllables Post Cognate\", colour = \"Stops by Cognate Status and Speaker Group\") + scale_color_hue(labels = c(\"/k/ Cognate HS\", \"/p/ Cognate HS\", \"/t/ Cognate HS\", \"/k/ Noncognate HS\", \"/p/ Noncognate HS\", \"/t/ Noncognate HS\", \"/k/ Cognate L2\", \"/p/ Cognate L2\", \"/t/ Cognate L2\", \"/k/ Noncognate L2\", \"/p/ Noncognate L2\", \"/t/ Noncognate L2\"))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18562555/" ]
74,553,488
<p>I have 4 tables in PostgreSQL:</p> <ol> <li>Projects</li> <li>Organizations</li> <li>Organization_membership</li> <li>User</li> </ol> <pre><code>CREATE TABLE IF NOT EXISTS organization( id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (), CONSTRAINT plan_id_fk FOREIGN KEY (plan_type) REFERENCES plan(plan_type) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION ); CREATE TABLE IF NOT EXISTS users( id varchar(100) PRIMARY KEY, email VARCHAR(50) NOT NULL UNIQUE, ); CREATE TABLE IF NOT EXISTS organization_membership( organization_id uuid not null, user_id varchar(100) not null, CONSTRAINT organization_id_fk FOREIGN KEY (organization_id) REFERENCES organization(id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE NO ACTION, CONSTRAINT users_uuid_fk FOREIGN KEY (user_id) REFERENCES users(id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE NO ACTION, PRIMARY KEY (organization_id, user_id) ); CREATE TABLE IF NOT EXISTS project( id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (), owner uuid NOT NULL, project_name VARCHAR(100), CONSTRAINT project_owner_fk FOREIGN KEY (owner) REFERENCES organization(id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE NO ACTION, ); </code></pre> <p>I am trying to get projects which belongs to user 1,</p> <p>so I am trying to get all projects for user 1 from all organizations of this user</p> <p>I just need raw sql code</p> <p>I tried this:</p> <pre><code> await database.fetch_all( query=&quot;SELECT organization_membership.*, organization.id FROM organization JOIN organization_membership ON organization.id = organization_membership.organization_id WHERE organization_membership.user_id = :id&quot;, values={'id': acting_user.id}, ) </code></pre> <p>but this returns only organizations for this user</p> <p>also I have tried this:</p> <pre><code>await database.fetch_all( query=&quot;SELECT * from project JOIN organization ON project.owner = organization.id JOIN organization_membership ON organization.id = organization_membership.organization_id WHERE organization_membership.user_id = :id&quot;, values={'id': acting_user.id}, ) </code></pre> <p>this returns empty data</p>
[ { "answer_id": 74583803, "author": "Russ Lenth", "author_id": 3961566, "author_profile": "https://Stackoverflow.com/users/3961566", "pm_score": 0, "selected": false, "text": "plot.data <- emmip(<your emmip arguments>, plotit = FALSE)\n ? emmip ggplot()" }, { "answer_id": 74592434, "author": "Hernán Rosario", "author_id": 19607817, "author_profile": "https://Stackoverflow.com/users/19607817", "pm_score": -1, "selected": false, "text": " (mylist222 <- list(Sylb_PostCog=seq(2,5,by = 1),phoneTxtGrid=c(\"p\",\"t\",\"k\"), CogStatus=c(\"Cog\", \"Cag\")))\nemmip(modelHSvsL2CSwithDistancePostCogToSwitch, phonemeTxtGrid*CogStatus*SpeakGroup ~ Sylb_PostCog, at=mylist222, CIs = TRUE) + ggplot2::facet_grid(SpeakGroup~factor(phonemeTxtGrid, levels = c(\"p\", \"t\", \"k\"))) + labs(x = \"Syllables Post Cognate\", colour = \"Stops by Cognate Status and Speaker Group\") + scale_color_hue(labels = c(\"/k/ Cognate HS\", \"/p/ Cognate HS\", \"/t/ Cognate HS\", \"/k/ Noncognate HS\", \"/p/ Noncognate HS\", \"/t/ Noncognate HS\", \"/k/ Cognate L2\", \"/p/ Cognate L2\", \"/t/ Cognate L2\", \"/k/ Noncognate L2\", \"/p/ Noncognate L2\", \"/t/ Noncognate L2\"))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585750/" ]
74,553,491
<p>I want to write a minimal FastAPI static file server launched from a script that allows you to specify the directory to share on the command line. Following the <a href="https://fastapi.tiangolo.com/tutorial/static-files/" rel="nofollow noreferrer">example in the FastAPI documentation</a>, I wrote this.</p> <pre><code>import uvicorn from fastapi import FastAPI from fastapi.staticfiles import StaticFiles server = FastAPI() if __name__ == &quot;__main__&quot;: import sys directory = sys.argv[1] server.mount(&quot;/static&quot;, StaticFiles(directory=directory), name=&quot;static&quot;) uvicorn.run(app=&quot;my_package:server&quot;) </code></pre> <p>If I run this with the argument <code>/my/directory</code> where this directory contains <code>file.txt</code> I expect that I'd be able to download <code>file.txt</code> at the URL <code>http://localhost:8000/static/file.txt</code>, but this returns an HTTP 404.</p> <p>How do I write this minimal static file server script?</p>
[ { "answer_id": 74553706, "author": "MatsLindh", "author_id": 137650, "author_profile": "https://Stackoverflow.com/users/137650", "pm_score": 2, "selected": true, "text": "sys.argv __main__ import uvicorn\nimport sys\nfrom fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\nserver = FastAPI()\ndirectory = sys.argv[1]\nserver.mount(\"/static\", StaticFiles(directory=directory), name=\"static\")\n\nif __name__ == \"__main__\":\n uvicorn.run(app=\"my_package:server\")\n" }, { "answer_id": 74553716, "author": "M.O.", "author_id": 11612918, "author_profile": "https://Stackoverflow.com/users/11612918", "pm_score": 0, "selected": false, "text": "uvicorn.run(app=\"my_package:server\") my_package if __name__ == \"__main__\": from fastapi import FastAPI\nfrom fastapi.staticfiles import StaticFiles\n\nserver = FastAPI()\n\ndirectory = os.getenv(\"DIRECTORY\")\nserver.mount(\"/static\", StaticFiles(directory=directory), name=\"static\")\n start.sh #!/usr/bin/env bash\nDIRECTORY=$1 uvicorn mypackage:server\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1120370/" ]
74,553,512
<p>I am using the react-query package to just return a simple list of products from an api and for some reason it keeps giving this error:</p> <pre><code>TypeError: Cannot read properties of undefined (reading 'map') </code></pre> <p>For some reason it doesn't recognize the products object return and won't iterate over them in the map. Very puzzling.</p> <pre><code>export default function ProductList() { const { data: products, isLoading } = useQuery('Products', () =&gt; axios('/api/products').then((res) =&gt; res.data.products) ); if (isLoading) return &lt;LoadingSpinner /&gt; return products.map((product) =&gt; ( &lt;ProductItem key={product.id} product={product} /&gt; )); } function ProductItem({ product }) { const price = formatProductPrice(product); return ( &lt;div className=&quot;p-4 md:w-1/3&quot;&gt; &lt;div className=&quot;h-full border-2 border-gray-800 rounded-lg overflow-hidden&quot;&gt; &lt;Link to={`/${product.id}`}&gt; &lt;img className=&quot;lg:h-96 md:h-36 w-full object-cover object-center&quot; src={product.image} alt={product.name} /&gt; &lt;/Link&gt; &lt;div className=&quot;p-6&quot;&gt; &lt;h2 className=&quot;tracking-widest text-xs title-font font-medium text-gray-500 mb-1&quot;&gt; {product.category} &lt;/h2&gt; &lt;h1 className=&quot;title-font text-lg font-medium text-white mb-3&quot;&gt; {product.name} &lt;/h1&gt; &lt;p className=&quot;leading-relaxed mb-3&quot;&gt;{product.description}&lt;/p&gt; &lt;div className=&quot;flex items-center flex-wrap &quot;&gt; &lt;Link to={`/${product.id}`} className=&quot;text-indigo-400 inline-flex items-center md:mb-2 lg:mb-0&quot;&gt; See More &lt;svg fill=&quot;none&quot; stroke=&quot;currentColor&quot; strokeLinecap=&quot;round&quot; strokeLinejoin=&quot;round&quot; strokeWidth=&quot;2&quot; className=&quot;w-4 h-4 ml-2&quot; viewBox=&quot;0 0 24 24&quot; &gt; &lt;path d=&quot;M5 12h14M12 5l7 7-7 7&quot;&gt;&lt;/path&gt; &lt;/svg&gt; &lt;/Link&gt; &lt;span className=&quot;text-gray-500 mr-3 inline-flex items-center lg:ml-auto md:ml-0 ml-auto leading-none text-lg pr-3 py-1 border-gray-800 font-bold&quot;&gt; {price} &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } </code></pre>
[ { "answer_id": 74555324, "author": "Miguel Caro", "author_id": 11206583, "author_profile": "https://Stackoverflow.com/users/11206583", "pm_score": -1, "selected": false, "text": " const { data: products = [], isLoading } = useQuery('Products', () => \n axios('/api/products').then((res) => res.data.products)\n );\n return (products || []).map((product) => (\n <ProductItem key={product.id} product={product} />\n ));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9132098/" ]
74,553,533
<p>I need to find if a string exists in JSON Kraken.com retrieved file: I get it this way:</p> <pre><code>$sURL = &quot;https://api.kraken.com/0/public/OHLC?pair=ETHAED&amp;interval=5&amp;since=&quot;. strtotime(&quot;-1 day&quot;); $ch = curl_init(); $config['useragent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0'; curl_setopt($ch, CURLOPT_USERAGENT, $config['useragent']); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $sURL); $result = curl_exec($ch); curl_close($ch); $obj = json_decode($result, true); </code></pre> <p>Sometimes pairs names differ from URL string and JSON (i.e. I can write LTCEUR but in JSON I see LTCZEUR</p> <p>So I need to check if the string <strong>does exists</strong> in the <code>$obj</code></p> <pre><code>$sName = &quot;ETHAED&quot;; print_r($obj); if (in_array($sName,$obj)){ echo(&quot;Found &quot;.$sName.&quot;&lt;br&gt;&quot;); }else{ echo(&quot;NOT FOUND&quot;.&quot;&lt;br&gt;&quot;); } </code></pre> <p>but this doesn't work.</p> <p>if I do a print_r() I can clearly see the pair name, but can't verify it. Any suggestion?</p> <p>Kraken.com JSON is not standard so I can't easily retrieve the name of the PAIR, I tried all possible combinations of $obj[&quot;result&quot;][$sName] but without result.</p> <p>Example: <a href="https://api.kraken.com/0/public/OHLC?pair=LTCUSD" rel="nofollow noreferrer">https://api.kraken.com/0/public/OHLC?pair=LTCUSD</a> Here pair is <strong>LTCUSD</strong></p> <p>But on Json:</p> <p><code>{&quot;error&quot;:[],&quot;result&quot;:{&quot;XLTCZUSD&quot;:[[1669197540,&quot;78.74&quot;,&quot;78.74&quot;,&quot;78.58&quot;,&quot;78.59&quot;,&quot;78.59&quot;,&quot;23.82168114&quot;,8]</code></p>
[ { "answer_id": 74555324, "author": "Miguel Caro", "author_id": 11206583, "author_profile": "https://Stackoverflow.com/users/11206583", "pm_score": -1, "selected": false, "text": " const { data: products = [], isLoading } = useQuery('Products', () => \n axios('/api/products').then((res) => res.data.products)\n );\n return (products || []).map((product) => (\n <ProductItem key={product.id} product={product} />\n ));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19459726/" ]
74,553,551
<p>My data frame has many rows ( over 2 million), averaging around 60,000 per 359 samples.</p> <p>One of my columns is called samples. I know how to subset the dataframe based on sample number</p> <pre><code> sample1 &lt;- df[(df$sample ==1), ] </code></pre> <p>However, what I am unsure of is whether I can automate this for the 359 samples I have using something like a for loop or one of the apply functions</p> <pre><code> for(i in 1:nrow(df)){ sample(i) &lt;- df[(df$sample == i), ] } </code></pre> <p>So the output would be sample1, sample2 etc up until sample359 with the correct subsetting based on the sample column of the original file.</p> <p>Would be grateful for any suggestions - thank you.</p>
[ { "answer_id": 74555324, "author": "Miguel Caro", "author_id": 11206583, "author_profile": "https://Stackoverflow.com/users/11206583", "pm_score": -1, "selected": false, "text": " const { data: products = [], isLoading } = useQuery('Products', () => \n axios('/api/products').then((res) => res.data.products)\n );\n return (products || []).map((product) => (\n <ProductItem key={product.id} product={product} />\n ));\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19122830/" ]
74,553,563
<p>I start out with an empty object in the global scope and then I fetch an ID at a time to which I'd like to add prices together with a quantity. The script iterates through a list and for each row the ID is present, I wish to add <code>quantity: price</code></p> <p>I want my object to look something like this:</p> <pre><code>const obj = { id1: { qty1: price qty2: price qty3: price qty4: price qty5: price qty6: price qty7: price } id2: { qty1: price qty2: price qty3: price qty4: price qty5: price qty6: price qty7: price } } </code></pre> <p>Currently I'm just getting one price as each run replaces the other.</p> <pre><code>const obj = {} obj[id] = { [qty]: price } // Result obj: { id: { qty: price } } </code></pre>
[ { "answer_id": 74553614, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "if (!obj[id]) obj[id] = {}\nif (!obj[id][qty]) obj[id][qty] = {}\n const ids = ['id1', 'id2']\nconst qtys = ['qty1', 'qty2']\nconst price = 1\n\nconst obj = {}\n\nfor (const id of ids) {\n for (const qty of qtys) {\n if (!obj[id]) obj[id] = {}\n if (!obj[id][qty]) obj[id][qty] = {}\n obj[id][qty] = Math.random() * 100 | 0\n }\n}\n\nconsole.log(obj)" }, { "answer_id": 74553650, "author": "Vajkis", "author_id": 18570930, "author_profile": "https://Stackoverflow.com/users/18570930", "pm_score": 2, "selected": true, "text": "const obj = {}\nobj[id] = {...obj[id], qty: price }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18519057/" ]
74,553,602
<p>I am working with a dataframe in <code>R</code> using <code>tidyverse</code>. I need to unnest it because it contains rows stored as dataframes. My dataframe <code>ex</code> is next (included as <code>dput</code>):</p> <pre><code>ex # A tibble: 2 x 2 name1 values &lt;chr&gt; &lt;list&gt; 1 A &lt;df [3 x 2]&gt; 2 B &lt;df [4 x 2]&gt; </code></pre> <p>It is actually a tibble. In order to unnest I use next code:</p> <pre><code>library(tidyverse) #Code ex2 &lt;- ex %&gt;% tidyr::unnest(c(values), .drop = TRUE) </code></pre> <p>Which returns next error:</p> <pre><code>Error: ! Can't combine `..1$value` &lt;character&gt; and `..2$value` &lt;integer&gt;. </code></pre> <p>The issue is that some columns in the nested dataframe are character and other integer. So I believed using <code>as.character()</code> would help but it did not worked.</p> <p>How can I unnest this tibble? Many thanks!</p> <p>Data is next:</p> <pre><code>#Data ex &lt;- structure(list(name1 = c(&quot;A&quot;, &quot;B&quot;), values = list(structure(list( value = c(&quot;Home&quot;, &quot;Draw&quot;, &quot;Away&quot;), odd = c(&quot;1.58&quot;, &quot;3.75&quot;, &quot;6.50&quot;)), class = &quot;data.frame&quot;, row.names = c(NA, 3L)), structure(list( value = c(2L, 3L, 1L, 0L), odd = c(&quot;7.77&quot;, &quot;29.34&quot;, &quot;2.80&quot;, &quot;1.92&quot;)), class = &quot;data.frame&quot;, row.names = c(NA, 4L)))), row.names = c(NA, -2L), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;)) </code></pre> <p>Many thanks!</p>
[ { "answer_id": 74553614, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "if (!obj[id]) obj[id] = {}\nif (!obj[id][qty]) obj[id][qty] = {}\n const ids = ['id1', 'id2']\nconst qtys = ['qty1', 'qty2']\nconst price = 1\n\nconst obj = {}\n\nfor (const id of ids) {\n for (const qty of qtys) {\n if (!obj[id]) obj[id] = {}\n if (!obj[id][qty]) obj[id][qty] = {}\n obj[id][qty] = Math.random() * 100 | 0\n }\n}\n\nconsole.log(obj)" }, { "answer_id": 74553650, "author": "Vajkis", "author_id": 18570930, "author_profile": "https://Stackoverflow.com/users/18570930", "pm_score": 2, "selected": true, "text": "const obj = {}\nobj[id] = {...obj[id], qty: price }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18747807/" ]
74,553,605
<p>I need to load in pandas a CSV file that is not 100% CSV &quot;compliant&quot;, below an example:</p> <pre><code>&quot;Transaction date&quot;;&quot;Accounting date&quot;;&quot;Counterparty's data&quot;;&quot;Title&quot; 2021-08-22;2021-08-22;&quot; &quot;SPOLEM&quot; ASS &quot;ALDONA&quot; AUGUSTOW &quot;;&quot; Title 450&quot; 2019-09-02;2019-09-02;&quot; 13XYZ05 &quot;SKOWRONEK&quot; NIEGOWA &quot;;&quot; Title 1300&quot; 2010-07-18;2010-07-18;&quot; APTEKA &quot;SLOWINSKA&quot; SPOLKALEBA &quot;;&quot; Title 123&quot; </code></pre> <p>I read this csv file (csv_in) into a pandas data frame with the following command:</p> <pre><code>df = pd.read_csv(csv_in, \ delimiter=';', \ engine='python', \ quoting=1) </code></pre> <p>I understand that the bad csv formatting is the culprit, but:</p> <ul> <li>how can I instruct pandas to indicate at which row the process breakes instead of simply informing me that <em>pandas.errors.ParserError: ';' expected after '&quot;'</em> ... I want to know at which row of the csv_in file it broke ... having a 6500 rows file you can imagine how hard was for me to find these malformed lines without any aid except &quot;hey there is an error!&quot;</li> <li>is it possible to instruct pandas to use the combo [;&quot;] as starting text field and [&quot;;] as ending text field? This should solve the issue and apparently is somehow understood by CSV module (import csv) that reads the file without throwing errors, without skipping lines</li> </ul> <p>Thanks! Evan</p>
[ { "answer_id": 74553614, "author": "Konrad", "author_id": 5089567, "author_profile": "https://Stackoverflow.com/users/5089567", "pm_score": 0, "selected": false, "text": "if (!obj[id]) obj[id] = {}\nif (!obj[id][qty]) obj[id][qty] = {}\n const ids = ['id1', 'id2']\nconst qtys = ['qty1', 'qty2']\nconst price = 1\n\nconst obj = {}\n\nfor (const id of ids) {\n for (const qty of qtys) {\n if (!obj[id]) obj[id] = {}\n if (!obj[id][qty]) obj[id][qty] = {}\n obj[id][qty] = Math.random() * 100 | 0\n }\n}\n\nconsole.log(obj)" }, { "answer_id": 74553650, "author": "Vajkis", "author_id": 18570930, "author_profile": "https://Stackoverflow.com/users/18570930", "pm_score": 2, "selected": true, "text": "const obj = {}\nobj[id] = {...obj[id], qty: price }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066865/" ]
74,553,651
<p>I have written a Python script that calls a National Oceanic and Atmospheric Administration (NOAA) endpoint with a zip code and gets a list of weather stations in response. The script then converts the response to a Pandas dataframe.</p> <p>I believe I have it working correctly based on this <a href="https://replit.com/@mxstrand/Tabpy-getStationsforZip-Script#main.py" rel="nofollow noreferrer">Replit</a>.The dataframe appears to print to console correctly and I can inspect it using breakpoints.</p> <p>Using this <a href="https://gunningfortableau.com/2019/10/08/web-data-conductors/" rel="nofollow noreferrer">blog tutorial</a> as my guide, my real goal is to leverage this Python script in a Tableau Prep flow. Tableau Prep is basically a desktop ETL tool, similar to PowerQuery, but different :).</p> <p>I have a local working instance of a TabPy server, whose logs also appear to be showing proper construction of the dataframe (image below). However, I'm getting a <code>TypeError : 'DataFrame' object is not callable</code>. I've also provided an image of the same error surfaced in the Tableau Prep interface.</p> <p>Any help is sincerely appreciated.</p> <p><a href="https://i.stack.imgur.com/PoUje.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PoUje.jpg" alt="Local Tabpy logs" /></a></p> <p><a href="https://i.stack.imgur.com/htc2C.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/htc2C.jpg" alt="Tableau Prep Error" /></a></p> <p>Here's the syntax of the actual script running on my TabPy server - with minimal modifications from what's on Replit.</p> <pre class="lang-py prettyprint-override"><code>import requests; import pandas as pd; import json; zip = '97034' userToken = 'foobar123' headerCreds = dict(token = userToken) url = 'https://www.ncei.noaa.gov/cdo-web/api/v2/stations?&amp;locationid=ZIP:' + zip global dfWorking def get_stations_for_zip(): r = requests.get(url, headers = headerCreds) data = json.loads(r.text) if 'results' in data: data = data.get('results') dfWorking = pd.DataFrame(data) # Column datatypes as received # elevation float64 # mindate object # maxdate object # latitude float64 # name int64 # datacoverage float64 # id object # elevationUnit object # longitude float64 dfWorking = dfWorking.astype({'name': 'str'}) # dfWorking['name'] = dfWorking.index # defining an index converts back to float64 print(dfWorking) else: print('no results object in response') return dfWorking # Note: the below prep functions are undefined until they are on a TabPy server def get_output_schema(): return pd.DataFrame({ 'elevation' : prep_decimal(), 'mindate' : prep_string(), 'maxdate' : prep_decimal(), 'latitude' : prep_date(), 'name' : prep_string(), 'datacoverage' : prep_decimal(), 'id' : prep_decimal(), 'name' : prep_string(), 'elevationUnit' : prep_decimal(), 'longitude' : prep_decimal() }); get_stations_for_zip() </code></pre>
[ { "answer_id": 74553746, "author": "404pio", "author_id": 1615070, "author_profile": "https://Stackoverflow.com/users/1615070", "pm_score": 0, "selected": false, "text": "execution_result = get_stations_for_zip()(pd.DataFrame(_arg1))\n get_stations_for_zip df = get_stations_for_zip()\ndf(pd.DataFrame(_arg1)) # and error is right here\n" }, { "answer_id": 74563647, "author": "mxs", "author_id": 2375980, "author_profile": "https://Stackoverflow.com/users/2375980", "pm_score": 1, "selected": false, "text": "get_stations_for_zip() get_stations_for_zip get_stations_for_zip def get_stations_for_zip(df):" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2375980/" ]
74,553,670
<p>I've seen this question before but the solution to solve it via Import / Export curly braces doesn't seem to be the root cause.</p> <p>I can trying to add a functional component into my page React.js, the component will include the Video imported from Expo. It seems to cause an error, I feel like it is something to do with the Video class sitting within VideoInstance causing the error, but am not sure.</p> <p><strong>Phase2.js</strong> page</p> <pre><code>import React from 'react' import { View, StyleSheet} from 'react-native' import { VideoInstance } from '../components/Videos' export default function Phase2() { return ( &lt;View style={styles.container}&gt; &lt;VideoInstance/&gt; &lt;/View&gt; ) } const styles = StyleSheet.create( { container: { flex:1, backgroundColor: 'red', } } ) </code></pre> <p><strong>Video.js Functional Comp (error lies in the Video I think as runs without that and Touchable)</strong></p> <pre><code>import React from 'react' import { View, Text, StyleSheet, TouchableWithoutFeedback } from 'react-native' import Video from 'expo-av' export const VideoInstance = () =&gt; { const video = React.useRef(null); const [status, setStatus] = React.useState({}) const onPlayPausePress = () =&gt; { status.isPlaying ? video.current.pauseAsync() : video.current.playAsync() } return ( &lt;View&gt; &lt;TouchableWithoutFeedback onPress={onPlayPausePress}&gt; &lt;Video ref={video} style={styles.video} source={{uri:&quot;https://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4&quot;}} resizeMode='contain' useNativeControls={false} isLooping shouldPlay onPlaybackStatusUpdate={setStatus} /&gt; &lt;/TouchableWithoutFeedback&gt; &lt;/View&gt; ) } const styles = StyleSheet.create( { container: { flex:1, backgroundColor: 'red', }, video: { flex: 1, alignSelf: 'stretch' } } ) </code></pre> <p><strong>**Full Error msg:</strong> <strong>**</strong></p> <pre><code>Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined, You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of `VideoInstance`., in VideoInstance (created by Phase2) </code></pre> <p>I want the Video to render on the Phase 2 page. But it won't render. I’ve tried to put the code for VideoInstance directly in the Phase2 function and it works, so the problem must be trying to put it in, just not sure what …</p>
[ { "answer_id": 74554953, "author": "basan nofal", "author_id": 19645465, "author_profile": "https://Stackoverflow.com/users/19645465", "pm_score": 0, "selected": false, "text": " export default const VideoInstance = () => {\n // Your code\n }\n" }, { "answer_id": 74558292, "author": "Stuti Dyer", "author_id": 19715291, "author_profile": "https://Stackoverflow.com/users/19715291", "pm_score": 0, "selected": false, "text": "const VideoInstance = () => {\n // Your code\n }\n \n export default VideoInstance;" }, { "answer_id": 74558636, "author": "tkuvek", "author_id": 20531167, "author_profile": "https://Stackoverflow.com/users/20531167", "pm_score": 1, "selected": false, "text": "import Video from 'expo-av import { Video } from 'expo-av'" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9221061/" ]
74,553,697
<blockquote> <p>Within my Facebook button I have set an animation to show the word &quot;Facebook&quot; if you hover over it. Although every time I set this in, it doesn't pop. The word &quot;Facebook&quot; has to show to the right if you hover over it. Also, I want my code to be responsive based on the size of a device. If the phone is bigger or smaller it should be set in its size based on that. Please and thank you.</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: rgb(243, 234, 234); } #eventcenterimg { z-index: -1; text-align: center; width: 30%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-repeat: no-repeat; } #starting-info { text-align: center; font-family: 'Roboto Condensed', sans-serif; margin-top: 32vh; } #starting-info2 { font-family: 'Roboto Condensed', sans-serif; text-align: center; } #phonenumber1 { text-align: center; font-family: 'Roboto Condensed', sans-serif; color: green; } #phonenumber2 { text-align: center; font-family: 'Roboto Condensed', sans-serif; color: green; } #address { text-align: center; font-family: 'Roboto Condensed', sans-serif; } .wrapper { display: grid; height: 100%; width: 100%; place-items: center; } .wrapper .button { display: inline-block; height: 60px; width: 60px; margin: 0 5px; overflow: hidden; border-radius: 50px; cursor: pointer; box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1); transition: all 0.3s ease-out; } .wrapper .button:hover { width: 200px; } .wrapper .button .icon { display: inline-block; height: 60px; width: 60px; text-align: center; border-radius: 50px; box-sizing: border-box; line-height: 60px; transition: all 0.3s ease-out; } .wrapper .button:nth-child(1):hover .icon { background: #4267B2; } .wrapper .button .icon i { font-size: 25px; line-height: 60px; transition: all 0.3s ease-out; } .wrapper .button span { font-size: 20px; font-weight: 500; line-height: 60px; margin-left: 10px; transition: all 0.3s ease-out; } .wrapper .button:nth-child(1) span { color: #4267B2; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, intitial-scale=1.0"&gt; &lt;title&gt;Correa Events&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"&gt; &lt;link rel="preconnect" href="https://fonts.googleapis.com"&gt; &lt;link rel="preconnect" href="https://fonts.gstatic.com" crossorigin&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&amp;display=swap" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;img src="img/correaevent.png" height="970" alt="" id="eventcenterimg"&gt; &lt;div class="correa-events-info"&gt; &lt;h4 id="starting-info"&gt;Book and experience any special events at Correa's Events Center.&lt;/h4&gt; &lt;h4 id="starting-info2"&gt;Call to book at:&lt;/h4&gt; &lt;h3 id="phonenumber1"&gt;&lt;b&gt;720-404-2284: Victor&lt;/b&gt;&lt;/h3&gt; &lt;h3 id="phonenumber2"&gt;&lt;b&gt;720-292-9963: Monica&lt;/b&gt;&lt;/h3&gt; &lt;h3 id="address"&gt;Address: 3890 Kipling St. Wheat Ridge, CO, 80033&lt;/h3&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;div class="button"&gt; &lt;div class="icon"&gt; &lt;a href="https://www.facebook.com/people/Correas-Event-Center/100077040368594/" target="_blank"&gt;&lt;i class="fab fa-facebook-f"&gt;&lt;/i&gt;&lt;/a&gt; &lt;span id="icontitle"&gt;Facebook&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74553846, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "display inline-block flex hover .icon .wrapper .button .icon:hover {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 60px;\n width: 100%;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n body {\n background: rgb(243, 234, 234);\n}\n\n.wrapper {\n display: grid;\n height: 100%;\n width: 100%;\n place-items: center;\n}\n\n.wrapper .button {\n display: inline-block;\n height: 60px;\n width: 60px;\n margin: 0 5px;\n overflow: hidden;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:hover {\n width: 200px;\n}\n\n.wrapper .button .icon {\n display: inline-block;\n height: 60px;\n width: 60px;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button .icon:hover {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 60px;\n width: 100%;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1):hover .icon {\n background: #4267B2;\n}\n\n.wrapper .button .icon i {\n font-size: 25px;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button span {\n font-size: 20px;\n font-weight: 500;\n line-height: 60px;\n margin-left: 50px;\n transition: all 0.3s ease-out;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,\n intitial-scale=1.0\">\n <title>Correa Events</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&display=swap\" rel=\"stylesheet\">\n</head>\n\n<body>\n <div class=\"wrapper\">\n <div class=\"button\">\n <div class=\"icon\">\n <a href=\"https://www.facebook.com/people/Correas-Event-Center/100077040368594/\" target=\"_blank\"><i class=\"fab fa-facebook-f\"></i></a>\n <span id=\"icontitle\">Facebook</span>\n </div>\n </div>\n </div>\n\n</body>\n\n</html>" }, { "answer_id": 74592486, "author": "Arleigh Hix", "author_id": 6127393, "author_profile": "https://Stackoverflow.com/users/6127393", "pm_score": 1, "selected": false, "text": ".icontitle .icon .button body {\n background: rgb(243, 234, 234);\n}\n\n.wrapper {\n display: grid;\n height: 100%;\n width: 100%;\n place-items: center;\n}\n\n.wrapper .button {\n display: inline-block;\n height: 60px;\n width: 60px;\n margin: 0 5px;\n overflow: hidden;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:hover {\n width: 200px;\n}\n\n.wrapper .button .icon {\n display: inline-block;\n height: 60px;\n width: 60px;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1):hover .icon {\n background: #4267B2;\n}\n\n.wrapper .button .icon i {\n font-size: 25px;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button span {\n font-size: 20px;\n font-weight: 500;\n line-height: 60px;\n margin-left: 10px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1) span {\n color: #4267B2;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,\n intitial-scale=1.0\">\n <title>Correa Events</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&display=swap\" rel=\"stylesheet\">\n</head>\n\n<body>\n\n <div class=\"wrapper\">\n <div class=\"button\">\n <div class=\"icon\">\n <a href=\"https://www.facebook.com/people/Correas-Event-Center/100077040368594/\" target=\"_blank\"><i class=\"fab fa-facebook-f\"></i></a>\n </div>\n <span id=\"icontitle\">Facebook</span>\n </div>\n </div>\n\n</body>\n\n</html>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16499019/" ]
74,553,733
<p>I have a file with 28 columns and numerous rows &gt;10000. I am splitting this file by the second column called gene_id, so that there are numerous outputs each file with a distinct gene_id.</p> <pre><code>variant_id gene_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se hg38_chr hg38_pos ref_allele alt_allele hg19_chr hg19_pos ID new_MAF CHROM POS REF ALT A1 OBS_CT BETA SE P SD Variance chr1_17726150_G_A_b38 ENSG00000272426.1 821374 68 78 0.0644628 0.764314 -0.0320846 0.106958 chr1 17726150 G A chr1 18052645 rs260514:18052645:G:A 0.058155 1 18052645 G A G 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048 chr1_17729225_G_A_b38 ENSG00000117118.9 675055 205 226 0.186777 0.770706 0.00898192 0.0308023 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828 chr1_17729225_G_A_b38 ENSG00000117122.13 748390 205 226 0.186777 0.0373499 0.0553745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828 chr1_177298830_G_A_b38 ENSG00000117122.13 7483450 245 246 0.106777 0.0377699 0.009745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890449757 0.79289055858 </code></pre> <pre><code>output 1 chr1_17726150_G_A_b38 ENSG00000272426.1 821374 68 78 0.0644628 0.764314 -0.0320846 0.106958 chr1 17726150 G A chr1 18052645 rs260514:18052645:G:A 0.058155 1 18052645 G A G 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048 output 2 chr1_17729225_G_A_b38 ENSG00000117118.9 675055 205 226 0.186777 0.770706 0.00898192 0.0308023 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828 output 3 chr1_17729225_G_A_b38 ENSG00000117122.13 748390 205 226 0.186777 0.0373499 0.0553745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828 chr1_17729883_G_A_b38 ENSG00000117122.13 7483450 245 246 0.106777 0.0377699 0.009745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890449757 0.79289055858 </code></pre> <p>I am using the r script below:</p> <pre><code>df &lt;- read.table(&quot;/data/coloc_eQTL/combined_GWAS_skin_eQTL_AL.txt&quot;, header = TRUE) mylist &lt;- split(df , f = df$gene_id) lapply(names(mylist), function(x) write.table(mylist[[x]], file=paste(x,&quot;.txt&quot;), sep=&quot;\t&quot;, row.names=FALSE, quote=FALSE)) </code></pre> <p>However, I notice in the output file there is a column inserted at the start with numbers even though I have stated rownames = FALSE. Also, the output does not show the P column. Therefore, everything is misaligned. How can I ensure all columns are retained and an additional column is not added at the start?</p> <pre><code>number variant_id gene_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se hg38_chr hg38_pos ref_allele alt_allele hg19_chr hg19_pos ID new_MAF CHROM POS REF ALT A1 OBS_CT BETA SE SD Variance 6253451 chr1_17726150_G_A_b38 ENSG00000074964.16 186315 68 78 0.0644628 0.966721 0.00151619 0.0363244 chr1 17726150 G A chr1 18052645 rs260514:18052645:G:A 0.058155 1 18052645 G A G 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048 </code></pre> <p>dput the original file (10 rows).</p> <pre><code>structure(list(variant_id = c(&quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17726150_G_A_b38&quot;), gene_id = c(&quot;ENSG00000272426.1&quot;, &quot;ENSG00000117118.9&quot;, &quot;ENSG00000142623.9&quot;, &quot;ENSG00000142619.4&quot;, &quot;ENSG00000179023.8&quot;, &quot;ENSG00000228549.3&quot;, &quot;ENSG00000058453.16&quot;, &quot;ENSG00000159339.13&quot;, &quot;ENSG00000074964.16&quot;, &quot;ENSG00000117122.13&quot; ), tss_distance = c(821374L, 671980L, 521024L, 477052L, -754832L, 855205L, 804200L, 417955L, 186315L, 745315L), ma_samples = c(68L, 68L, 68L, 68L, 68L, 68L, 68L, 68L, 68L, 68L), ma_count = c(78L, 78L, 78L, 78L, 78L, 78L, 78L, 78L, 78L, 78L), maf = c(0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628), pval_nominal = c(0.764314, 0.955989, 0.352575, 0.00666648, 0.667965, 0.0943182, 0.489115, 0.796736, 0.966721, 0.326205), slope = c(-0.0320846, -0.00275742, -0.0687903, -0.202377, 0.0460589, -0.180725, -0.0449686, 0.0258654, 0.00151619, -0.0424019), slope_se = c(0.106958, 0.0499406, 0.0739349, 0.0743021, 0.107318, 0.10783, 0.0649652, 0.10037, 0.0363244, 0.0431489), hg38_chr = c(&quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;), hg38_pos = c(17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 17726150L), ref_allele = c(&quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;), alt_allele = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;), hg19_chr = c(&quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;), hg19_pos = c(18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L ), ID = c(&quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;, &quot;rs260514:18052645:G:A&quot;), new_MAF = c(0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155 ), CHROM = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), POS = c(18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L), REF = c(&quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;), ALT = c(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;), A1 = c(&quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;, &quot;G&quot;), OBS_CT = c(1597L, 1597L, 1597L, 1597L, 1597L, 1597L, 1597L, 1597L, 1597L, 1597L), BETA = c(0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047), SE = c(0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528), P = c(0.822804, 0.822804, 0.822804, 0.822804, 0.822804, 0.822804, 0.822804, 0.822804, 0.822804, 0.822804), SD = c(2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368), Variance = c(6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048 )), row.names = c(NA, 10L), class = &quot;data.frame&quot;) </code></pre> <p>dput the results of mylist (the first 2 rows).</p> <pre><code>list(ENSG00000058453.16 = structure(list(variant_id = c(&quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17728143_GC_G_b38&quot;, &quot;chr1_17728290_G_A_b38&quot;, &quot;chr1_17729225_G_A_b38&quot;, &quot;chr1_17729967_C_T_b38&quot;, &quot;chr1_17731217_C_T_b38&quot;), gene_id = c(&quot;ENSG00000058453.16&quot;, &quot;ENSG00000058453.16&quot;, &quot;ENSG00000058453.16&quot;, &quot;ENSG00000058453.16&quot;, &quot;ENSG00000058453.16&quot;, &quot;ENSG00000058453.16&quot;), tss_distance = c(804200L, 806193L, 806340L, 807275L, 808017L, 809267L), ma_samples = c(68L, 395L, 167L, 205L, 233L, 233L), ma_count = c(78L, 486L, 183L, 226L, 262L, 263L), maf = c(0.0644628, 0.401653, 0.15124, 0.186777, 0.216529, 0.217355), pval_nominal = c(0.489115, 0.210837, 0.820243, 0.301818, 0.137132, 0.128855), slope = c(-0.0449686, 0.0404518, 0.0097847, 0.0413934, 0.0574705, 0.0585334), slope_se = c(0.0649652, 0.0322899, 0.0430392, 0.0400502, 0.0386021, 0.038484), hg38_chr = c(&quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;), hg38_pos = c(17726150L, 17728143L, 17728290L, 17729225L, 17729967L, 17731217L), ref_allele = c(&quot;G&quot;, &quot;GC&quot;, &quot;G&quot;, &quot;G&quot;, &quot;C&quot;, &quot;C&quot;), alt_allele = c(&quot;A&quot;, &quot;G&quot;, &quot;A&quot;, &quot;A&quot;, &quot;T&quot;, &quot;T&quot;), hg19_chr = c(&quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;), hg19_pos = c(18052645L, 18054638L, 18054785L, 18055720L, 18056462L, 18057712L), ID = c(&quot;rs260514:18052645:G:A&quot;, &quot;rs35592535:18054638:GC:G&quot;, &quot;rs1572792:18054785:G:A&quot;, &quot;rs11580304:18055720:G:A&quot;, &quot;rs1890743:18056462:C:T&quot;, &quot;rs7546135:18057712:C:T&quot;), new_MAF = c(0.058155, 0.371673, 0.17466, 0.194694, 0.197464, 0.198691), CHROM = c(1L, 1L, 1L, 1L, 1L, 1L), POS = c(18052645L, 18054638L, 18054785L, 18055720L, 18056462L, 18057712L), REF = c(&quot;G&quot;, &quot;GC&quot;, &quot;G&quot;, &quot;G&quot;, &quot;C&quot;, &quot;C&quot;), ALT = c(&quot;A&quot;, &quot;G&quot;, &quot;A&quot;, &quot;A&quot;, &quot;T&quot;, &quot;T&quot;), A1 = c(&quot;G&quot;, &quot;G&quot;, &quot;A&quot;, &quot;A&quot;, &quot;T&quot;, &quot;T&quot; ), OBS_CT = c(1597L, 1597L, 1597L, 1597L, 1597L, 1597L), BETA = c(0.0147047, 0.0138673, -0.0126002, 0.00515331, 0.00415908, 0.00597402), SE = c(0.0656528, 0.0269643, 0.0256229, 0.022282, 0.0220529, 0.0217018), P = c(0.822804, 0.607124, 0.622959, 0.817129, 0.850434, 0.783139), SD = c(2.62364886486368, 1.07756036432328, 1.02395469042471, 0.890444032956592, 0.88128862823752, 0.867257800664993), Variance = c(6.88353336610048, 1.16113633876053, 1.04848320804277, 0.792890575828, 0.77666964626077, 0.75213609281428 )), row.names = c(7L, 25L, 45L, 56L, 77L, 94L), class = &quot;data.frame&quot;), ENSG00000074964.16 = structure(list(variant_id = c(&quot;chr1_17726150_G_A_b38&quot;, &quot;chr1_17728143_GC_G_b38&quot;, &quot;chr1_17728290_G_A_b38&quot;, &quot;chr1_17729225_G_A_b38&quot;, &quot;chr1_17729967_C_T_b38&quot;, &quot;chr1_17731217_C_T_b38&quot;), gene_id = c(&quot;ENSG00000074964.16&quot;, &quot;ENSG00000074964.16&quot;, &quot;ENSG00000074964.16&quot;, &quot;ENSG00000074964.16&quot;, &quot;ENSG00000074964.16&quot;, &quot;ENSG00000074964.16&quot;), tss_distance = c(186315L, 188308L, 188455L, 189390L, 190132L, 191382L), ma_samples = c(68L, 395L, 167L, 205L, 233L, 233L), ma_count = c(78L, 486L, 183L, 226L, 262L, 263L), maf = c(0.0644628, 0.401653, 0.15124, 0.186777, 0.216529, 0.217355), pval_nominal = c(0.966721, 0.954589, 0.17366, 0.865996, 0.547435, 0.565949), slope = c(0.00151619, 0.00102964, -0.0327149, -0.00378263, -0.01301, -0.0123769 ), slope_se = c(0.0363244, 0.0180728, 0.0240136, 0.0224053, 0.0216116, 0.021548), hg38_chr = c(&quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;), hg38_pos = c(17726150L, 17728143L, 17728290L, 17729225L, 17729967L, 17731217L), ref_allele = c(&quot;G&quot;, &quot;GC&quot;, &quot;G&quot;, &quot;G&quot;, &quot;C&quot;, &quot;C&quot;), alt_allele = c(&quot;A&quot;, &quot;G&quot;, &quot;A&quot;, &quot;A&quot;, &quot;T&quot;, &quot;T&quot;), hg19_chr = c(&quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;, &quot;chr1&quot;), hg19_pos = c(18052645L, 18054638L, 18054785L, 18055720L, 18056462L, 18057712L), ID = c(&quot;rs260514:18052645:G:A&quot;, &quot;rs35592535:18054638:GC:G&quot;, &quot;rs1572792:18054785:G:A&quot;, &quot;rs11580304:18055720:G:A&quot;, &quot;rs1890743:18056462:C:T&quot;, &quot;rs7546135:18057712:C:T&quot;), new_MAF = c(0.058155, 0.371673, 0.17466, 0.194694, 0.197464, 0.198691), CHROM = c(1L, 1L, 1L, 1L, 1L, 1L), POS = c(18052645L, 18054638L, 18054785L, 18055720L, 18056462L, 18057712L), REF = c(&quot;G&quot;, &quot;GC&quot;, &quot;G&quot;, &quot;G&quot;, &quot;C&quot;, &quot;C&quot;), ALT = c(&quot;A&quot;, &quot;G&quot;, &quot;A&quot;, &quot;A&quot;, &quot;T&quot;, &quot;T&quot;), A1 = c(&quot;G&quot;, &quot;G&quot;, &quot;A&quot;, &quot;A&quot;, &quot;T&quot;, &quot;T&quot;), OBS_CT = c(1597L, 1597L, 1597L, 1597L, 1597L, 1597L), BETA = c(0.0147047, 0.0138673, -0.0126002, 0.00515331, 0.00415908, 0.00597402), SE = c(0.0656528, 0.0269643, 0.0256229, 0.022282, 0.0220529, 0.0217018), P = c(0.822804, 0.607124, 0.622959, 0.817129, 0.850434, 0.783139), SD = c(2.62364886486368, 1.07756036432328, 1.02395469042471, 0.890444032956592, 0.88128862823752, 0.867257800664993), Variance = c(6.88353336610048, 1.16113633876053, 1.04848320804277, 0.792890575828, 0.77666964626077, 0.75213609281428 )), row.names = c(9L, 23L, 38L, 66L, 76L, 97L), class = &quot;data.frame&quot;)) </code></pre>
[ { "answer_id": 74553846, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "display inline-block flex hover .icon .wrapper .button .icon:hover {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 60px;\n width: 100%;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n body {\n background: rgb(243, 234, 234);\n}\n\n.wrapper {\n display: grid;\n height: 100%;\n width: 100%;\n place-items: center;\n}\n\n.wrapper .button {\n display: inline-block;\n height: 60px;\n width: 60px;\n margin: 0 5px;\n overflow: hidden;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:hover {\n width: 200px;\n}\n\n.wrapper .button .icon {\n display: inline-block;\n height: 60px;\n width: 60px;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button .icon:hover {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 60px;\n width: 100%;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1):hover .icon {\n background: #4267B2;\n}\n\n.wrapper .button .icon i {\n font-size: 25px;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button span {\n font-size: 20px;\n font-weight: 500;\n line-height: 60px;\n margin-left: 50px;\n transition: all 0.3s ease-out;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,\n intitial-scale=1.0\">\n <title>Correa Events</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&display=swap\" rel=\"stylesheet\">\n</head>\n\n<body>\n <div class=\"wrapper\">\n <div class=\"button\">\n <div class=\"icon\">\n <a href=\"https://www.facebook.com/people/Correas-Event-Center/100077040368594/\" target=\"_blank\"><i class=\"fab fa-facebook-f\"></i></a>\n <span id=\"icontitle\">Facebook</span>\n </div>\n </div>\n </div>\n\n</body>\n\n</html>" }, { "answer_id": 74592486, "author": "Arleigh Hix", "author_id": 6127393, "author_profile": "https://Stackoverflow.com/users/6127393", "pm_score": 1, "selected": false, "text": ".icontitle .icon .button body {\n background: rgb(243, 234, 234);\n}\n\n.wrapper {\n display: grid;\n height: 100%;\n width: 100%;\n place-items: center;\n}\n\n.wrapper .button {\n display: inline-block;\n height: 60px;\n width: 60px;\n margin: 0 5px;\n overflow: hidden;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:hover {\n width: 200px;\n}\n\n.wrapper .button .icon {\n display: inline-block;\n height: 60px;\n width: 60px;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1):hover .icon {\n background: #4267B2;\n}\n\n.wrapper .button .icon i {\n font-size: 25px;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button span {\n font-size: 20px;\n font-weight: 500;\n line-height: 60px;\n margin-left: 10px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1) span {\n color: #4267B2;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,\n intitial-scale=1.0\">\n <title>Correa Events</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&display=swap\" rel=\"stylesheet\">\n</head>\n\n<body>\n\n <div class=\"wrapper\">\n <div class=\"button\">\n <div class=\"icon\">\n <a href=\"https://www.facebook.com/people/Correas-Event-Center/100077040368594/\" target=\"_blank\"><i class=\"fab fa-facebook-f\"></i></a>\n </div>\n <span id=\"icontitle\">Facebook</span>\n </div>\n </div>\n\n</body>\n\n</html>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14614150/" ]
74,553,752
<p>I'm trying to create a short program that calls a user's number and records the conversation using Twilio and send the recording to an S3 bucket</p> <p>Here's a link that does it to a dropbox instead of an S3: <a href="https://www.twilio.com/blog/recording-saving-outbound-voice-calls-python-twilio-dropbox" rel="nofollow noreferrer">https://www.twilio.com/blog/recording-saving-outbound-voice-calls-python-twilio-dropbox</a></p> <p>Here's the code I have so far that allows me to call and recorded conversations go to Twilio's online storage:</p> <pre><code> call = client.calls.create( record=True, url='http://demo.twilio.com/docs/voice.xml', to='+15558889988', from_='+18889992222' ) print(call.sid) </code></pre>
[ { "answer_id": 74553846, "author": "Nijat Mursali", "author_id": 10489887, "author_profile": "https://Stackoverflow.com/users/10489887", "pm_score": 0, "selected": false, "text": "display inline-block flex hover .icon .wrapper .button .icon:hover {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 60px;\n width: 100%;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n body {\n background: rgb(243, 234, 234);\n}\n\n.wrapper {\n display: grid;\n height: 100%;\n width: 100%;\n place-items: center;\n}\n\n.wrapper .button {\n display: inline-block;\n height: 60px;\n width: 60px;\n margin: 0 5px;\n overflow: hidden;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:hover {\n width: 200px;\n}\n\n.wrapper .button .icon {\n display: inline-block;\n height: 60px;\n width: 60px;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button .icon:hover {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 60px;\n width: 100%;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1):hover .icon {\n background: #4267B2;\n}\n\n.wrapper .button .icon i {\n font-size: 25px;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button span {\n font-size: 20px;\n font-weight: 500;\n line-height: 60px;\n margin-left: 50px;\n transition: all 0.3s ease-out;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,\n intitial-scale=1.0\">\n <title>Correa Events</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&display=swap\" rel=\"stylesheet\">\n</head>\n\n<body>\n <div class=\"wrapper\">\n <div class=\"button\">\n <div class=\"icon\">\n <a href=\"https://www.facebook.com/people/Correas-Event-Center/100077040368594/\" target=\"_blank\"><i class=\"fab fa-facebook-f\"></i></a>\n <span id=\"icontitle\">Facebook</span>\n </div>\n </div>\n </div>\n\n</body>\n\n</html>" }, { "answer_id": 74592486, "author": "Arleigh Hix", "author_id": 6127393, "author_profile": "https://Stackoverflow.com/users/6127393", "pm_score": 1, "selected": false, "text": ".icontitle .icon .button body {\n background: rgb(243, 234, 234);\n}\n\n.wrapper {\n display: grid;\n height: 100%;\n width: 100%;\n place-items: center;\n}\n\n.wrapper .button {\n display: inline-block;\n height: 60px;\n width: 60px;\n margin: 0 5px;\n overflow: hidden;\n border-radius: 50px;\n cursor: pointer;\n box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:hover {\n width: 200px;\n}\n\n.wrapper .button .icon {\n display: inline-block;\n height: 60px;\n width: 60px;\n text-align: center;\n border-radius: 50px;\n box-sizing: border-box;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1):hover .icon {\n background: #4267B2;\n}\n\n.wrapper .button .icon i {\n font-size: 25px;\n line-height: 60px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button span {\n font-size: 20px;\n font-weight: 500;\n line-height: 60px;\n margin-left: 10px;\n transition: all 0.3s ease-out;\n}\n\n.wrapper .button:nth-child(1) span {\n color: #4267B2;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width,\n intitial-scale=1.0\">\n <title>Correa Events</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\">\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@300;400&display=swap\" rel=\"stylesheet\">\n</head>\n\n<body>\n\n <div class=\"wrapper\">\n <div class=\"button\">\n <div class=\"icon\">\n <a href=\"https://www.facebook.com/people/Correas-Event-Center/100077040368594/\" target=\"_blank\"><i class=\"fab fa-facebook-f\"></i></a>\n </div>\n <span id=\"icontitle\">Facebook</span>\n </div>\n </div>\n\n</body>\n\n</html>" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14459020/" ]
74,553,801
<p>I am building an animation of stacked bar charts (calling <code>geom_col</code>). I have 100 columns. When I generate the animation I get a lot of white space in what should be filled columns.</p> <p>See the gif below:</p> <p><a href="https://i.stack.imgur.com/KsANh.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KsANh.gif" alt="enter image description here" /></a></p> <p>That gif is based on about 100k rows of data, so I can't post it all here. Notably, I can't reproduce this in a simpler example:</p> <pre><code>library('tidyverse') library('gganimate') data.frame(time = rep(1:50, 200)) %&gt;% arrange(time) %&gt;% mutate(type = rep(c(rep('A', 100), rep('B', 100)), 50), class = rep((1:100), 100), value = runif(10000, 0, 1)) %&gt;% ggplot(aes(x = class, y = value, fill = type)) + geom_col() + transition_time(time) </code></pre> <p>Works fine (ignoring the structure in the above data, but i don't get the white spaces):</p> <p><a href="https://i.stack.imgur.com/sDETN.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sDETN.gif" alt="enter image description here" /></a></p> <p>I tried adding <code>ease_aes()</code>, <code>enter_fade()</code>, <code>exit_fade()</code>, but none of that worked. Anyone have thoughts on what is causing this?</p> <p>---UPDATE---</p> <p>Following the comments I tried filtering the data down to see what was going on. Reducing to just two countries and 5 years of data, the problem appears to be that chunks of data are moving between percentiles. When what I want is for them to just grow and shrink within each percentile. You can see it in the gif below:</p> <p><a href="https://i.stack.imgur.com/Glxzn.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Glxzn.gif" alt="enter image description here" /></a></p> <p>The data that produced this is here:</p> <pre><code>structure(list(country = c(&quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;, &quot;US&quot;, &quot;DE&quot;), glob.perc = c(0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 1, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9), avg.income.country = c(437288.3, 95483.3754884956, 140784.030084749, 140733.5, 92860.7570361667, 27041.1685330627, 82474.4007614941, 22845.1776491941, 75584.1480877374, 20954.7760014288, 70400.3370710519, 19852.2326809271, 54038.6152996391, 15598.3057384556, 15170.9872445152, 62785.1002246113, 18201.6743099168, 39606.7790727414, 39051.1193095399, 450574.9, 89747.1381942579, 143040.424101143, 144413.3, 95281.4131057479, 26564.8030858664, 84645.1806598295, 22453.3134663253, 99495.4, 58448.7245539485, 16815.8081430027, 15925.4607078112, 67342.4870614877, 18775.7716260376, 52078.6261482834, 14908.4732454128, 14586.6597398625, 60740.8587598986, 17551.4029073371, 449672.7, 85860.9513060095, 138573.062299181, 107999.713224424, 26551.7207203881, 118606.7, 81673.5478130351, 22256.5124499113, 74664.7815210055, 20289.8692320157, 69424.4509484861, 19130.6427260963, 53441.6796042233, 15011.8413898757, 14554.8379632521, 62031.6543795656, 17372.7239256402, 17038.0153770701, 59253.6721580242, 478696.8, 87965.3040019279, 141489.41469306, 110750.734809188, 28139.4736007857, 121395.4, 84564.2106500617, 23136.9326230234, 77452.4071740221, 20809.5254887263, 72187.8010950261, 19423.2184457137, 67965.6133547784, 18489.4603327709, 64700.6833849069, 17811.5804850837, 50612.3590346861, 14165.4003733601, 13829.472811758, 542123.2, 89948.9091254987, 158338.248242006, 156908.9, 104475.681782063, 29031.666816329, 92305.5514014955, 23750.4970524401, 107775.8, 78090.1791649968, 21282.8059573008, 73283.2631907787, 19808.7465702618, 69304.0213872794, 18813.7418777938, 65958.7178466761, 18090.1791160505, 559720.3, 92129.3365959901, 159846.146463587, 123870.105638014, 30030.7222753586, 135301.9, 94785.176213572, 24358.2621716462, 110644.4, 80286.8697338142, 21690.4391200441, 75280.156096728, 20090.0002975319, 71136.641950609, 19006.2143886443, 67594.6662796918, 18216.0069568407), region = c(&quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;, &quot;Americas&quot;, &quot;Europe&quot;), year = c(1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1980L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1981L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1982L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1983L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1984L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L, 1985L)), row.names = c(NA, -110L ), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;)) </code></pre> <p>The code for the animation is as follows:</p> <pre><code>df %&gt;% ggplot(aes(x = glob.perc, y = avg.income.country/1000, fill = region)) + geom_col(position = 'stack') + theme_minimal() + labs(subtitle = &quot;Year: {frame_time}&quot;, x = element_blank(), y = element_blank(), fill = 'Region') + transition_time(year) </code></pre> <p>My sense is this is not an issue of missing data - at each year the visualization is complete without whitespace. i think its an issue of how the <code>geom_col()</code> transitions.</p>
[ { "answer_id": 74563718, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 0, "selected": false, "text": "value group_by sum filter library('tidyverse')\nlibrary('gganimate')\n\nddf_anim <- data.frame(time = rep(1:50, 200)) %>%\n arrange(time) %>%\n mutate(type = rep(c(rep('A', 100), rep('B', 100)), 50), \n class = rep((1:100), 100), \n value = runif(10000, 0, 1)) %>%\n filter(time <10) %>% \n group_by(class, type) %>% \n mutate(sum = cumsum(value)) %>% \n ggplot(aes(x = class, y = sum, fill = type)) +\n geom_col() +\n transition_time(time)\n\n\nddf_anim\n" }, { "answer_id": 74605651, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": true, "text": "df %>% \n group_by(year, region, country, glob.perc) %>%\n summarize(avg.income.country = mean(avg.income.country), n = n()) %>%\n ungroup() %>%\n complete(year, nesting(country, region), glob.perc, fill = list(avg.income.country = 0)) %>%\n \n ggplot(aes(x = glob.perc, y = avg.income.country/1000, fill = region)) + \n geom_col(position = 'stack', color = \"black\", alpha = 0.7) +\n theme_minimal() +\n labs(subtitle = \"Year: {frame_time}\", \n x = element_blank(), \n y = element_blank(), \n fill = 'Region') +\n transition_time(year)\n \n df %>% \n count(year, region, country, glob.perc) %>%\n ggplot(aes(year, glob.perc, fill = n)) +\n geom_tile() +\n facet_wrap(~country)\n df %>% \n filter(country == \"DE\", glob.perc >= 2) %>%\n ggplot(aes(year, avg.income.country, color = as.character(glob.perc), group = glob.perc)) +\n geom_line() +\n facet_wrap(~country)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8272788/" ]
74,553,807
<p>I am currently running some python code to extract words from a list and create a list of these words.</p> <p>The list I am using is from a .txt file with some lines from romeo and juliet.</p> <p>I read in the file, trimmed the whitespace, split each word up, and added these words to a list.</p> <p>I am now trying to create a list that does not include any words repeating.</p> <p>I know that I need to create a loop of some sort to go through the list, add the words, and then discard the repeated words.</p> <p>This is the code I currently have:</p> <pre><code>fname = input (&quot;Enter file name: &quot;) #Here we check to see if the file is in the correct format #If it is not, we will return a personalized error message #and quit the programme. try : fh = open(fname) except : print(&quot;Enter a valid file name: &quot;) quit() #Here I read in the file so that it returns as a complete #string. fread = fh.read() #print(fread) #Here we are stripping the file of any unnecessary #whitespace fstrip = fread.rstrip() #print(fstrip) #Here we are splitting all the words into individual values #in a list. This will allow us to write a loop to check #for repeating words. fsplit = fstrip.split() lst = list(fsplit) #print(lst) #This is going to be our for loop. wdlst = list() </code></pre> <p>Any help would be greatly appreciated, I am new to python and I just cannot seem to figure out what combination of statements needs to be added to create this new list.</p> <p>Many thanks,</p>
[ { "answer_id": 74563718, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 0, "selected": false, "text": "value group_by sum filter library('tidyverse')\nlibrary('gganimate')\n\nddf_anim <- data.frame(time = rep(1:50, 200)) %>%\n arrange(time) %>%\n mutate(type = rep(c(rep('A', 100), rep('B', 100)), 50), \n class = rep((1:100), 100), \n value = runif(10000, 0, 1)) %>%\n filter(time <10) %>% \n group_by(class, type) %>% \n mutate(sum = cumsum(value)) %>% \n ggplot(aes(x = class, y = sum, fill = type)) +\n geom_col() +\n transition_time(time)\n\n\nddf_anim\n" }, { "answer_id": 74605651, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": true, "text": "df %>% \n group_by(year, region, country, glob.perc) %>%\n summarize(avg.income.country = mean(avg.income.country), n = n()) %>%\n ungroup() %>%\n complete(year, nesting(country, region), glob.perc, fill = list(avg.income.country = 0)) %>%\n \n ggplot(aes(x = glob.perc, y = avg.income.country/1000, fill = region)) + \n geom_col(position = 'stack', color = \"black\", alpha = 0.7) +\n theme_minimal() +\n labs(subtitle = \"Year: {frame_time}\", \n x = element_blank(), \n y = element_blank(), \n fill = 'Region') +\n transition_time(year)\n \n df %>% \n count(year, region, country, glob.perc) %>%\n ggplot(aes(year, glob.perc, fill = n)) +\n geom_tile() +\n facet_wrap(~country)\n df %>% \n filter(country == \"DE\", glob.perc >= 2) %>%\n ggplot(aes(year, avg.income.country, color = as.character(glob.perc), group = glob.perc)) +\n geom_line() +\n facet_wrap(~country)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19967035/" ]
74,553,838
<p>I'm new to react and front development any help would be appreciate, please don't make stack overflow a toxic place, laughing or closing the tick you think it is too simple or stupid. No question is stupid</p> <p>A <code>Button</code> is stored in file <strong>panel.tsx</strong> a <code>Switch</code> is located in <strong>notes.tsx</strong> file the enable and disable status of the <code>button</code> is decided by the <code>switch</code> condition in the <strong>notes.tsx</strong> file.</p> <p>The following code is a simplified version of the issue described above</p> <pre><code># notes.tsx export const AddNotes: React.FC = () =&gt; { const [skipNotes, setSkipNotes] = useState(false); const onSkipNotes = (checked: boolean) =&gt; setSkipNotes(checked); return ( &lt;div&gt; &lt;CC.ToggleSwitch checked={skipNotesAndTags} onChange={onSkipNotes} label=&quot;Skip notes&quot; changeHighlight /&gt; &lt;/div&gt; ); }; # panel.tsx export const Panel: React.FC = () =&gt; { &lt;div&gt; &lt;CC.Button text={'Submit'} disabled={true}/&gt; // How can I disabled/enable it based on skipNotes from note.tsx &lt;/div&gt; </code></pre> <p>How can I disabled/enable the <strong>Button</strong> based on <strong>skipNotes</strong> from notes.tsx?</p>
[ { "answer_id": 74563718, "author": "MarBlo", "author_id": 4282026, "author_profile": "https://Stackoverflow.com/users/4282026", "pm_score": 0, "selected": false, "text": "value group_by sum filter library('tidyverse')\nlibrary('gganimate')\n\nddf_anim <- data.frame(time = rep(1:50, 200)) %>%\n arrange(time) %>%\n mutate(type = rep(c(rep('A', 100), rep('B', 100)), 50), \n class = rep((1:100), 100), \n value = runif(10000, 0, 1)) %>%\n filter(time <10) %>% \n group_by(class, type) %>% \n mutate(sum = cumsum(value)) %>% \n ggplot(aes(x = class, y = sum, fill = type)) +\n geom_col() +\n transition_time(time)\n\n\nddf_anim\n" }, { "answer_id": 74605651, "author": "Jon Spring", "author_id": 6851825, "author_profile": "https://Stackoverflow.com/users/6851825", "pm_score": 2, "selected": true, "text": "df %>% \n group_by(year, region, country, glob.perc) %>%\n summarize(avg.income.country = mean(avg.income.country), n = n()) %>%\n ungroup() %>%\n complete(year, nesting(country, region), glob.perc, fill = list(avg.income.country = 0)) %>%\n \n ggplot(aes(x = glob.perc, y = avg.income.country/1000, fill = region)) + \n geom_col(position = 'stack', color = \"black\", alpha = 0.7) +\n theme_minimal() +\n labs(subtitle = \"Year: {frame_time}\", \n x = element_blank(), \n y = element_blank(), \n fill = 'Region') +\n transition_time(year)\n \n df %>% \n count(year, region, country, glob.perc) %>%\n ggplot(aes(year, glob.perc, fill = n)) +\n geom_tile() +\n facet_wrap(~country)\n df %>% \n filter(country == \"DE\", glob.perc >= 2) %>%\n ggplot(aes(year, avg.income.country, color = as.character(glob.perc), group = glob.perc)) +\n geom_line() +\n facet_wrap(~country)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3004698/" ]
74,553,848
<p>I am trying to make the SwiftUI Form translucent. I've tried applying <code>.background(.thinMaterial)</code> modifier to the Form. However, this changes the look of the scroll view background. I'd like to apply translucency to the area that is white in the picture I attached.</p> <p>Is there a way to do it? I am developing for iOS 16.</p> <pre><code>var body: some View { NavigationStack(path: $path) { ZStack { LinearGradient(gradient: Gradient(colors: [.pink, .yellow]), startPoint: .topTrailing, endPoint: .bottomLeading) .edgesIgnoringSafeArea(.all) Form { VStack { ... } }.scrollContentBackground(.hidden) } } </code></pre> <p><a href="https://i.stack.imgur.com/w2tTk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w2tTk.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74554112, "author": "flanker", "author_id": 3218273, "author_profile": "https://Stackoverflow.com/users/3218273", "pm_score": 0, "selected": false, "text": "Form {\n /...\n}\n.opacity(0.5). // 0 = fully translucent ... 1 = opaque\n" }, { "answer_id": 74554380, "author": "burnsi", "author_id": 6950415, "author_profile": "https://Stackoverflow.com/users/6950415", "pm_score": 2, "selected": true, "text": "Form List .scrollContentBackground(.hidden) List .background Form List Section .listRowBackground listRowBackground func listRowBackground<V>(_ view: V?) -> some View where V : View\n .thinMaterial VStack var body: some View {\n NavigationStack(path: $path) {\n ZStack {\n LinearGradient(gradient: Gradient(colors: [.pink, .yellow]),\n startPoint: .topTrailing,\n endPoint: .bottomLeading)\n .edgesIgnoringSafeArea(.all)\n\n Form {\n VStack {\n TextField(\"\", text: $text)\n Button(\"test\"){\n \n }\n .buttonStyle(.borderedProminent)\n Button(\"test\"){\n \n }.buttonStyle(.borderedProminent)\n }\n // this will clear the background\n .listRowBackground(Color.clear)\n // add some padding around the VStack\n .padding()\n // apply a new background\n .background(.ultraThinMaterial)\n // make the edges round again\n .mask {\n RoundedRectangle(cornerRadius: 20)\n }\n \n }\n .scrollContentBackground(.hidden)\n }\n }\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348796/" ]
74,553,851
<p>I have a problem in my project. I created something like keyboard for hangman game with span. In click situation I need to have disabled span for that letter and if user choose wrong letter the hangman image should be change. But when I click any button it looks like it is disabled because I changed the color</p> <pre><code>. clickedLetter{ background-color :.... opacity:.1; pointer-events: none; } </code></pre> <p>But the letter is still clickable and when you click on disabled letter(span) the image of hangman going to change .</p> <p>I want to add something to stop any action</p> <p>It is my code:</p> <pre><code>document.addEventListener(&quot;click&quot;, (e) =&gt; { if(e.target.className ==='boxForLetter') { e.target.classList.add(&quot;clickedLetter&quot;);} let clickedLetter= e.target.innerHTML; </code></pre> <p>.......</p> <p>....</p> <p>...</p> <p>.</p> <p>I appreciate any thoughts about this problem</p>
[ { "answer_id": 74554112, "author": "flanker", "author_id": 3218273, "author_profile": "https://Stackoverflow.com/users/3218273", "pm_score": 0, "selected": false, "text": "Form {\n /...\n}\n.opacity(0.5). // 0 = fully translucent ... 1 = opaque\n" }, { "answer_id": 74554380, "author": "burnsi", "author_id": 6950415, "author_profile": "https://Stackoverflow.com/users/6950415", "pm_score": 2, "selected": true, "text": "Form List .scrollContentBackground(.hidden) List .background Form List Section .listRowBackground listRowBackground func listRowBackground<V>(_ view: V?) -> some View where V : View\n .thinMaterial VStack var body: some View {\n NavigationStack(path: $path) {\n ZStack {\n LinearGradient(gradient: Gradient(colors: [.pink, .yellow]),\n startPoint: .topTrailing,\n endPoint: .bottomLeading)\n .edgesIgnoringSafeArea(.all)\n\n Form {\n VStack {\n TextField(\"\", text: $text)\n Button(\"test\"){\n \n }\n .buttonStyle(.borderedProminent)\n Button(\"test\"){\n \n }.buttonStyle(.borderedProminent)\n }\n // this will clear the background\n .listRowBackground(Color.clear)\n // add some padding around the VStack\n .padding()\n // apply a new background\n .background(.ultraThinMaterial)\n // make the edges round again\n .mask {\n RoundedRectangle(cornerRadius: 20)\n }\n \n }\n .scrollContentBackground(.hidden)\n }\n }\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20585873/" ]
74,553,852
<p>I'm trying to use an algorithm in a function.</p> <p>Should be very simple.</p> <p>However, regardless of which algorithm I attempt to use, all of them cause the same error when used in a function.</p> <blockquote> <p>E0304 no instance of overloaded function &quot;std::begin&quot; matches the argument list</p> </blockquote> <blockquote> <p>E0304 no instance of overloaded function &quot;std::end&quot; matches the argument list</p> </blockquote> <p>I am guessing there is some small change that needs to be made.</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &quot;bool_element_option_03.h&quot; #include &quot;storage.h&quot; int main() { int arr_value[ELEMENTS]{ 1, 2, 9, 4, 5, 6, 7, 8 }; int arr_copy_value[ELEMENTS]; // array population for (int var_create_array_a = 0; var_create_array_a &lt; ELEMENTS; var_create_array_a++) { arr_copy_value[var_create_array_a] = 0; } //std::copy(std::begin(arr_value), std::end(arr_value), std::begin(arr_copy_value)); //std::sort(std::rbegin(arr_copy_value), std::rend(arr_copy_value)); for (int output = 0; output &lt; ELEMENTS; output++) { std::cout &lt;&lt; &quot;copied decimals: &quot; &lt;&lt; arr_copy_value[output] &lt;&lt; std::endl; } bool_element_option_03(arr_value, arr_copy_value); return 0; } </code></pre> <pre><code>#ifndef _STORAGE_H #define _STORAGE_H #define WIN32_LEAN_AND_MEAN // ----------------------------------------------------------------------------------------------------------------------------------------------------- // Constants // ----------------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------- const int ELEMENTS = 8; //----------------------------------------------- #endif </code></pre> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &quot;storage.h&quot; void bool_element_option_03(int arr_value[], int* arr_copy_value) { std::copy(std::begin(arr_value + ELEMENTS), std::end(arr_value + ELEMENTS), std::begin(arr_copy_value + ELEMENTS)); std::sort(std::rbegin(arr_copy_value + ELEMENTS), std::rend(arr_copy_value + ELEMENTS)); for (int output = 0; output &lt; ELEMENTS; output++) { std::cout &lt;&lt; &quot;copied decimals: &quot; &lt;&lt; arr_copy_value[output] &lt;&lt; std::endl; } } </code></pre> <p>If I take these algorithms out of the function and put them in main(), they work as they should.</p> <p>Should I intentionally overload this function (so I can use algorithms in it)?</p> <p>Overloading this function is not my intention. I'm not calling it multiple times with different arguments.<br /> This function is only being called once.</p>
[ { "answer_id": 74554112, "author": "flanker", "author_id": 3218273, "author_profile": "https://Stackoverflow.com/users/3218273", "pm_score": 0, "selected": false, "text": "Form {\n /...\n}\n.opacity(0.5). // 0 = fully translucent ... 1 = opaque\n" }, { "answer_id": 74554380, "author": "burnsi", "author_id": 6950415, "author_profile": "https://Stackoverflow.com/users/6950415", "pm_score": 2, "selected": true, "text": "Form List .scrollContentBackground(.hidden) List .background Form List Section .listRowBackground listRowBackground func listRowBackground<V>(_ view: V?) -> some View where V : View\n .thinMaterial VStack var body: some View {\n NavigationStack(path: $path) {\n ZStack {\n LinearGradient(gradient: Gradient(colors: [.pink, .yellow]),\n startPoint: .topTrailing,\n endPoint: .bottomLeading)\n .edgesIgnoringSafeArea(.all)\n\n Form {\n VStack {\n TextField(\"\", text: $text)\n Button(\"test\"){\n \n }\n .buttonStyle(.borderedProminent)\n Button(\"test\"){\n \n }.buttonStyle(.borderedProminent)\n }\n // this will clear the background\n .listRowBackground(Color.clear)\n // add some padding around the VStack\n .padding()\n // apply a new background\n .background(.ultraThinMaterial)\n // make the edges round again\n .mask {\n RoundedRectangle(cornerRadius: 20)\n }\n \n }\n .scrollContentBackground(.hidden)\n }\n }\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20506604/" ]
74,553,914
<pre><code>address = [1,2,3] p address new_address = address.reverse! p new_address p address.reverse! </code></pre> <p>Prints:</p> <pre><code>[1,2,3] [3,2,1] [1,2,3] </code></pre> <p>I don't understand why the last print out is 1,2,3 if it is meant to print the address in reverse, the address is 1,2,3</p> <p>I expected the last line to be [3,2,1].</p>
[ { "answer_id": 74554112, "author": "flanker", "author_id": 3218273, "author_profile": "https://Stackoverflow.com/users/3218273", "pm_score": 0, "selected": false, "text": "Form {\n /...\n}\n.opacity(0.5). // 0 = fully translucent ... 1 = opaque\n" }, { "answer_id": 74554380, "author": "burnsi", "author_id": 6950415, "author_profile": "https://Stackoverflow.com/users/6950415", "pm_score": 2, "selected": true, "text": "Form List .scrollContentBackground(.hidden) List .background Form List Section .listRowBackground listRowBackground func listRowBackground<V>(_ view: V?) -> some View where V : View\n .thinMaterial VStack var body: some View {\n NavigationStack(path: $path) {\n ZStack {\n LinearGradient(gradient: Gradient(colors: [.pink, .yellow]),\n startPoint: .topTrailing,\n endPoint: .bottomLeading)\n .edgesIgnoringSafeArea(.all)\n\n Form {\n VStack {\n TextField(\"\", text: $text)\n Button(\"test\"){\n \n }\n .buttonStyle(.borderedProminent)\n Button(\"test\"){\n \n }.buttonStyle(.borderedProminent)\n }\n // this will clear the background\n .listRowBackground(Color.clear)\n // add some padding around the VStack\n .padding()\n // apply a new background\n .background(.ultraThinMaterial)\n // make the edges round again\n .mask {\n RoundedRectangle(cornerRadius: 20)\n }\n \n }\n .scrollContentBackground(.hidden)\n }\n }\n}\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20568607/" ]
74,553,927
<p>I'm playing around with parcel before I used liveserver in vscode and I rarely ran into this problem. I'm trying to add a eventlistener to a inputform. DOM isn't finding the element no matter what I do. I've tried to put a if statement checking if the element exist before putting a listener but it doesn't change anything. I never had this problem using liveserver, do i have to write a asynchronous function and wait for the page to load? I tried putting defer inside the script tag aswell. Is parcel slower than liveserver somehow?</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>const input1 = document.getElementById("input1"); if(input1) { console.log("The input exists"); input1.addEventListener('click', () =&gt;{ console.log("heey"); }); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;link rel="stylesheet" href="./assets/scss/main.scss"&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;div class="form-group"&gt; &lt;label for="inputlg"&gt;input&lt;/label&gt; &lt;input class="form-control input-lg" id="inputlg" type="text" id="input1"&gt; &lt;label for="inputlg"&gt;output&lt;/label&gt; &lt;input class="form-control input-lg" id="inputlg" type="text"&gt; &lt;/div&gt; &lt;/form&gt; &lt;script type="module" src="./assets/js/main.js" &gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74553955, "author": "ray", "author_id": 636077, "author_profile": "https://Stackoverflow.com/users/636077", "pm_score": 1, "selected": false, "text": "getElementById const input1 = document.getElementById('input1');\nconsole.log(input1); // null\n\nconst inputlg = document.getElementById('inputlg');\nconsole.log(inputlg); // input#inputlg.form-control.input-lg <input class=\"form-control input-lg\" id=\"inputlg\" type=\"text\" id=\"input1\">" }, { "answer_id": 74553983, "author": "MrDiamond", "author_id": 15364728, "author_profile": "https://Stackoverflow.com/users/15364728", "pm_score": 0, "selected": false, "text": "document.addEventListener('DOMContentLoaded', () => { // code here }) document.onreadystatechange = () => { if (document.readystate == \"complete\") { // code here } }" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20104975/" ]
74,553,930
<p>so I have a form with a select option inside it, and I'm trying to get the choice of the user and then insert it into the table and then database, but it doesn't seem to be working. Here is the code I thought was necessary to understand the problem, if there is anything else you need please let me know!</p> <p><strong>HTML</strong></p> <pre><code>&lt;form method=&quot;POST&quot; action=&quot;{{ route('createEvent') }}&quot;&gt; &lt;label for=&quot;is_private&quot;&gt;Privacy&lt;/label&gt; &lt;select id=&quot;is_private&quot; name=&quot;is_private&quot; required autofocus&gt; &lt;option value=&quot;&quot; disabled selected&gt;-- select one --&lt;/option&gt; &lt;option value=&quot;is_public&quot;&gt;Public&lt;/option&gt; &lt;option value=&quot;is_private&quot;&gt;Private&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p><strong>EventController.php</strong></p> <pre><code>if (null !== $request-&gt;input('is_private')) { $event-&gt;is_private = 'true'; } else { $event-&gt;is_private = 'false'; } </code></pre> <p>The problem is that it's always returning with <code>$event-&gt;is_private = 'true';</code> and I don't know why...</p> <p>Thanks alot for any help you may provide!</p>
[ { "answer_id": 74553955, "author": "ray", "author_id": 636077, "author_profile": "https://Stackoverflow.com/users/636077", "pm_score": 1, "selected": false, "text": "getElementById const input1 = document.getElementById('input1');\nconsole.log(input1); // null\n\nconst inputlg = document.getElementById('inputlg');\nconsole.log(inputlg); // input#inputlg.form-control.input-lg <input class=\"form-control input-lg\" id=\"inputlg\" type=\"text\" id=\"input1\">" }, { "answer_id": 74553983, "author": "MrDiamond", "author_id": 15364728, "author_profile": "https://Stackoverflow.com/users/15364728", "pm_score": 0, "selected": false, "text": "document.addEventListener('DOMContentLoaded', () => { // code here }) document.onreadystatechange = () => { if (document.readystate == \"complete\") { // code here } }" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15775091/" ]
74,553,938
<p>I have two columns of data — id's and data values. I can get vlookup to work if I want to return the correct fruit if I provide an id, but I need to also be able to account for cases where multiple values are provided as well.</p> <p>Put another way, I need to be able to run my vlookup on each item in a comma-separated list in another cell.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>fruit</th> <th></th> <th>input</th> <th>output</th> </tr> </thead> <tbody> <tr> <td>2835</td> <td>apples</td> <td></td> <td>4792</td> <td>pears</td> </tr> <tr> <td>2232</td> <td>bananas</td> <td></td> <td>2835</td> <td>apples</td> </tr> <tr> <td>3244</td> <td>peaches</td> <td></td> <td>1199,3244,2835,4790</td> <td>should be: oranges,peaches,etc…</td> </tr> <tr> <td>4792</td> <td>pears</td> <td></td> <td></td> <td></td> </tr> <tr> <td>1199</td> <td>oranges</td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> <p><a href="https://i.stack.imgur.com/W2vXd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W2vXd.png" alt="enter image description here" /></a></p> <p><a href="https://stackoverflow.com/questions/43417099/lookup-multiple-values-in-a-single-cell-comma-separated-and-then-return-the-va">Lookup multiple values in a single cell (comma separated) and then return the values to a single cell (also comma separated)</a></p> <p><a href="https://stackoverflow.com/questions/74035706/vlookup-using-a-comma-separated-search-key-in-google-sheets">Vlookup using a comma separated search key in Google Sheets</a></p> <p>I feel like I'm very close with the linked posts above, but I keep getting errors. This is what I have, though I'm open to an alternative approach (or something using Google Apps Script)</p> <pre><code>=arrayformula(left(concatenate(vlookup(split(D4,&quot;,&quot;),$A$2:$B$6,2,false)&amp;&quot;,&quot;),len(concatenate(vlookup(split(D4,&quot;,&quot;),$A$2:$B$6,2,false)&amp;&quot;,&quot;))-1)) </code></pre>
[ { "answer_id": 74554051, "author": "Martín", "author_id": 20363318, "author_profile": "https://Stackoverflow.com/users/20363318", "pm_score": 3, "selected": true, "text": "=IF(ISNUMBER(D4),vlookup(D4,A:B,2,0),join(\",\",query(A:B,\"Select B where A = \"&JOIN(\" OR A = \",split(D4,\",\",1,1)))))\n =BYROW(D2:D,LAMBDA(each,IF(each=\"\",\"\",IF(isnumber(each),vlookup(each,A:B,2,0),join(\",\",query(A:B,\"Select B where A = \"&JOIN(\" OR A = \",split(each,\",\",1,1))))))))\n" }, { "answer_id": 74555104, "author": "Twilight", "author_id": 20038057, "author_profile": "https://Stackoverflow.com/users/20038057", "pm_score": 1, "selected": false, "text": "XLOOKUP =JOIN(\",\",ARRAYFORMULA(XLOOKUP(SPLIT(D4,\",\"),A:A,B:B,\"\",0,1)))\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2818091/" ]
74,553,992
<p>I have tried lots of different ways to sort the list, but it never sorts it.</p> <pre><code>list = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9'] </code></pre> <p>I want them to all be in order eg: ep1 ep2 ep3 ep4 ep5</p>
[ { "answer_id": 74554031, "author": "pigerfier", "author_id": 20586077, "author_profile": "https://Stackoverflow.com/users/20586077", "pm_score": 1, "selected": false, "text": "list.sort(key=lambda x: int(\"\".join([i for i in x if i.isdigit()])))\n" }, { "answer_id": 74554036, "author": "Paul M.", "author_id": 10987432, "author_profile": "https://Stackoverflow.com/users/10987432", "pm_score": 1, "selected": false, "text": "key import re\n\nepisodes = [\n 'american dad S1-EP1',\n 'american dad S1-EP10',\n 'american dad S1-EP11',\n 'american dad S1-EP12',\n 'american dad S1-EP13',\n 'american dad S1-EP14',\n 'american dad S1-EP15',\n 'american dad S1-EP16',\n 'american dad S1-EP17',\n 'american dad S1-EP18',\n 'american dad S1-EP19',\n 'american dad S1-EP2',\n 'american dad S1-EP20',\n 'american dad S1-EP21',\n 'american dad S1-EP22',\n 'american dad S1-EP23',\n 'american dad S1-EP3',\n 'american dad S1-EP4',\n 'american dad S1-EP5',\n 'american dad S1-EP6',\n 'american dad S1-EP7',\n 'american dad S1-EP8',\n 'american dad S1-EP9'\n]\n\npattern = \"S(\\\\d+)-EP(\\\\d+)\"\n\ndef key(episode):\n regex_match = re.search(pattern, episode)\n return tuple(map(int, regex_match.groups()))\n\nprint(sorted(episodes, key=key))\n ['american dad S1-EP1', 'american dad S1-EP2', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23']\n>>> \n" }, { "answer_id": 74554041, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": false, "text": "re key_function Name Season Episode import re\n\npat = re.compile(r\"(.*) S(\\d+)-EP(\\d+)\")\n\n\ndef key_function(value):\n name, season, episode = pat.search(value).groups()\n return name, int(season), int(episode)\n\n\nprint(sorted(lst, key=key_function))\n [\n \"american dad S1-EP1\",\n \"american dad S1-EP2\",\n \"american dad S1-EP3\",\n \"american dad S1-EP4\",\n \"american dad S1-EP5\",\n \"american dad S1-EP6\",\n \"american dad S1-EP7\",\n \"american dad S1-EP8\",\n \"american dad S1-EP9\",\n \"american dad S1-EP10\",\n \"american dad S1-EP11\",\n \"american dad S1-EP12\",\n \"american dad S1-EP13\",\n \"american dad S1-EP14\",\n \"american dad S1-EP15\",\n \"american dad S1-EP16\",\n \"american dad S1-EP17\",\n \"american dad S1-EP18\",\n \"american dad S1-EP19\",\n \"american dad S1-EP20\",\n \"american dad S1-EP21\",\n \"american dad S1-EP22\",\n \"american dad S1-EP23\",\n]\n" }, { "answer_id": 74554043, "author": "siIverfish", "author_id": 20480866, "author_profile": "https://Stackoverflow.com/users/20480866", "pm_score": 1, "selected": false, "text": "sorted list1 = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19',\n 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']\n\ndef get_last_digits(s):\n last_digits = s[s.index(\"P\") + 1:]\n return int(last_digits)\n\nlist1.sort(key=get_last_digits)\n" }, { "answer_id": 74554088, "author": "Pi Marillion", "author_id": 2892254, "author_profile": "https://Stackoverflow.com/users/2892254", "pm_score": 0, "selected": false, "text": "12.6 12.56 import re\n\nRE_NUM = re.compile(r'(\\d+)|(\\D+)')\n\ndef sort_mixed(strings):\n # sort list of strings with integers embedded in them\n split_strings = []\n for string in strings:\n split_string = [(int(i or 0), i or s) for i, s in RE_NUM.findall(string)]\n split_strings.append(split_string)\n return [''.join(s for _, s in v) for v in sorted(split_strings)]\n\n# example usage\nsort_mixed(['15.51', '12.9', '15.6.6', '15.6'])\n# ['12.9', '15.6', '15.6.6', '15.51']\n" }, { "answer_id": 74554129, "author": "jiayu", "author_id": 20566440, "author_profile": "https://Stackoverflow.com/users/20566440", "pm_score": 0, "selected": false, "text": "lambda list l = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']\nsorted_l = sorted(l, key=lambda x: int(x.split(\"-EP\")[1]))\nprint(sorted_l)\n l = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']\nep_list = [int(x.split(\"-EP\")[1]) for x in l]\nsorted_l = [x for _, x in sorted(zip(ep_list, l))]\nprint(sorted_l)\n ['american dad S1-EP1', 'american dad S1-EP2', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23']\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74553992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20586077/" ]
74,554,006
<p>I am working with a data frame with more than 1000 rows and I want to create a new variable based on part of another variable string.</p> <p>This is short version of the data but I want to extract the numbers from the 'id&quot; variable and create the &quot;height&quot; variable. The data frame should look like something like this:</p> <pre><code>df&lt;-data.frame(id=c(&quot;Necrosis_Char_cat_0.05m&quot;,&quot;Necrosis_Char_cat_0.1m&quot;, &quot;Necrosis_Char_cat_1.7m&quot;), height=c(0.05, 0.1, 1.7)) </code></pre> <p>I tried to use this code:</p> <pre><code> df_new &lt;- df%&gt;% mutate(height = as.numeric(str_replace(.id, &quot;.*(\\d)(\\d+)m.*&quot;, &quot;\\1.\\2&quot;))) </code></pre> <p>But I get the following Warning message:</p> <pre><code>In eval(cols[[col]], .data, parent.frame()) : NAs introduced by coercion </code></pre> <p>In addition to the NAs, some of the values like 0.05 shows as 0.5. I believe the issue might be the way I am writing the pattern and/or replacement in str_replace(). Any help with that is very much appreciated. Thank you.</p>
[ { "answer_id": 74554025, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(readr)\ndf %>% \n mutate(height2 = parse_number(id))\n" }, { "answer_id": 74554027, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "df %>%\n mutate(new_height = parse_number(id))\n id height new_height\n1 Necrosis_Char_cat_0.05m 0.05 0.05\n2 Necrosis_Char_cat_0.1m 0.10 0.10\n3 Necrosis_Char_cat_1.7m 1.70 1.70\n" }, { "answer_id": 74554134, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\n\ndf<-data.frame(id=c(\"Necrosis_Char_cat_0.05m\",\"Necrosis_Char_cat_0.1m\",\n \"Necrosis_Char_cat_1.7m\"), \n height=c(0.05, 0.1, 1.7))\n\n#option1\ndf |>\n extract(id, \n into = \"new_height\", \n regex = \".*_(\\\\d+\\\\.\\\\d+)m\",\n remove = FALSE,\n convert = TRUE)\n#> id new_height height\n#> 1 Necrosis_Char_cat_0.05m 0.05 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70 1.70\n\n#option 2\ndf |>\n mutate(new_height = as.numeric(sub(\".*_(\\\\d+\\\\.\\\\d+)m\", \"\\\\1\", id)))\n#> id height new_height\n#> 1 Necrosis_Char_cat_0.05m 0.05 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70 1.70\n\n#option 3\ndf |>\n mutate(new_height = as.numeric(str_extract(id, \"\\\\d.*(?=m)\")))\n#> id height new_height\n#> 1 Necrosis_Char_cat_0.05m 0.05 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70 1.70\n" }, { "answer_id": 74560556, "author": "moodymudskipper", "author_id": 2270475, "author_profile": "https://Stackoverflow.com/users/2270475", "pm_score": 1, "selected": false, "text": "library(unglue)\ndf <- data.frame(id = c(\n \"Necrosis_Char_cat_0.05m\", \"Necrosis_Char_cat_0.1m\", \"Necrosis_Char_cat_1.7m\"\n))\nunglue_unnest(\n df, id, \"Necrosis_Char_cat_{height}m\", \n remove = FALSE, convert = TRUE\n)\n#> id height\n#> 1 Necrosis_Char_cat_0.05m 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7033156/" ]
74,554,012
<p>I am helping a friend to make a time sheet.</p> <p>he has a time sheet where he logs his activities:</p> <p>sleep poker study youtube, etc</p> <p>and wanted to be able to count all the random activites that do not fall into those catagories</p> <p>i came up with</p> <p>=COUNTIFS(B18:C28,&quot;&lt;&gt;poker&quot;,B18:C28,&quot;&lt;&gt;study&quot;, B18:C28,&quot;&lt;&gt;sleep&quot;, B18:C28,&quot;&lt;&gt;watched y.tube&quot;, B18:C28,&quot;&lt;&gt;&quot;)</p> <p>which worked on my test sheet.</p> <p>however he wants to apply this to multiple ranges in his sheet</p> <p>so he for his sheet needed to use</p> <p>=COUNTIFS( L4:R27,C31:I54,L31:R54,C58:E81,&quot;&lt;&gt;poker&quot;, L4:R27,C31:I54,L31:R54,C58:E81,&quot;&lt;&gt;studied&quot;, L4:R27,C31:I54,L31:R54,C58:E81,&quot;&lt;&gt;sleep&quot;, L4:R27,C31:I54,L31:R54,C58:E81,&quot;&lt;&gt;watched y.tube&quot;, L4:R27,C31:I54,L31:R54,C58:E81,&quot;&lt;&gt;shower/eat&quot; , L4:R27,C31:I54,L31:R54,C58:E81,&quot;&lt;&gt;&quot;)</p> <p>now we get an error saying</p> <p>&quot;ERROR&quot; COUNTIFS expects all arguments after position 2 to be in pairs.</p> <p>it seems to be counting the extra ranges as arguments.</p> <p>i have tried to play with ARRAYFORMULA but this is now way above my skillset, so any help would be appreciated.</p>
[ { "answer_id": 74554025, "author": "Ruam Pimentel", "author_id": 13015865, "author_profile": "https://Stackoverflow.com/users/13015865", "pm_score": 1, "selected": false, "text": "library(dplyr)\nlibrary(readr)\ndf %>% \n mutate(height2 = parse_number(id))\n" }, { "answer_id": 74554027, "author": "onyambu", "author_id": 8380272, "author_profile": "https://Stackoverflow.com/users/8380272", "pm_score": 1, "selected": false, "text": "df %>%\n mutate(new_height = parse_number(id))\n id height new_height\n1 Necrosis_Char_cat_0.05m 0.05 0.05\n2 Necrosis_Char_cat_0.1m 0.10 0.10\n3 Necrosis_Char_cat_1.7m 1.70 1.70\n" }, { "answer_id": 74554134, "author": "AndS.", "author_id": 9778513, "author_profile": "https://Stackoverflow.com/users/9778513", "pm_score": 3, "selected": true, "text": "library(tidyverse)\n\n\ndf<-data.frame(id=c(\"Necrosis_Char_cat_0.05m\",\"Necrosis_Char_cat_0.1m\",\n \"Necrosis_Char_cat_1.7m\"), \n height=c(0.05, 0.1, 1.7))\n\n#option1\ndf |>\n extract(id, \n into = \"new_height\", \n regex = \".*_(\\\\d+\\\\.\\\\d+)m\",\n remove = FALSE,\n convert = TRUE)\n#> id new_height height\n#> 1 Necrosis_Char_cat_0.05m 0.05 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70 1.70\n\n#option 2\ndf |>\n mutate(new_height = as.numeric(sub(\".*_(\\\\d+\\\\.\\\\d+)m\", \"\\\\1\", id)))\n#> id height new_height\n#> 1 Necrosis_Char_cat_0.05m 0.05 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70 1.70\n\n#option 3\ndf |>\n mutate(new_height = as.numeric(str_extract(id, \"\\\\d.*(?=m)\")))\n#> id height new_height\n#> 1 Necrosis_Char_cat_0.05m 0.05 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70 1.70\n" }, { "answer_id": 74560556, "author": "moodymudskipper", "author_id": 2270475, "author_profile": "https://Stackoverflow.com/users/2270475", "pm_score": 1, "selected": false, "text": "library(unglue)\ndf <- data.frame(id = c(\n \"Necrosis_Char_cat_0.05m\", \"Necrosis_Char_cat_0.1m\", \"Necrosis_Char_cat_1.7m\"\n))\nunglue_unnest(\n df, id, \"Necrosis_Char_cat_{height}m\", \n remove = FALSE, convert = TRUE\n)\n#> id height\n#> 1 Necrosis_Char_cat_0.05m 0.05\n#> 2 Necrosis_Char_cat_0.1m 0.10\n#> 3 Necrosis_Char_cat_1.7m 1.70\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18071449/" ]
74,554,074
<p>I started learning C recently, and whenever I try to run this it's giving an error of &quot;a&quot; and &quot;b&quot; undeclared as first use in this function, even, though the course I was watching ran the same code with no erros, he just changed the number to 10 and 15 thats all</p> <pre><code>#define sum (a,b)(printf(&quot;%i&quot;, a + b)); int main () { the enitre code is #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define Name &quot;JSDJSDJ&quot; #define Age 3000 #define sum (a,b) (printf(&quot;%i&quot;,a + b)); int main () { sum(100,150); printf (&quot;%i&quot;, Age); return 0; } sum (100,150); } </code></pre> <p>Not much other than changing the numbers</p>
[ { "answer_id": 74554157, "author": "Barmar", "author_id": 1491895, "author_profile": "https://Stackoverflow.com/users/1491895", "pm_score": 3, "selected": true, "text": "( () #define sum(a,b) (printf(\"%i\", (a) + (b)));\n" }, { "answer_id": 74554259, "author": "pm100", "author_id": 173397, "author_profile": "https://Stackoverflow.com/users/173397", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#define Name \"JSDJSDJ\"\n#define Age 3000\n\nvoid sum (int a, int b){\n printf(\"%i\",a + b));\n}\n\nint main ()\n{\n sum(100,150);\n printf (\"%i\", Age);\n\n return 0;\n }\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20586108/" ]
74,554,076
<p>I've an array with arrays of different values that I need to re arrange.</p> <p><strong>Original Array</strong></p> <pre><code>$cars = [ [2022, &quot;Corolla&quot;], [2022, &quot;Toyota&quot;], [2021, &quot;Corolla&quot;], [2021, &quot;Toyota&quot;], [2021, &quot;Honda&quot;] ]; </code></pre> <p><strong>Expected Array</strong></p> <pre><code>$resultCars = [ [2022, &quot;Corolla&quot;, &quot;Toyota&quot;], [2021, &quot;Corolla&quot;, &quot;Toyota&quot;, &quot;Honda&quot;] ]; </code></pre>
[ { "answer_id": 74554128, "author": "Benjamin Penney", "author_id": 6545526, "author_profile": "https://Stackoverflow.com/users/6545526", "pm_score": 1, "selected": false, "text": "ResultCars = Cars.reduce((carry, [year, make]) =>\n{\n let item = carry.find(([existingYear]) => existingYear === year);\n if(item)\n item.push(make);\n else\n carry.push([year, make]);\n\n return(carry);\n}, []);\n" }, { "answer_id": 74554144, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 1, "selected": false, "text": "const cars = [\n [2022, \"Corolla\"],\n [2022, \"Toyota\"],\n [2021, \"Corolla\"],\n [2021, \"Toyota\"],\n [2021, \"Honda\"]\n];\nconsole.log(Object.entries(cars.reduce((a,[year,make])=>\n ((a[year]??=[]).push(make), a), {})).map(i=>i.flat()))" }, { "answer_id": 74554209, "author": "paddy", "author_id": 1553090, "author_profile": "https://Stackoverflow.com/users/1553090", "pm_score": 1, "selected": false, "text": "vector<pair<int, string>> cars {\n {2022, \"Corolla\"},\n {2022, \"Toyota\"},\n {2021, \"Corolla\"},\n {2021, \"Toyota\"},\n {2021, \"Honda\"}\n};\n\nmap<int, set<string>> resultCars;\nfor (const auto& c : cars)\n{\n resultCars[c.first].insert(c.second);\n}\n #include <iostream>\n#include <iterator>\n#include <map>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n // Input\n vector<pair<int, string>> cars {\n {2022, \"Corolla\"},\n {2022, \"Toyota\"},\n {2021, \"Corolla\"},\n {2021, \"Toyota\"},\n {2021, \"Honda\"}\n };\n\n // Index\n map<int, set<string>> resultCars;\n for (const auto& c : cars)\n {\n resultCars[c.first].insert(c.second);\n }\n\n // Output\n for (const auto& c : resultCars)\n {\n int year = c.first;\n const auto& names = c.second;\n cout << year << \" : \";\n copy(names.begin(), names.end(), ostream_iterator<string>(cout, \" \"));\n cout << \"\\n\";\n }\n}\n" }, { "answer_id": 74554228, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 2, "selected": false, "text": "const Cars = [ [2022, \"Corolla\"], [2022, \"Toyota\"], [2021, \"Corolla\"], [2021, \"Toyota\"], [2021, \"Honda\"] ];\n\nconst res = Cars.reduce((a, [year, name]) => ((a[year] ??= [year]).push(name),a),{});\n\nconsole.log(Object.values(res));" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11118828/" ]
74,554,098
<p>I have multiple cards with images inside those cards. I want the images to have rounded corners. The code kind of worked but the rounded corners don't look right.</p> <p><img src="https://i.stack.imgur.com/b97mT.png" alt="Unwanted result" /></p> <p>For the images, I'm just using the Bootstrap class <code>rounded</code>. The images are scaled down but not distorted. This is the CSS for the cards:</p> <pre><code>.card { position: relative; display: flex; flex-direction: column; min-width: 0; word-wrap: break-word; background-color: #F5F5F5; background-clip: border-box; border: 0.0625rem solid #E5E7EB; border-radius: 1rem; } </code></pre> <p>Simplified HTML:</p> <pre><code> &lt;div class=&quot;card border-0 p-3 p-md-3 p-lg-4 mb-3&quot;&gt; &lt;div class=&quot;row pb-4 text-left&quot;&gt; &lt;div class=&quot;col-1 ps-1&quot;&gt; &lt;h1 class=&quot;id-circle&quot;&gt;B&lt;/h1&gt; &lt;/div&gt; &lt;div class=&quot;col-11&quot;&gt; &lt;span class=&quot;description details-text pe-1&quot;&gt;Text&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row gy-3 mb-1 pb-0&quot;&gt; &lt;div class=&quot;col-lg-6 col-md-6 col-sm-6 pb-0&quot;&gt; &lt;div class=&quot;row pt-0 pb-0 image-row&quot;&gt; &lt;img class=&quot;rounded&quot; src=&quot;https://picsum.photos/id/237/300/200&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any ideas of what could be happening? Please let me know if more info is needed.</p>
[ { "answer_id": 74554128, "author": "Benjamin Penney", "author_id": 6545526, "author_profile": "https://Stackoverflow.com/users/6545526", "pm_score": 1, "selected": false, "text": "ResultCars = Cars.reduce((carry, [year, make]) =>\n{\n let item = carry.find(([existingYear]) => existingYear === year);\n if(item)\n item.push(make);\n else\n carry.push([year, make]);\n\n return(carry);\n}, []);\n" }, { "answer_id": 74554144, "author": "Andrew Parks", "author_id": 5898421, "author_profile": "https://Stackoverflow.com/users/5898421", "pm_score": 1, "selected": false, "text": "const cars = [\n [2022, \"Corolla\"],\n [2022, \"Toyota\"],\n [2021, \"Corolla\"],\n [2021, \"Toyota\"],\n [2021, \"Honda\"]\n];\nconsole.log(Object.entries(cars.reduce((a,[year,make])=>\n ((a[year]??=[]).push(make), a), {})).map(i=>i.flat()))" }, { "answer_id": 74554209, "author": "paddy", "author_id": 1553090, "author_profile": "https://Stackoverflow.com/users/1553090", "pm_score": 1, "selected": false, "text": "vector<pair<int, string>> cars {\n {2022, \"Corolla\"},\n {2022, \"Toyota\"},\n {2021, \"Corolla\"},\n {2021, \"Toyota\"},\n {2021, \"Honda\"}\n};\n\nmap<int, set<string>> resultCars;\nfor (const auto& c : cars)\n{\n resultCars[c.first].insert(c.second);\n}\n #include <iostream>\n#include <iterator>\n#include <map>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n // Input\n vector<pair<int, string>> cars {\n {2022, \"Corolla\"},\n {2022, \"Toyota\"},\n {2021, \"Corolla\"},\n {2021, \"Toyota\"},\n {2021, \"Honda\"}\n };\n\n // Index\n map<int, set<string>> resultCars;\n for (const auto& c : cars)\n {\n resultCars[c.first].insert(c.second);\n }\n\n // Output\n for (const auto& c : resultCars)\n {\n int year = c.first;\n const auto& names = c.second;\n cout << year << \" : \";\n copy(names.begin(), names.end(), ostream_iterator<string>(cout, \" \"));\n cout << \"\\n\";\n }\n}\n" }, { "answer_id": 74554228, "author": "Asraf", "author_id": 20361860, "author_profile": "https://Stackoverflow.com/users/20361860", "pm_score": 2, "selected": false, "text": "const Cars = [ [2022, \"Corolla\"], [2022, \"Toyota\"], [2021, \"Corolla\"], [2021, \"Toyota\"], [2021, \"Honda\"] ];\n\nconst res = Cars.reduce((a, [year, name]) => ((a[year] ??= [year]).push(name),a),{});\n\nconsole.log(Object.values(res));" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20433945/" ]
74,554,103
<p>In Julia, I would like to randomly generate an array of arbitrary size, where all the elements of the array are complex numbers with absolute value one. Is there perhaps any way to do this within Julia?</p>
[ { "answer_id": 74554399, "author": "Bill", "author_id": 4282847, "author_profile": "https://Stackoverflow.com/users/4282847", "pm_score": 2, "selected": false, "text": "randcomplex() = (c = Complex(rand(2)...); c / abs(c))\n\nrandcomplex(numwanted) = [randcomplex() for _ in 1:numwanted]\n randcomplex(dims...) = (a = zeros(Complex, dims...); for i in eachindex(a) a[i] = randcomplex() end; a)\n" }, { "answer_id": 74554548, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 3, "selected": true, "text": "f1(n) = exp.((2*im*π).*rand(n))\n\nf2(n) = map(x->(z = x[1]+im*x[2] ; z ./ abs(z) ),\n eachcol(randn(2,n)))\n\nf3(n) = [im*x[1]+x[2] for x in sincos.(2π*rand(n))]\n\nf4(n) = cispi.(2 .*rand(n))\n julia> using BenchmarkTools\n\njulia> begin\n @btime f1(1_000);\n @btime f2(1_000);\n @btime f3(1_000);\n @btime f4(1_000);\n end;\n 29.390 μs (2 allocations: 23.69 KiB)\n 15.559 μs (2 allocations: 31.50 KiB)\n 25.733 μs (4 allocations: 47.38 KiB)\n 27.662 μs (2 allocations: 23.69 KiB)\n" }, { "answer_id": 74558067, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 2, "selected": false, "text": "function f5(n)\n r = rand(2, n)\n for i in 1:n\n a = sqrt(r[1, i]^2 + r[2, i]^2)\n r[1, i] /= a\n r[2, i] /= a\n end\n return reinterpret(reshape, ComplexF64, r)\nend\n\nusing LoopVectorization: @turbo\nfunction f5t(n)\n r = rand(2, n)\n @turbo for i in 1:n\n a = sqrt(r[1, i]^2 + r[2, i]^2)\n r[1, i] /= a\n r[2, i] /= a\n end\n return reinterpret(reshape, ComplexF64, r)\nend\n\njulia> @btime f5(1000);\n 4.186 μs (1 allocation: 15.75 KiB)\n\njulia> @btime f5t(1000);\n 2.900 μs (1 allocation: 15.75 KiB)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19340302/" ]
74,554,108
<p>Good night,</p> <p>I'm trying to think of a simple excel formula to allow me to get the codes of the most valuables drinks.</p> <p>I don't wanna use <strong>PivotTable</strong> for this one.</p> <p>Ex:</p> <p><a href="https://i.stack.imgur.com/BZCmv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BZCmv.png" alt="enter image description here" /></a></p> <p>I want to retrieve, for MALIBU, the code <strong>8991</strong></p> <p>For JAMESON, the code <strong>6113</strong> etc</p> <p>I'm stuck here since I woke up haha</p> <p>Thanks!</p>
[ { "answer_id": 74554399, "author": "Bill", "author_id": 4282847, "author_profile": "https://Stackoverflow.com/users/4282847", "pm_score": 2, "selected": false, "text": "randcomplex() = (c = Complex(rand(2)...); c / abs(c))\n\nrandcomplex(numwanted) = [randcomplex() for _ in 1:numwanted]\n randcomplex(dims...) = (a = zeros(Complex, dims...); for i in eachindex(a) a[i] = randcomplex() end; a)\n" }, { "answer_id": 74554548, "author": "Dan Getz", "author_id": 3580870, "author_profile": "https://Stackoverflow.com/users/3580870", "pm_score": 3, "selected": true, "text": "f1(n) = exp.((2*im*π).*rand(n))\n\nf2(n) = map(x->(z = x[1]+im*x[2] ; z ./ abs(z) ),\n eachcol(randn(2,n)))\n\nf3(n) = [im*x[1]+x[2] for x in sincos.(2π*rand(n))]\n\nf4(n) = cispi.(2 .*rand(n))\n julia> using BenchmarkTools\n\njulia> begin\n @btime f1(1_000);\n @btime f2(1_000);\n @btime f3(1_000);\n @btime f4(1_000);\n end;\n 29.390 μs (2 allocations: 23.69 KiB)\n 15.559 μs (2 allocations: 31.50 KiB)\n 25.733 μs (4 allocations: 47.38 KiB)\n 27.662 μs (2 allocations: 23.69 KiB)\n" }, { "answer_id": 74558067, "author": "DNF", "author_id": 2749865, "author_profile": "https://Stackoverflow.com/users/2749865", "pm_score": 2, "selected": false, "text": "function f5(n)\n r = rand(2, n)\n for i in 1:n\n a = sqrt(r[1, i]^2 + r[2, i]^2)\n r[1, i] /= a\n r[2, i] /= a\n end\n return reinterpret(reshape, ComplexF64, r)\nend\n\nusing LoopVectorization: @turbo\nfunction f5t(n)\n r = rand(2, n)\n @turbo for i in 1:n\n a = sqrt(r[1, i]^2 + r[2, i]^2)\n r[1, i] /= a\n r[2, i] /= a\n end\n return reinterpret(reshape, ComplexF64, r)\nend\n\njulia> @btime f5(1000);\n 4.186 μs (1 allocation: 15.75 KiB)\n\njulia> @btime f5t(1000);\n 2.900 μs (1 allocation: 15.75 KiB)\n" } ]
2022/11/23
[ "https://Stackoverflow.com/questions/74554108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14211825/" ]