qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
74,530,068
<p>I am new to C programming, trying to do an Assignment for my class. I am trying to return char value in this function while using switch case. As an example, if i were to to put 'a', i expect 'b' to come out as the output.</p> <pre><code>#include &lt;stdio.h&gt; char *upgrade(char plan); int main() { char plan; printf(&quot;what is your plan \n&quot;); scanf(&quot;&amp;s&quot;,&amp;plan); upgrade(plan); printf(&quot;\n%s&quot;,plan); } char *upgrade(char plan) { switch(plan) { case 'a': plan = 'b'; case 'b': plan = 'c'; } return plan; } </code></pre> <p>Every time I try to do so, the error &quot;[warning] reutrn makes pointed from integer without a cast&quot; comes. What exactly happens and how do i fix it?</p>
[ { "answer_id": 74533147, "author": "Jonathan", "author_id": 3048505, "author_profile": "https://Stackoverflow.com/users/3048505", "pm_score": 2, "selected": true, "text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer" }, { "answer_id": 74533430, "author": "benkov", "author_id": 2769031, "author_profile": "https://Stackoverflow.com/users/2769031", "pm_score": -1, "selected": false, "text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570467/" ]
74,530,079
<p>` I'm making a rock-paper-scissors game with multiples rounds, but I'm having problems storing the number of player's victory. What am I doing wrong?</p> <pre><code>// THIS FUNCTION DECIDES IF THE COMPUTER CHOOSES ROCK, PAPER OR SCISSOS function getComputerChoice () { let rand = Math.floor(Math.random() * 10); if (rand &lt;= 3) { return &quot;Rock&quot; } else if (rand &lt;= 6) { return &quot;Paper&quot; } else { return &quot;Scissors&quot; }} // TESTING PLAYROUND FUNCTION function playRound(playerSelection, computerSelection) { const loseMessage = &quot;You lose! Paper beats Rock&quot;; const winMessage = &quot;You win! Rock beats Scissors&quot;; const drawMessage = &quot;Draw. You and the computer chose Rock&quot; if (computerSelection === &quot;Paper&quot; &amp;&amp; playerSelection === &quot;Rock&quot;) { alert (loseMessage); return loseMessage } else if (computerSelection === &quot;Rock&quot; &amp;&amp; playerSelection === &quot;Rock&quot;) { alert(drawMessage); return drawMessage } else if (computerSelection === &quot;Scissors&quot; &amp;&amp; playerSelection === &quot;Rock&quot;) { alert(winMessage); return winMessage } else { alert(&quot;Something went wrong&quot;) } } let playerScore = 0; function updatePlayerScore1() { let playRoundResults = playRound(); if (playRoundResults === &quot;You win! Rock beats Scissors&quot;) { playerScore += 1; } else { playerScore += 0 } return playerScore; } playRound(prompt(&quot;Rock, Paper or Scissors?&quot;, &quot;Rock&quot;), getComputerChoice()); alert (updatePlayerScore1()); </code></pre> <p>`</p> <p>I was expecting the updatePlayerScore1 function would store the number of player victories and alert it.</p>
[ { "answer_id": 74533147, "author": "Jonathan", "author_id": 3048505, "author_profile": "https://Stackoverflow.com/users/3048505", "pm_score": 2, "selected": true, "text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer" }, { "answer_id": 74533430, "author": "benkov", "author_id": 2769031, "author_profile": "https://Stackoverflow.com/users/2769031", "pm_score": -1, "selected": false, "text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19839050/" ]
74,530,088
<p>Hi I need the text to be in a specific format in a spreadsheet to be able to upload it on a translation tool.</p> <p>I have already used the text split function to separate the text in a cell with bullet points, moving each bullet point to a separate cell.</p> <p><a href="https://i.stack.imgur.com/9oS3L.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Then I used the transpose function to separate each set of data. For context, you are looking at fashion products. The name of the product is on the first row, followed by a list of features (e.g. &quot;Bracciale&quot; means bracelet and it is followed by the list of materials)</p> <p><a href="https://i.stack.imgur.com/XK0xX.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Now for the last step, I need these sets to be vertical, not horizontal. Like this:</p> <p><a href="https://i.stack.imgur.com/S6XUr.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I would like to set up an automatic system so that every time we receive a list with hundreds of these products we do not need to copy-paste them one below the other.</p> <p>With pivot tables maybe? Keep in mind that if it is too complex it might be hard to train the translators to do it each time. Please let me know your suggestions. Thank you!</p> <p>I am not a programmer. I tried pivot tables but the data was in the wrong order and I am not sure how to get the data out from the pivot table with values only without the sub-menus.</p>
[ { "answer_id": 74533147, "author": "Jonathan", "author_id": 3048505, "author_profile": "https://Stackoverflow.com/users/3048505", "pm_score": 2, "selected": true, "text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer" }, { "answer_id": 74533430, "author": "benkov", "author_id": 2769031, "author_profile": "https://Stackoverflow.com/users/2769031", "pm_score": -1, "selected": false, "text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570378/" ]
74,530,101
<p>I am opening a cook-book 'recipes.txt' and it reads like this:</p> <pre><code>f = open('recipes.txt', 'r', encoding='utf-8') for x in f: print(x) </code></pre> <p><em><strong>result:</strong></em></p> <pre><code>Omelet 3 Egg | 2 | PCS Milk | 100 | ml Tomato | 2 | PCS Peking Duck 4 Duck | 1 | PCS Water | 2 | l Honey | 3 | t.sp Soy sauce | 60 | ml </code></pre> <p>I need to read / convert it into a nested dictionary format, like this:</p> <pre><code>cook_book = { 'Omelet': [ {'ingredient_name': 'Egg', 'quantity': 2, 'measure': 'PCS'}, {'ingredient_name': 'Milk', 'quantity': 100, 'measure': 'ml'}, {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'PCS'} ], 'Peking Duck': [ {'ingredient_name': 'Duck', 'quantity': 1, 'measure': 'PCS'}, {'ingredient_name': 'Water', 'quantity': 2, 'measure': 'l'}, {'ingredient_name': 'Honey', 'quantity': 3, 'measure': 't.sp'}, {'ingredient_name': 'Soy sauce', 'quantity': 60, 'measure': 'ml'} ] } </code></pre> <p>I cannot get on my own how to get exactly desired format. Would appreciate any suggestions.</p>
[ { "answer_id": 74532430, "author": "Hunter", "author_id": 15076691, "author_profile": "https://Stackoverflow.com/users/15076691", "pm_score": 1, "selected": false, "text": "cook_book = {}\n\nindexes = []\n\nwith open('recipes.txt', 'r', encoding='utf-8') as fp:\n data = fp.read()\n linedData = data.split('\\n')\n i = 0\n for line in data.split('\\n'):\n try:\n amount = int(line)\n indexes.append(i)\n indexes.append(amount)\n except:\n pass\n i += 1\n for x in range(len(indexes)):\n if (x % 2) == 0:\n mealName = linedData[indexes[x]-1]\n focusedData = linedData[indexes[x] + 1:]\n focusedData = focusedData[:(indexes[x+1])]\n totalIngredients = []\n for line in focusedData:\n ingredients = {}\n try:\n name, amm, ref = line.split(' | ')\n ingredients['ingredient_name'] = name\n ingredients['quantity'] = int(amm)\n ingredients['measure'] = ref\n except:\n pass\n totalIngredients.append(ingredients)\n cook_book[mealName] = totalIngredients\n\n print(cook_book)\n {'Omelette': [{'ingredient_name': 'Egg', 'quantity': 2, 'measure': 'PCS'}, {'ingredient_name': 'Milk', 'quantity': 100, 'measure': 'ml'}, {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'PCS'}], 'Peking duck': [{'ingredient_name': 'Duck', 'quantity': 1, 'measure': 'PCS'}, {'ingredient_name': 'Water', 'quantity': 2, 'measure': 'l'}, {'ingredient_name': 'Honey', 'quantity': 3, 'measure': 'tbsp'}, {'ingredient_name': 'Soy sauce', 'quantity': 60, 'measure': 'ml'}], 'Baked potatoes': [{'ingredient_name': 'Potatoes', 'quantity': 1, 'measure': 'kg'}, {'ingredient_name': 'Garlic', 'quantity': 3, 'measure': 'tooth'}, {'ingredient_name': 'Gouda cheese', 'quantity': 100, 'measure': 'G'}], 'Fajitos': [{'ingredient_name': 'Beef', 'quantity': 500, 'measure': 'G'}, {'ingredient_name': 'Sweet pepper', 'quantity': 1, 'measure': 'PCS'}, {'ingredient_name': 'Lavash', 'quantity': 2, 'measure': 'state'}, {'ingredient_name': 'Wine vinegar', 'quantity': 1, 'measure': 'tbsp'}, {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'state'}]}\n {\n'Omelette': [\n {'ingredient_name': 'Egg', 'quantity': 2, 'measure': 'PCS'}, \n {'ingredient_name': 'Milk', 'quantity': 100, 'measure': 'ml'}, \n {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'PCS'}\n ],\n'Peking duck': [\n {'ingredient_name': 'Duck', 'quantity': 1, 'measure': 'PCS'}, \n {'ingredient_name': 'Water', 'quantity': 2, 'measure': 'l'}, \n {'ingredient_name': 'Honey', 'quantity': 3, 'measure': 'tbsp'}, \n {'ingredient_name': 'Soy sauce', 'quantity': 60, 'measure': 'ml'}\n ], \n'Baked potatoes': [\n {'ingredient_name': 'Potatoes', 'quantity': 1, 'measure': 'kg'}, \n {'ingredient_name': 'Garlic', 'quantity': 3, 'measure': 'tooth'}, \n {'ingredient_name': 'Gouda cheese', 'quantity': 100, 'measure': 'G'}\n ], \n'Fajitos': [\n {'ingredient_name': 'Beef', 'quantity': 500, 'measure': 'G'}, \n {'ingredient_name': 'Sweet pepper', 'quantity': 1, 'measure': 'PCS'}, \n {'ingredient_name': 'Lavash', 'quantity': 2, 'measure': 'state'}, \n {'ingredient_name': 'Wine vinegar', 'quantity': 1, 'measure': 'tbsp'}, \n {'ingredient_name': 'Tomato', 'quantity': 2, 'measure': 'state'}\n ]\n}\n" }, { "answer_id": 74533110, "author": "Chris", "author_id": 14408656, "author_profile": "https://Stackoverflow.com/users/14408656", "pm_score": 2, "selected": false, "text": "with open('recipes.txt', 'r', encoding='utf-8') as recipes:\n cook_book = {}\n for line in recipes:\n if (line.replace(\"\\n\", \"\")).isnumeric() or line == \"\\n\": # Ignore unwanted lines\n continue\n elif \"|\" not in line: # Initialize individual recipes\n current_recipe = line.replace(\"\\n\", \"\")\n cook_book[current_recipe] = []\n elif len(line.strip(\"|\")) > 2: # Add ingredients\n ingredient = {}\n ingredient_lst = line.split(\"|\")\n ingredient[\"ingredient_name\"] = ingredient_lst[0].strip()\n ingredient[\"quantity\"] = ingredient_lst[1].strip()\n ingredient[\"measure\"] = ingredient_lst[2].replace(\"\\n\", \"\").strip()\n\n cook_book[current_recipe].append(ingredient)\n\nprint(cook_book)\n import json\n\nwith open('cook_book.json', 'w', encoding='utf-8') as f:\n json.dump(cook_book, f, ensure_ascii=False, indent=4)\n {\n \"Omelet\": [\n {\n \"ingredient_name\": \"Egg \",\n \"quantity\": \" 2 \",\n \"measure\": \" PCS\"\n },\n {\n \"ingredient_name\": \"Milk \",\n \"quantity\": \" 100 \",\n \"measure\": \" ml\"\n },\n {\n \"ingredient_name\": \"Tomato \",\n \"quantity\": \" 2 \",\n \"measure\": \" PCS\"\n }\n ],\n \"Peking Duck\": [\n {\n \"ingredient_name\": \"Duck \",\n \"quantity\": \" 1 \",\n \"measure\": \" PCS\"\n },\n {\n \"ingredient_name\": \"Water \",\n \"quantity\": \" 2 \",\n \"measure\": \" l\"\n },\n {\n \"ingredient_name\": \"Honey \",\n \"quantity\": \" 3 \",\n \"measure\": \" t.sp\"\n },\n {\n \"ingredient_name\": \"Soy sauce \",\n \"quantity\": \" 60 \",\n \"measure\": \" ml\"\n }\n ]\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15923390/" ]
74,530,157
<p>In our application we are using the Apache ignite 2.12 version and the same is deployed using kubernetes. We use binary object approach and everything works fine but after couple of days we are not able to query the cache and below are the errors/exception.</p> <p>Any help is appreciated.</p> <p>Errors in the pod:</p> <pre><code>Thread [name=&quot;query-#1741%ignite-service%&quot;, id=2004, state=TIMED_WAITING, blockCnt=0, waitCnt=29] Lock [object=java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@3f30bea2, ownerName=null, ownerId=-1] at java.base@11.0.17/jdk.internal.misc.Unsafe.park(Native Method) at java.base@11.0.17/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:234) at java.base@11.0.17/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2123) at java.base@11.0.17/java.util.concurrent.LinkedBlockingQueue.poll(LinkedBlockingQueue.java:458) at java.base@11.0.17/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1053) at java.base@11.0.17/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1114) at java.base@11.0.17/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base@11.0.17/java.lang.Thread.run(Thread.java:829) Thread [name=&quot;Connection evictor&quot;, id=2021, state=TIMED_WAITING, blockCnt=0, waitCnt=123] at java.base@11.0.17/java.lang.Thread.sleep(Native Method) at org.apache.http.impl.client.IdleConnectionEvictor$1.run(IdleConnectionEvictor.java:66) at java.base@11.0.17/java.lang.Thread.run(Thread.java:829) Thread [name=&quot;sys-#1773%ignite-service%&quot;, id=2048, state=TIMED_WAITING, blockCnt=0, waitCnt=1] Lock [object=java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@4cd18e1b, ownerName=null, ownerId=-1] at java.base@11.0.17/jdk.internal.misc.Unsafe.park(Native Method) at java.base@11.0.17/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:234) at java.base@11.0.17/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2123) at java.base@11.0.17/java.util.concurrent.LinkedBlockingQueue.poll(LinkedBlockingQueue.java:458) at java.base@11.0.17/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1053) at java.base@11.0.17/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1114) at java.base@11.0.17/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base@11.0.17/java.lang.Thread.run(Thread.java:829) 2022-11-15 04:22:20.783 WARN [app-service,,] 1 --- [otlist-service%] o.a.i.i.p.cache.CacheDiagnosticManager : Page locks dump: 2022-11-15 04:22:29.834 ERROR [app-service,,] 1 --- [otlist-service%] o.apache.ignite.internal.util.typedef.G : Blocked system-critical thread has been detected. This can lead to cluster-wide undefined behaviour [workerName=disco-event-worker, threadName=disco-event-worker-#44%ignite-service%, blockedFor=834s] 2022-11-15 04:22:29.837 WARN [app-service,,] 1 --- [otlist-service%] : Possible failure suppressed accordingly to a configured handler [hnd=StopNodeOrHaltFailureHandler [tryStop=false, timeout=0, super=AbstractFailureHandler [ignoredFailureTypes=UnmodifiableSet [SYSTEM_WORKER_BLOCKED, SYSTEM_CRITICAL_OPERATION_TIMEOUT]]], failureCtx=FailureContext [type=SYSTEM_WORKER_BLOCKED, err=class o.a.i.IgniteException: GridWorker [name=disco-event-worker, igniteInstanceName=ignite-service, finished=false, heartbeatTs=1668485315026]]] org.apache.ignite.IgniteException: GridWorker [name=disco-event-worker, igniteInstanceName=ignite-service, finished=false, heartbeatTs=1668485315026] at java.base@11.0.17/jdk.internal.misc.Unsafe.park(Native Method) ~[na:na] at java.base@11.0.17/java.util.concurrent.locks.LockSupport.park(LockSupport.java:323) ~[na:na] at org.apache.ignite.internal.util.future.GridFutureAdapter.get0(GridFutureAdapter.java:178) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.util.future.GridFutureAdapter.get(GridFutureAdapter.java:141) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.IgniteKernal.resetLostPartitions(IgniteKernal.java:3797) ~[ignite-core-2.12.0.jar:2.12.0] at com.app.dao.ignite.IgniteProvider.lambda$resetLostPartition$3(IgniteProvider.java:267) ~[app-core-2022.4.2-RC1.jar:2022.4.2-RC1] at com.app.dao.ignite.IgniteProvider$$Lambda$2152/0x0000000800eab440.accept(Unknown Source) ~[na:na] at java.base@11.0.17/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na] at com.app.dao.ignite.IgniteProvider.resetLostPartition(IgniteProvider.java:264) ~[app-core-2022.4.2-RC1.jar:2022.4.2-RC1] at com.app.dao.ignite.IgniteProvider.lambda$getOrStartIgniteNode$37431c07$1(IgniteProvider.java:103) ~[app-core-2022.4.2-RC1.jar:2022.4.2-RC1] at com.app.dao.ignite.IgniteProvider$$Lambda$1640/0x0000000800bce840.apply(Unknown Source) ~[na:na] at org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager$UserListenerWrapper.onEvent(GridEventStorageManager.java:1492) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager.notifyListeners(GridEventStorageManager.java:894) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager.notifyListeners(GridEventStorageManager.java:879) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager.record0(GridEventStorageManager.java:350) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager.record(GridEventStorageManager.java:313) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$DiscoveryWorker.recordEvent(GridDiscoveryManager.java:3074) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$DiscoveryWorker.body0(GridDiscoveryManager.java:3291) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.managers.discovery.GridDiscoveryManager$DiscoveryWorker.body(GridDiscoveryManager.java:3094) ~[ignite-core-2.12.0.jar:2.12.0] at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:125) ~[ignite-core-2.12.0.jar:2.12.0] at java.base@11.0.17/java.lang.Thread.run(Thread.java:829) ~[na:na] </code></pre> <p>Restarting the ignite pods is fixing the issue but the same cannot be done in higher environments.</p>
[ { "answer_id": 74531263, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 0, "selected": false, "text": "blockedFor=834s" }, { "answer_id": 74532363, "author": "Vladimir Pligin", "author_id": 5558122, "author_profile": "https://Stackoverflow.com/users/5558122", "pm_score": 2, "selected": false, "text": "org.apache.ignite.internal.IgniteKernal.resetLostPartitions(IgniteKernal.java:3797) ~[ignite-core-2.12.0.jar:2.12.0]\n com.app.dao.ignite.IgniteProvider.lambda$resetLostPartition$3 EVT_NODE_LEFT EVT_NODE_FAILED" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20568880/" ]
74,530,197
<pre><code> public void charFrequency(){ int maximumCount = 0; int minimumCount = 0; for (int i = 0; i &lt;str.length() ; i++) { char c = str.charAt(i); if(numCount.containsKey(c)){ int count = numCount.get(c); count++; if(maximumCount&lt;count) maximumCount++; numCount.put(c, count); }else{ numCount.put(c, 1); minimumCount = 1; } } System.out.println(&quot;Characters with most frequency in String&quot;); for(char maxKey: numCount.keySet()){ if(numCount.get(maxKey) == maximumCount){ System.out.println(&quot;Character: &quot; + maxKey + &quot;\t Have frequency of: &quot; + maximumCount); } } System.out.println(&quot;Characters with the lowest frequency in String&quot;); for(char minKey: numCount.keySet()){ if(numCount.get(minKey) == minimumCount){ System.out.println(&quot;Character: &quot; + minKey + &quot;\t Have frequency of: &quot; + minimumCount); } } } </code></pre> <p>I need to find the frequency of all the characters, for example if i had the string &quot;HELLO WORLD!&quot; the characters &quot;L&quot; AND &quot; O&quot; are the 2 characters with most frequency..</p> <p>but i can't understand what to do to.. for example i want to print that:</p> <p>Character: L: have frequency of 3</p> <p>Character: O: have frequency of 2</p> <p>Character: H E R D have frequency of 1 1 1 1</p>
[ { "answer_id": 74531263, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 0, "selected": false, "text": "blockedFor=834s" }, { "answer_id": 74532363, "author": "Vladimir Pligin", "author_id": 5558122, "author_profile": "https://Stackoverflow.com/users/5558122", "pm_score": 2, "selected": false, "text": "org.apache.ignite.internal.IgniteKernal.resetLostPartitions(IgniteKernal.java:3797) ~[ignite-core-2.12.0.jar:2.12.0]\n com.app.dao.ignite.IgniteProvider.lambda$resetLostPartition$3 EVT_NODE_LEFT EVT_NODE_FAILED" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13084927/" ]
74,530,253
<pre><code>{ &quot;List1&quot;: [ { &quot;f1&quot;: &quot;b6ff&quot;, &quot;f2&quot;: &quot;day&quot;, &quot;f3&quot;: &quot;HO&quot;, &quot;List2&quot;: [{&quot;f1&quot;: 1.5,&quot;f2&quot;: &quot;RATE&quot;}] }] } </code></pre> <p>This is nested JSON in which there's a list 'List2' inside another list 'List1'.</p> <p>how to filter f1 = 1.5 in List2? I have tried using @&gt; operator used for contains but it doesn't work with nested JSON.</p>
[ { "answer_id": 74531263, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 0, "selected": false, "text": "blockedFor=834s" }, { "answer_id": 74532363, "author": "Vladimir Pligin", "author_id": 5558122, "author_profile": "https://Stackoverflow.com/users/5558122", "pm_score": 2, "selected": false, "text": "org.apache.ignite.internal.IgniteKernal.resetLostPartitions(IgniteKernal.java:3797) ~[ignite-core-2.12.0.jar:2.12.0]\n com.app.dao.ignite.IgniteProvider.lambda$resetLostPartition$3 EVT_NODE_LEFT EVT_NODE_FAILED" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570740/" ]
74,530,267
<p>!correction this does not work with android version 11 per pixel!</p> <p>I have three xamarin projects.forms, android and ios. Ios is not at the center of the problem at the moment. On any Pixel devices and under any Android (I tested 13, 12, 11, 10). The device says I don't have access. &quot;Access to the trail...&quot; On any other devices, namely: Samsung Xiaomi, Bq, Huawei. All devices on different Android platforms!!! and everything works!!! What was done for this: The very first is the manifesto</p> <pre><code>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt; &lt;uses-permission android:name=&quot;android.permission.MANAGE_EXTERNAL_STORAGE&quot; /&gt; </code></pre> <p>Further, when launching the application, the user requests permission to read and write or to the explorer as a whole. This code is located in MainActivity.</p> <pre><code>ActivityCompat.RequestPermissions(thisActivity, new string[] { Manifest.Permission.PostNotifications, Manifest.Permission.WriteExternalStorage, Manifest.Permission.RecordAudio, Manifest.Permission.ReadExternalStorage }, 1); </code></pre> <p>In the main xamarin project.forms I get the path to the root folder of the repository: and create the path to the folder I want to create.</p> <pre><code>folderPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, &quot;CorpFiles&quot;); </code></pre> <p>The folderPath variable stores the path to the folder I need. Then I check if there is a folder on this path and create it if necessary</p> <pre><code>if (!System.IO.File.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } </code></pre> <p>This code works great. But not on Pixel.With tears in my eyes, I ask you to help me figure this out. This is the third week I've been solving a simple problem that I can't find anywhere.</p>
[ { "answer_id": 74553857, "author": "user2153142", "author_id": 2153142, "author_profile": "https://Stackoverflow.com/users/2153142", "pm_score": 2, "selected": true, "text": " https://www.zoftino.com/how-to-create-browse-files-option-in-android\n https://mateuszteteruk.pl/how-to-use-android-storage-access-framework-with-example\n https://thedroidlady.com/2020-08-24-android-scoped-storage-demystified\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15739701/" ]
74,530,280
<p>We have;</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>PositionId</th> <th>X</th> <th>Y</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>-1</td> <td>-2</td> </tr> <tr> <td>2</td> <td>-1</td> <td>-1</td> </tr> <tr> <td>3</td> <td>1</td> <td>2</td> </tr> <tr> <td>4</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div> <p>I want to query positions in a list:</p> <p>arg = [(-1;-2), (1;1)]</p> <p>My expected:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>PositionId</th> <th>X</th> <th>Y</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>-1</td> <td>-2</td> </tr> <tr> <td>4</td> <td>1</td> <td>1</td> </tr> </tbody> </table> </div>
[ { "answer_id": 74553857, "author": "user2153142", "author_id": 2153142, "author_profile": "https://Stackoverflow.com/users/2153142", "pm_score": 2, "selected": true, "text": " https://www.zoftino.com/how-to-create-browse-files-option-in-android\n https://mateuszteteruk.pl/how-to-use-android-storage-access-framework-with-example\n https://thedroidlady.com/2020-08-24-android-scoped-storage-demystified\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18205975/" ]
74,530,300
<p>I added <strong>Notification Extension Service</strong> for push notification image purpose. It can running on read device as expected</p> <p>but when I tried to archive it, some errors appears, look like the following :</p> <p><img src="https://i.stack.imgur.com/cfNNB.png" alt="Undefined Symbol : OBJC_CLASS$_FlutterBasicMessageChannel" /></p> <p>The error message :</p> <pre><code>Could not find or use auto-linked framework 'Flutter' Undefined symbol: _FlutterMethodNotImplemented Undefined symbol: _OBJC_CLASS_$_FlutterBasicMessageChannel Undefined symbol: _OBJC_CLASS_$_FlutterError Undefined symbol: _OBJC_CLASS_$_FlutterMethodChannel Undefined symbol: _OBJC_CLASS_$_FlutterStandardMessageCodec Undefined symbol: _OBJC_CLASS_$_FlutterStandardReader Undefined symbol: _OBJC_CLASS_$_FlutterStandardReaderWriter Undefined symbol: _OBJC_CLASS_$_FlutterStandardTypedData Undefined symbol: _OBJC_CLASS_$_FlutterStandardWriter Undefined symbol: _OBJC_METACLASS_$_FlutterStandardReader Undefined symbol: _OBJC_METACLASS_$_FlutterStandardReaderWriter Undefined symbol: _OBJC_METACLASS_$_FlutterStandardWriter </code></pre> <p>I have tried some solutions that provided on internet like :</p> <pre><code>1. TargetSettings -&gt; Build Phases -&gt; Compile Sources -&gt; add your .m class -&gt;Build and Run 2. Set development target of extension must equal to runner's development target 3. Clean and build folder for severals time, but still doesn't work </code></pre> <p>Those solutions above have no good result, still face the errors.</p> <p>Just info, I got this after update to XCode 14 and add Notification Extension Services</p> <p>If there's any solution that I have to try, please let me know, I appreciate it very much.</p> <p>Thank you</p>
[ { "answer_id": 74553857, "author": "user2153142", "author_id": 2153142, "author_profile": "https://Stackoverflow.com/users/2153142", "pm_score": 2, "selected": true, "text": " https://www.zoftino.com/how-to-create-browse-files-option-in-android\n https://mateuszteteruk.pl/how-to-use-android-storage-access-framework-with-example\n https://thedroidlady.com/2020-08-24-android-scoped-storage-demystified\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20476465/" ]
74,530,306
<p>I am working on Google Sheets since couple of years and found i very useful but now there is one situation i got faced and make me troubled to fix it.</p> <p>In the current stage, when the line break is included in the cell value, when the cell is copied and pasted, it seems that it becomes <code>&quot;&quot;&quot;test&quot;&quot;&quot;</code>. In that case, when i want to copy and paste the cell values like <code>&quot;test&quot;</code> instead of <code>&quot;&quot;&quot;test&quot;&quot;&quot;</code>,</p> <p>And there are some situations where i have added <code>IF</code> condition in formula which results comes sometimes in Line Break or sometimes in single line.</p> <pre><code>=CHAR(34)&amp;SUBSTITUTE(A1,&quot;,&quot;,CHAR(10))&amp;CHAR(34) </code></pre> <p>This formula works for Single Line string but when it comes to Line Break it adds more qoutation like<code>&quot;&quot;&quot;test&quot;&quot;&quot;</code></p> <p>I only want the solution like this even if its single line or Multiple line breaks always result should be <code>&quot;test&quot;</code>.</p> <p>your help will be much appreciated.</p>
[ { "answer_id": 74530443, "author": "David Morales", "author_id": 9652475, "author_profile": "https://Stackoverflow.com/users/9652475", "pm_score": -1, "selected": false, "text": "=CHAR(34)&SUBSTITUTE(A1,\"\"\"\",\"\")&CHAR(34)\n" }, { "answer_id": 74532572, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 3, "selected": true, "text": "={\"\"; CHAR(34)&SUBSTITUTE(A1,\",\",CHAR(10))&CHAR(34)}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16968735/" ]
74,530,313
<p>I have a huge text file and need to split it to some file. In the text file there is an identifier to split the file. Here is some part of the text file looks like:</p> <pre><code>Comp MOFVersion 10.1 Copyright 1997-2006. All rights reserved. -------------------------------------------------- Mon 11/19/2022 8:34:22.35 - Starting The Process... -------------------------------------------------- There are a lot of content here ... exit --------------------- list volume list partition exit --------------------- Volume 0 is the selected volume. Disk ### Status Size Free Dyn Gpt -------- ------------- ------- ------- --- --- * Disk 0 Online 238 GB 136 GB * -------------------------------------------------- Tue 11/20/2022 8:34:22.35 - Starting The Process... -------------------------------------------------- There are a lot of content here .... SERVICE_NAME: vds TYPE : 10 WIN32_OWN_PROCESS STATE : 1 STOPPED WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 --------------------- *exit /b 0 File not found - *.* 0 File(s) copied -------------------------------------------------- Wed 11/21/2022 8:34:22.35 - Starting The Process... -------------------------------------------------- There are a lot of content here ========================================== Computer: . ========================================== Active: True DmiRevision: 0 list disk exit --------------------- *exit /b 0 11/19/2021 08:34 AM &lt;DIR&gt; . 11/19/2021 08:34 AM &lt;DIR&gt; .. 11/19/2021 08:34 AM 0 SL 1 File(s) 0 bytes 2 Dir(s) 80,160,923,648 bytes free </code></pre> <p>My expectation is split the file by mapping the string &quot;Starting The Process&quot;. So if I have a text file like above example, then the file will split to 3 files and each file has differen content. For example:</p> <pre><code>file1 -------------------------------------------------- Mon 11/19/2022 8:34:22.35 - Starting The Process... -------------------------------------------------- There are a lot of content here ... exit --------------------- list volume list partition exit --------------------- Volume 0 is the selected volume. Disk ### Status Size Free Dyn Gpt -------- ------------- ------- ------- --- --- * Disk 0 Online 238 GB 136 GB * file2 -------------------------------------------------- Tue 11/20/2022 8:34:22.35 - Starting The Process... -------------------------------------------------- There are a lot of content here .... SERVICE_NAME: vds TYPE : 10 WIN32_OWN_PROCESS STATE : 1 STOPPED WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 --------------------- *exit /b 0 File not found - *.* 0 File(s) copied file 3 -------------------------------------------------- Wed 11/21/2022 8:34:22.35 - Starting The Process... -------------------------------------------------- There are a lot of content here ========================================== Computer: . ========================================== Active: True DmiRevision: 0 list disk exit --------------------- *exit /b 0 11/19/2021 08:34 AM &lt;DIR&gt; . 11/19/2021 08:34 AM &lt;DIR&gt; .. 11/19/2021 08:34 AM 0 SL 1 File(s) 0 bytes 2 Dir(s) 80,160,923,648 bytes free </code></pre> <p>here is what i've tried:</p> <pre><code>logfile = &quot;E:/DATA/result.txt&quot; with open(logfile, 'r') as text_file: lines = text_file.readlines() for line in lines: if &quot;Starting The Process...&quot; in line: print(line) </code></pre> <p>I am only able to find the line with the string, but I don't know how to get the content of each line after split to 3 parts and output to new file.</p> <p>Is it possible to do it in Python? Thank you for any advice.</p>
[ { "answer_id": 74530406, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "re.findall with open('data.txt', 'r') as file:\n data = file.read()\n parts = re.findall(r'-{10,}[^-]*\\n\\w{3} \\d{2}\\/\\d{2}\\/\\d{4}.*?-{10,}.*?(?=-{10,}|$)', data, flags=re.S)\n\ncnt = 1\nfor part in parts:\n output = open('file ' + str(cnt), 'w')\n output.write(part)\n output.close()\n cnt = cnt + 1\n" }, { "answer_id": 74530641, "author": "ChaoS Adm", "author_id": 12575770, "author_profile": "https://Stackoverflow.com/users/12575770", "pm_score": 0, "selected": false, "text": "with open('file.txt', 'r') as f: \nsplit_text = f.read().split('--------------------------------------------------')\nsplit_text.pop(0) # To remove the Copyright message at the start\n\nfor i in range(0, len(split_text) - 1, 2): \n with open(f'file{int(i/2)}.txt', 'w') as temp: \n temp_txt = ''.join(split_text[i:i+2])\n temp.write(temp_txt) \n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11076819/" ]
74,530,402
<p><strong>I want to reject duplicate socket connection when the same connected client try to connect again.</strong> The below code I tried to store gamerId into an array then later check the array if new gamerId already exist or not. But seems the duplicate connection already made but I don't want to make any duplicate connection.</p> <pre><code>$address = '127.0.0.5'; $port = 8085; $sock = socket_create(AF_INET, SOCK_STREAM, 0) or die('Not Created'); $bind = socket_bind($sock, $address, $port) or die(&quot;Not Binded&quot;); $listen = socket_listen($sock, 1) or die(&quot;Didnot listen&quot;); $accept = socket_accept($sock) or die(&quot;Not Accepted&quot;); $readData = trim(socket_read($accept, 1024)); $gamerId = array(); $errHandler = array(); $gamerIdlen = count($gamerId); function checkDuplicate($gamerId, $gamerIdLen, $readData, $errHandler) { for ($i = 0; $i &lt; $gamerIdLen; $i++) { if ($gamerId[$i] === $readData) { return 1; } } } if (checkDuplicate($gamerId, $gamerIdlen, $readData, $errHandler) == 1) { array_push($errHandler, &quot;exist&quot;); } else if (checkDuplicate($gamerId, $gamerIdlen, $readData, $errHandler) != 1) { array_push($gamerId, $readData); } do { global $accept; $accept = socket_accept($sock) or die(&quot;Not Accepted&quot;); print_r($errHandler); print_r($gamerId); } while (true); </code></pre>
[ { "answer_id": 74530406, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "re.findall with open('data.txt', 'r') as file:\n data = file.read()\n parts = re.findall(r'-{10,}[^-]*\\n\\w{3} \\d{2}\\/\\d{2}\\/\\d{4}.*?-{10,}.*?(?=-{10,}|$)', data, flags=re.S)\n\ncnt = 1\nfor part in parts:\n output = open('file ' + str(cnt), 'w')\n output.write(part)\n output.close()\n cnt = cnt + 1\n" }, { "answer_id": 74530641, "author": "ChaoS Adm", "author_id": 12575770, "author_profile": "https://Stackoverflow.com/users/12575770", "pm_score": 0, "selected": false, "text": "with open('file.txt', 'r') as f: \nsplit_text = f.read().split('--------------------------------------------------')\nsplit_text.pop(0) # To remove the Copyright message at the start\n\nfor i in range(0, len(split_text) - 1, 2): \n with open(f'file{int(i/2)}.txt', 'w') as temp: \n temp_txt = ''.join(split_text[i:i+2])\n temp.write(temp_txt) \n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10183096/" ]
74,530,404
<p>I am new to pine and am having trouble with this. its probably syntax or improper calculation. Code as follows:</p> <pre><code>buySignal = input.bool(true,title='Buy Signal') sellSignal = input.bool(true,title='Sell Signal') plotshape(buySignal ? lenema &gt; lenema[1] and lenema[1] &lt; lenema[2]: na,title='Buy Shape', style=shape.triangleup,color=color.green, location=location.belowbar,size=size.large) plotshape(sellSignal ? lenema &lt; lenema[1] and lenema[1] &gt; lenema[2]: na,title='Sell Shape',style=shape.triangledown,color=color.red, location=location.abovebar,size=size.large) </code></pre> <p>Trying to plot shape when value of the indicator ema first increases or decreases</p> <p>previous code is:</p> <pre><code>// RSI code rsi = ta.rsi(close, len) plot(rsi, color=color.new(color.white, 0), linewidth=3) plot(rsi) lenema = input.int(200, minval=1, title='RSI EMA Length') out = ta.ema(rsi, lenema) col = out &gt;= out[1] ? color.lime : color.red plot(out, title='RSI EMA', color=col, linewidth=2) </code></pre>
[ { "answer_id": 74530406, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "re.findall with open('data.txt', 'r') as file:\n data = file.read()\n parts = re.findall(r'-{10,}[^-]*\\n\\w{3} \\d{2}\\/\\d{2}\\/\\d{4}.*?-{10,}.*?(?=-{10,}|$)', data, flags=re.S)\n\ncnt = 1\nfor part in parts:\n output = open('file ' + str(cnt), 'w')\n output.write(part)\n output.close()\n cnt = cnt + 1\n" }, { "answer_id": 74530641, "author": "ChaoS Adm", "author_id": 12575770, "author_profile": "https://Stackoverflow.com/users/12575770", "pm_score": 0, "selected": false, "text": "with open('file.txt', 'r') as f: \nsplit_text = f.read().split('--------------------------------------------------')\nsplit_text.pop(0) # To remove the Copyright message at the start\n\nfor i in range(0, len(split_text) - 1, 2): \n with open(f'file{int(i/2)}.txt', 'w') as temp: \n temp_txt = ''.join(split_text[i:i+2])\n temp.write(temp_txt) \n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570804/" ]
74,530,430
<p>Does anyone know how can i filter and get numbers greater than 250 in an array consisting of two different types i.e</p> <pre><code>interface Foo { myNumber: number } interface Bar { present: boolean } const myArray : (Foo | Bar)[] = [{myNumber: 200}, {myNumber:600}, {myNumber:450}, {present: true}] myArray.filter((it: Foo|Bar) =&gt; it?.myNumber &gt;= 250) </code></pre> <p>The error i am getting is &quot;Property 'myNumber' does not exist on type 'Foo | Bar'.&quot;</p> <p>i know the reason behind the error message however can't think of a straight forward solution atm.</p> <p><a href="https://www.typescriptlang.org/play?target=9#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChkHIC2AngHICuRARtAFzIhW1S4C%20uuoksiKAQnCg58hAA5QIAZwjgG1TABsIcEO04J0IKWGIkAglChwSyBgAoMWAD7JBUAJQBtALrIAvMifZSlGvWQAJgAGYLYAGhxfZnoANlCIqPIYqDoAFgBWMMjsCWlZMAYwKAoINhdOUkNjEgA6GGBFHnNzYEK0TGt7Bw8APmQ2gH5a6P9hXs9ArIdcIA" rel="nofollow noreferrer">playground</a></p>
[ { "answer_id": 74530406, "author": "Tim Biegeleisen", "author_id": 1863229, "author_profile": "https://Stackoverflow.com/users/1863229", "pm_score": 1, "selected": false, "text": "re.findall with open('data.txt', 'r') as file:\n data = file.read()\n parts = re.findall(r'-{10,}[^-]*\\n\\w{3} \\d{2}\\/\\d{2}\\/\\d{4}.*?-{10,}.*?(?=-{10,}|$)', data, flags=re.S)\n\ncnt = 1\nfor part in parts:\n output = open('file ' + str(cnt), 'w')\n output.write(part)\n output.close()\n cnt = cnt + 1\n" }, { "answer_id": 74530641, "author": "ChaoS Adm", "author_id": 12575770, "author_profile": "https://Stackoverflow.com/users/12575770", "pm_score": 0, "selected": false, "text": "with open('file.txt', 'r') as f: \nsplit_text = f.read().split('--------------------------------------------------')\nsplit_text.pop(0) # To remove the Copyright message at the start\n\nfor i in range(0, len(split_text) - 1, 2): \n with open(f'file{int(i/2)}.txt', 'w') as temp: \n temp_txt = ''.join(split_text[i:i+2])\n temp.write(temp_txt) \n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083529/" ]
74,530,461
<p>I have looked for solutions but seem to find none that point me in the right direction, hopefully, someone on here can help. I have a stock price data set, with a frequency of Month Start. I am trying to get an output where the calendar years are the column names, and the day and month will be the index (there will only be 12 rows since it is monthly data). The rows will be filled with the stock prices corresponding to the year and month. I, unfortunately, have no code since I have looked at <code>for</code> loops, <code>groupby</code>, etc but can't seem to figure this one out.</p> <p><a href="https://i.stack.imgur.com/ScvSC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ScvSC.png" alt="Stock Prices" /></a></p> <p><a href="https://i.stack.imgur.com/EPxQx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EPxQx.png" alt="Example of what I am looking to achieve" /></a></p>
[ { "answer_id": 74530712, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "month year pivot s = pd.to_datetime(df.index)\n\nout = (df\n .assign(year=s.year, month=s.month)\n .pivot_table(index='month', columns='year', values='Close', fill_value=0)\n)\n year 2003 2004\nmonth \n1 0 2\n2 0 3\n3 0 4\n12 1 0\n df = pd.DataFrame({'Close': [1,2,3,4]},\n index=['2003-12-01', '2004-01-01', '2004-02-01', '2004-03-01'])\n" }, { "answer_id": 74530982, "author": "ffrosch", "author_id": 9152905, "author_profile": "https://Stackoverflow.com/users/9152905", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\n# Test Dataframe\ndf = pd.DataFrame({'Date': ['2003-12-01', '2004-01-01', '2004-02-01', '2004-12-01'],\n 'Close': [6.661, 7.053, 6.625, 8.999]})\n\n# Split datestring into list of form [year, month-day]\ndf = df.assign(Date=df.Date.str.split(pat='-', n=1))\n# Separate date-list column into two columns\ndf = pd.DataFrame(df.Date.to_list(), columns=['Year', 'Date'], index=df.index).join(df.Close)\n# Pivot the table\ndf = df.pivot(columns='Year', index='Date')\ndf\n Close \nYear 2003 2004\nDate \n01-01 NaN 7.053\n02-01 NaN 6.625\n12-01 6.661 8.999\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13085087/" ]
74,530,487
<p>I was trying to write a vba that can help detect whether within a range of cell exisit a cetain word in many sentences, but I don't know why the code did not work?</p> <pre><code>Private Sub Worksheet_Change(ByVal target As Range) Application.EnableEvents = False Set Rng = Range(&quot;Z10:Z35&quot;) certaintext = &quot;Pc Owner&quot; For Each Cell In Rng.Cells If Cell.Value Like &quot;*&quot; &amp; certaintext &amp; &quot;*&quot; Then Range(&quot;AF10&quot;) = &quot;DONE&quot; End If Next Application.EnableEvents = True End Sub </code></pre> <p>I tried the same code in normal sub without &quot;worksheet_change&quot; and it works, if I want to activate this vba anytime when the worksheet changes, what should I do? Thank you!</p>
[ { "answer_id": 74530712, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "month year pivot s = pd.to_datetime(df.index)\n\nout = (df\n .assign(year=s.year, month=s.month)\n .pivot_table(index='month', columns='year', values='Close', fill_value=0)\n)\n year 2003 2004\nmonth \n1 0 2\n2 0 3\n3 0 4\n12 1 0\n df = pd.DataFrame({'Close': [1,2,3,4]},\n index=['2003-12-01', '2004-01-01', '2004-02-01', '2004-03-01'])\n" }, { "answer_id": 74530982, "author": "ffrosch", "author_id": 9152905, "author_profile": "https://Stackoverflow.com/users/9152905", "pm_score": 1, "selected": false, "text": "import pandas as pd\n\n# Test Dataframe\ndf = pd.DataFrame({'Date': ['2003-12-01', '2004-01-01', '2004-02-01', '2004-12-01'],\n 'Close': [6.661, 7.053, 6.625, 8.999]})\n\n# Split datestring into list of form [year, month-day]\ndf = df.assign(Date=df.Date.str.split(pat='-', n=1))\n# Separate date-list column into two columns\ndf = pd.DataFrame(df.Date.to_list(), columns=['Year', 'Date'], index=df.index).join(df.Close)\n# Pivot the table\ndf = df.pivot(columns='Year', index='Date')\ndf\n Close \nYear 2003 2004\nDate \n01-01 NaN 7.053\n02-01 NaN 6.625\n12-01 6.661 8.999\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570146/" ]
74,530,552
<p>This is the variable i am having right now</p> <pre><code>[ { &quot;_id&quot;:&quot;63773059c3160f782c087e33&quot;, &quot;nfrid&quot;:&quot;637328ebf5c4b2558b064809&quot;, &quot;nfrname&quot;:&quot;azuread&quot;, &quot;fileName&quot;:&quot;package.json&quot;, &quot;isImport&quot;:false, &quot;isConst&quot;:false, &quot;isComponent&quot;:false, &quot;isNewFile&quot;:false, &quot;landmark&quot;:&quot;\&quot;react\&quot;&quot;, &quot;isAfter&quot;:false, &quot;fileContent&quot;:&quot;\&quot;@azure/msal-react\&quot;: \&quot;^1.4.9\&quot;,&quot;, &quot;filePath&quot;:&quot;package.json&quot;, &quot;isPackage&quot;:true, &quot;isIndexHtml&quot;:false, &quot;projecttypeid&quot;:&quot;6372366d1b568e00d8af2e44&quot;, &quot;projecttypetitle&quot;:&quot;PWA React&quot;, &quot;nfrGitIo&quot;:[ { &quot;_id&quot;:&quot;637328ebf5c4b2558b064809&quot;, &quot;iconpath&quot;:&quot;https://cdnerapidxdevportal.azureedge.net/webdesignerimages/azure-active-directory-aad-icon-488x512-3d71nrtk.png&quot;, &quot;title&quot;:&quot;Azure AD&quot;, &quot;description&quot;:&quot;Azure Active Directory (Azure AD), part of Microsoft Entra, is an enterprise identity service that provides single sign-on, multifactor authentication, and conditional access to guard against 99.9 percent of cybersecurity attacks.&quot; } ] }, { &quot;_id&quot;:&quot;63773144c3160f782c087e35&quot;, &quot;nfrid&quot;:&quot;637328ebf5c4b2558b064809&quot;, &quot;nfrname&quot;:&quot;azuread&quot;, &quot;fileName&quot;:&quot;index.js&quot;, &quot;isImport&quot;:true, &quot;isConst&quot;:false, &quot;isComponent&quot;:false, &quot;isNewFile&quot;:false, &quot;isPackage&quot;:false, &quot;landmark&quot;:null, &quot;isAfter&quot;:null, &quot;fileContent&quot;:&quot;import { MsalProvider } from '@azure/msal-react';import { msalConfig } from './authConfig';import {PublicClientApplication } from '@azure/msal-browser';&quot;, &quot;filePath&quot;:&quot;src/index.js&quot;, &quot;isIndexHtml&quot;:false, &quot;projecttypeid&quot;:&quot;6372366d1b568e00d8af2e44&quot;, &quot;projecttypetitle&quot;:&quot;PWA React&quot;, &quot;nfrGitIo&quot;:[ { &quot;_id&quot;:&quot;637328ebf5c4b2558b064809&quot;, &quot;iconpath&quot;:&quot;https://cdnerapidxdevportal.azureedge.net/webdesignerimages/azure-active-directory-aad-icon-488x512-3d71nrtk.png&quot;, &quot;title&quot;:&quot;Azure AD&quot;, &quot;description&quot;:&quot;Azure Active Directory (Azure AD), part of Microsoft Entra, is an enterprise identity service that provides single sign-on, multifactor authentication, and conditional access to guard against 99.9 percent of cybersecurity attacks.&quot; } ] }, ] </code></pre> <p>I am having many flags like isImport, isPackage, isIndexHtml like that. I am trying to put those flags in a switch case and call individual function when each flag is true.Something like this,</p> <pre><code>for (let i = 0; i &lt; cosmos.length; i++) { console.log(cosmos[0].isPackage); switch (cosmos[i]) { case `${cosmos[i].isImport === true}`: const statusImport = common.updateImport(cosmos[i]); console.log(statusImport); break; // case `${cosmos[i].isConst === true}`: // console.log(&quot;I own a dog&quot;); // break; case `${cosmos[i].isPackage === true}`: const statusPackage = common.updatePackage(cosmos[i]); console.log(statusPackage); break; case `${cosmos[i].isIndexHtml === true}`: const statusIndexHtml = common.updateIndexHTML(cosmos[i]); console.log(statusIndexHtml); break; // case `${cosmos[i].isNewFile === true}`: // const statusNewFile = common.addNewFile(cosmos[i]); // console.log(statusNewFile); // break; default: console.log(&quot;Nothing to add/update&quot;); break; } } </code></pre> <p>But when I run this i am always getting the default console log. I dont know what i am missing</p> <p>This is my first switch case implementation. Can someone point me in the right direction?</p>
[ { "answer_id": 74530619, "author": "callOfCode", "author_id": 5080069, "author_profile": "https://Stackoverflow.com/users/5080069", "pm_score": 0, "selected": false, "text": "switch if/else" }, { "answer_id": 74530623, "author": "Justinas", "author_id": 1346234, "author_profile": "https://Stackoverflow.com/users/1346234", "pm_score": 1, "selected": false, "text": "true for (let i = 0; i < cosmos.length; i++) {\n console.log(cosmos[0].isPackage);\n switch (true) {\n case cosmos[i].isImport:\n const statusImport = common.updateImport(cosmos[i]);\n console.log(statusImport);\n break;\n case cosmos[i].isPackage:\n const statusPackage = common.updatePackage(cosmos[i]);\n console.log(statusPackage);\n break;\n case cosmos[i].isIndexHtml:\n const statusIndexHtml = common.updateIndexHTML(cosmos[i]);\n console.log(statusIndexHtml); \n break;\n default:\n console.log(\"Nothing to add/update\");\n break;\n }\n }\n" }, { "answer_id": 74530627, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 0, "selected": false, "text": "cosmos[i] switch if else if else for (let i = 0; i < cosmos.length; i++) {\n if (cosmos[i].isImport) {\n const statusImport = common.updateImport(cosmos[i]);\n console.log(statusImport);\n } else if (cosmos[i].isPackage) {\n const statusPackage = common.updatePackage(cosmos[i]);\n console.log(statusPackage);\n } else if (cosmos[i].isIndexHtml) {\n const statusIndexHtml = common.updateIndexHTML(cosmos[i]);\n console.log(statusIndexHtml);\n } else {\n console.log(\"Nothing to add/update\");\n }\n}\n for-of for for (const entry of cosmos) {\n if (entry.isImport) {\n const statusImport = common.updateImport(entry);\n console.log(statusImport);\n } else if (entry.isPackage) {\n const statusPackage = common.updatePackage(entry);\n console.log(statusPackage);\n } else if (entry.isIndexHtml) {\n const statusIndexHtml = common.updateIndexHTML(entry);\n console.log(statusIndexHtml);\n } else {\n console.log(\"Nothing to add/update\");\n }\n}\n" }, { "answer_id": 74530725, "author": "mli", "author_id": 17839690, "author_profile": "https://Stackoverflow.com/users/17839690", "pm_score": 0, "selected": false, "text": "switch if if (cosmos[i].isImport === true) {\n const statusImport = common.updateImport(cosmos[i]);\n console.log(statusImport);\n}\n\nif (cosmos[i].isPackage === true) {\n const statusPackage = common.updatePackage(cosmos[i]);\n console.log(statusPackage);\n}\n\nif (cosmos[i].isIndexHtml === true) {\n const statusIndexHtml = common.updateIndexHTML(cosmos[i]);\n console.log(statusIndexHtml); \n} isImport isPackage isIndexHtml" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19672461/" ]
74,530,598
<p>My code is:</p> <pre><code>n = 3 for i in range(1, n+1): for j in range(1, n+1): print(j*i, end='*') print(end='\b\n') </code></pre> <p>Result of this code is:</p> <pre><code>1*2*3* 2*4*6* 3*6*9* </code></pre> <p>But I need expected result like this (without aesthetics in end of rows):</p> <pre><code>1*2*3 2*4*6 3*6*9 </code></pre>
[ { "answer_id": 74530663, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n for j in range(1, n+1):\n print(j*i, end='')\n if j != n:\n print('*', end='')\n print(end='\\b\\n')\n" }, { "answer_id": 74530734, "author": "Rajesh Kanna", "author_id": 15656258, "author_profile": "https://Stackoverflow.com/users/15656258", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n print(*[j*i for j in range(1, n+1)], sep='*', end=\"\\n\")\n" }, { "answer_id": 74530739, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": -1, "selected": false, "text": "n = int(input())\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if(j*i == n*n):\n print(j*i)\n else:\n print(j*i, end='*')\n \n print(end='\\b\\n')\n" }, { "answer_id": 74530763, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 0, "selected": false, "text": "'*'.join() end print() for i in range(1, n + 1):\n print('*'.join(f'{j * i}' for j in range(1, n + 1)), end='\\n')\n 1*2*3\n2*4*6\n3*6*9\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18174916/" ]
74,530,600
<p>this is my code snippet bellow, I am trying to close the websocket connection after component unmounts, I just totally dont know how to do it I am using this useEffect inside the same component I am also using useref to count the mounted count of the component so that the websocket doesn't creates more that 1 instance at a time</p> <pre><code>const mountedCount = useRef(0); useEffect(() =&gt; { const handleWebsocket = () =&gt; { mountedCount.current++; const socketURL = 'socket url here' const socket = new WebSocket(socketURL); socket.onopen = () =&gt; { console.log('socket open') }; socket.onclose = (closeEvent) =&gt; { if (closeEvent.wasClean) return; timeout = setTimeout(() =&gt; { handleWebsocket(); }, envVariables.webSocketReconnectionTimeout); }; socket.onerror = () =&gt; { console.log('error here') }; socket.onmessage = (messageEvent) =&gt; { console.log('got the message') }; return socket; }; if (mountedCount.current === 0) { handleWebsocket(); } return () =&gt; { clearTimeout(timeout); }; }, [ dispatch, userData.userInformation, wss.connectionStatus ]); </code></pre>
[ { "answer_id": 74530663, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n for j in range(1, n+1):\n print(j*i, end='')\n if j != n:\n print('*', end='')\n print(end='\\b\\n')\n" }, { "answer_id": 74530734, "author": "Rajesh Kanna", "author_id": 15656258, "author_profile": "https://Stackoverflow.com/users/15656258", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n print(*[j*i for j in range(1, n+1)], sep='*', end=\"\\n\")\n" }, { "answer_id": 74530739, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": -1, "selected": false, "text": "n = int(input())\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if(j*i == n*n):\n print(j*i)\n else:\n print(j*i, end='*')\n \n print(end='\\b\\n')\n" }, { "answer_id": 74530763, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 0, "selected": false, "text": "'*'.join() end print() for i in range(1, n + 1):\n print('*'.join(f'{j * i}' for j in range(1, n + 1)), end='\\n')\n 1*2*3\n2*4*6\n3*6*9\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19843225/" ]
74,530,649
<p>I'm trying to fetch the shop and it's coupons, I have two model one for the shop and one for the coupon, also two routers, one for fetching shops and one for fetching coupons, the shops are fetching fine and showing in client side, but the coupons are not showing in the client side. When <em><code>/coupons/${shopName}</code></em> I try it in postman it works fine, but in the client side not, I don't know why. Console log is giving me <em>[object Object]</em></p> <p><a href="https://i.stack.imgur.com/yat4Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yat4Q.png" alt="enter image description here" /></a></p> <pre><code>export default function ShopPage() { const [shop, setShop] = useState(&quot;&quot;); const shopName = useParams().shopName; const [coupons, setCoupons] = useState([]); useEffect(() =&gt; { const fetchShop = async () =&gt; { const res = await axios.get(`/shops/${shopName}`); setShop(res.data); console.log(res.data); }; fetchShop(); }, [shopName]); useEffect(() =&gt; { const fetchShopCoupons = async () =&gt; { const response = await axios.get(`/coupons/${shopName}`); setCoupons(response.data); console.log(&quot;Shop Coupons are:&quot; + response.data); }; fetchShopCoupons(); }, []); return ( &lt;&gt; &lt;Box&gt; &lt;Stack&gt; &lt;Stack &gt; &lt;Avatar alt={(shop.shopName)} src={shop.shopPic}/&gt; &lt;Stack&gt; &lt;Box&gt; &lt;Typography&gt; {shop.shopName} &lt;/Typography&gt; &lt;/Box&gt; &lt;/Box&gt; &lt;/Stack&gt; &lt;/Stack&gt; &lt;Box&gt; &lt;Coupons coupons={coupons}/&gt; &lt;/Box&gt; &lt;/Stack&gt; &lt;/Box&gt; &lt;/&gt; ) } </code></pre> <p>Coupons Component:</p> <pre><code>export default function Coupons({ coupons = [] }) { const [filteredResults, setFilteredResults] = useState([]); const [searchInput, setSearchInput] = useState(''); const [isLoading, setIsLoading] = useState(false); const filter = (e) =&gt; { const keyword = e.target.value; if (keyword !== '') { const filteredData = coupons.filter((coupon) =&gt; { return Object.values(coupon) .join('') .toLowerCase() .includes(searchInput.toLowerCase()) }) setFilteredResults(filteredData) } else { setFilteredResults(coupons); } setSearchInput(keyword); } console.log(&quot;filtered Coupons are:&quot;, filteredResults); return ( &lt;div className=&quot;coupons&quot;&gt; &lt;div className=&quot;couponsContainer&quot;&gt; &lt;div className=&quot;couponsSearchContainer&quot;&gt; &lt;div className=&quot;couponsSearch&quot;&gt; &lt;div class=&quot;couponsSearchIconContainer&quot;&gt; &lt;SearchIcon class=&quot;w-5 h-5&quot; /&gt; &lt;/div&gt; &lt;input type=&quot;text&quot; className=&quot;couponsSearchInput&quot; placeholder=&quot;بحث&quot; name=&quot;couponSearchText&quot; id=&quot;couponSearchText&quot; onChange={filter} /&gt; &lt;/div&gt; {/* ENDS OF COUPONSSEARCHCONTAINER */} &lt;/div&gt; {/* ENDS OF COUPONSSEARCH */} &lt;div className=&quot;couponsBox&quot;&gt; {isLoading ? ( &lt;Box sx={{ display: 'flex' }}&gt; &lt;CircularProgress /&gt; &lt;/Box&gt; ) : ( filteredResults.length &gt; 0 ? ( filteredResults.map((f) =&gt; ( &lt;Coupon coupon={f} /&gt; )) ) : ( coupons.sort((a, b) =&gt; new Date(b.createdAt) - new Date(a.createdAt)) .map((c) =&gt; ( &lt;Coupon coupon={c} /&gt; ))) ) } &lt;/div&gt; {/* ENDS OF COUPONSBOX */} &lt;/div&gt; {/* ENDS OF COUPONSCONTAINER */} &lt;/div&gt; //ENDS OF COUPONS ); } </code></pre>
[ { "answer_id": 74530663, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n for j in range(1, n+1):\n print(j*i, end='')\n if j != n:\n print('*', end='')\n print(end='\\b\\n')\n" }, { "answer_id": 74530734, "author": "Rajesh Kanna", "author_id": 15656258, "author_profile": "https://Stackoverflow.com/users/15656258", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n print(*[j*i for j in range(1, n+1)], sep='*', end=\"\\n\")\n" }, { "answer_id": 74530739, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": -1, "selected": false, "text": "n = int(input())\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if(j*i == n*n):\n print(j*i)\n else:\n print(j*i, end='*')\n \n print(end='\\b\\n')\n" }, { "answer_id": 74530763, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 0, "selected": false, "text": "'*'.join() end print() for i in range(1, n + 1):\n print('*'.join(f'{j * i}' for j in range(1, n + 1)), end='\\n')\n 1*2*3\n2*4*6\n3*6*9\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17342280/" ]
74,530,666
<p>I discovered a different behaviour when I want to serialize an object of type <strong>INTERFACE</strong> in System.Text.Json.</p> <pre><code>public class ITestClass { } public class TestClass : ITestClass { public int MyProperty { get; set; } } </code></pre> <p>Newtonsoft.Json:</p> <pre><code>var result1 = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(testClass)); var result2 = Encoding.UTF8.GetString(result1); // {&quot;MyProperty&quot;:5} </code></pre> <p>System.Text.Json:</p> <pre><code>var result1 = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(testClass); var result2 = Encoding.UTF8.GetString(result1); // {} </code></pre> <p>How can I get the same result in System.Text.Json like in Newtonsoft.Json? I want to get: {&quot;MyProperty&quot;:5} not: {}</p>
[ { "answer_id": 74530663, "author": "Maxwell D. Dorliea", "author_id": 12906648, "author_profile": "https://Stackoverflow.com/users/12906648", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n for j in range(1, n+1):\n print(j*i, end='')\n if j != n:\n print('*', end='')\n print(end='\\b\\n')\n" }, { "answer_id": 74530734, "author": "Rajesh Kanna", "author_id": 15656258, "author_profile": "https://Stackoverflow.com/users/15656258", "pm_score": -1, "selected": false, "text": "n = 3\nfor i in range(1, n+1):\n print(*[j*i for j in range(1, n+1)], sep='*', end=\"\\n\")\n" }, { "answer_id": 74530739, "author": "TANIMUL ISLAM", "author_id": 18262004, "author_profile": "https://Stackoverflow.com/users/18262004", "pm_score": -1, "selected": false, "text": "n = int(input())\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if(j*i == n*n):\n print(j*i)\n else:\n print(j*i, end='*')\n \n print(end='\\b\\n')\n" }, { "answer_id": 74530763, "author": "Guy", "author_id": 5168011, "author_profile": "https://Stackoverflow.com/users/5168011", "pm_score": 0, "selected": false, "text": "'*'.join() end print() for i in range(1, n + 1):\n print('*'.join(f'{j * i}' for j in range(1, n + 1)), end='\\n')\n 1*2*3\n2*4*6\n3*6*9\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6560691/" ]
74,530,668
<p>I am trying to figure out if all the methods to create a build using expo must go through EAS (Expo Application Services) since apparently they limit the free tier to 30 builds per month.</p> <p>Can I build the web-app locally without an EAS account / 100% for free?</p> <p><a href="https://docs.expo.dev/build-reference/local-builds/" rel="nofollow noreferrer">The documentation</a> isn't clear to me.</p>
[ { "answer_id": 74530764, "author": "no_modules", "author_id": 19835828, "author_profile": "https://Stackoverflow.com/users/19835828", "pm_score": 2, "selected": false, "text": "android studio xcode build android studio xcode CD package.json npm android package.json wifi pairing" }, { "answer_id": 74557939, "author": "Guillem Poy", "author_id": 7927429, "author_profile": "https://Stackoverflow.com/users/7927429", "pm_score": 1, "selected": true, "text": "eas build --local" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7927429/" ]
74,530,685
<p>I received feedback:</p> <p>&quot;code test is not at the expected level there's a lack of understanding of async, HTTP clients, and just software development patterns in general. Poor structure and testing&quot;</p> <p>The simple test and solution are on GitHub <a href="https://github.com/sasa-yovanovicc/weatherapi" rel="nofollow noreferrer">https://github.com/sasa-yovanovicc/weatherapi</a></p> <p>I'll really appreciate any help to understand what is wrong because the code works, the test works,, and covers all solutions, and honestly, I don't know what they expect.</p> <p>I understand that in OOP code can be more abstracted and complex, but I can't see any purpose in making code more complex than needed to solve a given problems.</p>
[ { "answer_id": 74530764, "author": "no_modules", "author_id": 19835828, "author_profile": "https://Stackoverflow.com/users/19835828", "pm_score": 2, "selected": false, "text": "android studio xcode build android studio xcode CD package.json npm android package.json wifi pairing" }, { "answer_id": 74557939, "author": "Guillem Poy", "author_id": 7927429, "author_profile": "https://Stackoverflow.com/users/7927429", "pm_score": 1, "selected": true, "text": "eas build --local" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893211/" ]
74,530,715
<p>I have created some services with interfaces and added them as services the ConfigureServices method in the Startup.cs file (see screenshot and code).</p> <pre><code>public void ConfigureServices(IServiceCollection services) { if (Environment.IsDevelopment()) { EstablishDbContext(services, &quot;DevelopmentConnection&quot;); AddVOMApi(services, &quot;AuthorizationStringsDevelopment&quot;); } else { EstablishDbContext(services, &quot;ProductionConnection&quot;); AddVOMApi(services, &quot;AuthorizationStringsProduction&quot;); throw new NotImplementedException(&quot;The production environment has not been implemented.&quot;); } services.AddRazorPages(); services.AddServerSideBlazor(); services.AddTransient&lt;VomConnection, VomConnection&gt;(); services.AddTransient&lt;IImportInternalHelper, ImportInternalHelper&gt;(); } </code></pre> <p>When I want to inject the services in a Razor file, my IDE (Jetbrains Rider) adds the @using statements with the path to the classes.</p> <pre><code>@using Presentation.WebUI.Shared.Components @using Presentation.WebUI.Shared.Components.Tables @using Infrastructure.AdapterService.VOM @using Application.HelperClasses @inject VomConnection _Vom; @inject IImportInternalHelper _helper; </code></pre> <p>In the documentation for Blazor it looks like you do not have to use @using when injecting a service, @inject should be enough.</p> <p>My code works, but what is wrong with my code since I need to use both @inject and @using? I cannot inject without @using.</p> <pre><code>@using Presentation.WebUI.Shared.Components @using Presentation.WebUI.Shared.Components.Tables @*@using Infrastructure.AdapterService.VOM @using Application.HelperClasses*@ @inject VomConnection _Vom; @inject IImportInternalHelper _helper; </code></pre> <p><a href="https://i.stack.imgur.com/nBSOM.png" rel="nofollow noreferrer">Service added in Startup.cs file.</a></p> <p><a href="https://i.stack.imgur.com/pGyG0.png" rel="nofollow noreferrer">My injections + @ using. It works but does not look right, compared to Blazor documentation.</a></p> <p><a href="https://i.stack.imgur.com/AuPnO.png" rel="nofollow noreferrer">When deleting @using the injections does not work.</a></p> <p>I have tried to inject in different ways but the IDE always adds the @using part.</p>
[ { "answer_id": 74530823, "author": "AlirezaK", "author_id": 4444757, "author_profile": "https://Stackoverflow.com/users/4444757", "pm_score": 0, "selected": false, "text": "@using" }, { "answer_id": 74531266, "author": "T.Trassoudaine", "author_id": 10989407, "author_profile": "https://Stackoverflow.com/users/10989407", "pm_score": 2, "selected": false, "text": "@using _Imports.razor _Imports.razor" }, { "answer_id": 74535016, "author": "MrC aka Shaun Curtis", "author_id": 13065781, "author_profile": "https://Stackoverflow.com/users/13065781", "pm_score": 0, "selected": false, "text": "usings Blazr.App.Core WeatherForecastsViewService namespace Blazr.App.Core;\n\npublic class WeatherForecastsViewService\n{\n //....\n}\n @namespace Blazr.App.Components;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17350563/" ]
74,530,758
<p>Here is my code</p> <pre><code>module_a.py class Parent(object): def __init__(self) -&gt; None: pass def send(self): print('We send some message here') # send self.message class Child(Parent): def __init__(self, message): self.message = message super(Child, self).__init__() module_b.py from module_a import Child def some_function(): # do something Child('Some Message Here').send() # do something </code></pre> <p>Is there any way to test that <code>.send()</code> was called for Child not for parent and <code>self.message</code> inside <code>.send()</code> equals to some value.</p> <p>Thanks</p> <p>UPD: I am asking about writing a unit test and my main problem is how to patch /mock that in the correct way.</p>
[ { "answer_id": 74530826, "author": "Noah", "author_id": 14028308, "author_profile": "https://Stackoverflow.com/users/14028308", "pm_score": 1, "selected": false, "text": " class Parent(object):\n def __init__(self) -> None:\n pass\n\n def send(self):\n print(type(self))\n # send self.message\n\nclass Child(Parent):\n def __init__(self, message):\n self.message = message\n super(Child, self).__init__()\n\n\n\nChild('Some Message Here').send()\n\nParent().send()\n <class '__main__.Child'>\n<class '__main__.Parent'>\n isinstance(self, Child)\n" }, { "answer_id": 74534206, "author": "Roxy", "author_id": 13007041, "author_profile": "https://Stackoverflow.com/users/13007041", "pm_score": 1, "selected": false, "text": "patch call_count assert_called_with Child.send send from module_b import some_function\nimport unittest\nfrom unittest.mock import patch\n\n\nclass TestSomeFunc(unittest.TestCase):\n @patch(\"module_b.Child.send\")\n def test_some_func(self, mock_send):\n some_function()\n self.assertEqual(mock_send.call_count, 1)\n from module_b import some_function\nimport unittest\nfrom unittest.mock import patch\n\n\nclass TestSomeFunc(unittest.TestCase):\n @patch(\"module_b.Child\")\n def test_some_func(self, mock_child):\n some_function()\n mock_child.assert_called_with(\"Some Message Here\")\n" }, { "answer_id": 74535479, "author": "frankfalse", "author_id": 18108367, "author_profile": "https://Stackoverflow.com/users/18108367", "pm_score": 0, "selected": false, "text": "send() send() instanceof() module_a.py class Parent(object):\n def __init__(self) -> None:\n pass\n\n def send(self):\n print(type(self))\n if isinstance(self, Child):\n # send self.message\n print(\"send Child: \" + str(self.message))\n else:\n # for Parent doesn't exist self.message\n print(\"send Parent!\")\n\nclass Child(Parent):\n def __init__(self, message):\n self.message = message\n super(Child, self).__init__()\n\n send() Parent module_a.py module_b.py sut_child send() self.message sut_child sut_parent send() sut_parent module_b.py from module_a import Child, Parent\nimport unittest\nfrom unittest.mock import patch\n\nclass TestSomeFunc(unittest.TestCase):\n\n def test_send_func_child(self):\n sut_child = Child('Some Message Here')\n sut_child.send()\n self.assertEqual('Some Message Here', sut_child.message)\n self.assertTrue(isinstance(sut_child, Child))\n\n def test_send_func_parent(self):\n sut_parent = Parent()\n sut_parent.send()\n self.assertFalse(isinstance(sut_parent, Child))\n\nif __name__ == '__main__':\n unittest.main()\n module_b.py # output of test_send_func_child:\n<class 'module_a.Child'>\nsend Child: Some Message Here\n\n# output of test_send_func_parent\n<class 'module_a.Parent'>\nsend Parent!\n\n# output for the execution of 2 tests (the assert are correct)\nRan 2 tests in 0.000s\n\nOK\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5079255/" ]
74,530,771
<p>i want to create form when there will be possibility to add/remove additional selection rows, but all of this new selection should have possibility to show DIV depends on selected option.</p> <p>Everything is working fine for first row which is loaded with page, DIV is showing input form, normal text or another selection (this one not need to show anything in additional DIV) based what we choosed. But for added rows nothing happens after selection.</p> <p>Any idea how to fix it or use another solution?</p> <pre><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css&quot; integrity=&quot;sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;div style=&quot;width:100%;&quot;&gt; Replace: &lt;form&gt; &lt;div class=&quot;&quot;&gt; &lt;div class=&quot;col-lg-10&quot;&gt; &lt;div id=&quot;row&quot;&gt; &lt;div class=&quot;input-group m-3&quot;&gt; &lt;select class=&quot;custom-select custom-select-sm&quot; name=&quot;test&quot; id=&quot;type&quot;&gt;&lt;option&gt;select one&lt;/option&gt;&lt;option value=&quot;id&quot;&gt;ID:&lt;/option&gt;&lt;option value=&quot;client&quot;&gt;Client:&lt;/option&gt;&lt;option value=&quot;file&quot;&gt;File:&lt;/option&gt;&lt;/select&gt;&amp;nbsp;&amp;nbsp; with &amp;nbsp;&amp;nbsp; &lt;div id=&quot;values&quot;&gt;&lt;/div&gt; &lt;div class=&quot;input-group-prepend&quot; style=&quot;margin-left: 20px;&quot;&gt; &lt;button class=&quot;btn btn-danger&quot; id=&quot;DeleteRow&quot; type=&quot;button&quot;&gt; &lt;i class=&quot;bi bi-trash&quot;&gt;&lt;/i&gt; Delete row &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;newinput&quot;&gt;&lt;/div&gt; &lt;br /&gt; &lt;button id=&quot;rowAdder&quot; type=&quot;button&quot; class=&quot;btn btn-dark&quot;&gt; &lt;span class=&quot;bi bi-plus-square-dotted&quot;&gt; &lt;/span&gt; ADD row &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <pre><code> $(&quot;#rowAdder&quot;).click(function () { newRowAdd = '&lt;div id=&quot;row&quot;&gt;' + '&lt;div class=&quot;input-group m-3&quot;&gt;' + '&lt;br /&gt;&lt;select class=&quot;custom-select custom-select-sm&quot; name=&quot;test&quot; id=&quot;type&quot;&gt;&lt;option&gt;select one&lt;/option&gt;&lt;option value=&quot;id&quot;&gt;ID:&lt;/option&gt;&lt;option value=&quot;client&quot;&gt;Client:&lt;/option&gt;&lt;option value=&quot;file&quot;&gt;File:&lt;/option&gt;&lt;/select&gt;' + '&amp;nbsp;&amp;nbsp; with &amp;nbsp;&amp;nbsp;' + ' &lt;div id=&quot;values&quot;&gt;&lt;/div&gt;' + ' &lt;div class=&quot;input-group-prepend&quot; style=&quot;margin-left: 20px;&quot;&gt;' + ' &lt;button class=&quot;btn btn-danger&quot;' + ' id=&quot;DeleteRow&quot; type=&quot;button&quot;&gt;' + ' &lt;i class=&quot;bi bi-trash&quot;&gt;&lt;/i&gt;' + ' Delete row'+ ' &lt;/button&gt; &lt;/div&gt;' + '&lt;/div&gt; &lt;/div&gt;'; $('#newinput').append(newRowAdd); }); $(&quot;body&quot;).on(&quot;click&quot;, &quot;#DeleteRow&quot;, function () { $(this).parents(&quot;#row&quot;).remove(); }) </code></pre> <p>Example: <a href="http://jsfiddle.net/3th96bac/" rel="nofollow noreferrer">http://jsfiddle.net/3th96bac/</a></p>
[ { "answer_id": 74530895, "author": "Carsten Løvbo Andersen", "author_id": 2943218, "author_profile": "https://Stackoverflow.com/users/2943218", "pm_score": 0, "selected": false, "text": "$(\".type\").change(function() { $(document).ready(function() {\n\n $(document).on(\"change\", \".type\", function() {\n var val = $(this).val();\n if (val == \"id\") {\n $(this).next(\".values\").html(\"<select><option>First option</option><option>Second Option</option></select>\");\n } else if (val == \"client\") {\n $(this).next(\".values\").html(\"<input value='Example input' />\");\n\n } else if (val == \"file\") {\n $(this).next(\".values\").html(\"normal text\");\n }\n });\n});\n\n$(\"#rowAdder\").click(function() {\n newRowAdd =\n '<div class=\"row\">' +\n '<div class=\"input-group m-3\">' +\n '<br /><select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\"><option>select one</option><option value=\"id\">ID:</option><option value=\"client\">Client:</option><option value=\"file\">File:</option></select>' +\n '&nbsp;&nbsp; with &nbsp;&nbsp;' +\n ' <div class=\"values\"></div>' +\n ' <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">' +\n ' <button class=\"btn btn-danger DeleteRow\"' +\n ' id=\"\" type=\"button\">' +\n ' <i class=\"bi bi-trash\"></i>' +\n ' Delete row' +\n ' </button> </div>' +\n '</div> </div>';\n\n $('#newinput').append(newRowAdd);\n});\n\n$(\"body\").on(\"click\", \".DeleteRow\", function() {\n $(this).closest(\".row\").remove();\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n<div style=\"width:100%;\">\n Replace:\n <form>\n <div class=\"\">\n <div class=\"col-lg-10\">\n <div class=\"row\">\n <div class=\"input-group m-3\">\n <select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\">\n <option>select one</option>\n <option value=\"id\">ID:</option>\n <option value=\"client\">Client:</option>\n <option value=\"file\">File:</option>\n </select>&nbsp;&nbsp; with &nbsp;&nbsp;\n <div class=\"values\"></div>\n <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">\n <button class=\"btn btn-danger DeleteRow\" id=\"\" type=\"button\">\n <i class=\"bi bi-trash\"></i>\n Delete row\n </button>\n </div>\n </div>\n </div>\n\n <div id=\"newinput\"></div>\n <br />\n <button id=\"rowAdder\" type=\"button\" class=\"btn btn-dark\">\n <span class=\"bi bi-plus-square-dotted\">\n </span> ADD row\n </button>\n </div>\n </div>\n </form>\n</div>" }, { "answer_id": 74530898, "author": "Kairav Thakar", "author_id": 20447312, "author_profile": "https://Stackoverflow.com/users/20447312", "pm_score": -1, "selected": true, "text": "Please check below working link for your question.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570952/" ]
74,530,782
<p>After updating Next.js to version 13, I got this client error</p> <p><a href="https://i.stack.imgur.com/LnqBX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LnqBX.png" alt="enter image description here" /></a></p> <pre><code>&lt;Link href=&quot;/contact&quot;&gt; &lt;a&gt; Contact &lt;/a&gt; &lt;/Link&gt; </code></pre>
[ { "answer_id": 74530895, "author": "Carsten Løvbo Andersen", "author_id": 2943218, "author_profile": "https://Stackoverflow.com/users/2943218", "pm_score": 0, "selected": false, "text": "$(\".type\").change(function() { $(document).ready(function() {\n\n $(document).on(\"change\", \".type\", function() {\n var val = $(this).val();\n if (val == \"id\") {\n $(this).next(\".values\").html(\"<select><option>First option</option><option>Second Option</option></select>\");\n } else if (val == \"client\") {\n $(this).next(\".values\").html(\"<input value='Example input' />\");\n\n } else if (val == \"file\") {\n $(this).next(\".values\").html(\"normal text\");\n }\n });\n});\n\n$(\"#rowAdder\").click(function() {\n newRowAdd =\n '<div class=\"row\">' +\n '<div class=\"input-group m-3\">' +\n '<br /><select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\"><option>select one</option><option value=\"id\">ID:</option><option value=\"client\">Client:</option><option value=\"file\">File:</option></select>' +\n '&nbsp;&nbsp; with &nbsp;&nbsp;' +\n ' <div class=\"values\"></div>' +\n ' <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">' +\n ' <button class=\"btn btn-danger DeleteRow\"' +\n ' id=\"\" type=\"button\">' +\n ' <i class=\"bi bi-trash\"></i>' +\n ' Delete row' +\n ' </button> </div>' +\n '</div> </div>';\n\n $('#newinput').append(newRowAdd);\n});\n\n$(\"body\").on(\"click\", \".DeleteRow\", function() {\n $(this).closest(\".row\").remove();\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n<div style=\"width:100%;\">\n Replace:\n <form>\n <div class=\"\">\n <div class=\"col-lg-10\">\n <div class=\"row\">\n <div class=\"input-group m-3\">\n <select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\">\n <option>select one</option>\n <option value=\"id\">ID:</option>\n <option value=\"client\">Client:</option>\n <option value=\"file\">File:</option>\n </select>&nbsp;&nbsp; with &nbsp;&nbsp;\n <div class=\"values\"></div>\n <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">\n <button class=\"btn btn-danger DeleteRow\" id=\"\" type=\"button\">\n <i class=\"bi bi-trash\"></i>\n Delete row\n </button>\n </div>\n </div>\n </div>\n\n <div id=\"newinput\"></div>\n <br />\n <button id=\"rowAdder\" type=\"button\" class=\"btn btn-dark\">\n <span class=\"bi bi-plus-square-dotted\">\n </span> ADD row\n </button>\n </div>\n </div>\n </form>\n</div>" }, { "answer_id": 74530898, "author": "Kairav Thakar", "author_id": 20447312, "author_profile": "https://Stackoverflow.com/users/20447312", "pm_score": -1, "selected": true, "text": "Please check below working link for your question.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12490386/" ]
74,530,787
<p>I am trying to run a Streamlit app importing <code>pickle files</code> and a <code>DataFrame</code>. The pathfile for my script is :</p> <blockquote> <p>/Users/myname/Documents/Master2/Python/Final_Project/streamlit_app.py</p> </blockquote> <p>And the one for my <code>DataFrame</code> is:</p> <blockquote> <p>/Users/myname/Documents/Master2/Python/Final_Project/data/metabolic_syndrome.csv</p> </blockquote> <p>One could reasonably argue that I only need to specify <code>df = pd.read_csv('data/df.csv')</code> yet it does not work as the Streamlit app is unexpectedly not searching in its directory:</p> <blockquote> <p>FileNotFoundError: [Errno 2] No such file or directory: '/Users/myname/data/metabolic_syndrome.csv'</p> </blockquote> <p>How can I manage to make the app look for the files in the good directory (the one where it is saved) without having to use absolute pathfiles ?</p>
[ { "answer_id": 74530895, "author": "Carsten Løvbo Andersen", "author_id": 2943218, "author_profile": "https://Stackoverflow.com/users/2943218", "pm_score": 0, "selected": false, "text": "$(\".type\").change(function() { $(document).ready(function() {\n\n $(document).on(\"change\", \".type\", function() {\n var val = $(this).val();\n if (val == \"id\") {\n $(this).next(\".values\").html(\"<select><option>First option</option><option>Second Option</option></select>\");\n } else if (val == \"client\") {\n $(this).next(\".values\").html(\"<input value='Example input' />\");\n\n } else if (val == \"file\") {\n $(this).next(\".values\").html(\"normal text\");\n }\n });\n});\n\n$(\"#rowAdder\").click(function() {\n newRowAdd =\n '<div class=\"row\">' +\n '<div class=\"input-group m-3\">' +\n '<br /><select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\"><option>select one</option><option value=\"id\">ID:</option><option value=\"client\">Client:</option><option value=\"file\">File:</option></select>' +\n '&nbsp;&nbsp; with &nbsp;&nbsp;' +\n ' <div class=\"values\"></div>' +\n ' <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">' +\n ' <button class=\"btn btn-danger DeleteRow\"' +\n ' id=\"\" type=\"button\">' +\n ' <i class=\"bi bi-trash\"></i>' +\n ' Delete row' +\n ' </button> </div>' +\n '</div> </div>';\n\n $('#newinput').append(newRowAdd);\n});\n\n$(\"body\").on(\"click\", \".DeleteRow\", function() {\n $(this).closest(\".row\").remove();\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n<div style=\"width:100%;\">\n Replace:\n <form>\n <div class=\"\">\n <div class=\"col-lg-10\">\n <div class=\"row\">\n <div class=\"input-group m-3\">\n <select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\">\n <option>select one</option>\n <option value=\"id\">ID:</option>\n <option value=\"client\">Client:</option>\n <option value=\"file\">File:</option>\n </select>&nbsp;&nbsp; with &nbsp;&nbsp;\n <div class=\"values\"></div>\n <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">\n <button class=\"btn btn-danger DeleteRow\" id=\"\" type=\"button\">\n <i class=\"bi bi-trash\"></i>\n Delete row\n </button>\n </div>\n </div>\n </div>\n\n <div id=\"newinput\"></div>\n <br />\n <button id=\"rowAdder\" type=\"button\" class=\"btn btn-dark\">\n <span class=\"bi bi-plus-square-dotted\">\n </span> ADD row\n </button>\n </div>\n </div>\n </form>\n</div>" }, { "answer_id": 74530898, "author": "Kairav Thakar", "author_id": 20447312, "author_profile": "https://Stackoverflow.com/users/20447312", "pm_score": -1, "selected": true, "text": "Please check below working link for your question.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14820215/" ]
74,530,800
<p>I have a dataset (df3) with five columns x, y, r, g and b, although I only need to work with x, y and r. I want to find the average of all the consecutive rows in which the value of r is equal and store it in a database (df_final). To do this, I have generated a code that stores all the values in which r is equal to the one in previous row in a temporary database (df_inter), to later store the average of all the values in the final database (df_final). The code is this one:</p> <pre class="lang-py prettyprint-override"><code>d = {'x':[1,2,3,4,5,6,7],'y':[1,1,1,1,1,1,1],'r':[2,2,2,1,1,3,2]} df3 = pd.Dataframe(data=d) for i in range(len(df3)): if df3.iloc[i,3] == df3.iloc[i-1,3]: df_inter = pd.DataFrame(columns=['x','y', 'r']) df_inter.append(df3.iloc[i,1],df3.iloc[i,2],df3.iloc[i,3]) df_inter.to_csv(f'Resultados/df_inter.csv', index=False, sep=',') else: df_final.append(df_inter['x'].mean(),df_inter['y'].mean(),df_inter['r'].mean()) del [[df_inter]] gc.collect() df_inter=pd.DataFrame() df_inter = pd.DataFrame(columns=['x','y', 'r']) df_inter.append(df3.iloc[i,1],df3.iloc[i,2],df3.iloc[i,3]) df_final.to_csv(f'Resultados/df_final.csv', index=False, sep=',') </code></pre> <p>The objective is from a dataset for example like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x</th> <th>y</th> <th>r</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>2</td> </tr> <tr> <td>2</td> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>1</td> <td>2</td> </tr> <tr> <td>4</td> <td>1</td> <td>1</td> </tr> <tr> <td>5</td> <td>1</td> <td>1</td> </tr> <tr> <td>6</td> <td>1</td> <td>3</td> </tr> <tr> <td>7</td> <td>1</td> <td>2</td> </tr> </tbody> </table> </div> <p>Get something like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x</th> <th>y</th> <th>r</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>1</td> <td>2</td> </tr> <tr> <td>4.5</td> <td>1</td> <td>1</td> </tr> <tr> <td>6</td> <td>1</td> <td>3</td> </tr> <tr> <td>7</td> <td>1</td> <td>2</td> </tr> </tbody> </table> </div> <p>Nevertheless, when I execute the code I get this error message:</p> <pre><code>TypeError: cannot concatenate object of type '&lt;class 'numpy.int64'&gt;'; only Series and DataFrame objs are valid </code></pre> <p>I'm not sure what the problem is or even if there is a code more efficient for the purpose. Please, I would be grateful if you could help me. Thank you in advance.</p> <p>Irene</p> <hr /> <p>I solved it. The right code for my purpose would be:</p> <pre class="lang-py prettyprint-override"><code>d = {'x':[1,2,3,4,5,6,7],'y':[1,1,1,1,1,1,1],'r':[2,2,2,1,1,3,2]} df3 = pd.Dataframe(data=d) df_inter = pd.DataFrame(columns=['x','y', 'r']) df_final = pd.DataFrame(columns=['x','y','r']) for i in df3.index.values: if df3.iloc[i,2] == df3.iloc[i-1,2]: df_inter = df_inter.append({'x':df3.iloc[i,0],'y':df3.iloc[i,1],'r':df3.iloc[i,2]}, ignore_index=True) else: df_final = df_final.append({'x':df_inter['x'].mean(),'y':df_inter['y'].mean(),'r':df_inter['r'].mean()}, ignore_index=True) df_inter = pd.DataFrame(columns=['x','y', 'r']) df_inter = df_inter.append({'x':df3.iloc[i,0],'y':df3.iloc[i,1],'r':df3.iloc[i,2]}, ignore_index=True) df_final = df_final.append({'x':df_inter['x'].mean(),'y':df_inter['y'].mean(),'r':df_inter['r'].mean()}, ignore_index=True) df_final.to_csv(f'Resultados/df_final.csv', index=False, sep=',') </code></pre>
[ { "answer_id": 74530895, "author": "Carsten Løvbo Andersen", "author_id": 2943218, "author_profile": "https://Stackoverflow.com/users/2943218", "pm_score": 0, "selected": false, "text": "$(\".type\").change(function() { $(document).ready(function() {\n\n $(document).on(\"change\", \".type\", function() {\n var val = $(this).val();\n if (val == \"id\") {\n $(this).next(\".values\").html(\"<select><option>First option</option><option>Second Option</option></select>\");\n } else if (val == \"client\") {\n $(this).next(\".values\").html(\"<input value='Example input' />\");\n\n } else if (val == \"file\") {\n $(this).next(\".values\").html(\"normal text\");\n }\n });\n});\n\n$(\"#rowAdder\").click(function() {\n newRowAdd =\n '<div class=\"row\">' +\n '<div class=\"input-group m-3\">' +\n '<br /><select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\"><option>select one</option><option value=\"id\">ID:</option><option value=\"client\">Client:</option><option value=\"file\">File:</option></select>' +\n '&nbsp;&nbsp; with &nbsp;&nbsp;' +\n ' <div class=\"values\"></div>' +\n ' <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">' +\n ' <button class=\"btn btn-danger DeleteRow\"' +\n ' id=\"\" type=\"button\">' +\n ' <i class=\"bi bi-trash\"></i>' +\n ' Delete row' +\n ' </button> </div>' +\n '</div> </div>';\n\n $('#newinput').append(newRowAdd);\n});\n\n$(\"body\").on(\"click\", \".DeleteRow\", function() {\n $(this).closest(\".row\").remove();\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n<div style=\"width:100%;\">\n Replace:\n <form>\n <div class=\"\">\n <div class=\"col-lg-10\">\n <div class=\"row\">\n <div class=\"input-group m-3\">\n <select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\">\n <option>select one</option>\n <option value=\"id\">ID:</option>\n <option value=\"client\">Client:</option>\n <option value=\"file\">File:</option>\n </select>&nbsp;&nbsp; with &nbsp;&nbsp;\n <div class=\"values\"></div>\n <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">\n <button class=\"btn btn-danger DeleteRow\" id=\"\" type=\"button\">\n <i class=\"bi bi-trash\"></i>\n Delete row\n </button>\n </div>\n </div>\n </div>\n\n <div id=\"newinput\"></div>\n <br />\n <button id=\"rowAdder\" type=\"button\" class=\"btn btn-dark\">\n <span class=\"bi bi-plus-square-dotted\">\n </span> ADD row\n </button>\n </div>\n </div>\n </form>\n</div>" }, { "answer_id": 74530898, "author": "Kairav Thakar", "author_id": 20447312, "author_profile": "https://Stackoverflow.com/users/20447312", "pm_score": -1, "selected": true, "text": "Please check below working link for your question.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570777/" ]
74,530,809
<p>I have some code that creates several listeners. Thus I was thinking about adding a template that calls the notify on different types of listeners. However I am not sure how to call the member function (which all have different arguments) in a template. I am using C++17.</p> <pre><code>template &lt;class T&gt; void notifyListeners(std::vector&lt;T*&gt; listeners, std::function&lt;???&gt; memfunc) { // perhaps add a compile time check to see if memfunc exists for (auto&amp; listener : listeners) { listener-&gt;memfunc(); } } </code></pre> <p>For example I have two classes of listeners :</p> <pre><code>class IFooListener { void Foo(int, double, std::string); } class IBarListener { void Bar(std::string, std::string) } std::vector&lt;IFooListeners*&gt; fooListeners; std::vector&lt;IBarListeners*&gt; barListeners; </code></pre> <p>I would like to be able to do something like this:</p> <pre><code>notifyListeners(fooListeners, &amp;IFooListener::Foo, 1, 2.0, &quot;Bla&quot;); notifyListeners(barListeners, &amp;IBarListener::Bar, &quot;one&quot;, &quot;two&quot;); </code></pre> <p>How can this be done?</p>
[ { "answer_id": 74530895, "author": "Carsten Løvbo Andersen", "author_id": 2943218, "author_profile": "https://Stackoverflow.com/users/2943218", "pm_score": 0, "selected": false, "text": "$(\".type\").change(function() { $(document).ready(function() {\n\n $(document).on(\"change\", \".type\", function() {\n var val = $(this).val();\n if (val == \"id\") {\n $(this).next(\".values\").html(\"<select><option>First option</option><option>Second Option</option></select>\");\n } else if (val == \"client\") {\n $(this).next(\".values\").html(\"<input value='Example input' />\");\n\n } else if (val == \"file\") {\n $(this).next(\".values\").html(\"normal text\");\n }\n });\n});\n\n$(\"#rowAdder\").click(function() {\n newRowAdd =\n '<div class=\"row\">' +\n '<div class=\"input-group m-3\">' +\n '<br /><select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\"><option>select one</option><option value=\"id\">ID:</option><option value=\"client\">Client:</option><option value=\"file\">File:</option></select>' +\n '&nbsp;&nbsp; with &nbsp;&nbsp;' +\n ' <div class=\"values\"></div>' +\n ' <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">' +\n ' <button class=\"btn btn-danger DeleteRow\"' +\n ' id=\"\" type=\"button\">' +\n ' <i class=\"bi bi-trash\"></i>' +\n ' Delete row' +\n ' </button> </div>' +\n '</div> </div>';\n\n $('#newinput').append(newRowAdd);\n});\n\n$(\"body\").on(\"click\", \".DeleteRow\", function() {\n $(this).closest(\".row\").remove();\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\n<div style=\"width:100%;\">\n Replace:\n <form>\n <div class=\"\">\n <div class=\"col-lg-10\">\n <div class=\"row\">\n <div class=\"input-group m-3\">\n <select class=\"custom-select custom-select-sm type\" name=\"test\" id=\"\">\n <option>select one</option>\n <option value=\"id\">ID:</option>\n <option value=\"client\">Client:</option>\n <option value=\"file\">File:</option>\n </select>&nbsp;&nbsp; with &nbsp;&nbsp;\n <div class=\"values\"></div>\n <div class=\"input-group-prepend\" style=\"margin-left: 20px;\">\n <button class=\"btn btn-danger DeleteRow\" id=\"\" type=\"button\">\n <i class=\"bi bi-trash\"></i>\n Delete row\n </button>\n </div>\n </div>\n </div>\n\n <div id=\"newinput\"></div>\n <br />\n <button id=\"rowAdder\" type=\"button\" class=\"btn btn-dark\">\n <span class=\"bi bi-plus-square-dotted\">\n </span> ADD row\n </button>\n </div>\n </div>\n </form>\n</div>" }, { "answer_id": 74530898, "author": "Kairav Thakar", "author_id": 20447312, "author_profile": "https://Stackoverflow.com/users/20447312", "pm_score": -1, "selected": true, "text": "Please check below working link for your question.\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479628/" ]
74,530,814
<p>I have an array of objects whose ID is same but it contains the list of items which I want to merge in the same item. Below is the object I want the items of which to be merged on the basis of &quot;categoryID&quot;</p> <p>`</p> <pre><code>[ { &quot;addons&quot;: [ { &quot;addonId&quot;: &quot;Addon_5035fac357f446fb8b4fcff45d2e36e5&quot;, &quot;addonIdentifier&quot;: &quot;Gherkin&quot;, &quot;addonQuantity&quot;: 1, &quot;subTotal&quot;: 0.99, &quot;addonType&quot;: &quot;EXTRAS&quot; } ], &quot;categoryId&quot;: &quot;Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303&quot;, &quot;categoryIdentifier&quot;: &quot;Extra 1&quot; }, { &quot;addons&quot;: [ { &quot;addonId&quot;: &quot;Addon_700a1458fae54ba9b3e148da709eea4a&quot;, &quot;addonIdentifier&quot;: &quot;Hash Brown&quot;, &quot;addonQuantity&quot;: 1, &quot;subTotal&quot;: 0.99, &quot;addonType&quot;: &quot;EXTRAS&quot; } ], &quot;categoryId&quot;: &quot;Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303&quot;, &quot;categoryIdentifier&quot;: &quot;Extra 1&quot; }, { &quot;addons&quot;: [ { &quot;addonId&quot;: &quot;Addon_f4408295adb14723aa22a3a7e645a7a7&quot;, &quot;addonIdentifier&quot;: &quot;Cheese&quot;, &quot;addonQuantity&quot;: 1, &quot;subTotal&quot;: 0.99, &quot;addonType&quot;: &quot;EXTRAS&quot; } ], &quot;categoryId&quot;: &quot;Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303&quot;, &quot;categoryIdentifier&quot;: &quot;Extra 1&quot; } ] </code></pre> <p>In the Above example, as you can see that the categoryId of all the items is same, thus I want to merge all the items in one and create one list of &quot;Addons&quot;</p> <p>I have tried maps and group by but nothing has worked. Let me know if anything else is needed.</p> <p>Want to merge the list so that items with similar &quot;CategoryID&quot; be merged in single item while adding the list of &quot;Addons&quot; in that item.</p> <p>The resulting JSON should look like</p> <pre><code>[{ &quot;addons&quot;: [ { &quot;addonId&quot;: &quot;Addon_5035fac357f446fb8b4fcff45d2e36e5&quot;, &quot;addonIdentifier&quot;: &quot;Gherkin&quot;, &quot;addonQuantity&quot;: 1, &quot;subTotal&quot;: 0.99, &quot;addonType&quot;: &quot;EXTRAS&quot; }, { &quot;addonId&quot;: &quot;Addon_700a1458fae54ba9b3e148da709eea4a&quot;, &quot;addonIdentifier&quot;: &quot;Hash Brown&quot;, &quot;addonQuantity&quot;: 1, &quot;subTotal&quot;: 0.99, &quot;addonType&quot;: &quot;EXTRAS&quot; }, { &quot;addonId&quot;: &quot;Addon_f4408295adb14723aa22a3a7e645a7a7&quot;, &quot;addonIdentifier&quot;: &quot;Cheese&quot;, &quot;addonQuantity&quot;: 1, &quot;subTotal&quot;: 0.99, &quot;addonType&quot;: &quot;EXTRAS&quot; } ], &quot;categoryId&quot;: &quot;Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303&quot;, &quot;categoryIdentifier&quot;: &quot;Extra 1&quot;}] </code></pre>
[ { "answer_id": 74531855, "author": "AndrewL", "author_id": 1847378, "author_profile": "https://Stackoverflow.com/users/1847378", "pm_score": 1, "selected": false, "text": "import com.fasterxml.jackson.core.type.TypeReference\nimport com.fasterxml.jackson.databind.json.JsonMapper\nimport com.fasterxml.jackson.module.kotlin.KotlinModule\nimport java.math.BigDecimal\n\nfun main(args: Array<String>) {\n val mapper = JsonMapper.builder()\n .addModule(KotlinModule(strictNullChecks = true))\n .build()\n val categories: List<Category> = mapper.readValue(\n data,\n object : TypeReference<List<Category>>() {}\n )\n println(categories)\n val combinedCategories = categories\n .groupingBy { it.categoryId }\n .aggregate { key, accumulator: Category?, element: Category, first ->\n if(accumulator==null) {\n element\n }\n else {\n element.copy(\n addons = accumulator.addons.plus(element.addons)\n )\n }\n }\n .values.toList()\n combinedCategories.forEach { category -> println(category) }\n}\n\ndata class Category(\n val addons: List<AddOn>,\n val categoryId: String,\n val categoryIdentifier: String,\n)\n\ndata class AddOn(\n val addonId: String,\n val addonIdentifier: String,\n val addonQuantity: Int,\n val subTotal: BigDecimal,\n val addonType: String,\n)\n\nval data = \"\"\"\n [\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_5035fac357f446fb8b4fcff45d2e36e5\",\n \"addonIdentifier\": \"Gherkin\",\n \"addonQuantity\": 1,\n \"subTotal\": 0.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303\",\n \"categoryIdentifier\": \"Extra 1\"\n },\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_700a1458fae54ba9b3e148da709eea4a\",\n \"addonIdentifier\": \"Hash Brown\",\n \"addonQuantity\": 1,\n \"subTotal\": 0.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303\",\n \"categoryIdentifier\": \"Extra 1\"\n },\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_f4408295adb14723aa22a3a7e645a7a7\",\n \"addonIdentifier\": \"Cheese\",\n \"addonQuantity\": 1,\n \"subTotal\": 0.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303\",\n \"categoryIdentifier\": \"Extra 1\"\n },\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_2222222\",\n \"addonIdentifier\": \"Nuts\",\n \"addonQuantity\": 10,\n \"subTotal\": 9.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_222222\",\n \"categoryIdentifier\": \"Extra 2\"\n }\n ]\n\"\"\".trimIndent()\n groupingBy aggregate Category Category addons [Category(addons=[AddOn(addonId=Addon_5035fac357f446fb8b4fcff45d2e36e5, addonIdentifier=Gherkin, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1), Category(addons=[AddOn(addonId=Addon_700a1458fae54ba9b3e148da709eea4a, addonIdentifier=Hash Brown, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1), Category(addons=[AddOn(addonId=Addon_f4408295adb14723aa22a3a7e645a7a7, addonIdentifier=Cheese, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1), Category(addons=[AddOn(addonId=Addon_2222222, addonIdentifier=Nuts, addonQuantity=10, subTotal=9.99, addonType=EXTRAS)], categoryId=Addon_Cate_222222, categoryIdentifier=Extra 2)]\nCategory(addons=[AddOn(addonId=Addon_5035fac357f446fb8b4fcff45d2e36e5, addonIdentifier=Gherkin, addonQuantity=1, subTotal=0.99, addonType=EXTRAS), AddOn(addonId=Addon_700a1458fae54ba9b3e148da709eea4a, addonIdentifier=Hash Brown, addonQuantity=1, subTotal=0.99, addonType=EXTRAS), AddOn(addonId=Addon_f4408295adb14723aa22a3a7e645a7a7, addonIdentifier=Cheese, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1)\nCategory(addons=[AddOn(addonId=Addon_2222222, addonIdentifier=Nuts, addonQuantity=10, subTotal=9.99, addonType=EXTRAS)], categoryId=Addon_Cate_222222, categoryIdentifier=Extra 2)\n" }, { "answer_id": 74531882, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 2, "selected": true, "text": "data class Item(\n val addons: List<Addon>,\n val categoryId: String,\n val categoryIdentifier: String\n)\n // group as Id -> List<List<Addon>>, then flatten those lists into a single List<Addon>\nitems.groupBy({it.categoryId}, {it.addons})\n .mapValues { (_, addonLists) -> addonLists.flatten() }\n groupBy(keySelector, valueSelector) // turn each Item into a list of (Id, Addon) pairs then group those\nitems.flatMap { item ->\n item.addons.map { addon -> item.categoryId to addon }\n}.groupBy({it.first}, {it.second})\n // just make your own map - you could just use a for loop and add to a map too\nitems.fold(mutableMapOf<String, MutableList<Addon>>()) { groups, item ->\n groups.apply {\n getOrPut(item.categoryId) { mutableListOf() }\n .addAll(item.addons)\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15773565/" ]
74,530,837
<p>Im triying to change the source of a image with a js function but it seems to not work, the function executes on a mounted() of Framework7</p> <p>This is what i have right now</p> <p>HTML:</p> <pre><code>&lt;div&gt; &lt;span&gt; &lt;img id=&quot;star_1&quot; class=&quot;star&quot; src=&quot;../assets/empty_star.png&quot;&gt; &lt;/span&gt; &lt;span&gt; &lt;img id=&quot;star_2&quot; class=&quot;star&quot; src=&quot;../assets/empty_star.png&quot;&gt; &lt;/span&gt; &lt;span&gt; &lt;img id=&quot;star_3&quot; class=&quot;star&quot; src=&quot;../assets/empty_star.png&quot;&gt; &lt;/span&gt; &lt;span&gt; &lt;img id=&quot;star_4&quot; class=&quot;star&quot; src=&quot;../assets/empty_star.png&quot;&gt; &lt;/span&gt; &lt;span&gt; &lt;img id=&quot;star_5&quot; class=&quot;star&quot; src=&quot;../assets/empty_star.png&quot;&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code> setStars(){ var full_star = '../assets/full_star.svg'; document.getElementById('star_1').src = full_star; document.getElementById('star_2').src = full_star; document.getElementById('star_3').src = full_star; document.getElementById('star_4').src = full_star; document.getElementById('star_5').src = full_star; } </code></pre> <p>This keeps me the empty stars and i wanna change them depending of a rating, how can i fix it?</p> <p><img src="https://i.stack.imgur.com/I9viA.png" alt="Image of what im getting right now" /></p> <p>I also tryed to get the document.getElementById in var but still does not work</p>
[ { "answer_id": 74531855, "author": "AndrewL", "author_id": 1847378, "author_profile": "https://Stackoverflow.com/users/1847378", "pm_score": 1, "selected": false, "text": "import com.fasterxml.jackson.core.type.TypeReference\nimport com.fasterxml.jackson.databind.json.JsonMapper\nimport com.fasterxml.jackson.module.kotlin.KotlinModule\nimport java.math.BigDecimal\n\nfun main(args: Array<String>) {\n val mapper = JsonMapper.builder()\n .addModule(KotlinModule(strictNullChecks = true))\n .build()\n val categories: List<Category> = mapper.readValue(\n data,\n object : TypeReference<List<Category>>() {}\n )\n println(categories)\n val combinedCategories = categories\n .groupingBy { it.categoryId }\n .aggregate { key, accumulator: Category?, element: Category, first ->\n if(accumulator==null) {\n element\n }\n else {\n element.copy(\n addons = accumulator.addons.plus(element.addons)\n )\n }\n }\n .values.toList()\n combinedCategories.forEach { category -> println(category) }\n}\n\ndata class Category(\n val addons: List<AddOn>,\n val categoryId: String,\n val categoryIdentifier: String,\n)\n\ndata class AddOn(\n val addonId: String,\n val addonIdentifier: String,\n val addonQuantity: Int,\n val subTotal: BigDecimal,\n val addonType: String,\n)\n\nval data = \"\"\"\n [\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_5035fac357f446fb8b4fcff45d2e36e5\",\n \"addonIdentifier\": \"Gherkin\",\n \"addonQuantity\": 1,\n \"subTotal\": 0.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303\",\n \"categoryIdentifier\": \"Extra 1\"\n },\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_700a1458fae54ba9b3e148da709eea4a\",\n \"addonIdentifier\": \"Hash Brown\",\n \"addonQuantity\": 1,\n \"subTotal\": 0.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303\",\n \"categoryIdentifier\": \"Extra 1\"\n },\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_f4408295adb14723aa22a3a7e645a7a7\",\n \"addonIdentifier\": \"Cheese\",\n \"addonQuantity\": 1,\n \"subTotal\": 0.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303\",\n \"categoryIdentifier\": \"Extra 1\"\n },\n {\n \"addons\": [\n {\n \"addonId\": \"Addon_2222222\",\n \"addonIdentifier\": \"Nuts\",\n \"addonQuantity\": 10,\n \"subTotal\": 9.99,\n \"addonType\": \"EXTRAS\"\n }\n ],\n \"categoryId\": \"Addon_Cate_222222\",\n \"categoryIdentifier\": \"Extra 2\"\n }\n ]\n\"\"\".trimIndent()\n groupingBy aggregate Category Category addons [Category(addons=[AddOn(addonId=Addon_5035fac357f446fb8b4fcff45d2e36e5, addonIdentifier=Gherkin, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1), Category(addons=[AddOn(addonId=Addon_700a1458fae54ba9b3e148da709eea4a, addonIdentifier=Hash Brown, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1), Category(addons=[AddOn(addonId=Addon_f4408295adb14723aa22a3a7e645a7a7, addonIdentifier=Cheese, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1), Category(addons=[AddOn(addonId=Addon_2222222, addonIdentifier=Nuts, addonQuantity=10, subTotal=9.99, addonType=EXTRAS)], categoryId=Addon_Cate_222222, categoryIdentifier=Extra 2)]\nCategory(addons=[AddOn(addonId=Addon_5035fac357f446fb8b4fcff45d2e36e5, addonIdentifier=Gherkin, addonQuantity=1, subTotal=0.99, addonType=EXTRAS), AddOn(addonId=Addon_700a1458fae54ba9b3e148da709eea4a, addonIdentifier=Hash Brown, addonQuantity=1, subTotal=0.99, addonType=EXTRAS), AddOn(addonId=Addon_f4408295adb14723aa22a3a7e645a7a7, addonIdentifier=Cheese, addonQuantity=1, subTotal=0.99, addonType=EXTRAS)], categoryId=Addon_Cate_1a7bacd1a07b40ceb7d5d3a2229fb303, categoryIdentifier=Extra 1)\nCategory(addons=[AddOn(addonId=Addon_2222222, addonIdentifier=Nuts, addonQuantity=10, subTotal=9.99, addonType=EXTRAS)], categoryId=Addon_Cate_222222, categoryIdentifier=Extra 2)\n" }, { "answer_id": 74531882, "author": "cactustictacs", "author_id": 13598222, "author_profile": "https://Stackoverflow.com/users/13598222", "pm_score": 2, "selected": true, "text": "data class Item(\n val addons: List<Addon>,\n val categoryId: String,\n val categoryIdentifier: String\n)\n // group as Id -> List<List<Addon>>, then flatten those lists into a single List<Addon>\nitems.groupBy({it.categoryId}, {it.addons})\n .mapValues { (_, addonLists) -> addonLists.flatten() }\n groupBy(keySelector, valueSelector) // turn each Item into a list of (Id, Addon) pairs then group those\nitems.flatMap { item ->\n item.addons.map { addon -> item.categoryId to addon }\n}.groupBy({it.first}, {it.second})\n // just make your own map - you could just use a for loop and add to a map too\nitems.fold(mutableMapOf<String, MutableList<Addon>>()) { groups, item ->\n groups.apply {\n getOrPut(item.categoryId) { mutableListOf() }\n .addAll(item.addons)\n }\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15766722/" ]
74,530,847
<p><a href="https://i.stack.imgur.com/QZCmm.png" rel="nofollow noreferrer">enter image description here</a></p> <p>This can anyone explain me this logic.</p> <p>Here the answer I get is the actual answer which I want but I want to know the proper working flow behind this pattern.</p> <p>THANKS</p>
[ { "answer_id": 74531189, "author": "Dhruv Sakariya", "author_id": 13387235, "author_profile": "https://Stackoverflow.com/users/13387235", "pm_score": 1, "selected": false, "text": " Your for loop will run for 10 times from 0-9.\nthen inside your for loop you inserted the color.\nthen your if condition states that when there is even place print white \nelse black.(i%2==0 means even)\n" }, { "answer_id": 74531405, "author": "Dhruv Sakariya", "author_id": 13387235, "author_profile": "https://Stackoverflow.com/users/13387235", "pm_score": 0, "selected": false, "text": "if (i%2==0)\n{\n print\"Black\"\n} else { \n print\"White\"\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19236970/" ]
74,530,862
<p>I am using confd based Netconf agent. When I checked the XML payload received by the agent, I see a number prefixed in the payload. It is not message-id. What is this prefix? Please give any RFC reference which explains the prefix.</p> <p>For example, &quot;#164&quot; is prefixed with the get-config payload.</p> <pre><code>#164 &lt;?xml version=\&quot;1.0\&quot; encoding=\&quot;UTF-8\&quot;?&gt; &lt;rpc message-id=\&quot;0\&quot; xmlns=\&quot;urn:ietf:params:xml:ns:netconf:base:1.0\&quot;&gt; &lt;get-config&gt; &lt;source&gt; &lt;running/&gt; &lt;/source&gt; &lt;/get-config&gt; &lt;/rpc&gt; </code></pre> <p>Similarly, different prefixes are used for the other Netconf operation as listed below.</p> <pre><code>get 118 close-session 128 lock 154 unlock 158 delete-config 172 edit-config 190 copy-config 193 </code></pre>
[ { "answer_id": 74531189, "author": "Dhruv Sakariya", "author_id": 13387235, "author_profile": "https://Stackoverflow.com/users/13387235", "pm_score": 1, "selected": false, "text": " Your for loop will run for 10 times from 0-9.\nthen inside your for loop you inserted the color.\nthen your if condition states that when there is even place print white \nelse black.(i%2==0 means even)\n" }, { "answer_id": 74531405, "author": "Dhruv Sakariya", "author_id": 13387235, "author_profile": "https://Stackoverflow.com/users/13387235", "pm_score": 0, "selected": false, "text": "if (i%2==0)\n{\n print\"Black\"\n} else { \n print\"White\"\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20372664/" ]
74,530,881
<p>Lets say we have the following arrays.</p> <p><code>[1,2]</code> &amp; <code>[1,2,3]</code> &amp; <code>[1,2,3,4]</code></p> <p>Then let's say we want to loop through all <em><strong>unique</strong></em> possible combinations of this.</p> <p>The results should look something like this.</p> <pre><code> // IP1 IP2 IP3 //0 0 - 0 - 0 //1 0 - 0 - 1 //2 0 - 0 - 2 //3 0 - 0 - 3 //4 0 - 1 - 0 //5 0 - 1 - 1 //6 0 - 1 - 2 //7 0 - 1 - 3 //8 0 - 2 - 0 //9 0 - 2 - 1 //10 0 - 2 - 2 //11 0 - 2 - 3 //12 1 - 0 - 0 //13 1 - 0 - 1 //14 1 - 0 - 2 //15 1 - 0 - 3 //16 1 - 1 - 0 //17 1 - 1 - 1 //18 1 - 1 - 2 //19 1 - 1 - 3 //20 1 - 2 - 0 //21 1 - 2 - 1 //22 1 - 2 - 2 //23 1 - 2 - 3 </code></pre> <p>It should produce 24 different combinations that are unique.</p> <p>I can generate an array like this using the following cartersian function.</p> <pre><code>function cartesian() { console.log(&quot;Running cartesian()...&quot;); var r = [], arg = arguments, max = arg.length-1; function helper(arr, i) { try{ for (var j=0, l=arg[i].length; j&lt;l; j++) { var a = arr.slice(0); // clone arr a.push(arg[i][j]) if (i==max) { r.push(a); } else helper(a, i+1); } }catch(error){ console.log(error); } } helper([], 0); return r; }; </code></pre> <p>You would call this array something like this cartesian(...array_of_arrays) which uses the spread operator to send each array in the array as an argument.</p> <p>The problem with this method is this uses a <strong>large memory footprint</strong>. If the arrays start to exceed in the millions of values my applications start <em><strong>running out of memory</strong></em> and crashing. So while I could use this and simply just point to an index and know what my values would be in the Cartesian array I can't do this with large arrays.</p> <p>My goal is if I choose a number like <code>14</code> for the index that it will return an array with the values <code>[1,0,2]</code> but <strong>without creating the array</strong> to know this to save on memory.</p> <p>I created another interesting scenario to show how this might be possible. Let's say I have 3 arrays <code>[1,2]</code> &amp; <code>[1,2]</code> &amp; <code>[1,2]</code>. Now every combination might look like below.</p> <pre><code> // IP1 IP2 IP3 //0 0 - 0 - 0 //1 0 - 0 - 1 //2 0 - 1 - 0 //3 0 - 1 - 1 //4 1 - 0 - 0 //5 1 - 0 - 1 //6 1 - 1 - 0 //7 1 - 1 - 1 </code></pre> <p>Technically if we use number 5 we could assume the binary form of it and read the bits.</p> <p>This would tell us that for iteration 5 without knowing anything else that simply by it being the number 5 that the resultant array has a <code>[1,0,1]</code> which is the <strong>binary representation of 5 ironically enough</strong>. So if I had an array of nothing but pairs this technique could be used perhaps. Maybe this is a clue to how to solve this though.</p> <p>I'm not sure what to do <strong>when the arrays are varying sizes</strong> and not always binary pairs?</p> <p><strong>To be clear I need a function that does not take an array, but instead is given 'start', 'end' &amp; 'step' and can deduce from these what the array returned value would be from an index.</strong></p> <p>Something like: <code>cartesianElementPosition([[start,end,step],[start,end,step],[start,end,step]],14)</code> and this should return <code>[1,0,2]</code> from my example with the 24 possibilities where start end step are the <strong>rules describing how the arrays would</strong> be create<strong>d without actually creating it</strong></p> <p>What is the best way to approach this?</p>
[ { "answer_id": 74531506, "author": "R4ncid", "author_id": 14326899, "author_profile": "https://Stackoverflow.com/users/14326899", "pm_score": 2, "selected": true, "text": "const cartesianElementPosition = (data, position) => {\n\n const arrayLengths = data.map(([start, end, step]) => Math.floor((end - start) / step) + 1)\n\n const positions = arrayLengths.reduceRight((pos, l) => {\n const newRemain = Math.floor(pos.remain / l)\n\n return {\n result: [ pos.remain % l, ...pos.result],\n remain: newRemain\n }\n }, {\n result: [],\n remain: position\n })\n\n return positions.result\n}\n\nlet data = [\n [1, 2, 1],\n [10, 12, 1],\n [0.86, 0.89, 0.01]\n];\nconsole.log(cartesianElementPosition(data, 14)) class LazyArray {\n constructor(\n start,\n end,\n step\n ) {\n this.start = start;\n this.end = end;\n this.step = step;\n this.length = Math.floor((end - start) / step) + 1\n }\n element(position) {\n if (position < 0 || postition >= this.length()) {\n throw new Error('out of index')\n }\n return this.step * this.position + this.start;\n }\n\n}\n\n\n\nconst cartesianPositionAt = (data, pos) => {\n\n const arrayLengths = data.map(d => new LazyArray(...d).length)\n\n const positions = arrayLengths.reduceRight((pos, l) => {\n const newRemain = Math.floor(pos.remain / l)\n\n return {\n result: [pos.remain % l, ...pos.result],\n remain: newRemain\n }\n }, {\n result: [],\n remain: pos\n })\n\n return positions.result\n}\n\n\n\nlet data = [\n [1, 2, 1],\n [10, 12, 1],\n [0.86, 0.89, 0.01]\n];\nlet result = cartesianPositionAt(data, 14);\nconsole.log(\"result below\");\nconsole.log(result);" }, { "answer_id": 74542586, "author": "Joseph Astrahan", "author_id": 1606689, "author_profile": "https://Stackoverflow.com/users/1606689", "pm_score": 0, "selected": false, "text": "function cartesianPositionAt(arraysOfSES,position){\n let arraySizes = [];\n let returnArray = [];\n \n for(let i=0;i<arraysOfSES.length;i++){\n let end = arraysOfSES[i][1];\n let start = arraysOfSES[i][0];\n let step = arraysOfSES[i][2];\n let maxIterationsOfInput = parseInt((( end - start) / step + 1).toFixed(2))\n arraySizes.push(maxIterationsOfInput);\n }\n \n function recurse(r_arraySizes,r_position){\n if(r_arraySizes.length>1){\n var block_size=r_arraySizes.slice(-1)[0];\n for(let j=r_arraySizes.length;j>2;j--){\n block_size = block_size * r_arraySizes[j-2];\n }\n returnArray.push(0);//@JA - Assume skip value 0\n \n while(r_position>=block_size){\n r_position = r_position - block_size\n returnArray[returnArray.length-1] = returnArray[returnArray.length-1] +1\n }\n \n r_arraySizes.shift()//remove the first item in the array.\n recurse(r_arraySizes,r_position);\n }else{ //Final section of array to process\n returnArray.push(r_position);\n }\n }\n \n recurse(arraySizes,position);\n return returnArray\n}\n//[start,end,step]\nlet data = [[1,2,1],[10,12,1],[0.86,0.89,0.01]];\nlet result = cartesianPositionAt(data,14);\nconsole.log(\"result below\");\nconsole.log(result);" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1606689/" ]
74,530,916
<p><a href="https://codesandbox.io/s/little-thunder-so1omh?file=/src/menu/menu.scss" rel="nofollow noreferrer">https://codesandbox.io/s/little-thunder-so1omh?file=/src/menu/menu.scss</a></p> <p>this is my problem. when I refresh, menu opens and closes for a moment</p> <p>I want to prevent this from re-render. this my console.log when i refresh every time:</p> <blockquote> <p>false 'open'<br /> menu.jsx:23 item<br /> menu.jsx:25 rerendered<br /> menu.jsx:22 true 'open'<br /> menu.jsx:23 undefined 'item'<br /> menu.jsx:25 rerendered</p> </blockquote>
[ { "answer_id": 74531434, "author": "Devendra Kushwaha", "author_id": 15267060, "author_profile": "https://Stackoverflow.com/users/15267060", "pm_score": 0, "selected": false, "text": "https://codesandbox.io/s/eager-microservice-b7p4gc?file=/src/menu/menu.scss\n" }, { "answer_id": 74531465, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 2, "selected": true, "text": " // this is a flag to detect atleast one click \n // on the menu item\n // this will be false when app loads the first time\n // then after user click on the menu, it will set to true\n let isSelectedOnce = React.useRef(false);\n\n const handleDropDown = (id) => {\n setItemPressed(id);\n if (itemPressed !== id) {\n setOpen(true);\n } else {\n setOpen((pre) => !pre);\n }\n if (!isSelectedOnce.current) {\n isSelectedOnce.current = true;\n }\n };\n\n return (\n ...\n <ul\n className={`collapse ${\n open && itemPressed === \"menu\" ? \"show\" : \"\"\n } ${!isSelectedOnce.current ? \"hidden\" : \"\"}`}\n >\n <li>Menu Category</li>\n <li>products list</li>\n <li>Add product</li>\n </ul>\n </li>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19450127/" ]
74,530,930
<p>I want custom object in response of API having [required] data annotation on model properties like this:</p> <pre><code>{ &quot;resourceType&quot;: &quot;OperationOutcome&quot;, &quot;issue&quot;: [ { &quot;severity&quot;: &quot;fatal&quot;, &quot;code&quot;: &quot;required&quot;, &quot;location&quot;: [ &quot;/f:AllergyIntolerance/f:status&quot; ] } ] } </code></pre> <p>Is it possible to do it or I would have to code it.</p> <p>Because model validation happens before action is called, is there any way I can do it?</p>
[ { "answer_id": 74531434, "author": "Devendra Kushwaha", "author_id": 15267060, "author_profile": "https://Stackoverflow.com/users/15267060", "pm_score": 0, "selected": false, "text": "https://codesandbox.io/s/eager-microservice-b7p4gc?file=/src/menu/menu.scss\n" }, { "answer_id": 74531465, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 2, "selected": true, "text": " // this is a flag to detect atleast one click \n // on the menu item\n // this will be false when app loads the first time\n // then after user click on the menu, it will set to true\n let isSelectedOnce = React.useRef(false);\n\n const handleDropDown = (id) => {\n setItemPressed(id);\n if (itemPressed !== id) {\n setOpen(true);\n } else {\n setOpen((pre) => !pre);\n }\n if (!isSelectedOnce.current) {\n isSelectedOnce.current = true;\n }\n };\n\n return (\n ...\n <ul\n className={`collapse ${\n open && itemPressed === \"menu\" ? \"show\" : \"\"\n } ${!isSelectedOnce.current ? \"hidden\" : \"\"}`}\n >\n <li>Menu Category</li>\n <li>products list</li>\n <li>Add product</li>\n </ul>\n </li>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14210566/" ]
74,530,958
<p>It is one of the first times I am using boost and I am getting an error saying</p> <p><code>BaseKey boost::bimaps::container_adaptor::detail::key_to_base_identity&lt;BaseKey,KeyType&gt;::operator ()(Key &amp;) const': cannot convert argument 1 from 'const CompatibleKey' to 'Key &amp;</code></p> <p>and</p> <p><code>boost::multi_index::detail::ordered_index_impl&lt;KeyFromValue,Compare,SuperMeta,TagList,Category, AugmentPolicy&gt;::find': no matching overloaded function found</code></p> <p>I know most of the STL errors or at least where could they come from, but I am not experienced enough with boost to know what could be going on here. The code I have is the following, it is used to convert the values from an enum to strings and vice versa.</p> <p>file.h</p> <pre><code>namespace FOO_NS::BAR_NS { class FooClass { public: enum class Enum { Enum1, Enum2, Enum3, Enum4 }; ... }; namespace { using results_bimap = boost::bimap&lt;FooClass::Enum, std::string&gt;; using position = results_bimap::value_type; const auto EnumsAsStrings = []() { results_bimap result; result.insert(position(FooClass::Enum::Enum1, &quot;Enum1&quot;)); result.insert(position(FooClass::Enum::Enum2, &quot;Enum2&quot;)); result.insert(position(FooClass::Enum::Enum3, &quot;Enum3&quot;)); result.insert(position(FooClass::Enum::Enum4, &quot;Enum4&quot;)); return result; }; } // namespace }//namespace FOO_NS::BAR_NS </code></pre> <p>file.cpp</p> <pre><code>using namespace FOO_NS::BAR_NS; void doSmth() { ... std::string enumString = EnumsAsStrings().left.at(FooClass::Enum::Enum1); // Expected string &quot;Enum1&quot; } </code></pre> <p>Do you see any misconception or misusage I have in this code so that this mentioned error happens?</p>
[ { "answer_id": 74531434, "author": "Devendra Kushwaha", "author_id": 15267060, "author_profile": "https://Stackoverflow.com/users/15267060", "pm_score": 0, "selected": false, "text": "https://codesandbox.io/s/eager-microservice-b7p4gc?file=/src/menu/menu.scss\n" }, { "answer_id": 74531465, "author": "Azzy", "author_id": 2122822, "author_profile": "https://Stackoverflow.com/users/2122822", "pm_score": 2, "selected": true, "text": " // this is a flag to detect atleast one click \n // on the menu item\n // this will be false when app loads the first time\n // then after user click on the menu, it will set to true\n let isSelectedOnce = React.useRef(false);\n\n const handleDropDown = (id) => {\n setItemPressed(id);\n if (itemPressed !== id) {\n setOpen(true);\n } else {\n setOpen((pre) => !pre);\n }\n if (!isSelectedOnce.current) {\n isSelectedOnce.current = true;\n }\n };\n\n return (\n ...\n <ul\n className={`collapse ${\n open && itemPressed === \"menu\" ? \"show\" : \"\"\n } ${!isSelectedOnce.current ? \"hidden\" : \"\"}`}\n >\n <li>Menu Category</li>\n <li>products list</li>\n <li>Add product</li>\n </ul>\n </li>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20053601/" ]
74,530,966
<p>I'm trying to clean up the results presented on my HTML file with Jquery. I want to keep removing words that are repeated more than one time.</p> <p>A quick example</p> <pre><code>Accents Australian Accents English (RP) Dance Hip Hop Dance Jazz </code></pre> <p>It should be output as</p> <p>Accents</p> <ul> <li>Australian</li> <li>English (RP)</li> </ul> <p>Dance</p> <ul> <li>Hip Hop</li> <li>Jazz</li> </ul> <p>My original HTML looks like this</p> <pre><code>&lt;div role=&quot;list&quot; class=&quot;skill-items&quot;&gt; &lt;div role=&quot;listitem&quot; class=&quot;skill-item&quot;&gt; &lt;div class=&quot;skill-category&quot;&gt;Accents&lt;/div&gt; &lt;div&gt;Australian&lt;/div&gt; &lt;/div&gt; &lt;div role=&quot;listitem&quot; class=&quot;skill-item&quot;&gt; &lt;div class=&quot;skill-category&quot;&gt;Accents&lt;/div&gt; &lt;div&gt;English (RP)&lt;/div&gt; &lt;/div&gt; &lt;div role=&quot;listitem&quot; class=&quot;skill-item&quot;&gt; &lt;div class=&quot;skill-category&quot;&gt;Dance&lt;/div&gt; &lt;div&gt;Hip Hop&lt;/div&gt; &lt;/div&gt; &lt;div role=&quot;listitem&quot; class=&quot;skill-item&quot;&gt; &lt;div class=&quot;skill-category&quot;&gt;Dance&lt;/div&gt; &lt;div&gt;Jaz&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I tried my best but I'm not landing in a good place</p> <pre><code>$('.skill-category').text(function(index, oldText) { return oldText.replace($(this).parent().next().find('.skill-category').text(), ''); }) </code></pre> <p>Any suggestion?</p>
[ { "answer_id": 74531159, "author": "Kairav Thakar", "author_id": 20447312, "author_profile": "https://Stackoverflow.com/users/20447312", "pm_score": 2, "selected": false, "text": " const category = [...document.querySelectorAll('.skill-item > .skill-category')];\nconst texts = new Set(category.map(x => x.innerHTML));\ncategory.forEach(category => {\n if(texts.has(category.innerHTML)){\n texts.delete(category.innerHTML);\n }\n else{\n category.remove()\n }\n})\n" }, { "answer_id": 74535998, "author": "RickN", "author_id": 316310, "author_profile": "https://Stackoverflow.com/users/316310", "pm_score": 0, "selected": false, "text": ".skill-category <div> .skill-category <div> <div> <li> <li> <div> <ul> <li>s .skill-category <div> <li> <li>s <ul> <div>(s) <ul> .skill-category // Grouping the results.\n$('.skill-category').each(function() {\n // Get the previous .skill-item and find the category.\n var prev = $(this).parent().prev('.skill-item').find('.skill-category');\n // Check if the previous category === this category.\n var same = !!(prev.length && prev.text() === $(this).text());\n if (!same) {\n return; // Do nothing.\n }\n // Take every element after the category and move it to the\n // previous .skill-item.\n prev.after($(this).nextAll());\n // Then remove the now-empty category.\n // All content has been moved to the previous element, after all.\n $(this).parent().remove();\n});\n\n// Wrapping the contents of a category in a list.\n$('.skill-category').each(function() {\n var list = $('<ul></ul');\n // Find everything after the category.\n $(this).nextAll().each(function() {\n // Create a <li> and move the child elements to it.\n // Then add the <li> to the <ul>.\n $('<li></li>').append($(this).contents()).appendTo(list);\n }).remove(); // remove the now empty elements.\n // Add the list to current .skill-category.\n $(this).append(list);\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div role=\"list\" class=\"skill-items\">\n <div role=\"listitem\" class=\"skill-item\">\n <div class=\"skill-category\">Accents</div>\n <div>Australian</div>\n </div>\n <div role=\"listitem\" class=\"skill-item\">\n <div class=\"skill-category\">Accents</div>\n <div>English (RP)</div>\n </div>\n <div role=\"listitem\" class=\"skill-item\">\n <div class=\"skill-category\">Dance</div>\n <div>Hip Hop</div>\n </div>\n <div role=\"listitem\" class=\"skill-item\">\n <div class=\"skill-category\">Dance</div>\n <div>Jaz</div>\n </div>\n</div>" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3521090/" ]
74,530,977
<p>I have a table containing timeseries data and want to select a number of rows based on some &quot;first&quot; criteria as well as those with timestamps close to those select based on the first criteria.</p> <p>Example table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ts</th> <th>val</th> </tr> </thead> <tbody> <tr> <td>2022-11-01 09:55:00</td> <td>1</td> </tr> <tr> <td>2022-11-01 09:55:57</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:00:00</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:00:10</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:00:20</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:00:25</td> <td>2</td> </tr> <tr> <td>2022-11-01 10:00:30</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:00:57</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:20:15</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:20:35</td> <td>5</td> </tr> <tr> <td>2022-11-01 10:20:55</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:21:01</td> <td>1</td> </tr> <tr> <td>2022-11-01 10:21:30</td> <td>1</td> </tr> </tbody> </table> </div> <p>From this table, I want to <code>SELECT * FROM table WHERE val &gt; 1</code> plus any rows with <code>ts</code> close to those rows, for example a) within +/- 30 second time difference or b) within the same &quot;absolute&quot; minute (e.g. from second 00 of the minute of the timestamp until second 59.</p> <p>So as a result of option a), I would like to get:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ts</th> <th>val</th> <th>comment</th> </tr> </thead> <tbody> <tr> <td>2022-11-01 10:00:00</td> <td>1</td> <td>Data within 30 s of 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:10</td> <td>1</td> <td>Data within 30 s of 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:20</td> <td>1</td> <td>Data within 30 s of 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:25</td> <td>2</td> <td>Data within 30 s of 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:30</td> <td>1</td> <td>Data within 30 s of 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:20:15</td> <td>1</td> <td>Data within 30 s of 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:20:35</td> <td>5</td> <td>Data within 30 s of 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:20:55</td> <td>1</td> <td>Data within 30 s of 2022-11-01 10:20:35</td> </tr> </tbody> </table> </div> <p>or in case of option b), So as a result of option a), I would like to get:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ts</th> <th>val</th> <th>comment</th> </tr> </thead> <tbody> <tr> <td>2022-11-01 10:00:00</td> <td>1</td> <td>Same minute as 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:10</td> <td>1</td> <td>Same minute as 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:20</td> <td>1</td> <td>Same minute as 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:25</td> <td>2</td> <td>Same minute as 2022-11-01 10:00:25</td> </tr> <tr> <td>2022-11-01 10:00:30</td> <td>1</td> <td>Same minute as 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:00:57</td> <td>1</td> <td>Same minute as 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:20:15</td> <td>1</td> <td>Same minute as 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:20:35</td> <td>5</td> <td>Same minute as 2022-11-01 10:20:35</td> </tr> <tr> <td>2022-11-01 10:20:55</td> <td>1</td> <td>Same minute as 2022-11-01 10:20:35</td> </tr> </tbody> </table> </div> <p>I tried to get option a) working using a subquery and <code>DATEDIFF</code>, but it seems this won't work because it's not possible to use <code>DATEDIFF</code> and such functions on subqueries. This is the query I tried:</p> <pre><code>SELECT * FROM table t WHERE ABS(DATEDIFF(second, t.ts, (SELECT ts FROM table WHERE val &gt; 1))) &lt;= 30 </code></pre> <p>What's the best way to get this working only using SQL and for large tables?</p>
[ { "answer_id": 74531457, "author": "QueryingQuail", "author_id": 20173417, "author_profile": "https://Stackoverflow.com/users/20173417", "pm_score": 0, "selected": false, "text": "DATEDIFF CREATE TABLE events (\n event_ts DATETIME,\n event_value INTEGER\n);\n INSERT INTO events VALUES\n ('2022-11-01 10:00:00', 1),\n ('2022-11-01 10:00:10', 1),\n ('2022-11-01 10:00:20', 1),\n ('2022-11-01 10:00:25', 2),\n ('2022-11-01 10:00:30', 1),\n ('2022-11-01 10:00:55', 1),\n ('2022-11-01 10:20:15', 1),\n ('2022-11-01 10:20:35', 5),\n ('2022-11-01 10:20:55', 1),\n ('2022-11-01 10:30:55', 6)\n WITH events_filtered AS (\n SELECT *\n FROM events\n WHERE event_value > 1\n)\n\nSELECT\n *,\n DATEDIFF(mi, e1.event_ts, e2.event_ts) AS event_minute_difference\nFROM events_filtered AS e1\nINNER JOIN events_filtered AS e2\nON e1.event_ts < e2.event_ts\n" }, { "answer_id": 74537213, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 3, "selected": true, "text": "ts select t.*\nfrom t\nwhere exists (\n select * from t t2\n cross apply (values(\n case when val > 1 then DateAdd(second, -30, ts) end,\n case when val > 1 then DateAdd(second, 30, ts) end)\n )r(rmin,rmin)\n where t.ts >= rmin and t.ts <= rmin\n) order by ts;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1299769/" ]
74,530,984
<p>I want to enable my users to set certain global colors when using the app. Therefor I have created a 'dynamicVariables.css' file:</p> <pre><code> :root { --my-color: violet; } </code></pre> <p>It is imported in 'global.scss' file:</p> <pre><code>@import &quot;./theme/dynamicVariables.css&quot;; </code></pre> <p>Also, I've added a colorpicker on one page and I can set the --my-color variable fine from there.</p> <pre><code> onColorChange(data: any) { document.documentElement.style.setProperty('--my-color', data); } </code></pre> <p>Just when closing the app on my device (I've deployed it with <em>ionic capacitor run android</em>), it resets the css variable, because when I run it again the color is back to its default value.</p> <p>I'm pretty sure, I have a general misconception here and would be grateful for some clarification. I'm generally new to web development and would be grateful for any help.</p> <p>Thanks in advance.</p>
[ { "answer_id": 74531457, "author": "QueryingQuail", "author_id": 20173417, "author_profile": "https://Stackoverflow.com/users/20173417", "pm_score": 0, "selected": false, "text": "DATEDIFF CREATE TABLE events (\n event_ts DATETIME,\n event_value INTEGER\n);\n INSERT INTO events VALUES\n ('2022-11-01 10:00:00', 1),\n ('2022-11-01 10:00:10', 1),\n ('2022-11-01 10:00:20', 1),\n ('2022-11-01 10:00:25', 2),\n ('2022-11-01 10:00:30', 1),\n ('2022-11-01 10:00:55', 1),\n ('2022-11-01 10:20:15', 1),\n ('2022-11-01 10:20:35', 5),\n ('2022-11-01 10:20:55', 1),\n ('2022-11-01 10:30:55', 6)\n WITH events_filtered AS (\n SELECT *\n FROM events\n WHERE event_value > 1\n)\n\nSELECT\n *,\n DATEDIFF(mi, e1.event_ts, e2.event_ts) AS event_minute_difference\nFROM events_filtered AS e1\nINNER JOIN events_filtered AS e2\nON e1.event_ts < e2.event_ts\n" }, { "answer_id": 74537213, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 3, "selected": true, "text": "ts select t.*\nfrom t\nwhere exists (\n select * from t t2\n cross apply (values(\n case when val > 1 then DateAdd(second, -30, ts) end,\n case when val > 1 then DateAdd(second, 30, ts) end)\n )r(rmin,rmin)\n where t.ts >= rmin and t.ts <= rmin\n) order by ts;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16975737/" ]
74,530,987
<p>When I am using this command to build the ios ipa file:</p> <pre><code>➜ ios git:(master) ✗ ~/fvm/versions/2.5.0/bin/flutter build ipa Changing current working directory to: /Users/xiaoqiangjiang/source/reddwarf/frontend/flutter-netease-music Archiving com.reddwarf.musicapp... Automatically signing iOS for device deployment using specified development team in Xcode project: 6JP4P88ZJB Running pod install... 960ms Running Xcode build... └─Compiling, linking and signing... 4.7s Xcode archive done. 40.8s Built /Users/xiaoqiangjiang/source/reddwarf/frontend/flutter-netease-music/build/ios/archive/Runner.xcarchive. Building with sound null safety </code></pre> <p>I did not found the ipa file in the build folder. what should I do to generate the ipa file? The log output did not show any error, did not show the ipa file path. I found the flutter archive option are unavaliable:</p> <p><a href="https://i.stack.imgur.com/ierNc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ierNc.png" alt="enter image description here" /></a></p> <p>I have already tried to add the <code>info.plist</code> file in <code>${PROJECT}/ios/Runner/Info.plist</code>:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt; &lt;plist version=&quot;1.0&quot;&gt; &lt;dict&gt; &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt; &lt;string&gt;$(DEVELOPMENT_LANGUAGE)&lt;/string&gt; &lt;key&gt;CFBundleDisplayName&lt;/key&gt; &lt;string&gt;Music&lt;/string&gt; &lt;key&gt;CFBundleExecutable&lt;/key&gt; &lt;string&gt;$(EXECUTABLE_NAME)&lt;/string&gt; &lt;key&gt;CFBundleIdentifier&lt;/key&gt; &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt; &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt; &lt;string&gt;6.0&lt;/string&gt; &lt;key&gt;CFBundleName&lt;/key&gt; &lt;string&gt;dolphin&lt;/string&gt; &lt;key&gt;CFBundlePackageType&lt;/key&gt; &lt;string&gt;APPL&lt;/string&gt; &lt;key&gt;CFBundleShortVersionString&lt;/key&gt; &lt;string&gt;$(FLUTTER_BUILD_NAME)&lt;/string&gt; &lt;key&gt;CFBundleSignature&lt;/key&gt; &lt;string&gt;????&lt;/string&gt; &lt;key&gt;CFBundleVersion&lt;/key&gt; &lt;string&gt;$(FLUTTER_BUILD_NUMBER)&lt;/string&gt; &lt;key&gt;LSRequiresIPhoneOS&lt;/key&gt; &lt;true/&gt; &lt;key&gt;NSAppTransportSecurity&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;key&gt;UIBackgroundModes&lt;/key&gt; &lt;array&gt; &lt;string&gt;audio&lt;/string&gt; &lt;string&gt;bluetooth-central&lt;/string&gt; &lt;string&gt;bluetooth-peripheral&lt;/string&gt; &lt;string&gt;external-accessory&lt;/string&gt; &lt;string&gt;fetch&lt;/string&gt; &lt;string&gt;location&lt;/string&gt; &lt;string&gt;processing&lt;/string&gt; &lt;string&gt;remote-notification&lt;/string&gt; &lt;string&gt;voip&lt;/string&gt; &lt;/array&gt; &lt;key&gt;UILaunchStoryboardName&lt;/key&gt; &lt;string&gt;LaunchScreen&lt;/string&gt; &lt;key&gt;UIMainStoryboardFile&lt;/key&gt; &lt;string&gt;Main&lt;/string&gt; &lt;key&gt;UISupportedInterfaceOrientations&lt;/key&gt; &lt;array&gt; &lt;string&gt;UIInterfaceOrientationPortrait&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationLandscapeLeft&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationLandscapeRight&lt;/string&gt; &lt;/array&gt; &lt;key&gt;UISupportedInterfaceOrientations~ipad&lt;/key&gt; &lt;array&gt; &lt;string&gt;UIInterfaceOrientationPortrait&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationPortraitUpsideDown&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationLandscapeLeft&lt;/string&gt; &lt;string&gt;UIInterfaceOrientationLandscapeRight&lt;/string&gt; &lt;/array&gt; &lt;key&gt;UIViewControllerBasedStatusBarAppearance&lt;/key&gt; &lt;false/&gt; &lt;key&gt;CADisableMinimumFrameDurationOnPhone&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre> <p>and when I using the xcode 14.1 to archive the app, it works but could not build the app with the flutter command.</p>
[ { "answer_id": 74531457, "author": "QueryingQuail", "author_id": 20173417, "author_profile": "https://Stackoverflow.com/users/20173417", "pm_score": 0, "selected": false, "text": "DATEDIFF CREATE TABLE events (\n event_ts DATETIME,\n event_value INTEGER\n);\n INSERT INTO events VALUES\n ('2022-11-01 10:00:00', 1),\n ('2022-11-01 10:00:10', 1),\n ('2022-11-01 10:00:20', 1),\n ('2022-11-01 10:00:25', 2),\n ('2022-11-01 10:00:30', 1),\n ('2022-11-01 10:00:55', 1),\n ('2022-11-01 10:20:15', 1),\n ('2022-11-01 10:20:35', 5),\n ('2022-11-01 10:20:55', 1),\n ('2022-11-01 10:30:55', 6)\n WITH events_filtered AS (\n SELECT *\n FROM events\n WHERE event_value > 1\n)\n\nSELECT\n *,\n DATEDIFF(mi, e1.event_ts, e2.event_ts) AS event_minute_difference\nFROM events_filtered AS e1\nINNER JOIN events_filtered AS e2\nON e1.event_ts < e2.event_ts\n" }, { "answer_id": 74537213, "author": "Stu", "author_id": 15332650, "author_profile": "https://Stackoverflow.com/users/15332650", "pm_score": 3, "selected": true, "text": "ts select t.*\nfrom t\nwhere exists (\n select * from t t2\n cross apply (values(\n case when val > 1 then DateAdd(second, -30, ts) end,\n case when val > 1 then DateAdd(second, 30, ts) end)\n )r(rmin,rmin)\n where t.ts >= rmin and t.ts <= rmin\n) order by ts;\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2628868/" ]
74,530,988
<p>I want to add an icon next to the labels in my interface below :</p> <p><a href="https://i.stack.imgur.com/h9PYP.png" rel="nofollow noreferrer">actuel interface</a></p> <p>The problem is when I add the icon right to my labels, my interface changes and become like this :</p> <p><a href="https://i.stack.imgur.com/7YUFt.png" rel="nofollow noreferrer">interface after adding icons</a></p> <p>Is there anyway to add icons and conserve the same actual interface? I would appraciate some help, here is my code :</p> <pre><code>&lt;tr&gt; &lt;td className=&quot;name&quot;&gt;Critère d'agrégation&lt;/td&gt; &lt;td className=&quot;value column-2&quot;&gt; {aggregationDomain.map(codedValue =&gt; &lt;div className='blockTooltip'&gt; &lt;label className = {!config?.aggregationEnabled.includes(codedValue.code) ? 'text-gray' : ''} &gt; &lt;input type=&quot;radio&quot; name=&quot;AggregationSelection&quot; value={codedValue.code} checked={props.reportConfig.aggregation === codedValue.code} onChange={updateAggregation} disabled={!config?.aggregationEnabled.includes(codedValue.code)} /&gt; {codedValue.name} &lt;/label&gt; &lt;div className='svgTooltip'&gt; &lt;svg className='svgTooltipIcon' xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 512 512&quot; width='13' height='13'&gt;&lt;path d=&quot;M256 512c141.4 0 256-114.6 256-256S397.4 0 256 0S0 114.6 0 256S114.6 512 256 512zM216 336h24V272H216 192V224h24 48 24v24 88h8 24v48H296 216 192V336h24zm72-144H224V128h64v64z&quot;/&gt;&lt;/svg&gt; &lt;/div&gt; &lt;/div&gt; )} &lt;/td&gt; &lt;/tr&gt; </code></pre>
[ { "answer_id": 74531017, "author": "yo_sup", "author_id": 20538807, "author_profile": "https://Stackoverflow.com/users/20538807", "pm_score": 1, "selected": false, "text": ".blockTooltip {\n display: flex;\n flex-direction: row;\n gap: 10px;\n}\n" }, { "answer_id": 74531041, "author": "leo", "author_id": 16552231, "author_profile": "https://Stackoverflow.com/users/16552231", "pm_score": 0, "selected": false, "text": "blockTooltip" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74530988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16230569/" ]
74,531,014
<p>I have a model with a list of products. Each product has an ID, price, brand, etc. I want return all the objects of the model where brand name is distinct. I am currently using django's built-in SQLite, so it does not support something like</p> <pre><code>products = Product.objects.all().distinct('brand') </code></pre> <p>Is there another way of returning all the objects where the brand name is distinct?</p>
[ { "answer_id": 74531171, "author": "Ajay K", "author_id": 10782096, "author_profile": "https://Stackoverflow.com/users/10782096", "pm_score": -1, "selected": false, "text": "products = set(Product.objects.values_list('brand'))\n" }, { "answer_id": 74531273, "author": "Naser Fazal khan", "author_id": 19313399, "author_profile": "https://Stackoverflow.com/users/19313399", "pm_score": 0, "selected": false, "text": "query = \"\"\"\n SELECT DISTINCT brand FROM Product;\n \"\"\"\nself.execute(query)\n" }, { "answer_id": 74531290, "author": "Yevhen Kuzmovych", "author_id": 4727702, "author_profile": "https://Stackoverflow.com/users/4727702", "pm_score": 3, "selected": true, "text": ".distinct('field') products = list({p.brand: p for p in Product.objects.all()}.values())\n" }, { "answer_id": 74531340, "author": "White Wizard", "author_id": 9366059, "author_profile": "https://Stackoverflow.com/users/9366059", "pm_score": 0, "selected": false, "text": "distinctBrands = Product.objects.values('brand').annotate(count=Count('brand')).filter(count=1)\n\nproducts = Products.objects.filter(\n brand__in=distinctBrands \n).all()\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3085213/" ]
74,531,047
<p>I am using apex from oracle for learning PL/SQL for last 10 days. At a sudden, I wrote a code to take some inputs from user. `</p> <pre><code>declare a number; begin a := &amp;x; dbms_output.put_line(a*6); end; </code></pre> <p>` it is throwing some errors.&gt;&gt;ORA-06550</p> <p>I am expected to take user input from it. As Pl/sql is not that famous, there are very li'l stuffs available about it.</p>
[ { "answer_id": 74531225, "author": "Koen Lostrie", "author_id": 4189814, "author_profile": "https://Stackoverflow.com/users/4189814", "pm_score": 0, "selected": false, "text": "koen >set serveroutput on \nkoen >declare \n 2 a number;\n 3 begin\n 4 a := &x;\n 5 dbms_output.put_line(a*6); \n 6 end; \n 7* /\nEnter value for x: 5\nold:declare \n a number;\nbegin\n a := &x;\n dbms_output.put_line(a*6); \nend;\n\nnew:declare \n a number;\nbegin\n a := 5;\n dbms_output.put_line(a*6); \nend;\n30\n\n\nPL/SQL procedure successfully completed.\n\nkoen >\n" }, { "answer_id": 74531257, "author": "Littlefoot", "author_id": 9097906, "author_profile": "https://Stackoverflow.com/users/9097906", "pm_score": 1, "selected": false, "text": "SQL> set serveroutput on\nSQL> declare\n 2 a number;\n 3 begin\n 4 a := &x;\n 5 dbms_output.put_line(a*6);\n 6 end;\n 7 /\nEnter value for x: 4\nold 4: a := &x;\nnew 4: a := 4;\n24\n\nPL/SQL procedure successfully completed.\n\nSQL>\n declare \n a number;\nbegin\n a := :x; --> this\n dbms_output.put_line(a*6); \nend; \n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16772593/" ]
74,531,051
<p>In Python, I was using Spacy library there was trying below commands:-</p> <p><code>import spacy</code></p> <p>Getting Below Error</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'spacy' </code></pre> <p>Then tried to install spacy using below command:-</p> <p><code>pip install spacy</code></p> <p>Message:</p> <p>It gives Requirement already satisfied.</p> <p>Commands Used :-</p> <pre><code>import spacy pip install spacy </code></pre>
[ { "answer_id": 74531127, "author": "Gandhi", "author_id": 16977407, "author_profile": "https://Stackoverflow.com/users/16977407", "pm_score": 0, "selected": false, "text": "pip install -U spacy python -m spacy download en_core_web_sm" }, { "answer_id": 74531132, "author": "sogu", "author_id": 10270590, "author_profile": "https://Stackoverflow.com/users/10270590", "pm_score": 0, "selected": false, "text": "pip install -U pip setuptools wheel\npip install -U spacy\npython -m spacy download en_core_web_sm\n pip uninstall spacy" }, { "answer_id": 74531195, "author": "Mohammad Mufassir Khan", "author_id": 13589242, "author_profile": "https://Stackoverflow.com/users/13589242", "pm_score": -1, "selected": false, "text": "!pip install spacy" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20571220/" ]
74,531,081
<p>Since 19 november 2022 apt-get update on Debian 8 Jessie gives the follwowing error/warning when running apt-get update:</p> <pre><code>W: GPG error: http://archive.debian.org jessie Release: The following signatures were invalid: KEYEXPIRED 1587841717 </code></pre> <p>The contents of my /etc/apt/sources.list:</p> <pre><code>deb http://archive.debian.org/debian/ jessie main contrib non-free deb http://deb.freexian.com/extended-lts jessie-lts main contrib non-free </code></pre> <p>The expired keys: <code>apt-key list</code></p> <pre><code>/etc/apt/trusted.gpg.d/debian-archive-jessie-automatic.gpg pub 4096R/2B90D010 2014-11-21 [expired: 2022-11-19] uid Debian Archive Automatic Signing Key (8/jessie) &lt;ftpmaster@debian.org&gt; /etc/apt/trusted.gpg.d/debian-archive-jessie-security-automatic.gpg pub 4096R/C857C906 2014-11-21 [expired: 2022-11-19] uid Debian Security Archive Automatic Signing Key (8/jessie) &lt;ftpmaster@debian.org&gt; </code></pre> <p>I have the debian-archive-keyring package installed.</p> <p>I tried to update the keys, using:</p> <pre><code>gpg --keyserver keyring.debian.org --recv-key 2B90D010 gpg --keyserver keyring.debian.org --recv-key C857C906 </code></pre> <p>But these keys do not seem to be known on keyring.debian.org:</p> <pre><code>gpg: requesting key 2B90D010 from hkp server keyring.debian.org gpgkeys: key 2B90D010 can't be retrieved gpg: no valid OpenPGP data found. gpg: Total number processed: 0 gpg: requesting key C857C906 from hkp server keyring.debian.org gpgkeys: key C857C906 can't be retrieved gpg: no valid OpenPGP data found. gpg: Total number processed: 0` </code></pre> <p>So I suppose my questions are:</p> <p>All keys on the archive.debian.org site are expired.</p> <ol> <li>Am I trying to update the keys against the correct keyserver (keyring.debian.org)?</li> <li>If that is not the issue, then will somebody at Debian fix this (update and publish keys)?</li> <li>If no, then is there a way to get rid of the warnings when <code>apt-get update</code> and <code>apt-get install</code> are run?</li> </ol>
[ { "answer_id": 74558753, "author": "Reyn4ld", "author_id": 4215114, "author_profile": "https://Stackoverflow.com/users/4215114", "pm_score": 1, "selected": false, "text": "debian:jessie debian/eol:jessie" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20570778/" ]
74,531,104
<p>I have a dimension table with column A, B, C, D, E. And I create the start model to link column A to Table A, column B to table B, column C to table C, column D to table D, column E to table E. The 5 columns doesn't follow the hierarchy structure. And I need to create the slicers for each column based on the dimension table.</p> <p>The data example distribution is:</p> <pre><code>A1, B1, C1, D1, E1 A1, B2, C3, D3, E2 A2, B2, C2, D2, E3 A2, B3, C2, D3, E4 </code></pre> <p>The slicer A may first have value A1, A2, and then if the user select A1, the slicer B may just provide choice B1 &amp; B2 (B3 may be trimmed due to slicer A). How could I achieve this with each slicer change due to the up level slicers?</p> <p>Actually I create a measure count for the table and add the the filter with condition &gt; 0 for each slicer. This works at the beginning, but due to the single select setting for the slicer, after all the slicers have been selected, there is no choice to change for all the slicers.</p> <p>What I want is that slicer A may contains choice A1, A2, and for slicer B if slicer select A1 then it will provide choice B1, B2. And if slicer B select B2 then slicer C have option C2, C3, etc. How could I achieve? Thanks.</p>
[ { "answer_id": 74533267, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 0, "selected": false, "text": "Table A = VALUES(MainTable[A])\nTable B = VALUES(MainTable[B])\nTable C = VALUES(MainTable[C])\nTable D = VALUES(MainTable[D])\nTable E = DISTINCT(MainTable[E])\n" }, { "answer_id": 74534043, "author": "Marcus", "author_id": 16528000, "author_profile": "https://Stackoverflow.com/users/16528000", "pm_score": 1, "selected": false, "text": "Table A Table B DISTINCT Table A = DISTINCT ( 'Table'[A] )\nTable B = DISTINCT ( 'Table'[B] )\n Table Table A Table B Table A Table B Table Table Slicer Filter = \nIF ( COUNTROWS ( 'Table' ) > 0 , 1 )\n Table B Table B Table A1 A2 Table A Table B" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266554/" ]
74,531,114
<p>I have created 5 columns for storing some data, but when the text inside one column is too long, the width will be changed.</p> <p>Expect: The word will wrap to next line and each column width should stay the same.</p> <p><a href="https://playcode.io/1017243" rel="nofollow noreferrer">https://playcode.io/1017243</a></p>
[ { "answer_id": 74533267, "author": "Ozan Sen", "author_id": 19469088, "author_profile": "https://Stackoverflow.com/users/19469088", "pm_score": 0, "selected": false, "text": "Table A = VALUES(MainTable[A])\nTable B = VALUES(MainTable[B])\nTable C = VALUES(MainTable[C])\nTable D = VALUES(MainTable[D])\nTable E = DISTINCT(MainTable[E])\n" }, { "answer_id": 74534043, "author": "Marcus", "author_id": 16528000, "author_profile": "https://Stackoverflow.com/users/16528000", "pm_score": 1, "selected": false, "text": "Table A Table B DISTINCT Table A = DISTINCT ( 'Table'[A] )\nTable B = DISTINCT ( 'Table'[B] )\n Table Table A Table B Table A Table B Table Table Slicer Filter = \nIF ( COUNTROWS ( 'Table' ) > 0 , 1 )\n Table B Table B Table A1 A2 Table A Table B" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18689387/" ]
74,531,115
<p>is there any way to get $('#div') inside callback function? $('#div') changes</p> <pre><code>var param = { a: 'haha' } $('#div').load('/foo.html', param, foo()) function foo() { var div = caller? // this variable should be &quot;$('#div')[0]&quot; } </code></pre>
[ { "answer_id": 74531333, "author": "freedomn-m", "author_id": 2181514, "author_profile": "https://Stackoverflow.com/users/2181514", "pm_score": 1, "selected": false, "text": "this .load $('#div').load('/foo.html', param, function() { $(this).show() })\n var fooResult = foo();\n$('#div').load('/foo.html', param, fooResult);\n" }, { "answer_id": 74531398, "author": "mli", "author_id": 17839690, "author_profile": "https://Stackoverflow.com/users/17839690", "pm_score": 0, "selected": false, "text": "this var $div = $(this); // the jQuery object representing the div\nvar div = this; // the HTMLElement representing the div\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3471346/" ]
74,531,133
<p>Is it possible to call a global variable that is defined in the function from outside of the function in JavaScript? For example, I can print the selected item in the console.log that is located within the function. However, if I try to fetch the same value outside of the function, it's not working. Is there anyway to fetch the value defined within a function outside the function?</p> <pre><code>var selectedItem = ''; document.getElementById('select-option').addEventListener('change', function () { //re-assign a new value to the variable selectedItem = this.value; // working consol.log('Selected Item:', selectedItem); }); // not working console.log('Selected Item:', selectedItem); </code></pre>
[ { "answer_id": 74531289, "author": "David Fontes", "author_id": 11755228, "author_profile": "https://Stackoverflow.com/users/11755228", "pm_score": 0, "selected": false, "text": "// 1. This happens first, you initialize your variable in the global scope.\nvar selectedItem = '';\n\n// 2. Next you add an event listener to your HTML element (the actual event will come later)\ndocument.getElementById('select-option').addEventListener('change', function () {\n // 4. You set a new value to the variable in the global scope\n selectedItem = this.value;\n consol.log('Selected Item:', selectedItem); \n});\n\n// 3. You are logging the variable before the event has occurred, therefor, the variable is still empty.\nconsole.log('Selected Item:', selectedItem);\n setInterval // Point 3.\nsetInterval(() => {\n console.log('Selected Item:', selectedItem);\n}, 1000);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17670715/" ]
74,531,141
<p>I have onClick event and I'm calling a function i.e handleFunc(). handleFunc() includes if statement with count value. If count value is 0 then i call function1(). If count value is 1 then it calls function1() and function2(). If count value is 2 the it calls function1 (), function2(), function3(). But based on count value when i call more then 1 function then it's not working i mean functions are not called.</p> <p>Here is code I'm approaching</p> <pre><code>const function1 = () = { // Block of code } const function2 = () = { // Block of code } const function3 = () = { // Block of code } // A function invoke other functions const handleFunc = ()=&gt; { if( count === 0 ) { function1() } if( count === 1 ){ function1 (); function2(); } if( count === 2 ) { function1 (); function2 (); function3(); } } return ( &lt;&gt; // button &lt;button onClick={handleFunc ()}&gt; Call function&lt;/button&gt; &lt;/&gt; ) </code></pre> <p>My query is how to have multiple functions in if statement and on each click, call function one after another. Any suggestions please</p>
[ { "answer_id": 74531289, "author": "David Fontes", "author_id": 11755228, "author_profile": "https://Stackoverflow.com/users/11755228", "pm_score": 0, "selected": false, "text": "// 1. This happens first, you initialize your variable in the global scope.\nvar selectedItem = '';\n\n// 2. Next you add an event listener to your HTML element (the actual event will come later)\ndocument.getElementById('select-option').addEventListener('change', function () {\n // 4. You set a new value to the variable in the global scope\n selectedItem = this.value;\n consol.log('Selected Item:', selectedItem); \n});\n\n// 3. You are logging the variable before the event has occurred, therefor, the variable is still empty.\nconsole.log('Selected Item:', selectedItem);\n setInterval // Point 3.\nsetInterval(() => {\n console.log('Selected Item:', selectedItem);\n}, 1000);\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20338321/" ]
74,531,160
<p><strong>this is the cypress test file</strong></p> <pre><code>import { Given, Then } from &quot;cypress-cucumber-preprocessor/steps&quot;; import { quickSignIn } from &quot;../../../support/services/commonServices&quot;; import { storyTableViewResultColumnCheck } from &quot;../../../support/services/calculationStoryService&quot;; Given('Logged into the application', () =&gt; { quickSignIn(Cypress.env('username'), Cypress.env('password')); }); Then('navigate to the story', () =&gt; { storyTableViewResultColumnCheck(); }); </code></pre> <p><strong>this is calculationStoryService.js file</strong></p> <pre><code>export function storyTableViewResultColumnCheck() { const stories = getAllCalculationStoriesFromExcel(); // return undefined value expect(stories).not.to.be.undefined cy.log(&quot;method - storyTableViewResultColumnCheck&quot;,stories) } function getAllCalculationStoriesFromExcel() { cy.task(&quot;getExcelData&quot;, Cypress.env(&quot;calculationRelatedStoryPath&quot;)).then((stories) =&gt; { console.log(stories) // in here print all the stories without any issue. return stories; }); } </code></pre> <p>when calling the &quot;getAllCalculationStoriesFromExcel&quot; method inside the &quot;storyTableViewResultColumnCheck&quot; method, it always returns undefined value. but console log inside the &quot;<strong>then</strong>&quot; block in the &quot;getAllCalculationStoriesFromExcel&quot; method print all the stories to the console.</p> <p>I want to know how to return a value once cy.task is completed</p> <p><a href="https://i.stack.imgur.com/dQMEh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dQMEh.png" alt="enter image description here" /></a></p>
[ { "answer_id": 74531485, "author": "Mikhail Bolotov", "author_id": 13109074, "author_profile": "https://Stackoverflow.com/users/13109074", "pm_score": 0, "selected": false, "text": "cy.task return then function getAllCalculationStoriesFromExcel() {\n return cy.task(\"getExcelData\", Cypress.env(\"calculationRelatedStoryPath\")).then((stories) => {\n console.log(stories) // in here print all the stories without any issue. \n return stories;\n });\n }\nexport function storyTableViewResultColumnCheck() {\n getAllCalculationStoriesFromExcel().then(stories => {\n expect(stories).not.to.be.undefined\n cy.log(\"method - storyTableViewResultColumnCheck\",stories)\n })\n}\n" }, { "answer_id": 74539354, "author": "TesterDick", "author_id": 18366749, "author_profile": "https://Stackoverflow.com/users/18366749", "pm_score": 1, "selected": false, "text": "export async function storyTableViewResultColumnCheck() {\n const stories = await getAllCalculationStoriesFromExcel(); \n expect(stories).not.to.be.undefined\n cy.log(\"method - storyTableViewResultColumnCheck\",stories)\n}\n \nfunction getAllCalculationStoriesFromExcel() {\n return new Promise(resolve => {\n cy.task(\"getExcelData\", Cypress.env(\"calculationRelatedStoryPath\"))\n .then((stories) => resolve(stories))\n })\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13246500/" ]
74,531,190
<p>I'm trying to build a validation attribute that will validate the size of a collection, I want the method to be able to handle reference types like string and also non reference types like int. I tried to use <code>IEnumerable&lt;object&gt;</code> but that stays null in case I pass a <code>IEnumerable&lt;int&gt;</code>.</p> <p>This is my current code -</p> <pre><code>[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public class EnumerableSizeAttribute : ValidationAttribute&lt;IEnumerable&lt;object&gt;&gt; { protected override ValidationResult? IsValid(IEnumerable&lt;object&gt;? enumerable, ValidationContext validationContext) { //check collection size } } </code></pre> <p>What should I use as parameter to allow me to pass any collection type into the method? Thanks for the help!</p>
[ { "answer_id": 74531361, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "IEnumerable<T> IEnumerable IList ICollection .Count IEnumerable" }, { "answer_id": 74531553, "author": "Panagiotis Kanavos", "author_id": 134204, "author_profile": "https://Stackoverflow.com/users/134204", "pm_score": 2, "selected": false, "text": "[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]\npublic class EnumerableSizeAttribute<T> : ValidationAttribute<IEnumerable<T>>\n{\n \n protected override ValidationResult? IsValid(IEnumerable<T>? enumerable, ValidationContext validationContext)\n {\n //check collection size\n }\n}\n IsValid enumerable ICollection<T> Count if(enumerable is ICollection<T> col && col.Count <...)\n{\n \n}\n if(enumerable is ICollection<T> {Count: < MaxLength} col)\n{\n \n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19442297/" ]
74,531,221
<p>I have an AppModule, in which i lazy load MainModule and which lazy loads HomeModule.</p> <p>MainModule is loads fine, but HomeModule is loaded, but not rendered inside router-outlet. If i load it without lazy loading, it works.</p> <p>How can i make lazy loaded HomeModule render?</p> <p>I've created a Stackblitz <a href="https://stackblitz.com/edit/angular-ivy-x1gcfr?file=src/app/app.module.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ivy-x1gcfr?file=src/app/app.module.ts</a></p> <p><strong>app.module.ts</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; const routes: Routes = [ { path: '', loadChildren: () =&gt; import('./main/main.module').then(m =&gt; m.MainModule), }, ]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes) ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } </code></pre> <p><strong>app.component.ts</strong></p> <pre><code>import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `&lt;router-outlet&gt;&lt;/router-outlet&gt;` }) export class AppComponent { } </code></pre> <p><strong>main.module.ts</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { MainComponent } from './main.component'; // import { HomeComponent } from '../home/home.component'; const routes: Routes = [ { path: '', component: MainComponent, children: [ { path: '', loadChildren: () =&gt; import('../home/home.module').then(m =&gt; m.HomeModule), // Loaded but not rendered // component: HomeComponent, // It works }, ], }, ]; @NgModule({ declarations: [MainComponent], imports: [CommonModule, RouterModule.forChild(routes)], }) export class MainModule {} </code></pre> <p><strong>main.component.ts</strong></p> <pre><code>import { Component } from '@angular/core'; @Component({ template: `Header &lt;router-outlet&gt;&lt;/router-outlet&gt; Footer` }) export class MainComponent { } </code></pre> <p><strong>home.module.ts</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home.component'; @NgModule({ declarations: [ HomeComponent ], imports: [ CommonModule ] }) export class HomeModule { } </code></pre> <p><strong>home.component.ts</strong></p> <pre><code>import { Component } from '@angular/core'; @Component({ template: `&lt;p&gt;Home component works!!!&lt;/p&gt;` }) export class HomeComponent { } </code></pre>
[ { "answer_id": 74531361, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "IEnumerable<T> IEnumerable IList ICollection .Count IEnumerable" }, { "answer_id": 74531553, "author": "Panagiotis Kanavos", "author_id": 134204, "author_profile": "https://Stackoverflow.com/users/134204", "pm_score": 2, "selected": false, "text": "[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]\npublic class EnumerableSizeAttribute<T> : ValidationAttribute<IEnumerable<T>>\n{\n \n protected override ValidationResult? IsValid(IEnumerable<T>? enumerable, ValidationContext validationContext)\n {\n //check collection size\n }\n}\n IsValid enumerable ICollection<T> Count if(enumerable is ICollection<T> col && col.Count <...)\n{\n \n}\n if(enumerable is ICollection<T> {Count: < MaxLength} col)\n{\n \n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14246269/" ]
74,531,279
<p>I'm trying to make this <a href="https://codepen.io/bramus/embed/ExaEqMJ?height=687&amp;theme-id=default&amp;default-tab=result&amp;user=bramus&amp;slug-hash=ExaEqMJ&amp;pen-title=Smooth%20Scrolling%20Sticky%20ScrollSpy%20Navigation&amp;name=cp_embed_4#result-box" rel="nofollow noreferrer">Smooth Scrolling Navigation</a> work in Svelte. But still, have this TypeScript error <strong>object is possibly 'null'.ts(2531)</strong>. I realized that this error is because TypeScript thinks that this element may have a value of null. So I have to declare what is this element with an <code>if</code> statement or use the exclamation mark operator <code>!</code> (like this is not null). I've tried numerous possibilities for both solutions but still without success.</p> <p><a href="https://svelte.dev/repl/7006d7890b964928b8f72622a3d067ac?version=3.42.5" rel="nofollow noreferrer">REPL</a> of full code in svelte, where is visible that <code>IntersectionObserver</code>doesn't work.</p> <pre><code>&lt;script&gt; import { onMount } from 'svelte'; let id; onMount(() =&gt; { const observer = new IntersectionObserver((entries) =&gt; { entries.forEach((entry) =&gt; { id = entry.target.getAttribute('id'); if (entry.intersectionRatio &gt; 0) { document.querySelector(`nav li a[href=&quot;#${id}&quot;]`) //error .parentElement //error .classList .add('active'); } else { document.querySelector(`nav li a[href=&quot;#${id}&quot;]`) //error .parentElement //error .classList .remove('active'); }; }); document.querySelectorAll('section[id]').forEach((section) =&gt; { observer.observe(section); }); }); }); &lt;/script&gt; </code></pre> <p>Original code is from <a href="https://www.bram.us/" rel="nofollow noreferrer">Bram</a>. Thanks for sharing.</p>
[ { "answer_id": 74531361, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "IEnumerable<T> IEnumerable IList ICollection .Count IEnumerable" }, { "answer_id": 74531553, "author": "Panagiotis Kanavos", "author_id": 134204, "author_profile": "https://Stackoverflow.com/users/134204", "pm_score": 2, "selected": false, "text": "[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]\npublic class EnumerableSizeAttribute<T> : ValidationAttribute<IEnumerable<T>>\n{\n \n protected override ValidationResult? IsValid(IEnumerable<T>? enumerable, ValidationContext validationContext)\n {\n //check collection size\n }\n}\n IsValid enumerable ICollection<T> Count if(enumerable is ICollection<T> col && col.Count <...)\n{\n \n}\n if(enumerable is ICollection<T> {Count: < MaxLength} col)\n{\n \n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15594352/" ]
74,531,286
<p>My output looks like that, but isn't my code bad practice? Is there a way to replace the for with numpy functions?</p> <pre><code>[[ 1. 1.5 2. 2.5 3. ] [ 3.5 4. 4.5 5. 5.5] [ 6. 6.5 7. 7.5 8. ] [ 8.5 9. 9.5 10. 10.5] [11. 11.5 12. 12.5 13. ] [13.5 14. 14.5 15. 15.5] [16. 16.5 17. 17.5 18. ] [18.5 19. 19.5 20. 20.5]] </code></pre> <pre><code>import numpy as np list = [] x = 0.5 for i in range(8): temp = [] list.append(temp) for j in range(5): x += 0.5 temp.append(x) array = np.array(list) </code></pre>
[ { "answer_id": 74531358, "author": "Ftagliacarne", "author_id": 4470987, "author_profile": "https://Stackoverflow.com/users/4470987", "pm_score": 2, "selected": false, "text": "np.arange arr = np.arange(1,21,0.5).reshape((8,5))\n" }, { "answer_id": 74531360, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "numpy.arange reshape n, m = 8, 5\nstart = 0.5\nstep = 0.5\n\nout = np.arange(start+step, start+step*(n*m+1), step).reshape(n, m)\n array([[ 1. , 1.5, 2. , 2.5, 3. ],\n [ 3.5, 4. , 4.5, 5. , 5.5],\n [ 6. , 6.5, 7. , 7.5, 8. ],\n [ 8.5, 9. , 9.5, 10. , 10.5],\n [11. , 11.5, 12. , 12.5, 13. ],\n [13.5, 14. , 14.5, 15. , 15.5],\n [16. , 16.5, 17. , 17.5, 18. ],\n [18.5, 19. , 19.5, 20. , 20.5]])\n" }, { "answer_id": 74531363, "author": "Victor", "author_id": 5372398, "author_profile": "https://Stackoverflow.com/users/5372398", "pm_score": 0, "selected": false, "text": "import numpy as np\nx = 0.5\n\narray = np.zeros((8,5))\nfor i in range(8):\n for j in range(5):\n x += 0.5\n array[i,j] = x\n" }, { "answer_id": 74531522, "author": "IAmParadox", "author_id": 13765172, "author_profile": "https://Stackoverflow.com/users/13765172", "pm_score": 0, "selected": false, "text": "np.arange range np.array([*range(10, 41*5+1, 5)]).reshape(8,5) / 10\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15488393/" ]
74,531,297
<p>I want to draw a table widget in my screen. This is my code:</p> <pre><code>body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: &lt;Widget&gt;[ Container( padding: const EdgeInsets.all(10), alignment: Alignment.center, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.grey.shade400, border: Border.all( color: Colors.black, // Set border color width: 1.5), // Set border width ), child: const Text(&quot;EMPLOYEE DETAILS&quot;,style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Lobster')), ), Container( margin: const EdgeInsets.all(20), alignment: Alignment.center, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.blue.shade300, border: Border.all( color: Colors.black, // Set border color width: 1.0), // Set border width ), child:Table( border: TableBorder.all( color: Colors.black, style: BorderStyle.solid, width: 2), children: [ TableRow( children: [ Column(children:const [Text('Employee No')]), Column(children:const [Text('NULL')]), ]), TableRow( children: [ Column(children:const [Text('Employee Name')]), Column(children:const [Text('NULL')]), ]), TableRow( children: [ Column(children:const [Text('Designation')]), Column(children:const [Text('NULL')]), ]), TableRow( children: [ Column(children:const [Text('Department')]), Column(children:const [Text('NULL')]), ]), TableRow( children: [ Column(children:const [Text('BU/Station')]), Column(children:const [Text('NULL')]), ]), TableRow( children: [ Column(children:const [Text('Qtr No')]), Column(children:const [Text('NULL')]), ]), ], ), ), </code></pre> <p>Upon executing the code, I find that there's an unnecessary space between the two containers.</p> <p><img src="https://i.stack.imgur.com/JuqSJ.png" alt="Please click here to view the table" /></p> <p>Why is the space there? How do I remove this space?</p>
[ { "answer_id": 74531358, "author": "Ftagliacarne", "author_id": 4470987, "author_profile": "https://Stackoverflow.com/users/4470987", "pm_score": 2, "selected": false, "text": "np.arange arr = np.arange(1,21,0.5).reshape((8,5))\n" }, { "answer_id": 74531360, "author": "mozway", "author_id": 16343464, "author_profile": "https://Stackoverflow.com/users/16343464", "pm_score": 2, "selected": false, "text": "numpy.arange reshape n, m = 8, 5\nstart = 0.5\nstep = 0.5\n\nout = np.arange(start+step, start+step*(n*m+1), step).reshape(n, m)\n array([[ 1. , 1.5, 2. , 2.5, 3. ],\n [ 3.5, 4. , 4.5, 5. , 5.5],\n [ 6. , 6.5, 7. , 7.5, 8. ],\n [ 8.5, 9. , 9.5, 10. , 10.5],\n [11. , 11.5, 12. , 12.5, 13. ],\n [13.5, 14. , 14.5, 15. , 15.5],\n [16. , 16.5, 17. , 17.5, 18. ],\n [18.5, 19. , 19.5, 20. , 20.5]])\n" }, { "answer_id": 74531363, "author": "Victor", "author_id": 5372398, "author_profile": "https://Stackoverflow.com/users/5372398", "pm_score": 0, "selected": false, "text": "import numpy as np\nx = 0.5\n\narray = np.zeros((8,5))\nfor i in range(8):\n for j in range(5):\n x += 0.5\n array[i,j] = x\n" }, { "answer_id": 74531522, "author": "IAmParadox", "author_id": 13765172, "author_profile": "https://Stackoverflow.com/users/13765172", "pm_score": 0, "selected": false, "text": "np.arange range np.array([*range(10, 41*5+1, 5)]).reshape(8,5) / 10\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,531,316
<p>I'm trying to create a React application using create-react-app.</p> <p>Whenever I run the command, nothing happens (no effect in console and no files created): <a href="https://i.stack.imgur.com/mQRVw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mQRVw.png" alt="create.react.app no effect" /></a></p> <p>I tried to reinstall npm, update node, clean cache, and other things.</p> <p>Can anyone help with this?</p>
[ { "answer_id": 74531365, "author": "Chukwunazaekpere", "author_id": 12589424, "author_profile": "https://Stackoverflow.com/users/12589424", "pm_score": -1, "selected": false, "text": "npm create react-app <your-app-name>\n npm create react-app <your-app-name> --template typescript\n" }, { "answer_id": 74531561, "author": "Peter Lam", "author_id": 19948640, "author_profile": "https://Stackoverflow.com/users/19948640", "pm_score": 0, "selected": false, "text": "npm\n npm <command>\n\nUsage:\n\nnpm install install all the dependencies in your project\nnpm install <foo> add the <foo> dependency to your project\nnpm test run this project's tests\nnpm run <foo> run the script named <foo>\nnpm <command> -h quick help on <command>\nnpm -l display usage info for all commands\nnpm help <term> search for help on <term>\nnpm help npm more involved overview\n\nAll commands:\n\n access, adduser, audit, bin, bugs, cache, ci, completion,\n config, dedupe, deprecate, diff, dist-tag, docs, doctor,\n edit, exec, explain, explore, find-dupes, fund, get, help,\n hook, init, install, install-ci-test, install-test, link,\n ll, login, logout, ls, org, outdated, owner, pack, ping,\n pkg, prefix, profile, prune, publish, rebuild, repo,\n restart, root, run-script, search, set, set-script,\n shrinkwrap, star, stars, start, stop, team, test, token,\n uninstall, unpublish, unstar, update, version, view, whoami\n\nSpecify configs in the ini-formatted file:\n /Users/peter.lam/.npmrc\nor on the command line via: npm <command> --key=value\n\nMore configuration info: npm help config\nConfiguration fields: npm help 7 config\n\nnpm@8.11.0 /usr/local/lib/node_modules/npm\n" }, { "answer_id": 74531628, "author": "Guit Adharsh", "author_id": 16612350, "author_profile": "https://Stackoverflow.com/users/16612350", "pm_score": 0, "selected": false, "text": "'npm cache clean --force'" }, { "answer_id": 74531881, "author": "Bhavin Parghi", "author_id": 6148640, "author_profile": "https://Stackoverflow.com/users/6148640", "pm_score": 0, "selected": false, "text": "node -v npx create-react-app my-app\ncd my-app\nnpm start\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12979980/" ]
74,531,351
<p>Hi I'm new to react and I'm trying to make a workout tracker but I have become hardstuck on trying to capture the input of the exercises the way I'd like, as you can see by the many commented out code blocks I think that I'm missing something fundamental with useState maybe?</p> <p>this is my useState</p> <pre><code>const [formData, setFormData] = useState({ title: &quot;&quot;, date: &quot;&quot;, exercises: [{ Exercise: &quot;benchpress&quot;, Reps: &quot;5&quot;, Sets: &quot;5&quot; }], }); </code></pre> <p>this works with the title and date but i've tried many approaches and cant get it work with the object inside the exercise array</p> <p>this is the onChange function on the form inputs</p> <pre><code> const updateForm = (e) =&gt; { setFormData((currentFormData) =&gt; ({ ...currentFormData, [e.target.name]: e.target.value, })); </code></pre> <p>All the solutions I've tried has just led to adding whole new objects to the exercises array, or just adding the name + value in the original object next to the title and date.</p>
[ { "answer_id": 74531365, "author": "Chukwunazaekpere", "author_id": 12589424, "author_profile": "https://Stackoverflow.com/users/12589424", "pm_score": -1, "selected": false, "text": "npm create react-app <your-app-name>\n npm create react-app <your-app-name> --template typescript\n" }, { "answer_id": 74531561, "author": "Peter Lam", "author_id": 19948640, "author_profile": "https://Stackoverflow.com/users/19948640", "pm_score": 0, "selected": false, "text": "npm\n npm <command>\n\nUsage:\n\nnpm install install all the dependencies in your project\nnpm install <foo> add the <foo> dependency to your project\nnpm test run this project's tests\nnpm run <foo> run the script named <foo>\nnpm <command> -h quick help on <command>\nnpm -l display usage info for all commands\nnpm help <term> search for help on <term>\nnpm help npm more involved overview\n\nAll commands:\n\n access, adduser, audit, bin, bugs, cache, ci, completion,\n config, dedupe, deprecate, diff, dist-tag, docs, doctor,\n edit, exec, explain, explore, find-dupes, fund, get, help,\n hook, init, install, install-ci-test, install-test, link,\n ll, login, logout, ls, org, outdated, owner, pack, ping,\n pkg, prefix, profile, prune, publish, rebuild, repo,\n restart, root, run-script, search, set, set-script,\n shrinkwrap, star, stars, start, stop, team, test, token,\n uninstall, unpublish, unstar, update, version, view, whoami\n\nSpecify configs in the ini-formatted file:\n /Users/peter.lam/.npmrc\nor on the command line via: npm <command> --key=value\n\nMore configuration info: npm help config\nConfiguration fields: npm help 7 config\n\nnpm@8.11.0 /usr/local/lib/node_modules/npm\n" }, { "answer_id": 74531628, "author": "Guit Adharsh", "author_id": 16612350, "author_profile": "https://Stackoverflow.com/users/16612350", "pm_score": 0, "selected": false, "text": "'npm cache clean --force'" }, { "answer_id": 74531881, "author": "Bhavin Parghi", "author_id": 6148640, "author_profile": "https://Stackoverflow.com/users/6148640", "pm_score": 0, "selected": false, "text": "node -v npx create-react-app my-app\ncd my-app\nnpm start\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569664/" ]
74,531,372
<p>I have some parameter in the constructor. I need to convert it to something else and give it to the parent constructor. But the problem is that I want to remember the result of the conversion (which I give to the parent constructor) and I don't need to store it in the base class. How initialize value in the parent constructor argument? Like &quot;val&quot; in base constructor?</p> <pre><code> protected open class BindingViewHolder(binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) protected open class ModelViewHolder&lt;Model : Identifiable&lt;*&gt;?, Binding : ViewDataBinding&gt;( parent: ViewGroup, inflateBinding: (LayoutInflater, ViewGroup, Boolean) -&gt; Binding ) : BindingViewHolder(parent.inflateChildBinding(inflateBinding)) { //some code } </code></pre> <p>I have one problem in this code. I cant &quot;val&quot; &quot;parent.inflateChildBinding(inflateBinding)&quot;</p>
[ { "answer_id": 74531600, "author": "devmike01", "author_id": 5265414, "author_profile": "https://Stackoverflow.com/users/5265414", "pm_score": 0, "selected": false, "text": "SharedPreference val sharedPref = context?.getPreferences(Context.MODE_PRIVATE) ?: return\nwith (sharedPref.edit()) {\n putInt(getString(R.string.converted_value), convertedValue)\n apply()\n}\n SharedPreference val sharedPref = context?.getPreferences(Context.MODE_PRIVATE)\n SharedPreference" }, { "answer_id": 74533156, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "binding protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root)\n protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root) {\n\n constructor(\n parent: ViewGroup,\n inflateBinding: (LayoutInflater, ViewGroup, Boolean) -> T\n ): this(parent.inflateChildBinding(inflateBinding))\n}\n\n binding" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14335049/" ]
74,531,384
<p>I have a working snippet that I've wrote, but I kinda don't understand how flutter is (re)using the widgets creating in the build method:</p> <pre><code>import 'dart:math'; import 'package:flutter/material.dart'; void main() { runApp(const MyGame()); } class MyGame extends StatelessWidget { const MyGame({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp(home: GameWidget()); } } class GameWidget extends StatefulWidget { const GameWidget({Key? key}) : super(key: key); static const squareWidth = 50.0; static const squareHeight = 50.0; @override State&lt;GameWidget&gt; createState() =&gt; _GameWidgetState(); } class _GameWidgetState extends State&lt;GameWidget&gt; { List&lt;Offset&gt; offsets = []; @override Widget build(BuildContext context) { if (offsets.isEmpty) { for(int i = 0; i &lt; 20; i++) { offsets.add(calculateNextOffset()); } } List&lt;Widget&gt; squareWidgets = []; for (int j = 0; j &lt; offsets.length; j++) { squareWidgets.add(AnimatedPositioned( left: offsets[j].dx, top: offsets[j].dy, curve: Curves.easeIn, duration: const Duration(milliseconds: 500), child: GestureDetector( onTapDown: (tapDownDetails) { setState(() { offsets.removeAt(j); for (int k = 0; k &lt; offsets.length; k++) { offsets[k] = calculateNextOffset(); } }); }, behavior: HitTestBehavior.opaque, child: Container( width: GameWidget.squareWidth, height: GameWidget.squareHeight, color: Colors.blue, ), ), )); } return Stack( children: squareWidgets, ); } Offset calculateNextOffset() { return randomOffset( MediaQuery.of(context).size, const Size(GameWidget.squareWidth, GameWidget.squareHeight), MediaQuery.of(context).viewPadding.top); } double randomNumber(double min, double max) =&gt; min + Random().nextDouble() * (max - min); Offset randomOffset( Size parentSize, Size childSize, double statusBarHeight) { var parentWidth = parentSize.width; var parentHeight = parentSize.height; var randomPosition = Offset( randomNumber(parentWidth, childSize.width), randomNumber(statusBarHeight,parentHeight - childSize.height), ); return randomPosition; } } </code></pre> <p>Every time I click on a container, i expect my &quot;offsets&quot; state to be updated, but I also expect all the AnimationPositioned widgets, GestureDetector widgets and the square widgets that you see would be rerendered.</p> <p>With rerendered i mean they would disappear from the screen and new ones would be rerendered (and the animation from the first widgets would be cancelled and never displayed)</p> <p>However it works? Could someone explain this to me?</p> <p><strong>EDIT: I've updated my snippet of code in my question to match what i'm asking, which i'm also going to rephrase here:</strong></p> <p>Every time I click on a square, i want that square to disappear and all the other square to randomly animate to another position. But every time I click on a square, another random square is deleted, and the one i'm clicking is animating.</p> <p>I want the square that I click on disappears and the rest will animate.</p>
[ { "answer_id": 74531600, "author": "devmike01", "author_id": 5265414, "author_profile": "https://Stackoverflow.com/users/5265414", "pm_score": 0, "selected": false, "text": "SharedPreference val sharedPref = context?.getPreferences(Context.MODE_PRIVATE) ?: return\nwith (sharedPref.edit()) {\n putInt(getString(R.string.converted_value), convertedValue)\n apply()\n}\n SharedPreference val sharedPref = context?.getPreferences(Context.MODE_PRIVATE)\n SharedPreference" }, { "answer_id": 74533156, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "binding protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root)\n protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root) {\n\n constructor(\n parent: ViewGroup,\n inflateBinding: (LayoutInflater, ViewGroup, Boolean) -> T\n ): this(parent.inflateChildBinding(inflateBinding))\n}\n\n binding" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4719741/" ]
74,531,389
<p>I have this vector <code>m = [1,0.8,0.6,0.4,0.2,0]</code> and I have to create the following matrix in Python:</p> <p><a href="https://i.stack.imgur.com/6PSky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6PSky.png" alt="enter image description here" /></a></p> <p>I create a matrix of zeros and a double</p> <pre><code>mm = np.zeros((6, 6)) for j in list(range(0,6,1)): for i in list(range(0,6,1)): ind = abs(i-j) m[j,i] = mm[ind] </code></pre> <p>But, I got the following output:</p> <pre><code>array([[1. , 0.8, 0.6, 0.4, 0.2, 0. ], [0.8, 1. , 0.8, 0.6, 0.4, 0.2], [0.6, 0.8, 1. , 0.8, 0.6, 0.4], [0.4, 0.6, 0.8, 1. , 0.8, 0.6], [0.2, 0.4, 0.6, 0.8, 1. , 0.8], [0. , 0.2, 0.4, 0.6, 0.8, 1. ]]) </code></pre> <p>That is what I wanted! Thanks anyway.</p>
[ { "answer_id": 74531600, "author": "devmike01", "author_id": 5265414, "author_profile": "https://Stackoverflow.com/users/5265414", "pm_score": 0, "selected": false, "text": "SharedPreference val sharedPref = context?.getPreferences(Context.MODE_PRIVATE) ?: return\nwith (sharedPref.edit()) {\n putInt(getString(R.string.converted_value), convertedValue)\n apply()\n}\n SharedPreference val sharedPref = context?.getPreferences(Context.MODE_PRIVATE)\n SharedPreference" }, { "answer_id": 74533156, "author": "Tenfour04", "author_id": 506796, "author_profile": "https://Stackoverflow.com/users/506796", "pm_score": 2, "selected": true, "text": "binding protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root)\n protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root) {\n\n constructor(\n parent: ViewGroup,\n inflateBinding: (LayoutInflater, ViewGroup, Boolean) -> T\n ): this(parent.inflateChildBinding(inflateBinding))\n}\n\n binding" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12548329/" ]
74,531,433
<p>I want to select only the first occurrence of codes.head with md.mnem=&quot;ht1&quot; and &quot;ht1c&quot; tag from the whole file, regardless of its parent. My Xml file looks like this-</p> <pre><code>&lt;printArtifactGroup&gt; &lt;!--Pubtags : [ANIP+, AN+, ANIP, AN]Sourcetags: [21, 21-A1]--&gt; &lt;bov ID=&quot;I2C37E8404E1711DF8062B84BC6F3033A&quot; legacy.identifier=&quot;000321783&quot;&gt; &lt;placeholder ID=&quot;I2C3836604E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;vols&quot;&gt; &lt;placeholder.text&gt;0390 V. 0390 Ch. 75, Arts. 42-end (2008)&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;head.block ID=&quot;I2C385D704E1711DF8062B84BC6F3033A&quot;&gt; &lt;codes.head ID=&quot;I2C385D714E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; &lt;ital&gt;Wests pso1_1&lt;/ital&gt; &lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; pso1_2&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;placeholder ID=&quot;I2C3920C14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;angen&quot;&gt; &lt;placeholder.text&gt;UL&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;/head.block&gt; &lt;head.block ID=&quot;I2C38D2A24E1711DF8062B84BC6F3033A&quot;&gt; &lt;codes.head ID=&quot;I2C38F9B04E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2&quot;&gt; &lt;head.info&gt; &lt;label.name&gt;CHAPTER&lt;/label.name&gt; &lt;label.designator&gt;75 pso1_4&lt;/label.designator&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C38F9B04E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2&quot;&gt; &lt;head.info&gt; &lt;label.name&gt;CHAPTER duplicate&lt;/label.name&gt; &lt;label.designator&gt;75 pso1_5&lt;/label.designator&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C38F9B14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; pso1_6&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;placeholder ID=&quot;I2C3920C14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;angen&quot;&gt; &lt;placeholder.text&gt;UL&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;/head.block&gt; &lt;/bov&gt; &lt;grade.content legacy.identifier=&quot;018840438&quot; ID=&quot;I2C3158904E1711DFAB97E78B3969CA63&quot;&gt; &lt;head.block ID=&quot;I2C31CDC04E1711DFAB97E78B3969CA63&quot;&gt; &lt;codes.head ID=&quot;I2C385D714E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; &lt;ital&gt;pso1&lt;/ital&gt; &lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt;pso2&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;srnl&quot;&gt; &lt;head.info&gt; &lt;headtext&gt;pso 4&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;/head.block&gt; &lt;/grade.content&gt; &lt;/printArtifactGroup&gt; </code></pre> <p>My XSLT scripts is -</p> <pre><code>&lt;xsl:template match=&quot;codes.head&quot;&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select=&quot;@*|node()&quot;/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match=&quot;codes.head[@md.mnem[starts-with(.,'ht1')]][position() &gt; 2]&quot;/&gt; </code></pre> <p>the output i'm getting</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;printArtifactGroup&gt;&lt;!--Pubtags : [ANIP+, AN+, ANIP, AN]Sourcetags: [21, 21-A1]--&gt; &lt;bov ID=&quot;I2C37E8404E1711DF8062B84BC6F3033A&quot; legacy.identifier=&quot;000321783&quot;&gt; &lt;placeholder ID=&quot;I2C3836604E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;vols&quot;&gt; &lt;placeholder.text&gt;0390 V. 0390 Ch. 75, Arts. 42-end (2008)&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;head.block ID=&quot;I2C385D704E1711DF8062B84BC6F3033A&quot;&gt; &lt;codes.head ID=&quot;I2C385D714E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; &lt;ital&gt;Wests pso1_1&lt;/ital&gt; &lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; pso1_2&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;placeholder ID=&quot;I2C3920C14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;angen&quot;&gt; &lt;placeholder.text&gt;UL&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;/head.block&gt; &lt;head.block ID=&quot;I2C38D2A24E1711DF8062B84BC6F3033A&quot;&gt; &lt;codes.head ID=&quot;I2C38F9B04E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2&quot;&gt; &lt;head.info&gt; &lt;label.name&gt;CHAPTER&lt;/label.name&gt; &lt;label.designator&gt;75 pso1_4&lt;/label.designator&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C38F9B04E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2&quot;&gt; &lt;head.info&gt; &lt;label.name&gt;CHAPTER duplicate&lt;/label.name&gt; &lt;label.designator&gt;75 pso1_5&lt;/label.designator&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C38F9B14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; pso1_6&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;placeholder ID=&quot;I2C3920C14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;angen&quot;&gt; &lt;placeholder.text&gt;UL&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;/head.block&gt; &lt;/bov&gt; &lt;grade.content legacy.identifier=&quot;018840438&quot; ID=&quot;I2C3158904E1711DFAB97E78B3969CA63&quot;&gt; &lt;head.block ID=&quot;I2C31CDC04E1711DFAB97E78B3969CA63&quot;&gt; &lt;codes.head ID=&quot;I2C385D714E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; &lt;ital&gt;pso1&lt;/ital&gt; &lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt;pso2&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;srnl&quot;&gt; &lt;head.info&gt; &lt;headtext&gt;pso 4&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;/head.block&gt; &lt;/grade.content&gt; &lt;/printArtifactGroup&gt; </code></pre> <p>This is keeping all the first occurrence of ht1 and ht1c in every block not in the whole file. What should be the correct way to select only the first occurrence in the whole file?</p> <p>desired output</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;printArtifactGroup&gt;&lt;!--Pubtags : [ANIP+, AN+, ANIP, AN]Sourcetags: [21, 21-A1]--&gt; &lt;bov ID=&quot;I2C37E8404E1711DF8062B84BC6F3033A&quot; legacy.identifier=&quot;000321783&quot;&gt; &lt;placeholder ID=&quot;I2C3836604E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;vols&quot;&gt; &lt;placeholder.text&gt;0390 V. 0390 Ch. 75, Arts. 42-end (2008)&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;head.block ID=&quot;I2C385D704E1711DF8062B84BC6F3033A&quot;&gt; &lt;codes.head ID=&quot;I2C385D714E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; &lt;ital&gt;Wests pso1_1&lt;/ital&gt; &lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;ht1c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; pso1_2&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;placeholder ID=&quot;I2C3920C14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;angen&quot;&gt; &lt;placeholder.text&gt;UL&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;/head.block&gt; &lt;head.block ID=&quot;I2C38D2A24E1711DF8062B84BC6F3033A&quot;&gt; &lt;codes.head ID=&quot;I2C38F9B04E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2&quot;&gt; &lt;head.info&gt; &lt;label.name&gt;CHAPTER&lt;/label.name&gt; &lt;label.designator&gt;75 pso1_4&lt;/label.designator&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C38F9B04E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2&quot;&gt; &lt;head.info&gt; &lt;label.name&gt;CHAPTER duplicate&lt;/label.name&gt; &lt;label.designator&gt;75 pso1_5&lt;/label.designator&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;codes.head ID=&quot;I2C38F9B14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;hg2c&quot;&gt; &lt;head.info&gt; &lt;headtext&gt; pso1_6&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;placeholder ID=&quot;I2C3920C14E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;angen&quot;&gt; &lt;placeholder.text&gt;UL&lt;/placeholder.text&gt; &lt;/placeholder&gt; &lt;/head.block&gt; &lt;/bov&gt; &lt;grade.content legacy.identifier=&quot;018840438&quot; ID=&quot;I2C3158904E1711DFAB97E78B3969CA63&quot;&gt; &lt;head.block ID=&quot;I2C31CDC04E1711DFAB97E78B3969CA63&quot;&gt; &lt;codes.head ID=&quot;I2C385D724E1711DF8062B84BC6F3033A&quot; md.mnem=&quot;srnl&quot;&gt; &lt;head.info&gt; &lt;headtext&gt;pso 4&lt;/headtext&gt; &lt;/head.info&gt; &lt;/codes.head&gt; &lt;/head.block&gt; &lt;/grade.content&gt; &lt;/printArtifactGroup&gt; </code></pre>
[ { "answer_id": 74534583, "author": "al.truisme", "author_id": 16750357, "author_profile": "https://Stackoverflow.com/users/16750357", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n version=\"3.0\"\n exclude-result-prefixes=\"#all\">\n\n <xsl:mode on-no-match=\"shallow-copy\" />\n \n <xsl:output method=\"xml\" indent=\"yes\" />\n \n <xsl:variable name=\"mdMnems\" as=\"xs:string*\" select=\"('ht1', 'ht1c')\" />\n \n <xsl:variable name=\"nodesToKeep\" as=\"element(codes.head)*\" \n select=\"for $mdMnem in $mdMnems\n return ((//codes.head[@md.mnem eq $mdMnem ])[1])\" />\n \n <xsl:template match=\"codes.head[@md.mnem = $mdMnems]\">\n <xsl:if test=\"$some $node in $nodesToKeep satisfies $node is .\">\n <xsl:next-match />\n </xsl:if>\n </xsl:template>\n \n</xsl:stylesheet>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<printArtifactGroup>\n <!--Pubtags : [ANIP+, AN+, ANIP, AN]Sourcetags: [21, 21-A1]-->\n <bov ID=\"I2C37E8404E1711DF8062B84BC6F3033A\" legacy.identifier=\"000321783\">\n <placeholder ID=\"I2C3836604E1711DF8062B84BC6F3033A\" md.mnem=\"vols\">\n <placeholder.text>0390 V. 0390 Ch. 75, Arts. 42-end (2008)</placeholder.text>\n </placeholder>\n <head.block ID=\"I2C385D704E1711DF8062B84BC6F3033A\">\n <codes.head ID=\"I2C385D714E1711DF8062B84BC6F3033A\" md.mnem=\"ht1\">\n <head.info>\n <headtext>\n <ital>Wests pso1_1</ital>\n </headtext>\n </head.info>\n </codes.head>\n <codes.head ID=\"I2C385D724E1711DF8062B84BC6F3033A\" md.mnem=\"ht1c\">\n <head.info>\n <headtext> pso1_2</headtext>\n </head.info>\n </codes.head>\n <placeholder ID=\"I2C3920C14E1711DF8062B84BC6F3033A\" md.mnem=\"angen\">\n <placeholder.text>UL</placeholder.text>\n </placeholder>\n </head.block>\n <head.block ID=\"I2C38D2A24E1711DF8062B84BC6F3033A\">\n <codes.head ID=\"I2C38F9B04E1711DF8062B84BC6F3033A\" md.mnem=\"hg2\">\n <head.info>\n <label.name>CHAPTER</label.name>\n <label.designator>75 pso1_4</label.designator>\n </head.info>\n </codes.head>\n <codes.head ID=\"I2C38F9B04E1711DF8062B84BC6F3033A\" md.mnem=\"hg2\">\n <head.info>\n <label.name>CHAPTER duplicate</label.name>\n <label.designator>75 pso1_5</label.designator>\n </head.info>\n </codes.head>\n <codes.head ID=\"I2C38F9B14E1711DF8062B84BC6F3033A\" md.mnem=\"hg2c\">\n <head.info>\n <headtext> pso1_6</headtext>\n </head.info>\n </codes.head>\n <placeholder ID=\"I2C3920C14E1711DF8062B84BC6F3033A\" md.mnem=\"angen\">\n <placeholder.text>UL</placeholder.text>\n </placeholder>\n </head.block>\n </bov>\n <grade.content legacy.identifier=\"018840438\" ID=\"I2C3158904E1711DFAB97E78B3969CA63\">\n <head.block ID=\"I2C31CDC04E1711DFAB97E78B3969CA63\">\n <codes.head ID=\"I2C385D724E1711DF8062B84BC6F3033A\" md.mnem=\"srnl\">\n <head.info>\n <headtext>pso 4</headtext>\n </head.info>\n </codes.head>\n </head.block>\n </grade.content>\n</printArtifactGroup>\n" }, { "answer_id": 74535969, "author": "Martin Honnen", "author_id": 252228, "author_profile": "https://Stackoverflow.com/users/252228", "pm_score": 2, "selected": true, "text": "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:map=\"http://www.w3.org/2005/xpath-functions/map\"\n exclude-result-prefixes=\"#all\"\n version=\"3.0\">\n \n <xsl:param name=\"codes\" as=\"xs:string*\" select=\"'ht1', 'ht1c'\"/>\n \n <xsl:accumulator name=\"element-counter\" as=\"map(xs:string, xs:integer)\" initial-value=\"map:merge($codes ! map { . : 0 })\">\n <xsl:accumulator-rule \n match=\"codes.head[@md.mnem = $codes]\"\n select=\"map:put($value, string(@md.mnem), $value(string(@md.mnem)) + 1)\"/>\n </xsl:accumulator>\n\n <xsl:mode on-no-match=\"shallow-copy\" use-accumulators=\"element-counter\"/>\n\n <xsl:template match=\"codes.head[@md.mnem = $codes][accumulator-before('element-counter')(string(@md.mnem)) gt 1]\"/>\n \n</xsl:stylesheet>\n streamable=\"yes\" xsl:mode xsl:accumulator" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15918089/" ]
74,531,459
<p>I'm creating a 2D in in Unity and I have a loading screen, that it's working (the loading animation). What I want to do next is to make the next screen appear (it's a gameobject), after a certain time. Right now, my code is:</p> <pre><code> public RectTransform mainIcon; public float timeStep; public float oneStepAngle; float startTime; // Start is called before the first frame update void Start() { startTime = Time.time; } // Update is called once per frame void Update() { if (Time.time - startTime &gt;= timeStep) { Vector3 iconAngle = mainIcon.localEulerAngles; iconAngle.z += oneStepAngle; mainIcon.localEulerAngles = iconAngle; startTime = Time.time; } } </code></pre> <p>what should I do now? Thank you</p>
[ { "answer_id": 74534583, "author": "al.truisme", "author_id": 16750357, "author_profile": "https://Stackoverflow.com/users/16750357", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n version=\"3.0\"\n exclude-result-prefixes=\"#all\">\n\n <xsl:mode on-no-match=\"shallow-copy\" />\n \n <xsl:output method=\"xml\" indent=\"yes\" />\n \n <xsl:variable name=\"mdMnems\" as=\"xs:string*\" select=\"('ht1', 'ht1c')\" />\n \n <xsl:variable name=\"nodesToKeep\" as=\"element(codes.head)*\" \n select=\"for $mdMnem in $mdMnems\n return ((//codes.head[@md.mnem eq $mdMnem ])[1])\" />\n \n <xsl:template match=\"codes.head[@md.mnem = $mdMnems]\">\n <xsl:if test=\"$some $node in $nodesToKeep satisfies $node is .\">\n <xsl:next-match />\n </xsl:if>\n </xsl:template>\n \n</xsl:stylesheet>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<printArtifactGroup>\n <!--Pubtags : [ANIP+, AN+, ANIP, AN]Sourcetags: [21, 21-A1]-->\n <bov ID=\"I2C37E8404E1711DF8062B84BC6F3033A\" legacy.identifier=\"000321783\">\n <placeholder ID=\"I2C3836604E1711DF8062B84BC6F3033A\" md.mnem=\"vols\">\n <placeholder.text>0390 V. 0390 Ch. 75, Arts. 42-end (2008)</placeholder.text>\n </placeholder>\n <head.block ID=\"I2C385D704E1711DF8062B84BC6F3033A\">\n <codes.head ID=\"I2C385D714E1711DF8062B84BC6F3033A\" md.mnem=\"ht1\">\n <head.info>\n <headtext>\n <ital>Wests pso1_1</ital>\n </headtext>\n </head.info>\n </codes.head>\n <codes.head ID=\"I2C385D724E1711DF8062B84BC6F3033A\" md.mnem=\"ht1c\">\n <head.info>\n <headtext> pso1_2</headtext>\n </head.info>\n </codes.head>\n <placeholder ID=\"I2C3920C14E1711DF8062B84BC6F3033A\" md.mnem=\"angen\">\n <placeholder.text>UL</placeholder.text>\n </placeholder>\n </head.block>\n <head.block ID=\"I2C38D2A24E1711DF8062B84BC6F3033A\">\n <codes.head ID=\"I2C38F9B04E1711DF8062B84BC6F3033A\" md.mnem=\"hg2\">\n <head.info>\n <label.name>CHAPTER</label.name>\n <label.designator>75 pso1_4</label.designator>\n </head.info>\n </codes.head>\n <codes.head ID=\"I2C38F9B04E1711DF8062B84BC6F3033A\" md.mnem=\"hg2\">\n <head.info>\n <label.name>CHAPTER duplicate</label.name>\n <label.designator>75 pso1_5</label.designator>\n </head.info>\n </codes.head>\n <codes.head ID=\"I2C38F9B14E1711DF8062B84BC6F3033A\" md.mnem=\"hg2c\">\n <head.info>\n <headtext> pso1_6</headtext>\n </head.info>\n </codes.head>\n <placeholder ID=\"I2C3920C14E1711DF8062B84BC6F3033A\" md.mnem=\"angen\">\n <placeholder.text>UL</placeholder.text>\n </placeholder>\n </head.block>\n </bov>\n <grade.content legacy.identifier=\"018840438\" ID=\"I2C3158904E1711DFAB97E78B3969CA63\">\n <head.block ID=\"I2C31CDC04E1711DFAB97E78B3969CA63\">\n <codes.head ID=\"I2C385D724E1711DF8062B84BC6F3033A\" md.mnem=\"srnl\">\n <head.info>\n <headtext>pso 4</headtext>\n </head.info>\n </codes.head>\n </head.block>\n </grade.content>\n</printArtifactGroup>\n" }, { "answer_id": 74535969, "author": "Martin Honnen", "author_id": 252228, "author_profile": "https://Stackoverflow.com/users/252228", "pm_score": 2, "selected": true, "text": "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:map=\"http://www.w3.org/2005/xpath-functions/map\"\n exclude-result-prefixes=\"#all\"\n version=\"3.0\">\n \n <xsl:param name=\"codes\" as=\"xs:string*\" select=\"'ht1', 'ht1c'\"/>\n \n <xsl:accumulator name=\"element-counter\" as=\"map(xs:string, xs:integer)\" initial-value=\"map:merge($codes ! map { . : 0 })\">\n <xsl:accumulator-rule \n match=\"codes.head[@md.mnem = $codes]\"\n select=\"map:put($value, string(@md.mnem), $value(string(@md.mnem)) + 1)\"/>\n </xsl:accumulator>\n\n <xsl:mode on-no-match=\"shallow-copy\" use-accumulators=\"element-counter\"/>\n\n <xsl:template match=\"codes.head[@md.mnem = $codes][accumulator-before('element-counter')(string(@md.mnem)) gt 1]\"/>\n \n</xsl:stylesheet>\n streamable=\"yes\" xsl:mode xsl:accumulator" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17646296/" ]
74,531,462
<p>Im trying to solve a problem which reads only characters '?', '0' and '1' from the console. I have been using the following if statement, but it only works when all three are included in the string.</p> <p>How should the statement look like if I only want '?', '0' and '1'? I want the program to stop if I use for instance &quot;10?=&quot;.</p> <pre><code> if(text.contains(&quot;?&quot;) &amp;&amp; text.contains(&quot;0&quot;) &amp;&amp; text.contains(&quot;1&quot;)) { //do something } </code></pre>
[ { "answer_id": 74531591, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 3, "selected": true, "text": "[?01]+ [?01]* * [?01] private Pattern pattern = Pattern.compile(\"[?01]+\");\n\nprivate boolean isMatching(String s) {\n return pattern.matcher(s).matches();\n}\n public static void main(String[] args) {\n System.out.println(isMatching(\"?\"));\n System.out.println(isMatching(\"?A\"));\n System.out.println(isMatching(\"N?\"));\n System.out.println(isMatching(\"3\"));\n System.out.println(isMatching(\"01\"));\n}\n true\nfalse\nfalse\nfalse\ntrue\n" }, { "answer_id": 74536267, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 0, "selected": false, "text": "[^01?]+ 0,1, ? String testString = \"ksks1ksks111;?001ksksksk10101 skksksk0ksks1ksk101010101jsjs\";\n\nScanner s = new Scanner(testString).useDelimiter(\"[^01\\\\?]+\");\n\nwhile (s.hasNext()) {\n String in = s.next();\n System.out.println(in);\n}\n 1\n111\n?001\n10101\n0\n1\n101010101\n\n System.in testString eof" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14779701/" ]
74,531,483
<p>The problem - I am receiving the following message:</p> <p><code>java.lang.ClassCastException: com.ibm.connector2.cics.ECIConnectionFactory incompatible with com.ibm.connector2.cics.ECIConnectionFactory</code></p> <p>I am receiving it when trying to make the following statement:</p> <p><code>eisDci = (ECIConnectionFactory)ctx.lookup(eisn);</code></p> <p>The 'eisDci' has been defined previously: <code>private static ECIConnectionFactory eisDci = null;</code></p> <p>And the 'eisn' is the String with the name of the conection like 'eis/DCIXxxxECI'</p> <p>These connection is defined in the Server.xml:</p> <pre><code>&lt;connectionFactory id=&quot;DCIXxxxECI&quot; jndiName=&quot;eis/DCIXxxxECI&quot;&gt; &lt;properties.cicseci ServerName=&quot;XXXX&quot; TPNName=&quot;xx&quot; connectionUrl=&quot;url&quot; portNumber=&quot;2006&quot;/&gt; &lt;/connectionFactory&gt; </code></pre> <p>I understand that this is warning me that the cast is not possible. What I don't know is what I'm doing wrong. That must be comparing one version of the ECIConnectionFactory class with a different version of ECIConnectionFactory.</p> <p>The server I'm working with is a Liberty, I'm going crazy, I can't figure out why Eclipse is comparing two different versions.</p> <p>Similar problems I have searched for:</p> <p><a href="https://stackoverflow.com/questions/826319/classcastexception-when-casting-to-the-same-class">ClassCastException when casting to the same class</a></p> <p>Waxwing's answer seems good, but I don't have access to make those changes, This connection is carried out by an external library.</p> <p>First Thank you for your answer Ben Cox, in Liberty's server.xml (for LOCAL) I have declared the library:</p> <pre><code>&lt;fileset caseSensitive=&quot;false&quot; dir=&quot;C:\CICSECI&quot;/&gt; </code></pre> <p>And in the Liberty Runtime/Shared/resources I have cicseci.rar which I have declared in the server.xml as a resourceAdapter:</p> <pre><code>&lt;resourceAdapter autoStart=&quot;true&quot; id=&quot;cicseci&quot; location=&quot;${shared.resource.dir}/cicseci.rar&quot;&gt; &lt;classloader apiTypeVisibility=&quot;spec, ibm-api, api, third-party&quot;/&gt; &lt;/resourceAdapter&gt; </code></pre> <p>I have checked the rest of the libraries that I am importing into the project, and so far I have not seen that I have the repeated library.</p>
[ { "answer_id": 74531591, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 3, "selected": true, "text": "[?01]+ [?01]* * [?01] private Pattern pattern = Pattern.compile(\"[?01]+\");\n\nprivate boolean isMatching(String s) {\n return pattern.matcher(s).matches();\n}\n public static void main(String[] args) {\n System.out.println(isMatching(\"?\"));\n System.out.println(isMatching(\"?A\"));\n System.out.println(isMatching(\"N?\"));\n System.out.println(isMatching(\"3\"));\n System.out.println(isMatching(\"01\"));\n}\n true\nfalse\nfalse\nfalse\ntrue\n" }, { "answer_id": 74536267, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 0, "selected": false, "text": "[^01?]+ 0,1, ? String testString = \"ksks1ksks111;?001ksksksk10101 skksksk0ksks1ksk101010101jsjs\";\n\nScanner s = new Scanner(testString).useDelimiter(\"[^01\\\\?]+\");\n\nwhile (s.hasNext()) {\n String in = s.next();\n System.out.println(in);\n}\n 1\n111\n?001\n10101\n0\n1\n101010101\n\n System.in testString eof" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20172978/" ]
74,531,517
<p>I have a table with this structure:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>DeviceID</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>01/01/2022</td> <td>SensorA</td> <td>1200</td> </tr> <tr> <td>01/01/2022</td> <td>SensorB</td> <td>1300</td> </tr> <tr> <td>01/01/2022</td> <td>SensorC</td> <td>900</td> </tr> <tr> <td>02/01/2022</td> <td>SensorA</td> <td>500</td> </tr> <tr> <td>02/01/2022</td> <td>SensorB</td> <td>50</td> </tr> <tr> <td>02/01/2022</td> <td>SensorC</td> <td>39</td> </tr> </tbody> </table> </div> <p>I'm interesting in create a new table that have the average by day of all sensors values but excluding the values which are lower than the average of all sensors by day. For example for 01/01/2022 the average of all sensors values is:</p> <p><code>(1200+1300+900) / 3 = 1133.3</code></p> <p>We then calculate the average sensor value for the day, excluding <code>SensorC</code> because its value is below <code>1133.3</code>:</p> <p><code>(1200+1300) / 2 = 1250</code></p> <p>The final table have to looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>01/01/2022</td> <td>1250</td> </tr> <tr> <td>02/01/2022</td> <td>500</td> </tr> </tbody> </table> </div> <p>Is it possible? Hope you can help me</p> <p>Thanks in advance!</p>
[ { "answer_id": 74531591, "author": "Yonatan Karp-Rudin", "author_id": 3899765, "author_profile": "https://Stackoverflow.com/users/3899765", "pm_score": 3, "selected": true, "text": "[?01]+ [?01]* * [?01] private Pattern pattern = Pattern.compile(\"[?01]+\");\n\nprivate boolean isMatching(String s) {\n return pattern.matcher(s).matches();\n}\n public static void main(String[] args) {\n System.out.println(isMatching(\"?\"));\n System.out.println(isMatching(\"?A\"));\n System.out.println(isMatching(\"N?\"));\n System.out.println(isMatching(\"3\"));\n System.out.println(isMatching(\"01\"));\n}\n true\nfalse\nfalse\nfalse\ntrue\n" }, { "answer_id": 74536267, "author": "WJS", "author_id": 1552534, "author_profile": "https://Stackoverflow.com/users/1552534", "pm_score": 0, "selected": false, "text": "[^01?]+ 0,1, ? String testString = \"ksks1ksks111;?001ksksksk10101 skksksk0ksks1ksk101010101jsjs\";\n\nScanner s = new Scanner(testString).useDelimiter(\"[^01\\\\?]+\");\n\nwhile (s.hasNext()) {\n String in = s.next();\n System.out.println(in);\n}\n 1\n111\n?001\n10101\n0\n1\n101010101\n\n System.in testString eof" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16092657/" ]
74,531,554
<p>So my question is. I have a very huge form to fill in 200 input fields+ and I have one field required (the title) but I also wanna check that they fill in at least one other field. doesn't matter which one. but once that requirement is met they can submit the form.</p>
[ { "answer_id": 74532029, "author": "Edmunds Folkmanis", "author_id": 19886561, "author_profile": "https://Stackoverflow.com/users/19886561", "pm_score": 0, "selected": false, "text": "new FormGroup(\n {\n requiredControl: new FormControl(initialValue, [Validators.required]),\n control1: new FormControl(...),\n ...\n control200: new FormControl(...)\n },\n [someValueValidator()]\n)\n\nprivate someValueValidator() {\n return (controls: AbstractControl) => {\n // check if any non-required control is set then return null, \n // otherwise return ValidationError\n }\n}\n" }, { "answer_id": 74532168, "author": "Flo", "author_id": 4472932, "author_profile": "https://Stackoverflow.com/users/4472932", "pm_score": 1, "selected": false, "text": " onSubmit(): void {\n let anyOtherControlIsFilled = false;\n\n Object.keys(this.form.controls).forEach((key) => {\n if (!this.form.controls[key].validator) {\n if (\n this.form.controls[key].value !== null &&\n this.form.controls[key].value !== ''\n ) {\n console.log('Passt');\n anyOtherControlIsFilled = true;\n }\n }\n });\n\n if (this.form.valid && anyOtherControlIsFilled) {\n this.submitted = true;\n alert('All ok');\n } else {\n this.submitted = true;\n alert('Error');\n return;\n }\n\n console.log(JSON.stringify(this.form.value, null, 2));\n }\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5373639/" ]
74,531,562
<p>I have an array in the following format.</p> <pre><code>const arr = [{name:'11'},{name:'10'},{name:'9'},{name:'8'},{name:'7'} {name:'6'},{name:'5'},{name:'4'},{name:'3'},{name:'2'},{name:'1'} {name:'UN'},{name:'PG'},{name:'LN'}, {name:'12'},{name:'13'}] </code></pre> <p>I can sort it to get an output like below.</p> <pre><code>arr.sort((x, y)=&gt; { if(x.name == 'LN' || x.name=='UN' || x.name== 'PG' || (parseInt(x.name)&lt;parseInt(y.name))) { return -1; } return 0; }) </code></pre> <p>Current Output : simplified for easy visualization</p> <pre><code>[LN,PG,UN,1,2,3,4,5,6,7,8,9,10,11,12,13] </code></pre> <p>I want PG to come after UN. Should do a swap like below after sorting or can it be done in the sort function it self?</p> <pre><code>[arr[1], arr[2]] = [arr[2],arr[1]] </code></pre> <p>Expected Output : simplified for easy visualization</p> <pre><code>[LN,UN,PG,1,2,3,4,5,6,7,8,9,10,11,12,13] </code></pre>
[ { "answer_id": 74531772, "author": "Keith", "author_id": 6870228, "author_profile": "https://Stackoverflow.com/users/6870228", "pm_score": 3, "selected": true, "text": "name const arr = [{name:'11'},{name:'10'},{name:'9'},{name:'8'},{name:'7'},\n{name:'6'},{name:'5'},{name:'4'},{name:'3'},{name:'2'},{name:'1'},\n{name:'UN'},{name:'PG'},{name:'LN'},\n{name:'12'},{name:'13'}];\n\nconst ranks = {\n LN: -3,\n UN: -2,\n PG: -1\n}\n\nfunction rank(n) {\n if (ranks[n]) return ranks[n]\n else return Number(n);\n}\n\narr.sort((a,b) => {\n return rank(a.name) - rank(b.name);\n});\n\nconsole.log(arr);" }, { "answer_id": 74531800, "author": "jsejcksn", "author_id": 438273, "author_profile": "https://Stackoverflow.com/users/438273", "pm_score": 2, "selected": false, "text": "Number() parseInt() const arr = [{name:'11'}, {name:'10'}, {name:'9'}, {name:'8'}, {name:'7'}, {name:'6'}, {name:'5'}, {name:'4'}, {name:'3'}, {name:'2'}, {name:'1'}, {name:'UN'}, {name:'PG'}, {name:'LN'}, {name:'12'}, {name:'13'}];\n\nconst result = arr.sort((oA, oB) => {\n // Handle case of same value:\n if (oA.name === oB.name) return 0;\n\n // Coerce to numbers:\n const nA = Number(oA.name);\n const nB = Number(oB.name);\n\n // Handle the case for two numbers:\n if (Number.isInteger(nA) && Number.isInteger(nB)) return nA - nB;\n\n // Handle the case for two non-numbers:\n if (Number.isNaN(nA) && Number.isNaN(nB)) {\n const valueMap = { LN: 0, UN: 1, PG: 2 };\n return valueMap[oA.name] - valueMap[oB.name];\n }\n\n // Handle the case for one number and one non-number:\n return Number.isNaN(nA) ? -1 : 1;\n});\n\nconsole.log(result);" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15781662/" ]
74,531,567
<p>I tried to convert a column of dates to <code>datetime</code> using <code>pd.to_datetime(df, format='%Y-%m-%d_%H-%M-%S')</code> but I received the error <code>ValueError: unconverted data remains: .1</code></p> <p>I ran:</p> <pre><code>data.loc[pd.to_datetime(data.date, format='%Y-%m-%d_%H-%M-%S', errors='coerce').isnull(), 'date'] </code></pre> <p>to identify the problem. 119/1037808 dates in the <code>date</code> column have an extra &quot;.1&quot; at the end of them. Other than the &quot;.1&quot;, the dates are fine. How can I remove the &quot;.1&quot; from the end of those dates only and then convert the column values to datetime?</p> <p>Here is an example dataframe that recreates the issue:</p> <pre><code>import pandas as pd data = pd.DataFrame({&quot;date&quot; : [&quot;2022-01-15_08-11-00.1&quot;,&quot;2022-01-15_08-11-30&quot;,&quot;2022-01-15_08-12-00.1&quot;, &quot;2022-01-15_08-12-30&quot;], &quot;value&quot; : [1,2,3,4]}) </code></pre> <p>I have tried:</p> <pre><code>data.date = data.date.replace(&quot;.1&quot;, &quot;&quot;) </code></pre> <p>and</p> <pre><code>data = data.replace(&quot;.1&quot;, &quot;&quot;) </code></pre> <p>but these did not remove the &quot;.1&quot;. The final result should look like this:</p> <pre><code>data = pd.DataFrame({&quot;date&quot; : [&quot;2022-01-15_08-11-00&quot;,&quot;2022-01-15_08-11-30&quot;,&quot;2022-01-15_08-12-00&quot;, &quot;2022-01-15_08-12-30&quot;], &quot;value&quot; : [1,2,3,4]}) </code></pre>
[ { "answer_id": 74531664, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "pandas.Series.replace data[\"date\"]= pd.to_datetime(data[\"date\"].replace(r\"\\.\\d+\", \"\",\n regex=True),\n format=\"%Y-%m-%d_%H-%M-%S\")\n print(data)\nprint(data.dtypes)\n\n date value\n0 2022-01-15 08:11:00 1\n1 2022-01-15 08:11:30 2\n2 2022-01-15 08:12:00 3\n3 2022-01-15 08:12:30 4\ndate datetime64[ns]\nvalue int64\ndtype: object\n data[\"date\"].replace(r\"\\.\\d+\", \"\", regex=True)" }, { "answer_id": 74531822, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 0, "selected": false, "text": "data = data.assign(date=pd.to_datetime(data['date'].str.split('\\.').str[0], format=\"%Y-%m-%d_%H-%M-%S\"))\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15213361/" ]
74,531,581
<p>I have this code to hide and show menu when scroll. How can i do it to appear class only of scroll &gt;= than 500px. I have traied to ad a if (scroll &gt;= 500) on code but it wont work.</p> <pre><code>jQuery(document).ready(function( $ ) { // console.log($); var lastScrollTop = 200; $(window).scroll(function(event){ var st = $(this).scrollTop(); if (st &gt; lastScrollTop){ $('nav').addClass('nav-off'); $('nav').removeClass('nav-on'); } else { $('nav').addClass('nav-on'); $('nav').removeClass('nav-off'); } lastScrollTop = st; }); </code></pre> <p>});</p>
[ { "answer_id": 74531664, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "pandas.Series.replace data[\"date\"]= pd.to_datetime(data[\"date\"].replace(r\"\\.\\d+\", \"\",\n regex=True),\n format=\"%Y-%m-%d_%H-%M-%S\")\n print(data)\nprint(data.dtypes)\n\n date value\n0 2022-01-15 08:11:00 1\n1 2022-01-15 08:11:30 2\n2 2022-01-15 08:12:00 3\n3 2022-01-15 08:12:30 4\ndate datetime64[ns]\nvalue int64\ndtype: object\n data[\"date\"].replace(r\"\\.\\d+\", \"\", regex=True)" }, { "answer_id": 74531822, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 0, "selected": false, "text": "data = data.assign(date=pd.to_datetime(data['date'].str.split('\\.').str[0], format=\"%Y-%m-%d_%H-%M-%S\"))\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20500636/" ]
74,531,582
<p>Below is my function and output. I want to remove the <code>\n</code> present in the output.</p> <pre><code>def printInventory(): fh = open(&quot;stock.txt&quot;,&quot;r&quot;) print('Current Inventory') print('-----------------') L=fh.readlines() print(&quot;List of all Stock Items&quot;) for i in L: L=i.split(&quot;,&quot;) print(L) CHOICE = int(input('Enter 98 to continue or 99 to exit: ')) if CHOICE == 98: menuDisplay() else: exit() </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>List of all Stock Items ['APPLE', '100\n'] ['BANANA', '50\n'] ['CHILLI', '100\n'] ['MANGO', '300\n'] </code></pre> <p>I would like to remove the <code>\n</code> from the output</p>
[ { "answer_id": 74531664, "author": "abokey", "author_id": 16120011, "author_profile": "https://Stackoverflow.com/users/16120011", "pm_score": 2, "selected": true, "text": "pandas.Series.replace data[\"date\"]= pd.to_datetime(data[\"date\"].replace(r\"\\.\\d+\", \"\",\n regex=True),\n format=\"%Y-%m-%d_%H-%M-%S\")\n print(data)\nprint(data.dtypes)\n\n date value\n0 2022-01-15 08:11:00 1\n1 2022-01-15 08:11:30 2\n2 2022-01-15 08:12:00 3\n3 2022-01-15 08:12:30 4\ndate datetime64[ns]\nvalue int64\ndtype: object\n data[\"date\"].replace(r\"\\.\\d+\", \"\", regex=True)" }, { "answer_id": 74531822, "author": "wwnde", "author_id": 8986975, "author_profile": "https://Stackoverflow.com/users/8986975", "pm_score": 0, "selected": false, "text": "data = data.assign(date=pd.to_datetime(data['date'].str.split('\\.').str[0], format=\"%Y-%m-%d_%H-%M-%S\"))\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20403674/" ]
74,531,610
<p>For example I would like to have:</p> <p>a</p> <p>. . .</p> <p>z</p> <p>aa</p> <p>ab</p> <p>. . .</p> <p>az</p> <p>bz</p> <p>. . .</p> <p>zz</p> <p>aaa</p> <p>and so on.</p> <p>Currently I'm here but I am lost. So feel free to propose a completely different solution.</p> <pre><code>count = 0 string = '' for i in range(100): count += 1 if i % 26 == 0: count = 0 string += 'a' ch = 'a' x = chr(ord(ch) + count) string = string[:-1] + x print(i + 1, string) </code></pre> <p>and my output is something like this:</p> <p>1 a</p> <p>2 b</p> <p>. . .</p> <p>26 z</p> <p>27 za</p> <p>28 zb</p> <p>. . .</p> <p>52 zz</p> <p>53 zza</p> <p>54 zzb</p> <p>. . .</p>
[ { "answer_id": 74531759, "author": "Noah", "author_id": 14028308, "author_profile": "https://Stackoverflow.com/users/14028308", "pm_score": 2, "selected": false, "text": "def printcharachters(base, depth):\n if depth > 0:\n for a in range(97, 123):\n print(base + chr(a))\n\n for a in range(97, 123):\n printcharachters(base + chr(a), depth - 1)\n\n\n\nprintcharachters(\"\", 2)\n" }, { "answer_id": 74531869, "author": "SUTerliakov", "author_id": 14401160, "author_profile": "https://Stackoverflow.com/users/14401160", "pm_score": 2, "selected": true, "text": "import itertools\nimport string\n\n\nfor i in range(1, 3): # Print items of length 1 and 2\n for prod in itertools.product(string.ascii_lowercase, repeat=i):\n print(''.join(prod))\n {'a'...'z'} n X (x_1, ..., x_n) x_i X itertools.product string.ascii_lowercase a..z itertools" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
74,531,622
<p>I am trying to get a good grasp of the State-Monad (and Monads in general) but I am struggling with rewriting the below function using the state Monad and the do-notation, which resulted as an exercise for me propose <a href="https://stackoverflow.com/questions/74404325/calculationg-perplexity-in-natural-language-processing-manually/74404591?noredirect=1#comment131448568_74404591">here</a></p> <pre><code>import Control.Monad import System.Random import Data.Complex import qualified System.Random as R import Control.Monad.Trans.State.Lazy giveRandomElement :: [a] -&gt; State R.StdGen a giveRandomElement lst = do let n = length lst rand &lt;- state $ randomR (0, n-1) return $ lst !! rand random_response_monad :: a -&gt; [a] -&gt; State R.StdGen a random_response_monad true_answer answers = do tal &lt;- state $ randomR (0, 1) :: StateT StdGen Data.Functor.Identity.Identity a if (tal == 0) then true_answer else giveRandomElement answers </code></pre> <p>As is immediately obvious there are some type problems for the <code>tal</code>-variable as it occurs in the <code>if</code>-clause and the first line of the <code>do</code>-expression. As is visible from the code I have tried to force the latter by a specific type in order to make it unambiguous and clearer for myself as well. I have done so by the compiler-suggestion I got when I first tried to force it to be of the <code>Int</code>-type. I Am however not able to use that value in an if-statement, and I am unsure of how to convert or unpack the value such that I get it as an <code>Int</code>. So far I have tried to add the folloowing line after <code>tal &lt;- ...</code> , <code>resp &lt;- get $ tal</code> but I get this output.</p> <pre><code>error: * Couldn't match expected type: t0 -&gt; StateT StdGen Data.Functor.Identity.Identity a1 with actual type: StateT s0 m0 s0 * The first argument of ($) takes one value argument, but its type `StateT s0 m0 s0' has none In a stmt of a 'do' block: resp &lt;- get $ tal In the expression: do tal &lt;- state $ randomR (0, 1) resp &lt;- get $ tal if (resp == 0) then giveRandomElement answers else giveRandomElement answers * Relevant bindings include tal :: t0 </code></pre> <p>Furthermore I am baffled what would be the best way to 'print' the result returned by <code>giveRandomElement</code> as the type is based on the type declared for the <code>State</code>-monad which as I understand it doesn't use the <code>deriving Show</code> also. But this can perhaps be solved by unpacking the value as enquired about above.</p> <p><strong>EDIT</strong></p> <p>I used the above packages although they are probably not all used in the above code. I am unsure of which is used by the code by I suspect the <code>qualified System.Random as R</code></p>
[ { "answer_id": 74531759, "author": "Noah", "author_id": 14028308, "author_profile": "https://Stackoverflow.com/users/14028308", "pm_score": 2, "selected": false, "text": "def printcharachters(base, depth):\n if depth > 0:\n for a in range(97, 123):\n print(base + chr(a))\n\n for a in range(97, 123):\n printcharachters(base + chr(a), depth - 1)\n\n\n\nprintcharachters(\"\", 2)\n" }, { "answer_id": 74531869, "author": "SUTerliakov", "author_id": 14401160, "author_profile": "https://Stackoverflow.com/users/14401160", "pm_score": 2, "selected": true, "text": "import itertools\nimport string\n\n\nfor i in range(1, 3): # Print items of length 1 and 2\n for prod in itertools.product(string.ascii_lowercase, repeat=i):\n print(''.join(prod))\n {'a'...'z'} n X (x_1, ..., x_n) x_i X itertools.product string.ascii_lowercase a..z itertools" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049138/" ]
74,531,639
<p>I am having an array like this : <code>arr = [ {id:0,name:Mark} , {id:1,name:Ron}, {id:2,name:Henry}, {id:3,name:Rose}]</code>.</p> <p>I want to create an object like this :</p> <p><code>obj1 = { Mark:false, Ron:false, Henry:false, Rose:flase }</code></p> <p>I am using <code>map</code> to traverse through the array like this</p> <pre><code>let obj1 = {}; obj1 = arr.map((item)=&gt; { obj1[item.name] = false; }) </code></pre> <p>How can I achieve the following result?</p>
[ { "answer_id": 74531759, "author": "Noah", "author_id": 14028308, "author_profile": "https://Stackoverflow.com/users/14028308", "pm_score": 2, "selected": false, "text": "def printcharachters(base, depth):\n if depth > 0:\n for a in range(97, 123):\n print(base + chr(a))\n\n for a in range(97, 123):\n printcharachters(base + chr(a), depth - 1)\n\n\n\nprintcharachters(\"\", 2)\n" }, { "answer_id": 74531869, "author": "SUTerliakov", "author_id": 14401160, "author_profile": "https://Stackoverflow.com/users/14401160", "pm_score": 2, "selected": true, "text": "import itertools\nimport string\n\n\nfor i in range(1, 3): # Print items of length 1 and 2\n for prod in itertools.product(string.ascii_lowercase, repeat=i):\n print(''.join(prod))\n {'a'...'z'} n X (x_1, ..., x_n) x_i X itertools.product string.ascii_lowercase a..z itertools" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10962364/" ]
74,531,688
<p>minDate = today</p> <p>maxDate = minDate + 5yrs</p> <p>I did not try anything. Asking for solution</p>
[ { "answer_id": 74531804, "author": "Mina", "author_id": 11887902, "author_profile": "https://Stackoverflow.com/users/11887902", "pm_score": 1, "selected": false, "text": "date minDate maxDate const currentDate = new Date()\n\nfunction addYears(date, years) {\n date.setFullYear(date.getFullYear() + years);\n return date;\n}\n\n return (\n <DatePicker\n ...props here\n minDate={currentDate}\n maxDate={addYears(currentDate, 5)}\n />\n );\n" }, { "answer_id": 74531955, "author": "Zablon", "author_id": 10580231, "author_profile": "https://Stackoverflow.com/users/10580231", "pm_score": 0, "selected": false, "text": "dayjs const minDate = dayjs();\nconst maxDate = minDate.add(5, 'year');\n// const maxDate = minDate.add(5, 'y');\n\nreturn (\n <DatePicker\n ...props\n minDate={minDate}\n maxDate={maxDate}\n />\n);\n" }, { "answer_id": 74532120, "author": "Thaiyalnayaki", "author_id": 15431167, "author_profile": "https://Stackoverflow.com/users/15431167", "pm_score": 0, "selected": false, "text": "import DatePicker from \"react-datepicker\";\nimport \"react-datepicker/dist/react-datepicker.css\";\n\n\n() => {\n const [startDate, setStartDate] = useState(null);\n return (\n <DatePicker\n selected={startDate}\n onChange={(date) => setStartDate(date)}\n minDate={new Date()}\n maxDate={addMonths(new Date(), 60)}\n placeholderText=\"Select a date between today and 5 years in the future\"\n />\n );\n};\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16242515/" ]
74,531,722
<p>I have an issue for which I'm not sure if I am getting the right path to the soluction, hope you guys could help me out.</p> <p>I have added an extra field to my serializer, called distance (distance is equal the distance in miles between 2 different locations) I am looking to return the Business Object order my this new field, would it be possible? or am I taking the wrong path for this soluction?</p> <p>Down here you have my Serializer and ModelViewSet</p> <p>Serializer</p> <pre><code>class BusinessesSerializer(serializers.ModelSerializer): distance = serializers.SerializerMethodField('get_location') class Meta: model= Businesses fields = ('id', 'address_first_line', 'address_second_line', 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance') def get_location(self, business): ip_info = requests.get('https://api64.ipify.org?format=json').json() ip_address = ip_info[&quot;ip&quot;] response = requests.get(f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json() latitude = response.get(&quot;latitude&quot;) longitude = response.get(&quot;longitude&quot;) first = (float(latitude), float(longitude)) second = (business.lat, business.long) distance = great_circle(first, second).miles return distance </code></pre> <p>ModelViewSet</p> <pre><code>class BusinessesViewSet(ModelViewSet): serializer_class = BusinessesSerializer queryset = Businesses.objects.all() </code></pre>
[ { "answer_id": 74531995, "author": "ThomasGth", "author_id": 6106166, "author_profile": "https://Stackoverflow.com/users/6106166", "pm_score": 0, "selected": false, "text": "annotate()" }, { "answer_id": 74532455, "author": "Eugene", "author_id": 874027, "author_profile": "https://Stackoverflow.com/users/874027", "pm_score": 2, "selected": true, "text": "class BusinessesAPIView(APIView):\n\n def get(self, request):\n # Get IP info once\n ip_info = requests.get('https://api64.ipify.org?format=json').json()\n ip_address = ip_info[\"ip\"]\n response = requests.get(\n f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json()\n latitude = response.get(\"latitude\")\n longitude = response.get(\"longitude\")\n first = (float(latitude), float(longitude))\n\n # Calculate distances for all businesses and pass them as a context to our serializer\n businesses = Businesses.objects.all()\n distances = {}\n for business in businesses:\n second = (business.lat, business.long)\n distance = great_circle(first, second).miles\n distances[business.id] = distance\n\n # Sort by distance\n businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data\n businesses_processed.sort(key=lambda x: x['distance'])\n\n return Response({'businesses': businesses_processed})\n\n\nclass BusinessesSerializer(serializers.ModelSerializer):\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model= Businesses\n fields = ('id', 'address_first_line', 'address_second_line',\n 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance')\n\n # Get distance by business id from context we passed from our APIView\n def get_distance(self, business):\n return self.context['distances'][business.id]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17862124/" ]
74,531,768
<p>Good morning guys, my problem is simple:</p> <p>Given a dataframe like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3, 4, 5, 6], 'b': [8, 18, 27, 20, 33, 49], 'c': [2, 24, 6, 16, 20, 52]}) print(df) </code></pre> <p>I would like to retrieve for each row the maximum value and compare it with all the others. If the difference is &gt;10, create another column with a string 'yes' or 'not'</p> <pre><code> a b c 0 1 8 2 1 2 18 24 2 3 27 6 3 4 20 16 4 5 33 20 5 6 49 52 </code></pre> <p>I expect this result:</p> <pre><code> a b c res 0 1 8 2 not 1 2 18 24 not 2 3 27 6 yes 3 4 20 16 not 4 5 33 20 yes 5 6 49 52 not </code></pre> <p>Thanks a lot in advance.</p>
[ { "answer_id": 74531995, "author": "ThomasGth", "author_id": 6106166, "author_profile": "https://Stackoverflow.com/users/6106166", "pm_score": 0, "selected": false, "text": "annotate()" }, { "answer_id": 74532455, "author": "Eugene", "author_id": 874027, "author_profile": "https://Stackoverflow.com/users/874027", "pm_score": 2, "selected": true, "text": "class BusinessesAPIView(APIView):\n\n def get(self, request):\n # Get IP info once\n ip_info = requests.get('https://api64.ipify.org?format=json').json()\n ip_address = ip_info[\"ip\"]\n response = requests.get(\n f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json()\n latitude = response.get(\"latitude\")\n longitude = response.get(\"longitude\")\n first = (float(latitude), float(longitude))\n\n # Calculate distances for all businesses and pass them as a context to our serializer\n businesses = Businesses.objects.all()\n distances = {}\n for business in businesses:\n second = (business.lat, business.long)\n distance = great_circle(first, second).miles\n distances[business.id] = distance\n\n # Sort by distance\n businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data\n businesses_processed.sort(key=lambda x: x['distance'])\n\n return Response({'businesses': businesses_processed})\n\n\nclass BusinessesSerializer(serializers.ModelSerializer):\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model= Businesses\n fields = ('id', 'address_first_line', 'address_second_line',\n 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance')\n\n # Get distance by business id from context we passed from our APIView\n def get_distance(self, business):\n return self.context['distances'][business.id]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8064373/" ]
74,531,778
<p>I'm making a category selection section that is supposed to overflow on small viewports and be scrollable.</p> <p>But for some reason when I add flex gap its only adding space to the left of the children.</p> <p><a href="https://codepen.io/DanNisenson/pen/xxzYYpq" rel="nofollow noreferrer">https://codepen.io/DanNisenson/pen/xxzYYpq</a></p> <p>`</p> <pre><code>.sections { display: flex; align-items: center; gap: 1.5rem; font-weight: 700; } </code></pre> <p>`</p> <p>For the moment I've removed the gap property and set padding left and right to the children. Can anyone tell me what I'm missing?</p>
[ { "answer_id": 74531995, "author": "ThomasGth", "author_id": 6106166, "author_profile": "https://Stackoverflow.com/users/6106166", "pm_score": 0, "selected": false, "text": "annotate()" }, { "answer_id": 74532455, "author": "Eugene", "author_id": 874027, "author_profile": "https://Stackoverflow.com/users/874027", "pm_score": 2, "selected": true, "text": "class BusinessesAPIView(APIView):\n\n def get(self, request):\n # Get IP info once\n ip_info = requests.get('https://api64.ipify.org?format=json').json()\n ip_address = ip_info[\"ip\"]\n response = requests.get(\n f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json()\n latitude = response.get(\"latitude\")\n longitude = response.get(\"longitude\")\n first = (float(latitude), float(longitude))\n\n # Calculate distances for all businesses and pass them as a context to our serializer\n businesses = Businesses.objects.all()\n distances = {}\n for business in businesses:\n second = (business.lat, business.long)\n distance = great_circle(first, second).miles\n distances[business.id] = distance\n\n # Sort by distance\n businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data\n businesses_processed.sort(key=lambda x: x['distance'])\n\n return Response({'businesses': businesses_processed})\n\n\nclass BusinessesSerializer(serializers.ModelSerializer):\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model= Businesses\n fields = ('id', 'address_first_line', 'address_second_line',\n 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance')\n\n # Get distance by business id from context we passed from our APIView\n def get_distance(self, business):\n return self.context['distances'][business.id]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16226698/" ]
74,531,780
<p>I have my date in entry :</p> <pre><code>2022-11-21T21:07:56.830-07:00 </code></pre> <p>And I would like to transform it like that:</p> <pre><code>21/11/2022 07:56 </code></pre>
[ { "answer_id": 74531995, "author": "ThomasGth", "author_id": 6106166, "author_profile": "https://Stackoverflow.com/users/6106166", "pm_score": 0, "selected": false, "text": "annotate()" }, { "answer_id": 74532455, "author": "Eugene", "author_id": 874027, "author_profile": "https://Stackoverflow.com/users/874027", "pm_score": 2, "selected": true, "text": "class BusinessesAPIView(APIView):\n\n def get(self, request):\n # Get IP info once\n ip_info = requests.get('https://api64.ipify.org?format=json').json()\n ip_address = ip_info[\"ip\"]\n response = requests.get(\n f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json()\n latitude = response.get(\"latitude\")\n longitude = response.get(\"longitude\")\n first = (float(latitude), float(longitude))\n\n # Calculate distances for all businesses and pass them as a context to our serializer\n businesses = Businesses.objects.all()\n distances = {}\n for business in businesses:\n second = (business.lat, business.long)\n distance = great_circle(first, second).miles\n distances[business.id] = distance\n\n # Sort by distance\n businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data\n businesses_processed.sort(key=lambda x: x['distance'])\n\n return Response({'businesses': businesses_processed})\n\n\nclass BusinessesSerializer(serializers.ModelSerializer):\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model= Businesses\n fields = ('id', 'address_first_line', 'address_second_line',\n 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance')\n\n # Get distance by business id from context we passed from our APIView\n def get_distance(self, business):\n return self.context['distances'][business.id]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19471847/" ]
74,531,796
<p>I have a dataframe like below:</p> <pre><code> TileDesc ReportDesc UrlLink 'AA' 'New Report-1' 'link-1' 'AA' 'New Report-2' 'link-2' 'AA' 'New Report-1' 'link-1' 'AA' 'New Report-1' 'link-1' 'AA' 'New Report-1' 'link-1' 'BB' 'New Report-4' 'link-4' 'BB' 'New Report-2' 'link-2' 'BB' 'New Report-4' 'link-4' 'BB' 'New Report-6' 'link-6' </code></pre> <p>Now I want to add a column to this that will maintain a sequence of integer which would change after every 2 consecutive times. So the resultant dataframe would look like:</p> <pre><code> TileDesc ReportDesc UrlLink Group 'AA' 'New Report-1' 'link-1' 1 'AA' 'New Report-2' 'link-2' 1 'AA' 'New Report-1' 'link-1' 2 'AA' 'New Report-4' 'link-4' 2 'AA' 'New Report-6' 'link-1' 3 'BB' 'New Report-4' 'link-4' 1 'BB' 'New Report-2' 'link-2' 1 'BB' 'New Report-4' 'link-4' 2 'BB' 'New Report-6' 'link-6' 2 </code></pre> <p>I am following the <code>ngroup()</code> approach but not able to get through.</p> <pre><code>df['Group'] = df.groupby(['TileDesc']).ngroup() </code></pre> <p>The above code snippet is giving me same Group Number for each Group. I.e. for <code>AA</code> for all three I am getting 0, and then for all <code>BB</code> I am getting 1 and so on.</p> <p>My second approach was more like:</p> <pre><code>df['Index'] = df.index + 1 df['Group'] = df['Index'].apply(lambda x : math.ceil(x/4)) </code></pre> <p>But this doesn't consider <code>TileDesc</code></p> <p>What I am missing here?</p> <p><strong>Edit</strong> The group value ONLY changes after each two consecutive row within a TileDesc group.</p>
[ { "answer_id": 74531995, "author": "ThomasGth", "author_id": 6106166, "author_profile": "https://Stackoverflow.com/users/6106166", "pm_score": 0, "selected": false, "text": "annotate()" }, { "answer_id": 74532455, "author": "Eugene", "author_id": 874027, "author_profile": "https://Stackoverflow.com/users/874027", "pm_score": 2, "selected": true, "text": "class BusinessesAPIView(APIView):\n\n def get(self, request):\n # Get IP info once\n ip_info = requests.get('https://api64.ipify.org?format=json').json()\n ip_address = ip_info[\"ip\"]\n response = requests.get(\n f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json()\n latitude = response.get(\"latitude\")\n longitude = response.get(\"longitude\")\n first = (float(latitude), float(longitude))\n\n # Calculate distances for all businesses and pass them as a context to our serializer\n businesses = Businesses.objects.all()\n distances = {}\n for business in businesses:\n second = (business.lat, business.long)\n distance = great_circle(first, second).miles\n distances[business.id] = distance\n\n # Sort by distance\n businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data\n businesses_processed.sort(key=lambda x: x['distance'])\n\n return Response({'businesses': businesses_processed})\n\n\nclass BusinessesSerializer(serializers.ModelSerializer):\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model= Businesses\n fields = ('id', 'address_first_line', 'address_second_line',\n 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance')\n\n # Get distance by business id from context we passed from our APIView\n def get_distance(self, business):\n return self.context['distances'][business.id]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7290715/" ]
74,531,827
<p>When I am injecting an object as below, it works properly</p> <pre><code>@Provides @Singleton public CommandObject getCommandObject(final Command command) { ... } </code></pre> <p>But as soon as I add @Named to above it starts giving error</p> <p>CommandObject cannot be provided without an @Inject constructor or from an @Provides-annotated method</p> <p>What am I missing here?</p>
[ { "answer_id": 74531995, "author": "ThomasGth", "author_id": 6106166, "author_profile": "https://Stackoverflow.com/users/6106166", "pm_score": 0, "selected": false, "text": "annotate()" }, { "answer_id": 74532455, "author": "Eugene", "author_id": 874027, "author_profile": "https://Stackoverflow.com/users/874027", "pm_score": 2, "selected": true, "text": "class BusinessesAPIView(APIView):\n\n def get(self, request):\n # Get IP info once\n ip_info = requests.get('https://api64.ipify.org?format=json').json()\n ip_address = ip_info[\"ip\"]\n response = requests.get(\n f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json()\n latitude = response.get(\"latitude\")\n longitude = response.get(\"longitude\")\n first = (float(latitude), float(longitude))\n\n # Calculate distances for all businesses and pass them as a context to our serializer\n businesses = Businesses.objects.all()\n distances = {}\n for business in businesses:\n second = (business.lat, business.long)\n distance = great_circle(first, second).miles\n distances[business.id] = distance\n\n # Sort by distance\n businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data\n businesses_processed.sort(key=lambda x: x['distance'])\n\n return Response({'businesses': businesses_processed})\n\n\nclass BusinessesSerializer(serializers.ModelSerializer):\n distance = serializers.SerializerMethodField()\n\n class Meta:\n model= Businesses\n fields = ('id', 'address_first_line', 'address_second_line',\n 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance')\n\n # Get distance by business id from context we passed from our APIView\n def get_distance(self, business):\n return self.context['distances'][business.id]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10110256/" ]
74,531,839
<p>I have a db table design like so:</p> <p>Table Appointments:</p> <p>id| start_time| patientId |.. etc other fields |</p> <p>And another table which is Patient table:</p> <p>id| name | last_name | .. etc other fields |</p> <p>On my appointment entity I have this defintion:</p> <pre><code>@OneToMany(() =&gt; AppointmentEntity, (appt) =&gt; appt.patient) appointments: Relation&lt;AppointmentEntity&gt;[]; </code></pre> <p>Here is what I'm trying to do, given an appointment id, fetch appointment details as well as patients first name, should be very straight forward. This is what I ended up doing:</p> <pre><code> async getAppt(apptId: any) { return this.apptRepo.findOne({ relations: ['patient'], where: { id: apptId }, select: { id: true, start_time: true patient: { name: true, }, }, }); } </code></pre> <p>This does give me expected results, but for whatever reason I am running two completely unnecessary db queries, instead of one. This is what gets run each time <code>getAppt</code> is executed:</p> <pre><code>query: SELECT DISTINCT &quot;distinctAlias&quot;.&quot;AppointmentEntity_id&quot; AS &quot;ids_AppointmentEntity_id&quot; FROM (SELECT &quot;AppointmentEntity&quot;.&quot;id&quot; AS &quot;AppointmentEntity_id&quot;, &quot;AppointmentEntity&quot;.&quot;start_time&quot; AS &quot;AppointmentEntity_start_time&quot;, &quot;AppointmentEntity__AppointmentEntity_patient&quot;.&quot;name&quot; AS &quot;AppointmentEntity__AppointmentEntity_patient_name&quot; FROM &quot;appointments&quot; &quot;AppointmentEntity&quot; LEFT JOIN &quot;patients&quot; &quot;AppointmentEntity__AppointmentEntity_patient&quot; ON &quot;AppointmentEntity__AppointmentEntity_patient&quot;.&quot;id&quot;=&quot;AppointmentEntity&quot;.&quot;patientId&quot; WHERE (&quot;AppointmentEntity&quot;.&quot;id&quot; = $1)) &quot;distinctAlias&quot; ORDER BY &quot;AppointmentEntity_id&quot; ASC LIMIT 1 -- PARAMETERS: [&quot;appt_id_xxx&quot;] query: SELECT &quot;AppointmentEntity&quot;.&quot;id&quot; AS &quot;AppointmentEntity_id&quot;, &quot;AppointmentEntity&quot;.&quot;start_time&quot; AS &quot;AppointmentEntity_start_time&quot;, &quot;AppointmentEntity__AppointmentEntity_patient&quot;.&quot;name&quot; AS &quot;AppointmentEntity__AppointmentEntity_patient_name&quot; FROM &quot;appointments&quot; &quot;AppointmentEntity&quot; LEFT JOIN &quot;patients&quot; &quot;AppointmentEntity__AppointmentEntity_patient&quot; ON &quot;AppointmentEntity__AppointmentEntity_patient&quot;.&quot;id&quot;=&quot;AppointmentEntity&quot;.&quot;patientId&quot; WHERE ( (&quot;AppointmentEntity&quot;.&quot;id&quot; = $1) ) AND ( &quot;AppointmentEntity&quot;.&quot;id&quot; IN ($2) ) -- PARAMETERS: [&quot;appt_id_xxx&quot;,&quot;appt_id_xxx&quot; </code></pre> <p>What I really wanted my query to execute is (one query):</p> <pre><code>select b.id, b.start_time, p.name from appointments b inner join patients p on p.id = b.&quot;patientId&quot; where b.id = 'appt_id_xxx'; </code></pre> <p>Or something similar to this, it's fine without aliases &quot;b&quot; and &quot;p&quot;, it's just how I write queries, but this is all it takes. I don't get this <code>distinctAlias</code> nonsence and why there are two db queries.</p> <p>Can you advise on how to accomplish one query (or similar), like shown above? thanks!</p>
[ { "answer_id": 74633145, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 1, "selected": false, "text": "createQueryBuilder(\"user\") createQueryBuilder(\"user\") createQueryBuilder().select(\"user\").from(User, \"user\")\n SELECT ... FROM users user\n createQueryBuilder()\n .select(\"user\")\n .from(User, \"user\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n SELECT ... FROM users user WHERE user.name = 'Timber'\n createQueryBuilder left-join leftJoinAndSelect createQueryBuilder" }, { "answer_id": 74659173, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 0, "selected": false, "text": "@OneToMany(() => AppointmentEntity, (appt) => appt.patient, { eager: true })\nappointments: Relation<AppointmentEntity>[];\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3616806/" ]
74,531,872
<p>I have a page on URL root, which is a Next page built with React.</p> <p>And now I want to expose an API endpoint on root too.</p> <pre><code>`http://localhost:3000/` &gt; points to React page `http://localhost:3000/foo` &gt; points to the Next API endpoint `http://localhost:3000/bar` &gt; points to the **same** Next API endpoint `http://localhost:3000/anything` &gt; points to the **same** Next API endpoint </code></pre> <p>Is it possible to rewrite the root path to an API endpoint? If yes, how?</p>
[ { "answer_id": 74633145, "author": "Rohit Khandelwal", "author_id": 15220748, "author_profile": "https://Stackoverflow.com/users/15220748", "pm_score": 1, "selected": false, "text": "createQueryBuilder(\"user\") createQueryBuilder(\"user\") createQueryBuilder().select(\"user\").from(User, \"user\")\n SELECT ... FROM users user\n createQueryBuilder()\n .select(\"user\")\n .from(User, \"user\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n SELECT ... FROM users user WHERE user.name = 'Timber'\n createQueryBuilder left-join leftJoinAndSelect createQueryBuilder" }, { "answer_id": 74659173, "author": "Friedrich", "author_id": 2689500, "author_profile": "https://Stackoverflow.com/users/2689500", "pm_score": 0, "selected": false, "text": "@OneToMany(() => AppointmentEntity, (appt) => appt.patient, { eager: true })\nappointments: Relation<AppointmentEntity>[];\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832490/" ]
74,531,889
<p>I have the following function:</p> <pre><code> public static string ShortMonthDayPattern(this DateTimeFormatInfo dateTimeFormatInfo) { // Basically takes the ShortDatePattern (dd-mm-yyyy, mm/dd/yyyy, etc) and strips everything except the dd-mm, mm/dd, etc. string shortPattern = dateTimeFormatInfo.ShortDatePattern; while (shortPattern[0] != 'd' &amp;&amp; shortPattern[0] != 'M') { shortPattern = shortPattern.Substring(1); if (shortPattern.Length == 0) return dateTimeFormatInfo.ShortDatePattern; } while (shortPattern[shortPattern.Length - 1] != 'd' &amp;&amp; shortPattern[shortPattern.Length - 1] != 'M') { shortPattern = shortPattern.Substring(0, shortPattern.Length - 1); if (shortPattern.Length == 0) return dateTimeFormatInfo.ShortDatePattern; } return shortPattern; } </code></pre> <p>I test this with the following unittest:</p> <pre><code> [TestMethod] public void ShortMonthDayPattern() { CultureInfo cultureNl = new CultureInfo(&quot;nl-NL&quot;); CultureInfo cultureUs = new CultureInfo(&quot;en-US&quot;); Assert.AreEqual(&quot;1-7&quot;, testDate1.ToString(cultureNl.DateTimeFormat.ShortMonthDayPattern(), cultureNl), &quot;Dutch culture&quot;); Assert.AreEqual(&quot;7/1&quot;, testDate1.ToString(cultureUs.DateTimeFormat.ShortMonthDayPattern(), cultureUs), &quot;United States culture&quot;); } </code></pre> <p>This runs fine on my local development machine, but when I push changes to my repo the Build Pipeline breaks with the following message:</p> <pre><code> Failed ShortMonthDayPattern [120 ms] Error Message: Assert.AreEqual failed. Expected:&lt;1-7&gt;. Actual:&lt;01-07&gt;. Dutch culture Stack Trace: at Helper.Test.Extensions.DateTimeFormatInfoExtensionsTest.ShortMonthDayPattern() in D:\a\1\s\Helper.Test\Extensions\DateTimeFormatInfoExtensionsTest.cs:line 22 </code></pre> <p>Since I specify the culture, how is it possible that the test fails on the build agent and succeeds on my local machine?</p>
[ { "answer_id": 74532018, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "ShortMonthDayPattern" }, { "answer_id": 74532272, "author": "Guru Stron", "author_id": 2501279, "author_profile": "https://Stackoverflow.com/users/2501279", "pm_score": 2, "selected": true, "text": "useUserOverride CultureInfo.GetCultureInfo" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6585443/" ]
74,531,927
<p>There are two dict main and input, I want to validate the &quot;input&quot; such that all the keys in the list of dictionary and nested dictionary (if present/all keys are optional) matches that of the main if not the wrong/different key should be returned as the output.</p> <pre><code>main = &quot;app&quot;:[{ &quot;name&quot;: str, &quot;info&quot;: [ { &quot;role&quot;: str, &quot;scope&quot;: {&quot;groups&quot;: list} } ] },{ &quot;name&quot;: str, &quot;info&quot;: [ {&quot;role&quot;: str} ] }] input_data = &quot;app&quot;:[{ 'name': 'nms', 'info': [ { 'role': 'user', 'scope': {'groups': ['xyz'] } }] },{ 'name': 'abc', 'info': [ {'rol': 'user'} ] }] </code></pre> <p>when compared input with main the wrong/different key should be given as output, in this case</p> <p><code>['rol']</code></p>
[ { "answer_id": 74532026, "author": "LITzman", "author_id": 18877953, "author_profile": "https://Stackoverflow.com/users/18877953", "pm_score": 1, "selected": false, "text": "SchemaUnexpectedTypeError input" }, { "answer_id": 74555931, "author": "Kevin Bhavsar", "author_id": 20526646, "author_profile": "https://Stackoverflow.com/users/20526646", "pm_score": 0, "selected": false, "text": "keys = []\ndef print_dict(d):\n if type(d) == dict:\n for val in d.keys():\n df = d[val]\n try:\n if type(df) == list:\n for i in range(0,len(df)):\n if type(df[i]) == dict:\n print_dict(df[i])\n except AttributeError:\n pass\n keys.append(val)\n else:\n try:\n x = d[0]\n if type(x) == dict:\n print_dict(d[0])\n except:\n pass\n return keys\nkeys_input = print_dict(input)\nkeys = []\nkeys_main = print_dict(main)\nprint(keys_input)\n\nprint(keys_main)\n\nfor i in keys_input[:]:\n if i in keys_main:\n keys_input.remove(i)\nprint(keys_input)\n" }, { "answer_id": 74590582, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "input_data == main main = {\"app\": [{\n \"name\": str,\n \"info\": [\n {\n \"role\": str,\n \"scope\": {\"groups\": list}\n }\n ]\n },{\n \"name\": str,\n \"info\": [\n {\"role\": str}\n ]\n}]}\n\ninput_data = {\"app\":[{\n 'name': 'nms',\n 'info': [\n {\n 'role': 'user',\n 'scope': {'groups': ['xyz']\n }\n }]\n},{\n 'name': 'abc',\n 'info': [\n {'rol': 'user'}\n ]\n}]}\n\ninput_data2 = {\"app\": [{\n 'name': 'nms',\n 'info': [\n {\n 'role': 'user',\n 'scope': {'groups': ['xyz']\n }\n }]\n}, {\n 'name': 'abc',\n 'info': [\n {'rol': 'user'}\n ]\n}]}\n input_data2 == input_data # True\nmain == input_data # False\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13754889/" ]
74,531,960
<p>Inner intervals are always inside the global one. All intervals are integer, left-closed, right-open intervals.</p> <p>Let's take this example. The &quot;global&quot; interval is [0, 22[. &quot;Inner&quot; intervals are [3, 6[ and [12, 15[.</p> <p>For this example I expect : [0, 3[ U [3, 6[ U [6, 12[ U [12, 15[ U [15, 22[</p> <p>I've tried to define a function but then messed up with indices while iterating over intervals.</p> <pre class="lang-py prettyprint-override"><code> def allspans(r, spans): pass allspans((0, 22), [(3,6), (12,15)]) # expected : [(0, 3), (3, 6), (6, 12), (12, 15), (15, 22)] </code></pre>
[ { "answer_id": 74532026, "author": "LITzman", "author_id": 18877953, "author_profile": "https://Stackoverflow.com/users/18877953", "pm_score": 1, "selected": false, "text": "SchemaUnexpectedTypeError input" }, { "answer_id": 74555931, "author": "Kevin Bhavsar", "author_id": 20526646, "author_profile": "https://Stackoverflow.com/users/20526646", "pm_score": 0, "selected": false, "text": "keys = []\ndef print_dict(d):\n if type(d) == dict:\n for val in d.keys():\n df = d[val]\n try:\n if type(df) == list:\n for i in range(0,len(df)):\n if type(df[i]) == dict:\n print_dict(df[i])\n except AttributeError:\n pass\n keys.append(val)\n else:\n try:\n x = d[0]\n if type(x) == dict:\n print_dict(d[0])\n except:\n pass\n return keys\nkeys_input = print_dict(input)\nkeys = []\nkeys_main = print_dict(main)\nprint(keys_input)\n\nprint(keys_main)\n\nfor i in keys_input[:]:\n if i in keys_main:\n keys_input.remove(i)\nprint(keys_input)\n" }, { "answer_id": 74590582, "author": "NameVergessen", "author_id": 11003343, "author_profile": "https://Stackoverflow.com/users/11003343", "pm_score": 0, "selected": false, "text": "input_data == main main = {\"app\": [{\n \"name\": str,\n \"info\": [\n {\n \"role\": str,\n \"scope\": {\"groups\": list}\n }\n ]\n },{\n \"name\": str,\n \"info\": [\n {\"role\": str}\n ]\n}]}\n\ninput_data = {\"app\":[{\n 'name': 'nms',\n 'info': [\n {\n 'role': 'user',\n 'scope': {'groups': ['xyz']\n }\n }]\n},{\n 'name': 'abc',\n 'info': [\n {'rol': 'user'}\n ]\n}]}\n\ninput_data2 = {\"app\": [{\n 'name': 'nms',\n 'info': [\n {\n 'role': 'user',\n 'scope': {'groups': ['xyz']\n }\n }]\n}, {\n 'name': 'abc',\n 'info': [\n {'rol': 'user'}\n ]\n}]}\n input_data2 == input_data # True\nmain == input_data # False\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20448700/" ]
74,531,967
<p><a href="https://i.stack.imgur.com/GTZEL.png" rel="nofollow noreferrer">enter image description here</a></p> <p>how to design the top right box in bootstrap with 4 rows and 2 columns.</p> <p>I try grid design and try to give border but i cant able to do it . Can anybody help with this .</p>
[ { "answer_id": 74544039, "author": "Jiale Xue - MSFT", "author_id": 16764901, "author_profile": "https://Stackoverflow.com/users/16764901", "pm_score": 0, "selected": false, "text": "Asp.Net Web Forms css Winforms Wpf" }, { "answer_id": 74550208, "author": "Albert D. Kallal", "author_id": 10527, "author_profile": "https://Stackoverflow.com/users/10527", "pm_score": 1, "selected": false, "text": " <div id=\"block1\" style=\"border:solid;width:30em;padding:25px\">\n <h2>Block1</h2>\n <div style=\"padding:5px;text-align:right\">\n <p>Hotel Name: <asp:TextBox ID=\"HotelName\" runat=\"server\" /></p>\n <p>First Name: <asp:TextBox ID=\"FirstName\" runat=\"server\" /></p>\n <p>Last Name: <asp:TextBox ID=\"LastName\" runat=\"server\" /></p>\n <p>City: <asp:TextBox ID=\"City\" runat=\"server\" /></p>\n <p>Province: <asp:TextBox ID=\"Province\" runat=\"server\" /></p>\n Active: <asp:CheckBox ID=\"Active\" runat=\"server\" />\n </div>\n </div>\n\n\n <div id=\"block2\" style=\"border:solid;width:20%\">\n <h2>Block2</h2>\n </div>\n\n\n <div id=\"block3\" style=\"border:solid;width:20%\">\n <h2>Block3</h2>\n </div>\n <div id=\"block1\" style=\"border:solid;width:30em;padding:25px;float:right\">\n <div id=\"block2\" style=\"border:solid;width:20%;float:left\">\n <h2>Block2</h2>\n </div>\n\n\n <div id=\"block3\" style=\"border:solid;width:20%;float:left\">\n <h2>Block3</h2>\n </div>\n <div id=\"block3\" style=\"border:solid;width:20%;float:left;margin-left:20px\">\n <div id=\"block3\" style=\"border:solid;width:20%;\">\n <div style=\"clear:both\"></div>\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button1\" CssClass=\"btn\"/>\n <asp:Button ID=\"Button2\" runat=\"server\" Text=\"Button2\" CssClass=\"btn\"/>\n <asp:Button ID=\"Button2\" runat=\"server\" Text=\"Button2\" CssClass=\"btn\"\n style=\"margin-left:14px\"/>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18187808/" ]
74,531,991
<p>Faced with the strange behavior of TS.</p> <pre><code>const isItLanding = false; if (isItLanding === undefined) { // valid return ...; } </code></pre> <p>But here</p> <pre><code>const isItLanding = 1; if (isItLanding === 'undefined') { // error return ...; } </code></pre> <p>Why doesn't TS insure against writing invalid comparisons? And how can I change this behavior?</p> <p>My TS config looks like:</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;strict&quot;: true, &quot;target&quot;: &quot;esnext&quot;, &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;], &quot;allowJs&quot;: true, &quot;skipLibCheck&quot;: true, &quot;forceConsistentCasingInFileNames&quot;: true, &quot;noEmit&quot;: true, &quot;esModuleInterop&quot;: true, &quot;module&quot;: &quot;esnext&quot;, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;resolveJsonModule&quot;: true, &quot;isolatedModules&quot;: true, &quot;importsNotUsedAsValues&quot;: &quot;error&quot;, &quot;allowSyntheticDefaultImports&quot;: true, &quot;incremental&quot;: true, &quot;tsBuildInfoFile&quot;: &quot;.next/cache/.tscache/&quot;, &quot;jsx&quot;: &quot;preserve&quot;, &quot;sourceMap&quot;: true, &quot;baseUrl&quot;: &quot;.&quot;, &quot;paths&quot;: { &quot;~/*&quot;: [&quot;src/*&quot;], &quot;test-utils&quot;: [&quot;./src/client/test-utils&quot;] } }, &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;cypress&quot;] } </code></pre>
[ { "answer_id": 74533230, "author": "Warm Red", "author_id": 14209943, "author_profile": "https://Stackoverflow.com/users/14209943", "pm_score": 3, "selected": false, "text": "true false undefined null let bool: boolean = true;\nbool = false;\nbool = null;\nbool = undefined;\n//All compiles without an issue\n\nif(bool === undefined){\n console.log(\"You will see me!\");\n}\n strictNullChecks true undefined null let bool: boolean = true;\nbool = false;\nbool = null; //Error > Type 'null' is not assignable to type 'boolean'.\nbool = undefined; //Error > Type 'undefined' is not assignable to type 'boolean'.\n const bool: boolean = false;\n\nif(bool === undefined){\n console.log(\"I am undefined!\");\n}\nif(bool === null){\n console.log(\"I am null!\");\n}\n\nconsole.log(\"It compiled?\");\n if(12 === undefined){\n console.log(\"impossible isn't it?\");\n}\nif(\"ab\" === null){\n console.log(\"no way it will ever be true!\");\n}\nif(false === undefined){\n console.log(\"never ever\");\n}\n\n/*\nif(12 === \"ab\") \n^this would error as comparison to different types is allowed only with null and undefined\n*/\n\nconsole.log(\"Yet, it will indeed compile\");\n" }, { "answer_id": 74561933, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 0, "selected": false, "text": "undefined null function fn(x: string) {\n if (x === undefined) throw new Error('x cannot be undefined');\n}\n undefined" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74531991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17572785/" ]
74,532,019
<p>I would like to have a header, footer and main content inside a page that never stretches beyond the browser window.</p> <p><a href="https://i.stack.imgur.com/ZEtLS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZEtLS.png" alt="Page layout" /></a></p> <p>If the component inside the main area overflows I would like it to have a scrollbar (<strong>EDIT</strong>: but it should still fill the main area). I tried flexbox, grid, various trails and errors and I could not find the solution if it is even possible. When the component overflows it always stretches the main area so much it pushes the footer out ot the browser boundaries or the main area overflows beyond the footer which stays in place at the bottom of the page.</p> <p>I found this question <a href="https://stackoverflow.com/q/24925510">How to make inner div with overflow:scroll stay inside outer div?</a>, but no combination of <code>height: 100%</code> worked for me.</p> <p><strong>EDIT:</strong> <a href="https://stackblitz.com/edit/web-platform-vwncgo?file=styles.css" rel="nofollow noreferrer">This</a> is my attempt so far</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { box-sizing: border-box; } body { margin: 0; height: 100vh; display: grid; grid-template-rows: 3rem 1fr 3rem; font-family: system-ui, sans-serif; } header, footer { background-color: lightblue; padding: 1rem; text-align: center; } main { padding: 2rem; text-align: center; height: 100%; } .component { background-color: lightblue; padding: 1rem; overflow-y: scroll; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;header&gt;header&lt;/header&gt; &lt;main&gt; &lt;p&gt;main&lt;/p&gt; &lt;div class="component"&gt; Lorem ipsum, dolor sit amet consectetur adipisicing elit. Nulla similique assumenda unde doloribus velit accusantium dolores accusamus iste! Doloribus atque fuga debitis, laboriosam rerum mollitia eum dolorem facilis, officiis, modi voluptatem optio reiciendis delectus minus pariatur nam nulla vitae quasi quis tenetur alias amet eaque molestias. Doloremque ipsam sit fuga ex delectus adipisci et porro perferendis accusantium sequi. Doloribus consequuntur quas quo temporibus saepe accusamus alias porro facilis error, perspiciatis ut rem? Ullam quibusdam quod est molestias? Obcaecati, similique praesentium quaerat doloribus beatae laboriosam corrupti qui, voluptatem officiis sed repellat commodi voluptates! Eos dicta, neque numquam facilis, quidem in laboriosam accusantium expedita hic eaque ad placeat, vitae praesentium temporibus quod. Perferendis consequuntur commodi debitis repellat ullam velit, at inventore repudiandae sit illo placeat autem, corrupti quibusdam praesentium soluta rerum? Minima libero deserunt praesentium suscipit recusandae, similique inventore sunt debitis ut corrupti dolorem placeat iure nemo eos mollitia earum vero dicta illum, necessitatibus rem a? Ad nemo quod possimus cum perferendis eum dicta placeat minima corporis velit impedit incidunt libero mollitia itaque quae inventore molestias dolorum non, aspernatur eos tempore. Sed perferendis corporis eius quod nulla temporibus architecto quia minus officiis maxime! A laborum quisquam tenetur natus consequatur magnam? Totam, illo? &lt;/div&gt; &lt;/main&gt; &lt;footer&gt;footer&lt;/footer&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 74533230, "author": "Warm Red", "author_id": 14209943, "author_profile": "https://Stackoverflow.com/users/14209943", "pm_score": 3, "selected": false, "text": "true false undefined null let bool: boolean = true;\nbool = false;\nbool = null;\nbool = undefined;\n//All compiles without an issue\n\nif(bool === undefined){\n console.log(\"You will see me!\");\n}\n strictNullChecks true undefined null let bool: boolean = true;\nbool = false;\nbool = null; //Error > Type 'null' is not assignable to type 'boolean'.\nbool = undefined; //Error > Type 'undefined' is not assignable to type 'boolean'.\n const bool: boolean = false;\n\nif(bool === undefined){\n console.log(\"I am undefined!\");\n}\nif(bool === null){\n console.log(\"I am null!\");\n}\n\nconsole.log(\"It compiled?\");\n if(12 === undefined){\n console.log(\"impossible isn't it?\");\n}\nif(\"ab\" === null){\n console.log(\"no way it will ever be true!\");\n}\nif(false === undefined){\n console.log(\"never ever\");\n}\n\n/*\nif(12 === \"ab\") \n^this would error as comparison to different types is allowed only with null and undefined\n*/\n\nconsole.log(\"Yet, it will indeed compile\");\n" }, { "answer_id": 74561933, "author": "Tobias S.", "author_id": 8613630, "author_profile": "https://Stackoverflow.com/users/8613630", "pm_score": 0, "selected": false, "text": "undefined null function fn(x: string) {\n if (x === undefined) throw new Error('x cannot be undefined');\n}\n undefined" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1714170/" ]
74,532,078
<p>I try to install Google Analytics, but then my site won't load.</p> <p>I had the error: <code>Uncaught Error: useLocation() may be used only in the context of a &lt;Router&gt; component.</code> So I added <code>&lt;Routes&gt;</code> to <code>index.js</code></p> <p>Index.js:</p> <pre class="lang-js prettyprint-override"><code>import React from &quot;react&quot;; import ReactDOM from &quot;react-dom/client&quot;; import App from &quot;./App&quot;; import { HelmetProvider } from &quot;react-helmet-async&quot;; import { Router } from &quot;react-router-dom&quot;; const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;)); root.render( &lt;Router&gt; &lt;HelmetProvider&gt; &lt;App /&gt; &lt;/HelmetProvider&gt; &lt;/Router&gt; ); </code></pre> <p>My App.js:</p> <pre class="lang-js prettyprint-override"><code>import React from &quot;react&quot;; import ReactGA from &quot;react-ga&quot;; import InitializeReactGA from &quot;./components/helper/googleAnalytics&quot;; import { BrowserRouter as Router, Routes, Route, useLocation, } from &quot;react-router-dom&quot;; import { useEffect } from &quot;react&quot;; ... const TRACKING_ID = &quot;A-1234567890&quot; ReactGA.initialize(TRACKING_ID ); function usePageViews() { let location = useLocation(); useEffect(() =&gt; { InitializeReactGA(ReactGA); ReactGA.set({ page: location.pathname }); ReactGA.pageview(location.pathname); }, [location]); function App() { usePageViews(); return ( &lt;&gt; &lt;Router&gt; &lt;Navbar /&gt; &lt;Routes&gt; &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt; &lt;Route path=&quot;/abouts&quot; element={&lt;AboutUs /&gt;} /&gt; ..... &lt;/Routes&gt; &lt;Footer /&gt; &lt;/Router&gt; &lt;/&gt; ); } </code></pre> <p>GA helper:</p> <pre class="lang-js prettyprint-override"><code> function InitializeReactGA(ReactGA) { if (!window.GA_INITIALIZED) { ReactGA.initialize(&quot;MANDO_GA&quot;); //just copied that, don't know what MANDO_GA is window.GA_INITIALIZED = true; } } export default InitializeReactGA; </code></pre> <p>now I get the error: <code>components.tsx:197 Uncaught TypeError: Cannot read properties of undefined (reading 'pathname')</code></p>
[ { "answer_id": 74532839, "author": "Spluli", "author_id": 19749827, "author_profile": "https://Stackoverflow.com/users/19749827", "pm_score": 1, "selected": true, "text": "\n<Router>\n <HelmetProvider>\n <App />\n </HelmetProvider>\n </Router>\n\n \nfunction App() {\n usePageViews();\n\n return (\n <>\n {/* DELETED! Router DELETED! */}\n <Navbar />\n <Routes>\n <Route path=\"/\" element={<Home />} />\n <Route path=\"/abouts\" element={<AboutUs />} />\n .....\n </Routes>\n <Footer />\n {/* DELETED! /Router DELETED!*/}\n \n </>\n );\n}\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19749827/" ]
74,532,080
<p>I created an android app using flutter After it was released for internal testing the app download page on google play shows the app name as the flutter package name. I changed the app name from the app settings on google play console, but it is still the same.</p> <p>Is it because of the internal testing app? will it be okay after moved to production?</p>
[ { "answer_id": 74532247, "author": "Abdullatif Eida", "author_id": 20570798, "author_profile": "https://Stackoverflow.com/users/20570798", "pm_score": 1, "selected": false, "text": "android:label=\"you app name\" android:name=\"${applicationName}\"" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179450/" ]
74,532,098
<p>I want to send a newsletter through email and I would like to see who opened my email.</p> <p>I send HTML in the content of the email, so I can not add javascript in there. (see <a href="https://stackoverflow.com/questions/1088016/html-email-with-javascript">here</a> )</p> <p>Is there any way to send a post request (to my server) only through HTML, every time the HTML is opened and not by pressing a button?</p>
[ { "answer_id": 74532403, "author": "Peter Bennett", "author_id": 1947068, "author_profile": "https://Stackoverflow.com/users/1947068", "pm_score": 1, "selected": true, "text": "<img src=\"https://yoururl/pixel.php?tid=%pixel_id%\" style=\"width:1px;height:1px;\" title=\"pixel\">\n <?php\n\n//YOU NEED TO INCLUDE YOUR DATABASE CONNECTION FILE HERE\n\n $conn_cms=get_dbc(); \n $stmt = $conn_cms->prepare(\"SELECT * FROM `pixel_tracker` WHERE `pixel_id` = ?\"); \n $stmt->bind_param(\"s\", $tid);\n $tid = $_GET['tid'];\n $stmt->execute();\n $result = $stmt->get_result();\n $assoc = $result->fetch_assoc();// get the mysqli result\n\n $stmt = $conn_cms->prepare(\"UPDATE `pixel_tracker` SET `seen` = ?,`seen_count` = ?,\n `seen_when`= ?, `header_track`= ? WHERE `pixel_id` = ?\"); \n $stmt->bind_param(\"sssss\", $seen, $seen_count, $seen_when, $header_track, $pixel_id);\n $seen = 1;\n $seen_count = $assoc['seen_count']+1;\n $seen_when = date(\"Y-m-d H:i:s\");\n if(isset($_SERVER['HTTP_REFERER'])){\n $header_track = $_SERVER['HTTP_REFERER'];\n } else {\n $header_track = \"none\";\n }\n $pixel_id = $tid;\n $stmt->execute();\n $result = $stmt->get_result(); // get the mysqli result\n\n $pixel = imagecreate(1,1);\n $color = imagecolorallocate($pixel,255,255,255);\n imagesetpixel($pixel,1,1,$color);\n header(\"content-type:image/jpg\");\n imagejpeg($pixel);\n imagedestroy($pixel);\n\n?>\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19373633/" ]
74,532,129
<p>I have a job that runs every 28 days. and I want to assign it a cycle number based on a starting reference date.</p> <p>e.g</p> <p>1st cycle is 01/27/22. and that cycle number would be 2201. subsequently I want to calculate the cycle number based on the current date. but for each year there could be either 13 or 14 cycles.</p> <p>I've managed to figure out the number of cycles since the reference date to figure out the latest cycle date (see below)</p> <pre><code>const REF_ZERO_DATE = '01/27/2022'; const REF_ZERO_CYCLE_YEAR = &quot;22&quot;; const REF_ZERO_CYCLE_NUM = &quot;01&quot;; $today = new \DateTime(&quot;2023/12/29&quot;); echo (&quot;Today = &quot;.$today-&gt;format(&quot;Y/m/d&quot;).&quot;\n&quot;); $ref_zero = new \DateTime(self::REF_ZERO_DATE); echo (&quot;ref_zero = &quot;.$ref_zero-&gt;format(&quot;Y/m/d&quot;).&quot;\n&quot;); $number_of_days_since_ref_zero = $today-&gt;diff($ref_zero)-&gt;format(&quot;%a&quot;); echo (&quot;Number of days since ref zero = &quot;.$number_of_days_since_ref_zero.&quot;\n&quot;); $number_of_cycles_since_ref_zero = floor($number_of_days_since_ref_zero/28); echo (&quot;Number of cycles since ref zero = &quot;.$number_of_cycles_since_ref_zero.&quot;\n&quot;); $interval = 'P' . $number_of_cycles_since_ref_zero*28 . 'D'; echo (&quot;Interval = &quot;.$interval); $date_of_lastest_cycle = date_add($ref_zero,new \DateInterval($interval)); echo (&quot;last Cycle Date = &quot;.$date_of_lastest_cycle-&gt;format(&quot;Y/m/d&quot;).&quot;\n&quot;); </code></pre> <p>But my math for the cycle adjustment is missing coping with 12 or 13 cycle in a specific year.</p>
[ { "answer_id": 74533294, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 0, "selected": false, "text": "$next_date = strtotime('+28 day', $timestamp);\n echo date('m/d/Y', $next_date);\n" }, { "answer_id": 74564793, "author": "ttdijkstra", "author_id": 6110823, "author_profile": "https://Stackoverflow.com/users/6110823", "pm_score": 3, "selected": true, "text": "function calculateIntervalCount($startDate, $endDate, $interval) {\n $start = new \\DateTime($startDate);\n $end = new \\DateTime($endDate);\n $interval = new \\DateInterval($interval);\n \n $periodDays = intval($end->diff($start)->format('%a'));\n $intervalDays = intval($interval->format('%d'));\n \n return floor($periodDays / $intervalDays);\n}\n function calculateCycleNumber($startDate, $endDate, $interval) {\n $totalCycles = calculateIntervalCount($startDate,$endDate,$interval);\n \n $startYear = intval((new \\DateTime($startDate))->format('Y'));\n $endYear = intval((new \\DateTime($endDate))->format('Y'));\n \n if($startYear < $endYear) {\n $endOfLastYearDate = (new \\DateTime($endDate))->modify('last day of December last year')->format('Y-m-d');\n $cyclesSinceEndOfLastYear = calculateIntervalCount($endOfLastYearDate, $endDate, $interval);\n $yearCycle = $totalCycles - $cyclesSinceEndOfLastYear + 1;\n } else {\n $yearCycle = $totalCycles;\n }\n \n $yearCode = substr($endYear,-2);\n $yearCycleCode = sprintf('%02d', $yearCycle);\n\n return $yearCode . $yearCycleCode;\n}\n echo calculateCycleNumber('01/27/2022','2023/12/29','P28D');\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/333661/" ]
74,532,184
<p>i'm seeing an unexpected behavior in jax.lax.switch.</p> <pre><code>def fun_a(): print('a') def fun_b(): print('b') def fun_c(): print('c') functions_list=[fun_a,fun_b,fun_c] </code></pre> <p>and then calling</p> <pre><code>jax.lax.switch(0,functions_list) </code></pre> <p>returns</p> <pre><code>a b c </code></pre> <p>I would expect to see only &quot;a&quot; printed.</p>
[ { "answer_id": 74533294, "author": "Abdulkhaliq Ghwainm", "author_id": 4879561, "author_profile": "https://Stackoverflow.com/users/4879561", "pm_score": 0, "selected": false, "text": "$next_date = strtotime('+28 day', $timestamp);\n echo date('m/d/Y', $next_date);\n" }, { "answer_id": 74564793, "author": "ttdijkstra", "author_id": 6110823, "author_profile": "https://Stackoverflow.com/users/6110823", "pm_score": 3, "selected": true, "text": "function calculateIntervalCount($startDate, $endDate, $interval) {\n $start = new \\DateTime($startDate);\n $end = new \\DateTime($endDate);\n $interval = new \\DateInterval($interval);\n \n $periodDays = intval($end->diff($start)->format('%a'));\n $intervalDays = intval($interval->format('%d'));\n \n return floor($periodDays / $intervalDays);\n}\n function calculateCycleNumber($startDate, $endDate, $interval) {\n $totalCycles = calculateIntervalCount($startDate,$endDate,$interval);\n \n $startYear = intval((new \\DateTime($startDate))->format('Y'));\n $endYear = intval((new \\DateTime($endDate))->format('Y'));\n \n if($startYear < $endYear) {\n $endOfLastYearDate = (new \\DateTime($endDate))->modify('last day of December last year')->format('Y-m-d');\n $cyclesSinceEndOfLastYear = calculateIntervalCount($endOfLastYearDate, $endDate, $interval);\n $yearCycle = $totalCycles - $cyclesSinceEndOfLastYear + 1;\n } else {\n $yearCycle = $totalCycles;\n }\n \n $yearCode = substr($endYear,-2);\n $yearCycleCode = sprintf('%02d', $yearCycle);\n\n return $yearCode . $yearCycleCode;\n}\n echo calculateCycleNumber('01/27/2022','2023/12/29','P28D');\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5779546/" ]
74,532,216
<p>I have a series of lists, and I want to combine them in a larger nested list. However, I want to order them in a certain way. I want the first sub-list to be the one whose first element is zero. Then i want the second sub-list to be the one whose first element is the same as the LAST element of the previous list.</p> <p>For example, here's four sub-lists;</p> <p><code>[0, 3], [7, 0], [3, 8], [8, 7]</code></p> <p>I want to end up with this;</p> <p><code>[[0, 3], [3, 8], [8, 7], [7,0]]</code></p> <p>I can't for the life of me see the code logic in my head that would achieve this for me.</p> <p>Can anyone help please?</p> <hr /> <p>UPDATE Solved! Many thanks to all who contributed!</p> <hr />
[ { "answer_id": 74532605, "author": "mousetail", "author_id": 6333444, "author_profile": "https://Stackoverflow.com/users/6333444", "pm_score": 0, "selected": false, "text": "source = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\n# Start at 0\nlast_val = 0\n# this will be the output\nl = []\nwhile len(l)==0 or last_val!=0:\n # Find the first value where the first element is last_val\n l.append(next(i for i in source if i[0]==last_val))\n # set last val to the second element of the list\n last_val = l[-1][1]\n\nprint(l)\n \n" }, { "answer_id": 74532750, "author": "John Coleman", "author_id": 4996248, "author_profile": "https://Stackoverflow.com/users/4996248", "pm_score": 2, "selected": true, "text": "links = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\nd = {link[0]:link for link in links}\nchain = []\ni = min(d)\nwhile d:\n link = d[i]\n chain.append(link)\n del d[i]\n i = link[1]\n\nprint(chain) #[[0, 3], [3, 8], [8, 7], [7, 0]]\n" }, { "answer_id": 74533046, "author": "Gábor Fekete", "author_id": 6464041, "author_profile": "https://Stackoverflow.com/users/6464041", "pm_score": 1, "selected": false, "text": "links = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\ndef get_path(links, *, start=0, end=0):\n linkmap = dict(links)\n key = start\n while True:\n link = linkmap[key]\n yield [key,link]\n key = link\n if link == end:\n break\n \nprint(list(get_path(links)))\nprint(list(get_path(links,start=3,end=3)))\n\n# [[0, 3], [3, 8], [8, 7], [7, 0]]\n# [[3, 8], [8, 7], [7, 0], [0, 3]]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20571936/" ]
74,532,217
<p><a href="https://i.stack.imgur.com/R1UDb.png" rel="nofollow noreferrer">enter image description here</a></p> <p>there are different unit for size : like k for 1,000, M for mega. I want to convert all data into same unit - bytes</p> <p>may i know how to make it?</p> <p>The expected result is update the size column into bytes like 9k will be 9,000</p>
[ { "answer_id": 74532605, "author": "mousetail", "author_id": 6333444, "author_profile": "https://Stackoverflow.com/users/6333444", "pm_score": 0, "selected": false, "text": "source = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\n# Start at 0\nlast_val = 0\n# this will be the output\nl = []\nwhile len(l)==0 or last_val!=0:\n # Find the first value where the first element is last_val\n l.append(next(i for i in source if i[0]==last_val))\n # set last val to the second element of the list\n last_val = l[-1][1]\n\nprint(l)\n \n" }, { "answer_id": 74532750, "author": "John Coleman", "author_id": 4996248, "author_profile": "https://Stackoverflow.com/users/4996248", "pm_score": 2, "selected": true, "text": "links = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\nd = {link[0]:link for link in links}\nchain = []\ni = min(d)\nwhile d:\n link = d[i]\n chain.append(link)\n del d[i]\n i = link[1]\n\nprint(chain) #[[0, 3], [3, 8], [8, 7], [7, 0]]\n" }, { "answer_id": 74533046, "author": "Gábor Fekete", "author_id": 6464041, "author_profile": "https://Stackoverflow.com/users/6464041", "pm_score": 1, "selected": false, "text": "links = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\ndef get_path(links, *, start=0, end=0):\n linkmap = dict(links)\n key = start\n while True:\n link = linkmap[key]\n yield [key,link]\n key = link\n if link == end:\n break\n \nprint(list(get_path(links)))\nprint(list(get_path(links,start=3,end=3)))\n\n# [[0, 3], [3, 8], [8, 7], [7, 0]]\n# [[3, 8], [8, 7], [7, 0], [0, 3]]\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20134602/" ]
74,532,249
<pre><code>import requests import pandas as pd from urllib.request import urlopen from bs4 import BeautifulSoup df = [] for x in range(1,31): url_allocine= 'https://www.allocine.fr/film/meilleurs/?page=' page = requests.get(url_allocine + str(x)) soup = BeautifulSoup(page.content, 'html.parser') films_all = soup.findAll('div',{'class':'card entity-card entity-card-list cf'}) #print(len(films_all)) film = films_all[0] #print(film) titre = film.find(&quot;div&quot;,{'class':'meta'}).find('a').text #print(titre) note = film.findAll(&quot;div&quot;,{'class':'rating-item'})[0] note_presse = note.find('span',{'class':'stareval-note'}).text #print(note_presse) note_1 = film.findAll(&quot;div&quot;,{'class':'rating-item'})[1] note_spectateur = note_1.find('span',{'class':'stareval-note'}).text #print(note_spectateur) for film in films_all: titre = film.find(&quot;div&quot;,{'class':'meta'}).find('a').text note_presse= (note.find('span',{'class':'stareval-note'}).text) note_spectateur = (note_1.find('span',{'class':'stareval-note'}).text) property_info = { 'titre': titre, 'note_presse': note_presse, 'note_spectateur': note_spectateur, } df.append(property_info) #print(len(df)) df_allocine = pd.DataFrame(df) print(df_allocine[0:20]) </code></pre> <p>In the above code and for the note selection, I could not select or find a way to create the note_presse and the note_spectateur on the same line, since they share the same tags. So, I tried to use indexation hoping to solve the problem. But, I found after creating the Datframe that for the first 10 rows the films have the same notes, and it changes for the second 10 rows(due to pagination but it stays the same for these also and so on). Hope I find a solution using urllib or requests but not another methode like selinium. Thanks in advance for your efforts.</p>
[ { "answer_id": 74538872, "author": "Andrej Kesely", "author_id": 10035985, "author_profile": "https://Stackoverflow.com/users/10035985", "pm_score": 2, "selected": true, "text": "import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\ndata = []\nfor page in range(1, 3): # <-- increase number of pages here\n url = f\"https://www.allocine.fr/film/meilleurs/?page={page}\"\n soup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\n for movie in soup.select(\"li.mdl\"):\n data.append(\n {\n \"Title\": movie.h2.text.strip(),\n \"Note Presse\": movie.select_one(\n \".rating-item:-soup-contains(Presse) .stareval-note\"\n ).text.strip(),\n \"Note Spectateurs\": movie.select_one(\n \".rating-item:-soup-contains(Spectateurs) .stareval-note\"\n ).text.strip(),\n }\n )\n\ndf = pd.DataFrame(data)\nprint(df)\n Title Note Presse Note Spectateurs\n0 Forrest Gump 2,6 4,6\n1 La Liste de Schindler 4,2 4,6\n2 La Ligne verte 2,8 4,6\n3 12 hommes en colère 5,0 4,6\n4 Le Parrain 4,6 4,5\n5 Les Evadés 3,2 4,5\n6 Le Seigneur des anneaux : le retour du roi 3,8 4,5\n7 Le Roi Lion 3,4 4,5\n8 Vol au-dessus d'un nid de coucou 5,0 4,5\n9 The Dark Knight, Le Chevalier Noir 4,0 4,5\n10 Pulp Fiction 4,4 4,5\n11 Il était une fois dans l'Ouest 4,0 4,5\n12 Le Bon, la brute et le truand 4,1 4,5\n13 Il était une fois en Amérique 4,9 4,5\n14 Django Unchained 4,6 4,5\n15 Le Seigneur des anneaux : la communauté de l'anneau 3,7 4,5\n16 Gladiator 4,3 4,5\n17 Gran Torino 4,7 4,5\n18 Le Seigneur des anneaux : les deux tours 4,0 4,5\n19 Interstellar 3,8 4,5\n" }, { "answer_id": 74539654, "author": "Raouf Yahiaoui", "author_id": 18448274, "author_profile": "https://Stackoverflow.com/users/18448274", "pm_score": 0, "selected": false, "text": "page = requests.get(url_allocine + str(x))\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n\nfilms_all = soup.find_all('div',{'class':'card entity-card entity-card-list cf'})\ndef remove_word(string):\n return string.replace(\"Presse\",\"\").replace(\"Spectateurs\",\"\")\n\nfor film in films_all:\n title = film.find('h2').get_text(strip=True)\n rates = film.find_all('div', class_='rating-holder rating-holder-3')\n for rate in rates:\n note_presse = remove_word(rate.find_all(\"div\",{'class':'rating-item'})[0].get_text(strip=True))\n note_spectateur = remove_word(rate.find_all(\"div\",{'class':'rating-item'})[1].get_text(strip=True))\n\n property_info = {\n 'title': title,\n 'note_presse': note_presse,\n 'note_spectateur': note_spectateur,\n }\n df.append(property_info)\n# print(len(df))\n" } ]
2022/11/22
[ "https://Stackoverflow.com/questions/74532249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18448274/" ]