instruction
stringlengths
0
30k
|linux|dns|bind9|
null
{"OriginalQuestionIds":[28703241],"Voters":[{"Id":1048572,"DisplayName":"Bergi","BindingReason":{"GoldTagBadge":"javascript"}}]}
Change your setTimeout callback to: setTimeout(() => { reject(new Error("error")) }, 2000)
i have a simple leaning in the game and when i lean right and move forward at the same time the camera starts glitching out. this only happens on the right lean. this is the code i use for leaning. if Input.is_action_pressed("lean_left") and !lean_left_ray.is_colliding() and !lean_left_ray_2.is_colliding() and !lean_left_ray_3.is_colliding(): lean_left_collision.disabled = false lean_right_collision_2.disabled = true head.position.x = lerp(head.position.x,-0.50, delta * lerp_speed) head.rotation.z = lerp(head.position.z,0.35, delta * lerp_speed) head.position.y = lerp(head.position.y,0.50, delta * lerp_speed) leaning = true else: head.position.x = lerp(head.position.x,0.0, delta * lerp_speed) head.rotation.z = lerp(head.position.z,0.0, delta * lerp_speed) lean_left_collision.disabled = true lean_right_collision_2.disabled = true leaning = false # leaning right if Input.is_action_pressed("lean_right") and !lean_right_ray.is_colliding() and !lean_right_ray_2.is_colliding() and !lean_right_ray_3.is_colliding(): lean_left_collision.disabled = true lean_right_collision_2.disabled = false head.position.x = lerp(head.position.x,0.50, delta * lerp_speed) head.rotation.z = lerp(head.position.z,-0.35, delta * lerp_speed) head.position.y = lerp(head.position.y,0.50, delta * lerp_speed) leaning = true else: head.position.x = lerp(head.position.x,0.0, delta * lerp_speed) lean_left_collision.disabled = true lean_right_collision_2.disabled = true leaning = false i couldnt think of anything to solve this problem as im still quiet new to coding i have no idea what could cause this.
godot lean mechanic makes camera glitch
|controller|camera|gdscript|godot4|
null
Is there a way to update plotly/dash faster when using a background callback?
You may write a Powershell script where you can use the following cmdlets in the script: - Get-DynamicDistributionGroupMember at Exchange Online: To view the calculated membership list that's stored on dynamic distribution group objects. Please note that the results from this cmdlet are updated every 24 hours. Ref: https://learn.microsoft.com/en-us/powershell/module/exchange/get-dynamicdistributiongroupmember?view=exchange-ps - For each member check that member has already been given access to the related shared mailbox , e.g. Get-MailboxPermission -Identity <SharedMailbox> -User <DynDistGrMember> - Check the results above and if it does not return any values SendAs, SendOnBehalf, FullControl etc for the queried dynamic distribution group member then provide the the member necessary rights to act on shared mailbox e.g. Add-MailboxPermission -Identity <sharedmailbox> -User <DynDistGrMember> AccessRights FullAccess according to your shared mailbox settings.
Me too I was having problem uploading with Safari for hours then I tried in brave browser and finally could upload.
choises = { "1": func1, "2": func2("CategoryA"), "3": func2("CategoryB"), ... "7": func3, ... } Do you see the key difference in how the dictionary is using `func2` versus `func1` and `func3`? The references to `func2` also have parentheses `()` after the function name, meaning the function is called _immediately_, and the returned value is stored in the dictionary. But `func1` and `func3` do not have parentheses after, so the dictionary is storing the actual function objects, which are called _later_. If you want `func2` to be called _later_, like `func1` and `func3`, then get rid of the parentheses in the dictionary definition. EDIT: If you want the dictionary to also contain arguments for the function calls, you can use `functools.partial()` for that: from functools import partial choises = { "1": partial(func1), "2": partial(func2, "CategoryA"), "3": partial(func2, "CategoryB"), ... "7": partial(func3), ... } Then later on, you can call the function object in the dict and call it, along with any arguments that you gave: choises["2"]()
I'm having an issue at the company where I work. In our print server, there are several printers that we've separated by Cost Center. There are multiple printers linked to the same IP address, where a specific security group in Active Directory automatically maps to the user. My issue is as follows: many users in the company, for example, a doctor, are always in different sections of the company, such as: Stations, Operating Room, Medical Office. They have a great difficulty; each time they move to a new location, they cannot go to the PC options and set a particular printer as default on the PC. What I wanted was to create a Python code that stays running continuously, and when the user logs into the PC on the domain, the code identifies their login, checks the hostname of the PC they are logged into, and their security group membership. For example: user "igorcarmona" who is part of the security group "IMP_TIC_COLOR" logged into the PC "TIC0068" will have printer X set as default. [Servidor de impressão](https://i.stack.imgur.com/xxTFf.png) Here is a draft of a code, but I am having difficulties building it. Has anyone been through this and can help me? I already tried to do this: ``` import os import time import pyad.adquery import win32print import socket AD_SERVER_IP = "192.168.0.193" PRINT_SERVER_IP = "192.168.0.230" def check_user_login(): query = pyad.adquery.ADQuery() query.execute_query( type=AD_SERVER_IP, attributes=["memberOf"], where_clause="objectClass = 'user' AND sAMAccountName = '" + os.getlogin() + "'" ) result = query.get_single_result() if result: groups = result['memberOf'] return groups return [] def get_host_name(): return socket.gethostname() def set_default_printer(printer_name): printer_info = win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS, None, 1) for printer in printer_info: if printer_name in printer[2]: win32print.SetDefaultPrinter(printer[2]) print("Default printer set to:", printer[2]) break def main(): while True: groups = check_user_login() hostname = get_host_name() if groups: for group in groups: print(group) if "IMP_TIC_COLOR" in group and hostname.startswith("TIC"): set_default_printer("IMP_TIC_COLOR") time.sleep(30) # Verifica a cada 30 segundos if __name__ == "__main__": main() ```
That happens because to run that .exe requires Python 3.10 and easiest solution would be to install it and add to PATH. Or unzip portable version in the same folder.
How do I generate wildcard HTTPS certificates? server { server_name subdomain.domain.com www.subdomain.domain.com *.subdomain.domain.com ~^(.*)\.subdomain\.domain\.com$; } Currently, for normal domains, I generate certificates like this: sudo certbot --nginx -d example.com
Generate wildcard HTTPS certificates with certbot
You should debug. Is `onAuthStateChanged` ever called? Maybe it's not running? `useNavigate` is a hook, it must be used inside a component.
I am curently working on an App implemented with REACT. The idea, or the task is to get data from Spotify, filter that data and add those songs to a new playlist which than can be saved to the spotify-profile. I already setup the main functionalities with mocked data. But now I am trying to connect the login button on my app to the authorization flow and I am really stucked. Spotify-for Developers provides a [boilerplate](https://github.com/spotify/web-api-examples/blob/master/authorization/authorization_code_pkce/public/app.js), that is stored on github . Here the boilerplate is linked as script to the index.html and the app is build with javascript. So I need a different approach. I saved the boilerplate in a js file and tried different ways to connect it with the App.js file in my application. Including the boilerplate directly in the App.js file throws errors because of the 'await' statements in the function. My last Idea was to import the the provided Clickhandlers and use them via props with the button. But of course it does not work as intendet. I get redirected to the Spotify-login-page. But when I click on the login there, i get redirected to my app with no informations. Which makes sense, because the rest of the boilerplate-code cant be executed. What would be the best approach to make this work? Do I have to extract some of the code and bring it to App.js? This is my App.js: ``` import {React, useState, useEffect} from "react"; import Navbar from './components/Navbar/Navbar'; import Footer from './components/Footer/Footer'; import Main from './components/Main/Main' import './assets/global.css'; import {loginWithSpotifyClick, logoutClick, refreshTokenClick} from './data/AuthContext2.js'; const App = () => { return ( <div className="appLayout"> <Navbar login={loginWithSpotifyClick} /> <Main /> <Footer /> </div> ); } export default App; ``` This is my Navbar-Component that includes the login-button: ``` import React from 'react'; import './Navbar.css'; const Navbar = ({login}) => { return ( <div className="container2"> <h1 className="ja"><span>ja</span><span className="mmm">mmm</span><span className="ing">ing</span></h1> <button className='login' onClick={login}>Login</button> </div> ); } export default Navbar; ``` This is the boilerplate-file (I already deleted the HTML related code from the original file). I named it AuthContext2.js: ``` /** * This is an example of a basic node.js script that performs * the Authorization Code with PKCE oAuth2 flow to authenticate * against the Spotify Accounts. * * For more information, read * https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow */ const clientId = "my client id is hidden!"; // your clientId const redirectUrl = 'http://localhost:3000/callback'; // your redirect URL - must be localhost URL and/or HTTPS const authorizationEndpoint = "https://accounts.spotify.com/authorize"; const tokenEndpoint = "https://accounts.spotify.com/api/token"; const scope = 'user-read-private user-read-email'; // Data structure that manages the current active token, caching it in localStorage const currentToken = { get access_token() { return localStorage.getItem('access_token') || null; }, get refresh_token() { return localStorage.getItem('refresh_token') || null; }, get expires_in() { return localStorage.getItem('refresh_in') || null }, get expires() { return localStorage.getItem('expires') || null }, save: function (response) { const { access_token, refresh_token, expires_in } = response; localStorage.setItem('access_token', access_token); localStorage.setItem('refresh_token', refresh_token); localStorage.setItem('expires_in', expires_in); const now = new Date(); const expiry = new Date(now.getTime() + (expires_in * 1000)); localStorage.setItem('expires', expiry); } }; // On page load, try to fetch auth code from current browser search URL const args = new URLSearchParams(window.location.search); const code = args.get('code'); // If we find a code, we're in a callback, do a token exchange if (code) { const token = await getToken(code); currentToken.save(token); // Remove code from URL so we can refresh correctly. const url = new URL(window.location.href); url.searchParams.delete("code"); const updatedUrl = url.search ? url.href : url.href.replace('?', ''); window.history.replaceState({}, document.title, updatedUrl); } // If we have a token, we're logged in, so fetch user data and render logged in template if (currentToken.access_token) { const userData = await getUserData(); } // Otherwise we're not logged in, so render the login template async function redirectToSpotifyAuthorize() { const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const randomValues = crypto.getRandomValues(new Uint8Array(64)); const randomString = randomValues.reduce((acc, x) => acc + possible[x % possible.length], ""); const code_verifier = randomString; const data = new TextEncoder().encode(code_verifier); const hashed = await crypto.subtle.digest('SHA-256', data); const code_challenge_base64 = btoa(String.fromCharCode(...new Uint8Array(hashed))) .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); window.localStorage.setItem('code_verifier', code_verifier); const authUrl = new URL(authorizationEndpoint) const params = { response_type: 'code', client_id: clientId, scope: scope, code_challenge_method: 'S256', code_challenge: code_challenge_base64, redirect_uri: redirectUrl, }; authUrl.search = new URLSearchParams(params).toString(); window.location.href = authUrl.toString(); // Redirect the user to the authorization server for login } // Soptify API Calls async function getToken(code) { const code_verifier = localStorage.getItem('code_verifier'); const response = await fetch(tokenEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ client_id: clientId, grant_type: 'authorization_code', code: code, redirect_uri: redirectUrl, code_verifier: code_verifier, }), }); return await response.json(); } async function refreshToken() { const response = await fetch(tokenEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: clientId, grant_type: 'refresh_token', refresh_token: currentToken.refresh_token }), }); return await response.json(); } async function getUserData() { const response = await fetch("https://api.spotify.com/v1/me", { method: 'GET', headers: { 'Authorization': 'Bearer ' + currentToken.access_token }, }); return await response.json(); } // Click handlers export async function loginWithSpotifyClick() { await redirectToSpotifyAuthorize(); } export async function logoutClick() { localStorage.clear(); window.location.href = redirectUrl; } export async function refreshTokenClick() { const token = await refreshToken(); currentToken.save(token); } ```
It is the browser in charge of rendering text, you have to analyze where text is rendered. With Canvas or SPAN Far from perfect. This one: * wraps each word in a ``<span>`` * calculates by ``offsetHeight`` if a SPAN spans multiple lines * of so it found a hyphened word * it then **removes** each _last_ character from the ``<span>`` to find when the word wrapped to a new line ![](https://i.imgur.com/zvCwk1H.png) The _Far from perfect_ is the word "demonstrate" which _**"fits"**_ when shortened to "demonstr" **-** "ate" But is not the English spelling ![](https://i.imgur.com/WtZTaiF.png) Needs some more JS voodoo <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <style> .hyphen { background: pink } .remainder { background: lightblue } </style> <process-text lang="en" style="display:inline-block; overflow-wrap: word-break; hyphens: auto; zoom:1.2; width: 7em"> By using words like "incomprehensibilities", we can demonstrate word breaks. </process-text> <script> customElements.define('process-text', class extends HTMLElement { connectedCallback() { setTimeout(() => { let words = this.innerHTML.trim().split(/(\W+)/); let spanned = words.map(w => `<span>${w}</span>`).join(''); this.innerHTML = spanned; let spans = [...this.querySelectorAll("span")]; let defaultHeight = spans[0].offsetHeight; let hyphend = spans.map(span => { let hyphen = span.offsetHeight > defaultHeight; console.assert(span.offsetHeight == defaultHeight, span.innerText, span.offsetWidth); span.classList.toggle("hyphen", hyphen); if (hyphen) { let saved = span.innerText; while (span.innerText && span.offsetHeight > defaultHeight) { span.innerText = span.innerText.slice(0, -1); } let remainder = document.createElement("span"); remainder.innerText = saved.replace(span.innerText, ""); remainder.classList.add("remainder"); span.after(remainder); } }) console.log(this.querySelectorAll("span").length, "<SPAN> created" ); }) //setTimeout to read innerHTML } // connectedCallback }); </script> <!-- end snippet -->
It looks like you want to render a stuff such as a tree structure with recursive content, for this I suggest the following solution based on this [one](https://v2.vuejs.org/v2/guide/components-edge-cases.html#Circular-References-Between-Components) <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> Vue.config.devtools = false; Vue.config.productionTip = false; Vue.component('tree', { props: ['item'], template: ` <p> <span>{{ item.contentType }}</span> <tree-item-contents :items="item.items"/> </p> ` }) Vue.component('tree-item-contents', { props: ['items'], template: `<ul> <li v-for="child in items"> <tree v-if="child.items" :item="child"/> <span v-else>{{ item.contentType }}</span> </li> </ul>` }) new Vue({ el: '#app', data() { return { item: { "contentType": "root", "items": [{ "contentType": "h1", "items": [{ "contentType": "b", "items": [{ "contentType": "i", "items": [ ], "id": 9 }], "id": 6 }], "id": 0 }] } } } }) <!-- language: lang-html --> <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app" class="container"> <tree :item="item" /> </div> <!-- end snippet -->
I have a numpy array and corresponding row and column indices: ``` matrix = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0,]) col_idx = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) ``` I would like to unravel the matrix by the groups specified by row_idx and col_idx. In the case of this example, the row_idx are all zero, so the elements would unravel by columns: ``` result = np.array([0, 3, 6, 1, 4, 7, 2, 5, 8]) ``` The problem with ravel is that it does not generalise to where the matrix has areas that are grouped by rows and other areas by columns based on the row_idx and col_idx. There can be a combination of both row and column grouping, as below: In this example ``` matrix = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]) col_idx = np.array([0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2]) ``` The result array is the top-left 2x2, [0, 1, 4, 5], followed by the top right 1x2, [2, 3], and so on based on the row and column groupings. ``` result = np.array([[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 10, 11]) ``` I have tried aggregate() from the numpy_groupies package, but it is both slow and returns an array combining np.arrays and ints (which makes further manipulation difficult and slow).
I have a table and would like to select one row of the duplicates. The table has multiple columns that adds up to identify as duplicates review the excel table data. [enter image description here](https://i.stack.imgur.com/fQZ2V.png) a short image of the table with data. Ther result should be [enter image description here](https://i.stack.imgur.com/aFcrP.png)
It's impossible. C6067 and other warnings with numbers 6000+ are Code Analysis warnings and are not associated with the compiler warnings.
The matrix you've posted is symmetric, and real-valued. (In other words, `A = A.T`, and it has no complex numbers.) This matters because all matrices which are symmetric and real-valued are [normal matrices](https://en.wikipedia.org/wiki/Normal_matrix). [Source](https://en.wikipedia.org/wiki/Symmetric_matrix#Symmetry_implies_normality). If the matrix is normal, then any polar decomposition of it follows `P @ U = U @ P`. [Source](https://math.stackexchange.com/questions/3038582/prove-that-the-polar-decomposition-of-normal-matrices-a-su-is-such-that-su). Any diagonal matrix is also symmetric. However, technically the matrix you have posted is not diagonal - it has entries outside its main diagonal. The matrix is only [tri-diagonal](https://en.wikipedia.org/wiki/Tridiagonal_matrix). These matrices are not necessarily symmetric. However, if your tridiagonal matrix is symmetric and real-valued, then its polar decomposition is commutative. In addition to mathematically proving this idea, you can also check it experimentally. The following code generates thousands of matrices, and their polar decompositions, and checks if they are commutative. ``` import numpy as np from scipy.linalg import polar N = 4 iterations = 10000 for i in range(iterations): A = np.random.randn(N, N) # A = A + A.T U, P = polar(A) are_equal = np.allclose(U @ P, P @ U) if not are_equal: print("Matrix A does not have commutative polar decomposition!") print("Value of A:") print(A) break if (i + 1) % (iterations // 10) == 0: print(f"Checked {i + 1} matrices, all had commutative polar decompositions") ``` If you run this, it will immediately find a counter-example, because the matrix is not symmetric. However, if you uncomment `A = A + A.T`, which forces the random matrix to be symmetric, then all of the matrices work. Lastly, if you need a left-sided polar decomposition, you can use the `side='left'` argument to `polar()` to get that. The [documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.polar.html) explains how to do this.
For anyone who came accross same issues, I found out that the solutions for the issues are: 1. > CSC : warning CS8785: Generator 'BaseExceptionGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'FileNotFoundException' with message 'Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.'` Followed the [cookbook][1] and got it fixed. 2. > Error CS0111 Type 'Hello' already defines a member called 'Display' with the same parameter types SourceGeneratorTest ..\SourceGeneratorTest\SourceGeneratorTest\Generators\SoruceGenerator.BaseExceptionGenerator\BaseException.cs 9 Active` Had to remove it from the compile, check this [link][2] out. Basically did something like : <ItemGroup> <Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" /> </ItemGroup> [1]: https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#use-functionality-from-nuget-packages [2]: https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-items?view=vs-2022#BKMK_RemoveAttribute
I don't know the entire explanation. But when i declare **flex** attribute in one of columns object, DataGrid will not create addition column and row. Just try it. example: ``` js const columns = [ { field: "FirstNm", headerName: "First Name", sortable: false, width: 150, flex: 1, // try to add this at least one of object in column }, { field: "LastNm", headerName: "Last Name", sortable: false, width: 150, }, ];
null
They should probably quote that, because it looks like the brackets are interpreted as a shell pattern by your shell; something like ```sh echo 'deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc]' \ https://pkg.jenkins.io/debian binary/ \ | sudo tee /etc/apt/sources.list.d/jenkins.list > /dev/null ```
null
How can I clone a git repository that has a submodule into an eclipse workspace? <br /> When I am done cloning, the submodule directory is empty and the project doesn't appear in the workspace. I've read: > **Cloning Repositories with Submodules** > > Submodules are repositories nested inside a parent repository. Therefore when doing a clone of a parent repository it is necessary to clone the submodule repositories so that the files/folders are available in the parent repository's working directory. > > Checking the Clone Submodules button from the Git Clone wizard will clone all submodule repositories after the clone of the parent > repository finishes. ![Clone Git Repository Window](http://i.stack.imgur.com/T0gIg.png)
Cloning A Git Repo With Submodules
|git|eclipse|git-submodules|git-clone|wizard|
null
Js variable to php using ajax
I'm trying to secure a page using a jwt token in a session in NextJS, I was looking at similar questions on the forum and I saw that they recommended using useeffect to get access but I still can't recover anything. The code I started with: ``` "use client"; import { useEffect, useState } from "react"; import { useRouter } from 'next/navigation' import { valJwt } from "@/libs/jwtSec"; import Cookies from "js-cookie"; export default function isAuth(Component: any) { return function IsAuth(props: any) { const auth = valJwt(sessionStorage.getItem("token_test")); useEffect(() => { if (!auth) { return redirect("/"); } }, []); if (!auth) { return null; } return < Component { ...props } />; }; } ``` Output: ```none ReferenceError: sessionStorage is not defined ``` And the edition with which I do not recover anything is this: ``` "use client"; import { useEffect, useState } from "react"; import { useRouter } from 'next/navigation' import { valJwt } from "@/libs/jwtSec"; import Cookies from "js-cookie"; export default function isAuth(Component: any) { return function IsAuth(props: any) { const [token, setToken] = useState(null); useEffect(() => { let tok_ses = sessionStorage.getItem("token_test"); if (tok_ses) { setToken(tok_ses); } }, []); useEffect(() => { if (token) { const auth = valJwt(sessionStorage.getItem("token_test")); if (!auth) { return redirect("/"); } } }, [token]); }; } ``` I tried with `js-cookie` but I can't get access from the same function either, how could I get access? I need to access the content of a `sessionStorage` from NextJS on the client side.
Key Differences **History and Context:** Retrieval QA Chain: Focuses on answering a single question based on a provided set of documents. It doesn't maintain a memory of previous interactions. Conversational Retrieval QA Chain: Designed for multi-turn conversations. It retains the history of past questions and answers, allowing it to provide more contextually relevant responses in subsequent turns. Use Cases: Retrieval QA Chain: Ideal for standalone question-answering systems where each question is independent. Conversational Retrieval QA Chain: Better suited for creating chatbots, virtual assistants, or any application where a continuous dialogue is expected. **How They Work** **Retrieval QA Chain:** A question is provided as input. A retriever searches through relevant documents to find passages that might contain the answer. A language model (LLM) processes the retrieved passages and the question to generate the final answer. **Conversational Retrieval QA Chain:** Leverages the Retrieval QA Chain but adds a conversational memory component. The current question, along with the conversation history (previous questions and answers), are fed into the retrieval process. The retriever takes this context into account to retrieve more relevant passages. The LLM uses the retrieved passages, the question, and the conversation context to generate an answer, ensuring continuity and relevance within the conversation. **Example** Imagine a chatbot answering questions about a company's products: Retrieval QA Chain User Question 1: "What is the price of Product X?" (Answer provided) User Question 2: "Does it come in other colors?" (May not understand the "it" without context) Conversational Retrieval QA Chain User Question 1: "What is the price of Product X?" (Answer provided) User Question 2: "Does it come in other colors?" (Understands "it" refers to Product X, providing a contextually accurate answer) **In Summary** The Conversational Retrieval QA Chain builds upon the Retrieval QA Chain by adding the ability to handle conversational context. If you're building a system designed to have continuous conversations, the Conversational Retrieval QA Chain is likely the better choice.
I want to set axisItems to a PlotItem useing pyqtgraph, I encountered an error while running my code. Here is my code: ``` plotItem = pg.PlotItem() plotItem.setAxisItems(axisItems={'bottom':pg.AxisItem('bottom')}) ``` ---------------------------------------------------------------------------------------------------- When I run this code, it shows the error as below: ``` Traceback (most recent call last): File "E:\Workspace\Python\VNPY-master\examples\candle_chart\tick\item\main.py", line 42, in <module> plotItem.setAxisItems(axisItems={'bottom':pg.AxisItem('bottom')}) File "E:\home\.conda\envs\Python310\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 312, in setAxisItems oldAxis.scene().removeItem(oldAxis) AttributeError: 'NoneType' object has no attribute 'removeItem' ``` I tried to set axises when initialzing PlotItem, it succeeded. but how to set axises after initialized PlotItem? ``` plotItem = pg.PlotItem(axisItems={'bottom':pg.AxisItem('bottom')}) ```
{"Voters":[{"Id":5320906,"DisplayName":"snakecharmerb"},{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":3744182,"DisplayName":"dbc"}],"SiteSpecificCloseReasonIds":[18]}
Is there any way to set a printer as default according with Active Directory Policy Security Group and PC hostname?
|python|windows|server|active-directory|printers|
null
I am trying to populate a ListBox with data I am reading from a text file, but have had no luck. I tried several ways to do `SendMessage` (please see below) but get the same "invalid cast type" error. ListBox: CreateWindow("listbox", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL| LBS_NOTIFY, 20, 90, 200, 365, hwnd, (HMENU)LST_LISTBOX, NULL, NULL); I keep on changing the `SendMessage`: SendMessage(LST_LISTBOX, LB_INSERTSTRING, 0, (LPARAM)10); //myline[i]); SendMessage(LST_LISTBOX, LB_ADDSTRING, 0, (LPARAM) myline[i]); SendMessage(GetDlgItem(hwnd, LST_LISTBOX), LB_ADDSTRING, 0, (LPARAM) myline[i] ); What would be the best way to populate a listbox from a file?
How to populate a ListBox with SendMessage?
In my game I have a state machine which rules when the player controller can possess a pawn. After spawning the pawn in INIT state, I tried to possess the pawn when GAMEPLAY state is entered. The scheme of the game state is: INIT > MAIN_MENU > GAMEPLAY The problem is I can't move the character after possessing, but other key mapping; eg. turning on/off flashlight works. Tried possessing it from game mode, game state and the player controller itself. The only thing I know from these trials and errors: possessing only works from server side.
Unreal Engine | [MULTIPLAYER[ Possessing a pawn (thirdpersoncharacter), simple movement with WASD not working
|unreal-engine5|unreal-blueprint|
null
I found another drawer https://github.com/nativescript-community/ui-drawer and it working fine [![Drawer][1]][1] [1]: https://i.stack.imgur.com/fl53D.png
This is the form i made using Shadcn just like it says in the docs: /app/admin/products/_components/ProductForm.tsx ```js "use client"; import { addProduct } from "@/app/admin/_actions/products"; import { zodResolver } from "@hookform/resolvers/zod"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { NewProductSchema } from "@/zod/schemas"; import { formatCurrency } from "@/lib/formatters"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; export function ProductForm() { const form = useForm<z.infer<typeof NewProductSchema>>({ resolver: zodResolver(NewProductSchema), defaultValues: { name: "", description: "", priceInCents: 200, file: undefined, image: undefined, }, }); const fileRef = form.register("file", { required: true }); const fileRef2 = form.register("image", { required: true }); const [priceInCents, setPriceInCents] = useState<number>(200); async function onSubmit(values: z.infer<typeof NewProductSchema>) { console.log(values); await addProduct(values); } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-2"> <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input placeholder="name" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> //.... more fields <Button disabled={form.formState.isSubmitting} type="submit"> {form.formState.isSubmitting ? "Saving..." : "Save"} </Button> </form> </Form> ); } ``` I tried to trim it down as much as possible. As you can see, this compoentn is a client component becasue of the "use client" at the top. I wrote a separate function that i want to be run on the server since it requires the prisma client and the fs which can only be run on the server: /app/admin/_actions/products: ```js "use server"; import fs from "fs/promises"; import { redirect } from "next/navigation"; import { z } from "zod"; import { NewProductSchema } from "@/zod/schemas"; import { prisma } from "@/lib/prismaClient"; export const addProduct = async (values: z.infer<typeof NewProductSchema>) => { const result = NewProductSchema.safeParse(values); console.log(result); if (result.success === false) { return result.error.formErrors.fieldErrors; } const data = result.data; fs.mkdir("products", { recursive: true }); const filePath = `products/${crypto.randomUUID()}-${data.file.name}`; await fs.writeFile(filePath, Buffer.from(await data.file.arrayBuffer())); fs.mkdir("public/products", { recursive: true }); const imagePath = `/products/${crypto.randomUUID()}-${data.image.name}`; await fs.writeFile( `public${imagePath}`, Buffer.from(await data.image.arrayBuffer()), ); await prisma.product.create({ data: { name: data.name, description: data.description, priceInCents: data.priceInCents, filePath, imagePath, }, }); redirect("/admin/products"); }; ``` If i remove "use server" from the top, i get errors like fs cannot imported etc meaning that the function cannot be run on the client as i said. My problem is that when i click on the submit button on the form, the onSubmit function does run, it logs the values, but it never runs the addProduct function. Does anyone know why this is happening? I admit i maybe am not that good at programming and i probably wrote something stupid but nextjs is pissing me off.
Server action function not being called Nextjs Shadcn React hook form
|next.js|react-hook-form|react-server-components|shadcnui|
You can achieve this with NTILE(). Assuming your data is actually like this, rather than grouped, you can use the following, but you can modify with GROUP BY and HAVING if these are summations. But that will return the records in the reverse Quartile. To accommodate your order you can subtract the quartile from 5. SELECT product, 5 - NTILE(4) OVER (ORDER BY by sales) FROM mytable WHERE sales > 0 ORDER BY sales DESC
LemMinX is an XML language server, written in Java, and based on the Eclipse LSP4J framework
null
I have a column in my Bigquery table that is filled by C# Ticks: DateUtc = DateTime.UtcNow.Ticks; This is something like: 638148714773184690 I want to convert it to Bigquery DateTime.
|pdf|twig|
|html|symfony|pdf|twig|
With "Android Studio 2023.2.1", now in 2024-04, it is like this: 5.1 ( Burger Menu ) > Build > Rebuild Project ”( Burger Menu ) > Build > Select Build Variant…”. “Build Variants:”. “Module” = ”:app” “Active Build Variant”. “debug ( default )”. “release”. ”( Burger Menu ) > Build > Rebuild Project”. “AndroidStudioProjects\{project name}\app\build\outputs\apk\debug\app-debug.apk”. “AndroidStudioProjects\{project name}\app\build\outputs\apk\release\app-release-unsigned.apk”. You may either create a “debug” or a “release” items. One directory with the item is created. Other items in the directory are deleted. If the other directory exist, it is deleted. When building a “release” build, the “debug” directory is deleted. When building a “debug” build, the “release” directory is deleted. So you can't generate “bundle” files by this. So you may have just either a “debug” or a “release” item at the same time :-). 5.2 ( Burger Menu ) > Build > Build Bundle(s) / APK(s) ”( Burger Menu ) > Build > Select Build Variant…”. “Build Variants:”. “Module” = ”:app” “Active Build Variant”. “debug ( default )”. “release”. ”( Burger Menu ) > Build > Build Bundle(s) / APK(s)”. “Build APK(s)”: “AndroidStudioProjects\{project name}\app\build\outputs\apk\debug\app-debug.apk”. “AndroidStudioProjects\{project name}\app\build\outputs\apk\release\app-release-unsigned.apk”. “Build Bundle(s)”. “AndroidStudioProjects\{project name}\app\build\outputs\bundle\debug\app-debug.aab”. “AndroidStudioProjects\{project name}\app\build\outputs\bundle\release\app-release.aab”. You may either create a “debug” or a “release” item. One directory with the item is created. Other items in the directory are deleted. If the other directory exist, it is not deleted. So you may have “apk” and “bundle” directories and so “apk” and “bundle” files at the same time :-). 5.3 ( Burger Menu ) > Build > Generate Signed Bundle / APK... ”( Burger Menu ) > Build > Generate Signed Bundle / APK…”. “Build APK(s)”. “AndroidStudioProjects\{project name}\app\debug\app-debug.apk”. “AndroidStudioProjects\{project name}\app\release\app-release.apk”. “Build Bundle(s)” “AndroidStudioProjects\{project name}\app\debug\app-debug.aab”. “AndroidStudioProjects\{project name}\app\release\app-release.aab”. You may either create “debug” or “release” items, or “debug” and “release” items at the same time. One directory with the item is created. Other items in the directory are deleted. If one item is generated, and if the other directories exist, they are not deleted. So you may have “debug” and “release” directories directories at the same time :-). But you can have either “apk” and “bundle” files at the same time :-(.
select duplicates from data based on another column
|excel|excel-formula|
null
I had a working function to insert a new doc in my database but I reviewed my assignment and the instructions want a function that takes args, when I re-wrote the code I get a type error. (working code) ``` def create(): new_animal = {'animal_id': input('Enter animal_id'), 'rec_num': input('Enter rec_num'), 'age_upon_outcome': input('Enter age_upon_outcome')} print(new_animal) animals_collection = DbTools.db.animals result = animals_collection.insert_one(new_animal) document_id = result.inserted_id print(f"_id of inserted document: {document_id}") print(new_animal) document_to_find = {'_id': ObjectId(document_id)} result = animals_collection.find_one(document_id) print("Found :", document_id) print(result) ``` re wrote to this to align with assignment requirements "Input argument to function will be a set of key/value pairs in the data type acceptable to the MongoDB driver insert API call" (Main.py) ``` import CRUD CRUD new_animal = { 'animal_id': input('Enter animal_id'), 'rec_num': input('Enter rec_num'), 'age_upon_outcome': input('Enter age_upon_outcome')} for key,val in new_animal.items(): CRUD.DbTools.create(key,val) ``` (CRUD.py) ``` def create(key, value): new_animal = {key, value} print(new_animal) animals_collection = DbTools.db.animals result = animals_collection.insert_one(new_animal) document_id = result.inserted_id print(f"_id of inserted document: {document_id}") print(new_animal) document_to_find = {'_id': ObjectId(document_id)} result = animals_collection.find_one(document_id) print("Found :", document_id) print(result) ``` Output: ``` Pinged your deployment. You successfully connected to MongoDB! Enter animal_id111 Enter rec_num222 Enter age_upon_outcome333 {'111', 'animal_id'} Traceback (most recent call last): File "/Users/CS340WS/Main.py", line 28, in <module> CRUD.DbTools.create(key,val) File "/Users/CS340WS/CRUD.py", line 34, in create result = animals_collection.insert_one(new_animal) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/collection.py", line 663, in insert_one common.validate_is_document_type("document", document) File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/common.py", line 552, in validate_is_document_type raise TypeError( TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping ```
using Python to insert_one to my mongo_db, How do I pass key values into a function?
|python|python-3.x|mongodb|mongodb-query|
null
First easy way to update it is to delete the android directory of your flutter project and run the following command in your flutter repository ``` flutter create . ``` > But before that please note that it will create all the android directory from scratch and you will loose settings like if you have added permissions, launcher icons or have done some work in native side etc so be on safer side initialize git repo and commit the code before deleting it and compare android directory after running the following command >if you have created the git repository then restore all the previous files except both project and app level `build.gradle` and `settings.gradle` another way is to follow the steps given in the official documentation [here][1] which was little bit confusing for me for the first time. be careful while following the guide otherwise you might get into trouble. [1]: https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply
I want to monitor a job triggered which is already triggered through emrserverlessstartjoboperator. If the job is either successful or failed, want to retrigger the same job in EMR. Basically i want to know how to monitor a job status which is running/completed. Then retrigger the same job in EMR. thanks, Mag
I want to monitor a job triggered through emrserverlessstartjoboperator. If the job is either is success or failed, want to rerun the job in airflow
|pyspark|airflow|directed-acyclic-graphs|
{"Voters":[{"Id":6752050,"DisplayName":"273K"}],"DeleteType":1}
There's nothing "cleaner" or "optimized" about the second class, it simply has fewer fields. If you are writing a new app, and creating a new database alongside it, then remove unnecessary fields from the database. If you are writing an app for an existing database, you may want to isolate your ORM/entity classes from the rest of your logic. Since you don't control the database, the ORM/entitiy classes are subject to change (several ORM libraries will create the classes for you from an existing database). Either way, you should aim to have an ORM/Entity layer which strictly represents your data and has no other logic, then another layer which has translations or abstractions over the "raw" data (whether or not this is necessary depends on your app), then you should build your app logic based on the abstraction later (or the ORM/Entity if abstractions are not necessary).
I figured how to do this. I have created two Boxes inside main Box (for the 1st half of the screen and for the 2nd half) and use detectDragGestures for them separately. ``` Box( modifier = Modifier .fillMaxHeight() .width(screenWidth / 2) .pointerInput(Unit) { detectDragGestures( onDragStart = { offset -> Log.d(TAG, "drag start: $offset") }, onDrag = { change, dragAmount -> } ) } ) Box( modifier = Modifier .fillMaxHeight() .width(screenWidth / 2) .offset(screenWidth / 2) .pointerInput(Unit) { detectDragGestures( onDragStart = { offset -> Log.d(TAG, "drag start: $offset") }, onDrag = { change, dragAmount -> } ) } ) ```
I just want to record a video, copy it to local storage and be able to replay it. I have tried numerous different solutions. It works fine when debugging on an actual device from VS but as soon as the app is transferred to Apple I only get the red rectangle without content. XAML: ``` <xct:MediaElement BackgroundColor="red" x:Name="mediaElement" Source="{Binding Video}" ShowsPlaybackControls="True" HeightRequest="400" HorizontalOptions="Fill"/> ``` MVVM: ``` public async void MoveVideo(FileResult fileResult) { var documentsFolder = GetVideoFolderPath(); var newFile = Path.Combine(documentsFolder, fileResult.FileName); using (var stream = await fileResult.OpenReadAsync()) using (var newStream = File.OpenWrite(newFile)) await stream.CopyToAsync(newStream); var ex = System.IO.File.Exists(Path.Combine(documentsFolder, fileResult.FileName)); // just to validate - returns true } public string GetVideoFolderPath() { var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); return documentsFolder; } private void CheckVideo() { var documentsFolder = _videoService.GetVideoFolderPath(); var pathAndFile = Path.Combine(documentsFolder, LocalFilePath); var b = new System.Uri(pathAndFile).AbsolutePath; if(File.Exists(pathAndFile)) { Video = MediaSource.FromFile(b); } } ``` Please note that it works and shows the video when debugging from VS. How can I ensure the playback? Thanks!
If you don't want to edit your history and you don't mind an extra commit you can do this by: 1. Go back to a commit before the changes which have been reverted. 2. Create a branch, and merge your branch into it with the option --no-ff (no fast forward) If you blame the new branch you should now see the original author for the lines which were reverted. --- Just a note, this should in theory automatically happen if you at some point merge your branch into a master/main making this unnecessary (assuming your don't ever merge into master/main with fast forward). --- I haven't tested how any of this works if you revert something from an older branch which already is merged into master/main. My best guess would be that you would need to create the branch from step 2 at a version of master which didn't have the change which should be reverted. it might just work ¯\\_(ツ)_/¯.
I have data that always starts with a substring repeated twice without a delimiter, and then other data that I don't care about. The length of the repeated substring varies, and in the example below I'm using mostly \[a-z\] characters for the sake of simplicity, but the repeated substring is mostly unicode squiggles in the real dataset. | my data | what I want to extract | | --- | --- | | `johnjohnsajoalsas` | `john` | | `peterpeteraaksoskco` | `peter` | | `a8co.a8co.robinson` | `a8co.` | | `robrob7s:s7` | `rob` | | `dkoisawks` | `\[null\]` | This can be done easily with a positive lookahead ``` ^(.+)(?=\1) ``` or directly referencing the capture group like this ``` ^(.+)\1 ``` However, Google Sheets doesn't support either of these. Any help will be greatly appreaciated.
Regex to match repeated substring in Google Sheets
|regex|google-sheets|re2|
Based on [this answer](https://stackoverflow.com/a/28823545/1525840), I managed to put an image as my icon appearing inside an INPUT control at its right edge. If I use a GIF that rotates, I'm all set. I only need to set the class on my control and it is "progressing". input.busy { background-image: url(...); ... } However... Now, I want to control the pace of the rotation, so I need to actually animate the image. I can do that as shown [in this blog](https://unused-css.com/blog/rotate-background-image/), which works for many, but not all, elements. And my INPUT is one of the unfortunate exceptions. div::after { content: "this shows"; background-image: url(...); } input::after { content: "this shows not"; background-image: url(...); } How can I rotate (in fact, animate the rotation) of an image (let's say PNG) that will reside at the rightmost edge of an INPUT tag?
How to animate rotation of an image inside input control?
|css|angular|animation|pseudo-class|
My replacing merge tree engine has following design: ENGINE = ReplacingMergeTree(ModifiedOn) PRIMARY KEY (CompanyId, OrderDateKey, InvoiceDateKey) ORDER BY (CompanyId, OrderDateKey, InvoiceDateKey, AttendanceGuid, SaleOrderId, InvoiceId, ProductId) SETTINGS index_granularity = 8192, allow_nullable_key = 1; I am getting an error - SQL Error [36] [07000]: Code: 36. DB::Exception: Cannot read out of marks range.: While executing MergeTreeSelect(pool: ReadPoolInOrder, algorithm: InOrder). (BAD_ARGUMENTS) (version 24.2.1.2248 (official build)) , server ClickHouseNode(addr=http:20.235.209.193:8123, db=unify)@-115343875 while running a query - select InvoiceId, SUM(InvoiceNetValue) from unify.ProductWiseDemandSales FINAL where CompanyId = 11307 and InvoiceDateKey = 20240328 and InvoiceId is not NULL group by InvoiceId order by InvoiceId I was expecting it to work smoothly without any issue.
I came up with a solution myself. ``` SELECT DISTINCT * FROM ( SELECT group_concat(v2_id ORDER BY v2_sort_me ASC) FROM ( SELECT v1.id as v1_id, v2.id as v2_id, v1.sort_me as v1_sort_me, v2.sort_me as v2_sort_me FROM t v1 JOIN t v2 ON abs(v1.value - v2.value) < 20 ) GROUP BY v1_id HAVING COUNT(*) > 1 ORDER BY v1_sort_me ASC ) ```
I’m writing a program in C# for a windows forms application in .NET Framework. My program plays musical chairs. There is a method that runs synchronously and takes about 60 seconds to run, let's call it DanceMoves(). This method needs to run in a loop until the condition hasMusic is false. The condition hasMusic is being modified in another task, asynchronously. The exact moment when this condition is met, not only should the loop break, but the synchronous method DanceMoves() should be aborted immediately so we can run the GrabChair() method. So if it happens when 25 seconds have passed, it shouldn't finish the last 35 seconds of the DanceMoves() method, it should just immediately be aborted and run the GrabChair() method. I cannot modify the synchronous method DanceMoves(); How can I acheive this? ``` using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace MusicalChairs { public partial class Form1 : Form { public Form1() { // Do not modify this method InitializeComponent(); } private bool hasMusic = true; private Random random = new Random(); private async void StartMusicButton_Click(object sender, EventArgs e) { hasMusic = true; ChangeMusicStatusAsync(); while (hasMusic) { DanceMoves(); } GrabChair(); } private async Task ChangeMusicStatusAsync() { // Do not modify this method await Task.Delay(random.Next(1, 11) * 20000); hasMusic = false; } private void DanceMoves() { // Do not modify this method Thread.Sleep(60000); } private void GrabChair() { // Do not modify this method } } } ```
Musical chairs: How can an asynchronous task cancel a synchronous one in c#?
|c#|.net|winforms|asynchronous|task|
**Promise resolution** The technical explanation is that pairs of `resolve`/`reject` functions are "one shots" in that once you call one of them, further calls to either function of the pair are ignored without error. If you resolve a promise with a promise or thenable object, Promise code internally creates a new, second pair of resolve/reject functions for the promise being resolved and adds a `then` clause to the resolving promise to resolve or reject the promise being resolved, according to the settled state of the resolving promise. Namely, in ```js const test = new Promise((resolve, reject) => { resolve(Promise.resolve(78)) }) ``` `resolve(Promise.resolve(78))` conceptually becomes ```js Promise.resolve(78).then(resolve2,reject2) ``` where `resolve2`/`reject2` are a new pair of resolve/reject functions created for the promise `test`. If and when executed, one of the `then` clause's handlers (namely `resolve2` in this case) will be called by a Promise Reaction Job placed in the microtask queue. Jobs in the microtask queue are executed asynchonously to calling code, where `test` will remain pending at least until after the synchronous code returns. Note in summary: you can only _settle_ a promise with a non-promise value. **Promise Rejection** Promise rejection is certain if a promise's `reject` function is called. Hence you can reject a promise with any JavaScript value, including a Promise object in any state. Namely in ```js const test2 = new Promise((resolve, reject) => { reject(Promise.resolve(78)) }) ``` the rejection can be performed synchronously, and the the rejection reason of `test2` is the _promise object_ `Promise.resolve(78)`, not the number 78. Demo: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const test2 = new Promise((resolve, reject) => { reject(Promise.resolve(78)) }) test2.catch(reason => console.log("reason is a promise: ", reason instanceof Promise) ); <!-- end snippet -->
Playing local recorded video
|ios|xamarin|xamarin.forms|
Using data.table library(data.table) melt(setDT(HAVE), measure=measure(INPUT, value.name, pattern=".(\\d+)(TAB|TIME)")) # STUDENT CLASS GROUP INPUT TIME TAB # <int> <int> <int> <char> <int> <int> # 1: 1 0 2 1 NA NA # 2: 2 0 7 1 4 NA # 3: 3 1 5 1 NA NA # 4: 1 0 2 2 NA NA # 5: 2 0 7 2 NA 5 # 6: 3 1 5 2 4 6 # 7: 1 0 2 3 6 NA # 8: 2 0 7 3 4 NA # 9: 3 1 5 3 5 NA # 10: 1 0 2 4 NA 7 # 11: 2 0 7 4 NA NA # 12: 3 1 5 4 NA NA # 13: 1 0 2 5 NA 5 # 14: 2 0 7 5 NA 2 # 15: 3 1 5 5 NA NA You can rename the last two columns using `setnames(c("TIME", "TAB"), c("S.TIME", "H.TAB"))`
**You don't use functions and logic codes in jsx section!** <p>change your code to this:<p> ```js import { useState, useEffect } from "react"; import axios from "axios"; const Component = () => { const [abilities, setAbilities] = useState([]); async function fetchURL() { const res = await axios.get("url to fetch"); const data = res.data; setAbilities(data); } useEffect(() => { fetchURL(); }, []); return ( <ul className=""> {abilities.map((ability, index) => ( <li key={index} className="inline px-3"> {ability.name} <p>{ability.effect}</p> </li> ))} </ul> ); }; export default Component; ``` for learn more about this codes go to react documents
Is anyone here familiar with deepface library? I was [following this article][1] to start my adventures into facial recognition, but I ran into an issue that I can't seem to resolve (due to my lack of knowledge in this area). **Here's what I'm trying to do**: I have a photo of Angelina Jolie in a group. I've created the face embeddings for everyone in the photo, and stored it into a sqlite db. Now I have a single photo of Angelina Jolie by herself, and I want to match this single face and get back the photo and face embedding that's stored in the sqlite db. **The problem:** The sql command that calculates the Euclidean distance to find matches in the db returns nothing (so it thinks there's no Angelina Jolie faces in the db when there is). I think the sql command is incorrect because loading all the db data first and then running the distance calculation with pure python actually does return a result. Here's the group photo that I've stored into the db: [![angie_group.jpg][2]][2] This is the code used to do the distance calculation in sql: ``` with conn: cur = conn.cursor() # compare target_img = "angie_single.jpg" target_represent = DeepFace.represent(img_path=target_img, model_name="Facenet", detector_backend="retinaface")[0] target_embedding = target_represent["embedding"] target_facial_area = target_represent["facial_area"] target_statement = "" for i, value in enumerate(target_embedding): target_statement += 'select %d as dimension, %s as value' % (i, str(value)) #sqlite if i < len(target_embedding) - 1: target_statement += ' union all ' select_statement = f''' select * from ( select img_name, sum(subtract_dims) as distance_squared from ( select img_name, (source - target) * (source - target) as subtract_dims from ( select meta.img_name, emb.value as source, target.value as target from face_meta meta left join face_embeddings emb on meta.id = emb.face_id left join ( {target_statement} ) target on emb.dimension = target.dimension ) ) group by img_name ) where distance_squared < 100 order by distance_squared asc ''' results = cur.execute(select_statement) instances = [] for result in results: print(result) img_name = result[0] distance_squared = result[1] instance = [] instance.append(img_name) instance.append(math.sqrt(distance_squared)) instances.append(instance) result_df = pd.DataFrame(instances, columns = ['img_name', 'distance']) print(result_df) ``` And here is the target photo I'm using to query: [![angie_single.jpg][3]][3] Unfortunately the above code finds nothing even though there should be one hit (from the group photo): ``` Empty DataFrame Columns: [img_name, distance] Index: [] ``` If I grab all the db data into memory and then run it against a calculation done in python (not sql), then I do get a match: ``` def findEuclideanDistance(row): source = np.array(row['embedding']) target = np.array(row['target']) distance = (source - target) return np.sqrt(np.sum(np.multiply(distance, distance))) ``` Finds one match: ``` img_name embedding target distance 0 angie_group.jpg [0.10850527882575989, 0.5568691492080688, 0.81... [-0.6434235572814941, 0.5883399248123169, 0.29... 8.263514 ``` **What's missing in the sql code?** Why does it not match anything? [1]: https://sefiks.com/2021/02/06/deep-face-recognition-with-sql/ [2]: https://i.stack.imgur.com/7uk1e.jpg [3]: https://i.stack.imgur.com/OY7Oz.jpg
I have a numpy array and corresponding row and column indices: ``` matrix = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0,]) col_idx = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) ``` I would like to unravel the matrix by the groups specified by row_idx and col_idx. In the case of this example, the row_idx are all zero, so the elements would unravel by columns: ``` result = np.array([0, 3, 6, 1, 4, 7, 2, 5, 8]) ``` **Why ravel doesn't work** The problem with ravel is that it does not generalise to where the matrix has areas that are grouped by rows and other areas by columns based on the row_idx and col_idx. There can be a combination of both row and column grouping, as below: In this example ``` matrix = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]) col_idx = np.array([0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2]) ``` The result array is the top-left 2x2, [0, 1, 4, 5], followed by the top right 1x2, [2, 3], and so on based on the row and column groupings. ``` result = np.array([[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 10, 11]) ``` **Why numpy_groupies.aggregate() doesn't work** I have tried aggregate() from the numpy_groupies package, but it is both slow and returns an array combining np.arrays and ints (which makes further manipulation difficult and slow).
I have integrated the [Postal framework ](https://github.com/snipsco/Postal) in my sample iOS application for IMAP functionality. NOTE no other functionality just a iOS app and Framework added in it and using only one method and it's runs successfully on simulator but crash in iOS device.Sample code which you can [download](https://drive.google.com/file/d/1kzmkzGzdpcxULbyPja6GMKykkQm50GJs/view?usp=sharing) I have tried al the require solution but yet not able to get any success. Please let me know if someone find out why it's crash in iPhone device or what are possible reason of the crash only on iPhone.
Postal Framework crash in iPhone but runs successfully in simulator
|ios|iphone|xcode|imap|postal|
I have a numpy array and corresponding row and column indices: ``` matrix = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0,]) col_idx = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) ``` I would like to unravel the matrix by the groups specified by row_idx and col_idx. In the case of this example, the row_idx are all zero, so the elements would unravel by columns: ``` result = np.array([0, 3, 6, 1, 4, 7, 2, 5, 8]) ``` **Why ravel doesn't work** The problem with ravel is that it does not generalise to where the matrix has areas that are grouped by rows and other areas by columns based on the row_idx and col_idx. There can be a combination of both row and column grouping, as below: In this example ``` matrix = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) row_idx = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]) col_idx = np.array([0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2]) ``` The result array is the top-left 2x2, [0, 1, 4, 5], followed by the top right 1x2, [2, 3], and so on based on the row_idx and col_idx groupings. ``` result = np.array([[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 10, 11]) ``` **Why numpy_groupies.aggregate() doesn't work** I have tried aggregate() from the numpy_groupies package, but it is both slow and returns an array combining np.arrays and ints (which makes further manipulation difficult and slow).
Error when using Final keyword in replacing merge tree table
|clickhouse|
null