instruction
stringlengths
0
30k
I am trying to contruct a new `NetworkManager` from a function, but it takes a reference to another variable which is also created in the same scope. ```rust fn test() -> NetworkManager<'_> { let dbus = Connection::new_system().unwrap(); NetworkManager::new(&dbus) } ``` How can I return this NetworkManager ? Rn I get a compiler error ```lang-none error[E0515]: cannot return value referencing local variable `dbus` --> src/lib.rs:40:5 | 38 | let nm = NetworkManager::new(&dbus); | ----- `dbus` is borrowed here 39 | 40 | nm | ^^ returns a value referencing data owned by the current function ``` Which I understand. I just don't know how to return it properly. NOTE: I can change the return type of the function, so I can create a new type encapsulating the dbus Connexion and NetworkManager but I didn't find a way to express this type. Tried to create a new type: ```rust struct Test<'a> { dbus: Connection, nm: NetworkManager<'a>, } ``` But as there is no relation between dbus and nm here, there is no way the compiler understands what I want to do.
It appears Intl.DateTimeFormat() only accepts `"narrow", "short", "long"` as the `weekday` option. I would like it to return as a `number`. i.e. Sunday = 0, Monday = 1 and so on. If I'm correct in reading "numerical" is not an option, what would be an easy way to return the value weekday as a number? ``` const day = new Intl.DateTimeFormat('en-US', { timeZone: America/New_York, weekday: 'long', }); const weekdayNumber = ["0", "1", "2", "3", "4", "5", "6"]; const dayNumber = weekdayNumber[day.format(now)]; console.log('Weekday: ' + dayNumber); // returns error ```
Intl.DateTimeFormat() - return weekday as number?
|javascript|datetime|
null
[root@workspace tmp]# ll total 8 -rw-------. 1 root root 6 Mar 31 13:18 * -rw-------. 1 root root 6 Mar 31 13:18 ? [root@workspace tmp]# for f in "`find . -type f`";do echo "$f";done ./* ./? [root@workspace tmp]# for f in "`find . -type f`";do echo $f;done ./* ./? ./* ./? I am confused about the output ... the differenct of the commands is: the double quote around the $f thanx any help in advance.
why variable substitution is so different?
|bash|shell|
null
@Chukwujiobi_Canon's answer is excellent, and scalable, though it did take me a whole day to almost get it working, and it's still not quite there. I expect it may take me another day to perfect it, however given my files are under 1mb in size, I decided to explore my original thought: embed the file content in base64 in the rendered page (hidden), and trigger it's download automatically in javascript. It took me under an hour, it is full functional, and it took very little code. Granted, some of that code was re-used from the work on the other solution. Here is how I generate the file content. I included the method that takes a pandas-style dict and converts it to and xlsxwriter (`pip install xlsxwriter`). ``` import xlswriter def form_valid(self, form): # This buffers errors associated with the study data self.validate_study() # This generates a dict representation of the study data with fixes and # removes the errors it fixed self.perform_fixes() # This sets self.results (i.e. the error report) self.format_validation_results_for_template() study_stream = BytesIO() xlsxwriter = self.create_study_file_writer(study_stream) xlsxwriter.close() # Rewind the buffer so that when it is read(), you won't get an error about opening a zero-length file in Excel study_stream.seek(0) study_data = base64.b64encode(study_stream.read()).decode('utf-8') study_filename = self.animal_sample_filename if self.animal_sample_filename is None: study_filename = "study.xlsx" return self.render_to_response( self.get_context_data( results=self.results, form=form, submission_url=self.submission_url, study_data=study_data, study_filename=study_filename, ), ) def create_study_file_writer(self, stream_obj: BytesIO): xlsxwriter = pd.ExcelWriter(stream_obj, engine='xlsxwriter') # This iterates over the desired order of the sheets and their columns for order_spec in self.get_study_sheet_column_display_order(): sheet = order_spec[0] columns = order_spec[1] # Create a dataframe and add it as an excel object to an xlsxwriter sheet pd.DataFrame.from_dict(self.dfs_dict[sheet]).to_excel( excel_writer=xlsxwriter, sheet_name=sheet, columns=columns ) return xlsxwriter ``` This is the tag in the template where I render the data ``` <pre style="display: none" id="output_study_file">{{study_data}}</pre> ``` This is the javascript that "downloads" the file: ``` document.addEventListener("DOMContentLoaded", function(){ // If there is a study file that was produced if ( typeof study_file_content_tag !== "undefined" && study_file_content_tag ) { browserDownloadExcel('{{ study_filename }}', study_file_content_tag.innerHTML) } }) function browserDownloadExcel (filename, base64_text) { const element = document.createElement('a'); element.setAttribute( 'href', 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + encodeURIComponent(base64_text) ); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } ```
I know, that it's been a few years, but I wanted to share my solution, that I've been using for a while. I just came about this post, because I was searching for a better way. ```Python import aiohttp import http from bs4 import BeautifulSoup async def playercount(gameid): url = f'https://steamcharts.com/app/{gameid}' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'} async with aiohttp.ClientSession(headers=headers) as session: async with session.get(url) as response: if response.status != 200: return{"error": {"code": response.status, "message": http.HTTPStatus(response.status).phrase}} html = await response.text() soup = BeautifulSoup(html, 'html.parser') data = {} count = 0 for stats in soup.find_all('div', class_='app-stat'): soup2 = BeautifulSoup(str(stats), 'html.parser') for stat in soup2.find_all('span', class_='num'): stat = str(stat).replace('<span class="num">', '').replace('</span>', '') if count == 0: data['Current Players'] = stat elif count == 1: data['Peak Players 24h'] = stat elif count == 2: data['Peak Players All Time'] = stat count += 1 return data ```
I am trying to convert string of mathematical expression to lambda function in C++17. How can I do this type of conversion with function? std::function<void()> str2lambda(const std::string& str) { // Code } Example: > Input Mathematical function: > "x^2+1" > > Output Lambda Function: > `auto func = [](float x) -> float { return pow(x, 2) + 1; }; `
The problem is occurring because `adapter` is not set to the `RecyclerView`. **Solution:** Set the `stockPriceAdapter` to the `stockPriceList` before notifying it for the dataset changed. **Updated Code:** ```java public void StockPrice() { String name = Name; String Symbol = symbol; String price = "$20"; String ap = "7d0e928bad8b4a428b2d4d5351bd8a51"; String url = "https://api.twelvedata.com/price?symbol=" + symbol + "&apikey=" + ap; stockPriceList = new ArrayList<>(); stockPriceAdapter = new StockPriceAdapter(stockPriceList, MainActivity.this); stockPriceList.setAdapter(stockPriceAdapter); stockPriceList.add(new defualtWatchListModel(name, Symbol, price)); stockPriceAdapter.notifyDataSetChanged(); } ```
{"Voters":[{"Id":23528,"DisplayName":"Daniel A. White"},{"Id":13808319,"DisplayName":"Mike Organek"},{"Id":839601,"DisplayName":"gnat"}]}
I am following this [tutorial][1] to fetch the auth token for the HERE maps. I am able to fetch the token with my iOS app, However I cannot seem to get the token with Android. I keep getting the error `errorCode: '401300'. Signature mismatch. Authorization signature or client credential is wrong."` Below is my code to fetch the token : **HEREOAuthManager.java** <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> public void fetchOAuthToken(final HereTokenFetchListener callback) { String timestamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())); String nonce = Util.randomStringGenerator(); String grant_type = "grant_type=client_credentials"; String oauth_consumer_key = "&oauth_consumer_key=" + clientID ; String oauth_nonce = "&oauth_nonce=" + nonce; String oauth_signature_method = "&oauth_signature_method=HMAC-SHA256"; String oauth_timestamp = "&oauth_timestamp=" + timestamp; String oauth_version = "&oauth_version=1.0"; String paramsString = grant_type + oauth_consumer_key + oauth_nonce + oauth_signature_method + oauth_timestamp + oauth_version; String baseString = "POST&" + Util.urlEncode(tokenEndpoint) + "&" + Util.urlEncode(paramsString); // Generate signature String secret = Util.urlEncode(clientSecret) + "&"; String signature = Util.calculateHmacSha256(secret, baseString); // Construct Authorization header String authString = "OAuth oauth_consumer_key=\"" + clientID + "\",oauth_nonce=\"" + nonce + "\",oauth_signature=\"" + Util.urlEncode(signature) + "\",oauth_signature_method=\"HMAC-SHA256\"," + "oauth_timestamp=\"" + timestamp + "\",oauth_version=\"1.0\""; // Create HTTP client OkHttpClient client = new OkHttpClient(); // Create request body RequestBody requestBody = new FormBody.Builder() .add("grant_type", "client_credentials") .build(); // // Create HTTP request Request request = new Request.Builder() .url(tokenEndpoint) .post(requestBody) .addHeader("Authorization", authString) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); } <!-- end snippet --> **Utils.java** <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> public static String calculateHmacSha256(String secret, String data) { try { String secretWithAmpersand = secret + "&"; SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKeySpec); byte[] hmacData = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); String baseEncodedSignature = Base64.getEncoder().encodeToString(hmacData); return urlEncode(baseEncodedSignature); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return null; } } public static String urlEncode(String stringToEncode) { try { return java.net.URLEncoder.encode(stringToEncode, "UTF-8") .replace("+", "%20") // Replace '+' with '%20' .replace("=", "%3D") .replace("*", "%2A") // Replace '*' with '%2A' .replace("&", "%26") .replace( "~","%7E"); // Replace '~' with '%7E'; } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static String randomStringGenerator() { String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm"; final Random random=new Random(); final StringBuilder sb=new StringBuilder(8); for(int i=0;i<8;++i) sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length()))); return sb.toString(); } <!-- end snippet --> What could I be missing? Any help is appreciated [1]: https://www.here.com/docs/bundle/identity-and-access-management-developer-guide/page/topics/sdk.html
I try to use FocusNode() in TextFormField so it will detect when I focus on the TextFormField, the text above will have it's color changed. But it seems not working, what seems to be the problem? ``` import 'package:flutter/material.dart'; class SignIn extends StatefulWidget { const SignIn({Key? key}) : super(key: key); @override _SignInState createState() => _SignInState(); } class _SignInState extends State<SignIn> { bool isPasswordVisible = false; bool _isEmail = true; bool _isPassword = true; TextEditingController emailInput = TextEditingController(); TextEditingController passwordInput = TextEditingController(); FocusNode emailText = FocusNode(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( child: Container( padding: EdgeInsets.all(30.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Sign In to Coinify', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24.0, fontFamily: "Graphik", ) ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Email', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, color: emailText.hasFocus ? Colors.blue : Colors.black, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( focusNode: emailText, controller: emailInput, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red) ), hintText: 'Enter your email', errorText: _isEmail ? null : "Email must not be empty", ), ) ], ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Password', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( controller: passwordInput, obscureText: !isPasswordVisible, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), hintText: 'Enter your password', errorText: _isPassword ? null : "Password must not be empty", suffixIcon: GestureDetector( onTap: () { setState(() { isPasswordVisible = !isPasswordVisible; }); }, child: Icon( isPasswordVisible ? Icons.visibility : Icons.visibility_off, ), ), ), ) ], ), SizedBox(height: 50.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/forgot-password'); }, child: Text( 'Forgot password?', style: TextStyle( color: Colors.blue, ) ) ) ), MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/privacy-policy'); }, child: Text( 'Privacy policy', style: TextStyle( color: Colors.blue, ) ) ) ), ] ), SizedBox(height: 20.0), ElevatedButton( onPressed: () { setState(() { if(emailInput.text == ""){_isEmail = false;} else{_isEmail = true;} if(passwordInput.text == ""){_isPassword = false;} else{_isPassword = true;} if(_isEmail && _isPassword) {Navigator.pushNamed(context, '/sign-in-code');} }); }, child: Text( "Sign in", style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.normal, color: Colors.white ), ), style: ButtonStyle( shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)) ), minimumSize: MaterialStateProperty.all(Size.fromHeight(60.0)), backgroundColor: MaterialStateProperty.all(Colors.blue), shadowColor: MaterialStateProperty.all(Colors.transparent) ), ) ] ) ), ) ); } } ``` I have tried to change the color in the ternary operator and realized that the Color seems to stuck in false value
Text Color didn't change
|flutter|flutter-textformfield|
null
What I do is npm i @tanstack/react-query @tanstack/react-query-devtools && npm i -D @tanstack/eslint-plugin-query Here what I did was install all dependencies with **npm i with space** to **separate packages** and when **I want to download dev dependencies** I use **&&** and npm i -D with space to install multiple dev dependencies packages. Generate Rule npm i **package1 package2 ....** && npm i **-D devDependenciesPackage1 devDependenciesPackage2** ... **Indication** **&&** to separate dependencies with Dev Dependecies **...** to indicate that you are add more package before && symbol
I want to create progress bars to see my advancements during the year in different topics along the year in Obsidian. I've checked several options, like this tutorial, but don't seem clear to me: [Progress Bar on Tasks](https://obsidianttrpgtutorials.com/Obsidian+TTRPG+Tutorials/Plugin+Tutorials/Dataview/DataviewJS+-+Progress+Bar+on+Tasks) In the following example they provide: ```dataviewjs (await dv.tryQuery('TASK FROM "Test" ')).values.length const Tasks = dv.page("Test").file.tasks let CompletedTasks = Tasks .where(t => t.completed) dv.span( "![progress](https://progress-bar.dev/" + parseInt((CompletedTasks.length / Tasks.length) * 100) + "/)" ) ``` - [ ] Quest 1 - [ ] Quest 2 - [ ] Quest 3 - [ ] Quest 4 - [ ] Quest 5 What do I have to modify to obtain a progress bar?
|javascript|obsidian|obsidian-dataview|
null
I want to create progress bars to see my advancements during the year in different topics along the year in Obsidian. I've checked several options, like this tutorial, but don't seem clear to me: [Progress Bar on Tasks](https://obsidianttrpgtutorials.com/Obsidian+TTRPG+Tutorials/Plugin+Tutorials/Dataview/DataviewJS+-+Progress+Bar+on+Tasks) In the following example they provide: (await dv.tryQuery('TASK FROM "Test" ')).values.length const Tasks = dv.page("Test").file.tasks let CompletedTasks = Tasks .where(t => t.completed) dv.span( "![progress](https://progress-bar.dev/" + parseInt((CompletedTasks.length / Tasks.length) * 100) + "/)" ) and - [ ] Quest 1 - [ ] Quest 2 - [ ] Quest 3 - [ ] Quest 4 - [ ] Quest 5 What do I have to modify to obtain a progress bar?
My code segment is this: ``` <> <Divider orientation="left">{resultLinkTitle}</Divider> <Intension /> <Form form={form} name="auditForm" ref={auditFormRef}> <Form.Item label="files"> <Button type="link" onClick={() => handleDownLoadFile(aduitInfo?.fileUrl)}> download </Button> </Form.Item> </Form> </> ``` then I use `swc.parse` to get ast. But I cannot get the original code with `swc.printSync`. It returns an error `unknown variant 'JSXElement', expected 'Module' or 'Script'`. How can I solve this? How do I get the original code with swc.
How to use swc to make ast restore be code segment
null
Seeking to get some help around the cidrsubents functionality in terraform. I have a vpc cidr, 10.0.0.0/16, I wanted to get three private database subnets /25, four public /26 subnets and four other private /23 subnets. How can I achieve this dynamically using cidrsubnets? Also, in future if I need to add an extra database subnet, it should be scalable such that it doesn’t re create any other subnets. Any help would be appreciated. TIA!
I am trying to scrape my instagram followers, but I am having issues with the scrolling mechanism to load more followers. ``` dialog_box = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "(//div[@class='_aano'])[1]/div[1]")) ) driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", dialog_box) ``` The element is being correctly located, but the scrolling script is not doing anything. Any suggestions? Note: the XPATH is locating the div whose height actually changes upon scroll. It is not the dialog box element, which I have already tried and it did not work.
Scrolling Instagram Followers Not Working
|python|selenium-webdriver|scroll|instagram|
When running the command: "pip3 install pyaudio", I get this error: "Collecting pyaudio Using cached PyAudio-0.2.14.tar.gz (47 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: pyaudio Building wheel for pyaudio (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for pyaudio (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [18 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-cpython-38 creating build/lib.macosx-10.9-x86_64-cpython-38/pyaudio copying src/pyaudio/__init__.py -> build/lib.macosx-10.9-x86_64-cpython-38/pyaudio running build_ext building 'pyaudio._portaudio' extension creating build/temp.macosx-10.9-x86_64-cpython-38 creating build/temp.macosx-10.9-x86_64-cpython-38/src creating build/temp.macosx-10.9-x86_64-cpython-38/src/pyaudio gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DMACOS=1 -I/usr/local/include -I/usr/include -I/opt/homebrew/include "-I<PATH FROM STEP 3>/include/" -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c src/pyaudio/device_api.c -o build/temp.macosx-10.9-x86_64-cpython-38/src/pyaudio/device_api.o src/pyaudio/device_api.c:9:10: fatal error: 'portaudio.h' file not found #include "portaudio.h" ^~~~~~~~~~~~~ 1 error generated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] Note: This error originates from a subprocess and is likely not a problem with pip. ERROR: Failed building wheel for pyaudio Failed to build pyaudio ERROR: Could not build wheels for pyaudio, which is required to install pyproject.toml-based projects" I am running MacOS 14.3.1. Any suggestions?
|installation|pip|subprocess|pyaudio|
null
Your code wouldn't work for me in the code snippet, but did as soon as I copied it out to a local html file and ran it there. The iframe is messing with the intersection observer's root. Your code was useful to me, I hadn't been able to find an example combining the :enter and :leave modifiers. (I had to write this as an answer rather than a comment due to insufficient points.)
A web project does not need to run on the whole World Wide Web. A very large amount of questions we get about website projects are for training only - usually from following a tutorial or a course. Another thing is that serving the project is not hard at all. For simple sites with just static assets, you can even run ```bash python -m SimpleHTTPServer 8000 ``` in your command line to start a simple HTTP server that would serve the contents of the current directory. Then <kbd>Ctrl</kbd> + <kbd>C</kbd> to stop it. It's not sophisticated but enough to see your website. There are other server software, though, if it's a project with frontend + backend, the backend often comes with built in serving capability based on the stack used. Webpack, Vite, Vue and others offer a web server bundled with them. Might be a matter of some configuration but the setup for a dev environment is rarely complex. If it needs to really be showcased online, there are dev environments for that as well. For example StackBlitz can take your code and run it - both backend and frontend. I personally often use JSBin for simple frontend things. It's useful because I can write the code and run it immediately and I even get a shareable link I can bookmark for later. I have several simple tools or demos living just in JSBin. Toy or learning projects often don't need "real hosting" because the goal is rarely to publish them. They can be just for teaching something or to try something or maybe even to pad out a portfolio. In the last case, that project might just be uploaded to GitHub or similar and doesn't need to run continuously. ---- Even then, if this is not meant to be just a toy project - there are plenty of options. You don't need to *start* with figuring out how to put the project on the Web. There are many hosting providers, including GitHub. Other hosting providers also exist with a lot of cheap or maybe even free options (I've not checked how the free landscape at least for a decade, though). Also hosting providers nowadays try to make it convenient to use them. A lot offer to register the domain for you, you just need to search for one (using their own site) that you like. They may even have options to host, say, Angular projects, or Django projects. Which reduces the setup needed. Bottom line is, that setting up a web hosting is not really that hard and you can start a project without even doing this until the end.
null
{"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":8017690,"DisplayName":"Yong Shun"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]}
I have two tables one for Credit and the second for those who have paid their credits Table 1 credit_id customer_id total_amount_given disbursement_date 1 1 50000 2020-09-02 2 2 60000 2020-09-02 3 1 10000 2020-10-05 4 3 100000 2020-09-02 Table 2 payment_id credit_id amount type payment_timestamp 1 1 50000 disbursement 2020-10-01 10:01:12 2 2 1000 repayment 2020-10-01 10:05:12 3 1 10000 repayment 2020-10-01 10:31:01 4 2 100 repayment 2020-11-01 17:11:01 Definition of Total outstanding balance = total disbursed amount (type=’disbursement’ in table 2) - total repaid amount (type=’repayment’ in table 2) Assuming that all credit tenure irrespective of the credit amount is for 90 days only. I want to write a query to create a table that will give me total outstanding balance on each day from disbursement day till last repayment date of the rent for each customer – credit combination. Required Table Structure Required Table Structure date|Customer_id|credit_id|total_amount_disbursed|total_outstanding_amount|latest_repayment_date
I'm trying a solution to resolve a duplication of requests happening in my Ruby on Rails 6 project deployed to Heroku. This seems to occur when those anchors with hyperlinks are used, so it loads 2x. As a result, it ends up generating duplicate logs because it also calls the controller (GET -> Controller -> Model -> View). Below are some logs that prove the duplicate request: ```ruby caio-agiani in ~ via ⬢ v14.21.3 took 10m 37s ❯ heroku logs -a levante-web -t | grep 2804:7f0:b8c2:13f:8755:4a1e:74b8:x735,172.71.10.17 2024-03-31T02:32:36.318790+00:00 heroku[router]: at=info method=GET path="/levante/search?query=caioagiani" host=app request_id=3e84b5d5-b478-41aa-b1e8-218838f37ca1 fwd="2804:7f0:b8c2:13f:8755:4a1e:74b8:x735,172.71.10.17" dyno=web.1 connect=0ms service=426ms status=200 bytes=12075 protocol=https 2024-03-31T02:32:57.648033+00:00 heroku[router]: at=info method=GET path="/levante/search?query=caioagiani" host=app request_id=f17c6635-3541-4153-8283-3811659ff00a fwd="2804:7f0:b8c2:13f:8755:4a1e:74b8:x735,172.71.10.17" dyno=web.1 connect=0ms service=330ms status=200 bytes=12077 protocol=https 2024-03-31T02:33:01.813927+00:00 heroku[router]: at=info method=GET path="/levante/shop/index" host=app request_id=cc5dd643-41c3-45e9-bffa-a73ed617d0b0 fwd="2804:7f0:b8c2:13f:8755:4a1e:74b8:x735,172.71.10.17" dyno=web.1 connect=0ms service=42ms status=200 bytes=25575 protocol=https 2024-03-31T02:33:02.145246+00:00 heroku[router]: at=info method=GET path="/levante/shop/index" host=app request_id=7bdfadad-273e-4b8a-ab88-4f0422ececaf fwd="2804:7f0:b8c2:13f:8755:4a1e:74b8:x735,172.71.10.17" dyno=web.1 connect=0ms service=39ms status=200 bytes=25564 protocol=https ``` [![enter image description here](https://i.stack.imgur.com/Oot1a.png)](https://i.stack.imgur.com/Oot1a.png) PS: Could this be linked to Turbolink/Load or some internal Rails script like ujs? I have evidence that yes, as I have another application in production using exactly the same setup, however, 1 uses the conventional rails native import scripts and css template (javascript_include_tag, javascript_pack_tag, stylesheet_pack_tag) and the other uses simple HTML meta tags - I've already tested it in a local environment and this doesn't happen. - I saw some comments about Serviceworker, but I didn't validate it 100%. - There is no Loadbalance/Nginx configuration. Direct environment between Heroku with Node/Ruby Buildpacks and the RoR project.
Duplicate GET requests - Rails & Heroku
|ruby-on-rails|ruby|heroku|deployment|
null
`/apps/postgres` directory is created when your container is created. The `volumes` parameter in the Docker Compose file maps a directory from the host file system to a directory within the container. If you didn't delete the `/apps/postgres` directory, your database won't be cleared. You can delete the `/apps/postgres` directory ✅
I have a problem such that $F(G(x))=G(x)$, where $x$ is real numbers and I know that function $F$ can be computed if value $G(x)$ is given. $F$ is a probability function. I want to obtain a function form $G$ (or an algorithm G). What is the problem? Is there any knowledge about "finding a function that gives fixed points of another given function"?
How to find function G(x), and make for every x, G(x) always returns fixed point for another function F(G(x))
Terraform cidrsubnets
|terraform|terraform-provider-aws|
1. If the variable is in the TAB menu then `Stats` is supposed to be named `leaderstats` 2. If the variable is a Gui then change the text in the gui
This is an interesting problem, but I'm not sure you're approach is going to get to a solution. This is an ordinary differential equation (ODE), where the position of a particle at any time depends upon its acceleration and velocity (and previous position). By considering a 10x10x10 grid, you are forcing the body to only be at one of 1000 discrete positions. What you really want is to figure out where the body is at time *t*, without restricting its position to only having one of 1000 discrete values. In general, there is no exact solution and an analytical approximation can be found with an ODE solver. You'll need to rewrite the E field as a function. See, for example https://pythonnumericalmethods.berkeley.edu/notebooks/chapter22.06-Python-ODE-Solvers.html
i dockerized my mern app (Next js, node js , mongodb) and trying to deploy it on aws ec2 instance. when i try to access my backend on port 5000 via aws public ip then it works fine when i try to access frontend then terminal stuck and if i try to reload the terminal then ssh gives error. this is error i am seeing if i try to reload the terminal: **Failed to connect to your instance Error establishing SSH connection to your instance. Try again later.** then i have to stop the instance and start the instance. then again backend works fine and when try to access frontend it gives error. this is my folder structure looks like **myecommerce folder then it have two more folders backend frontend nginx (nginx have two files one is dockerfile and second is nginx.conf) docker-compose.yml** **this is how my nginx docker file looks like** FROM nginx:latest RUN rm /etc/nginx/conf.d/* COPY ./nginx.conf /etc/nginx/conf.d/ CMD [ "nginx", "-g", "daemon off;" ] **this is how my nginx.conf file looks like** events {} http { server { listen 80; server_name here my aws public ip; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } } } **this is my frontend folder docker file** FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD npm run dev **this is my backend folder docker file** FROM node:20-alpine RUN npm install -g nodemon WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 5000 CMD ["npm", "run", "dev"] **this is how my docker-compose.yml looks like** version: '3' services: frontend: image: my frontend image from docker hub ports: - "3000:3000" backend: image:my backend image from dockerhub ports: - "5000:5000" nginx: image: my nginx image from dockerhub ports: - "80:80" later i want to setup github ci cd pipelines for it and using custom domain to access the website later. i am not sure if i am using docker-compose i still need to setup pm2. i am also posting my inbound rules i dont know why frontend is not working. guys i am beginner in aws deployment and dockerization. i am improving my skills please help me i am stuck in this from many days i saw alot of videos and watched multiple videos but not a single article or video doing what i am actually trying to do. Thanks in advance [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/Douvi.png
Good morning... need help... I'm trying to use inno setup. But I don't have much experience in programming. The idea was... to install the program and in the end, the necessary components for it (.net, mysql connector, mysql server...) There was a program for it (first see if the programs existed and then install it), in any of them (whether it exits or not), the program continues installing... .net runs very well and is working When I go to install the mysql connector, it initially gave the code 192, it is not valid Win32 After reading some posts, I managed to get around this problem. At this point, the installation window appears. As I already have the connector installed, I will click on cancel... "Are you sure you want to cancel mysql connector?" I click yes... and then click finish. when it should close the mysql installer and return to the program installer, I then receive error 193 %1 is not a valid win 32 application.. I don't know what else I can do... someone can help me? please... ``` [Run] Filename: "{app}\dotnet-sdk-8.0.203-win-x64.exe"; Flags: skipifdoesntexist; BeforeInstall: CheckDotNet Filename: "{app}\mysql-connector-net-8.3.0.msi"; Flags: skipifdoesntexist; BeforeInstall: InstallMySQLConnectorNet Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent runascurrentuser [Code] function IsDotNetInstalled(): Boolean; var DotNetVersion: Cardinal; begin DotNetVersion := GetWindowsVersion; Result := (DotNetVersion >= $0008000300); // 8.0.3 end; function IsMySQLConnectorInstalled(): Boolean; begin Result := FileExists(ExpandConstant('{app}\mysql-connector-net-8.3.0.msi')); end; procedure CheckDotNet; begin if not IsDotNetInstalled() then begin MsgBox('A instalação do .NET Runtime 8.0.3 é necessária para continuar. A instalação será cancelada.', mbError, MB_OK); Abort; end; end; [Code] function IsMySQLConnectorNetInstalled: Boolean; begin Result := RegKeyExists(HKEY_LOCAL_MACHINE, 'SOFTWARE\MySQL AB\MySQL Connector/Net'); end; procedure InstallMySQLConnectorNet; var ResultCode: Integer; begin if not IsMySQLConnectorNetInstalled then begin if not ShellExec('', ExpandConstant('{app}\mysql-connector-net-8.3.0.msi'), '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then begin MsgBox('Falha ao iniciar a instalação do MySQL Connector .NET 8.3.0.', mbError, MB_OK); Abort; end; end; end; function InitializeSetup: Boolean; begin Result := True; end; ```
InnoSetup error 193 afeter install Mysql Connector
|mysql|
null
{"Voters":[{"Id":3689450,"DisplayName":"VLAZ"},{"Id":11683,"DisplayName":"GSerg"},{"Id":839601,"DisplayName":"gnat"}]}
The shell _expands_ the commands before executing them. There are 7 consecutive expansions: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion (see [this section of the bash manual](https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html)). In your case brace expansion, tilde expansion and arithmetic expansion have no effect because you do not use these features. Before the `for` loop is executed command substitution replaces the `find` command with `./? ./*`. Because it is enclosed in double quotes the word splitting does not split `./? ./*` and filename expansion is skipped. The `for` command is thus not further transformed before execution. The loop iterates only once with value `./? ./*` of variable `f`. In `echo "$f"` `$f` is expanded (parameter expansion) and replaced with the value of variable `f`. Again, because of the double quotes, word splitting and filename expansion are skipped, the result is printed without further modifications, and you see `./? ./*`. In `echo $f`, `$f` is also expanded and replaced with the value of `f` but the expansion continues with word splitting and pathname expansion. Word splitting separates the two words `./?` and `./*` such that they are treated separately in the next steps. Pathname expansion replaces `./?` with the list of all single-character file names in current directory (in your case `./?` and `./*`) and `./*` is replaced with the list of all file names in current directory (in your case `./?` and `./*`). So, finally what is echoed is `./? ./* ./? ./*`.
You should use serverless-offline to run serverless locally. 1) npm i serverless-offline 2) add serverless-offline in plugins of your serverless.yml file ```yaml plugins: - serverless-offline ``` 3) then you can run it locally as `serverless offline start`
The transposition table uses keys from the position of player 0 and player 1 from bitboards and includes the player turn at the end, I did that to guarantee unique keys for all states. But this seems to be slow because of fmt.Sprintf. I have two functions where I store and retrieve, and in each of them I build the key and do a check or store. type TTFlag int64 const ( Exact TTFlag = 0 UpperBound TTFlag = 1 LowerBound TTFlag = 2 ) type TTEntry struct { BestScore float64 BestMove int Flag TTFlag Depth int IsValid bool } type Solver struct { NodeVisitCounter int TTMapHitCounter int TTMap map[string]TTEntry } func NewSolver() *Solver { return &Solver{ NodeVisitCounter: 0, TTMapHitCounter: 0, TTMap: make(map[string]TTEntry), } } func (s *Solver) StoreEntry(p *Position, entry TTEntry) { key := fmt.Sprintf("%d:%d:%d", p.Bitboard[0], p.Bitboard[1], p.PlayerTurn) s.TTMap[key] = entry } func (s *Solver) RetrieveEntry(p *Position) TTEntry { key := fmt.Sprintf("%d:%d:%d", p.Bitboard[0], p.Bitboard[1], p.PlayerTurn) if entry, exists := s.TTMap[key]; exists { s.TTMapHitCounter++ return entry } return TTEntry{} } What can I do to optimize this further? How can I make better keys without the use of fmt.Sprintf and string concatenation? Edit: The Position struct is keeps track of game state: type Position struct { Bitboard [2]uint64 PlayerTurn int HeightBB [7]int NumberOfMoves int } HeightBB is an array that keeps track of the height of the columns, so we know where to put the piece in the bitmap.
I have my own CMS system with settings for an multi language website and I save this in my database. But I can't check that variable in my htacces so I want to check my request url like this: cms2024.nl/nl/home or cms2024.nl/home and then give different RewriteRules to get my right url order If there is an language in the url I want these rules: `RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /index.php?taal=$1&page=$2&title=$3&beginnenbij=$4 [L] RewriteRule ^([^/]*)/([^/]*)/([^/]*)/$ /index.php?taal=$1&page=$2&title=$3 [L] RewriteRule ^([^/]*)/([^/]*)/$ /index.php?taal=$1&title=$2 [L]` and otherwise: `RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /index.php?page=$1&title=$2&beginnenbij=$3 [QSA,L] RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?page=$1&title=$2 [QSA,L] RewriteRule ^([^/]+)/?$ /index.php?title=$1 [QSA,L]` how do I check this in my htaccess file for an right url build-up?
Check REQUEST_URI for any /nl/ or /en/ to change my RewriteRules
|php|.htaccess|content-management-system|
null
What about using `usePathname` in `next/navigation`?
|optimization|fixed-point|
null
I got the same error in production build when I tried to upload an image through an input, although everything worked fine in the dev mode. Upon studying, I found out that's because the public folder is inaccessible during the production build and in order to load the newly generated image, you can make use of services like Amazon S3.. hope it helps someone.
The data structure for this is a [Trie][1] (Prefix Tree): * Time Efficiency: Search, Insertion & Deletion: With a time complexity of O(m) where m is the length of the string. * Space Efficiency: Store the unique characters present in the strings. This can be a space advantage compared to storing the entire strings. ```php <?php class TrieNode { public $childNode = []; // Associative array to store child nodes public $endOfString = false; // Flag to indicate end of a string } class Trie { private $root; public function __construct() { $this->root = new TrieNode(); } public function insert($string) { if (!empty($string)) { $this->insertRecursive($this->root, $string); } } private function insertRecursive(&$node, $string) { if (empty($string)) { $node->endOfString = true; return; } $firstChar = $string[0]; $remainingString = substr($string, 1); if (!isset($node->childNode[$firstChar])) { $node->childNode[$firstChar] = new TrieNode(); } $this->insertRecursive($node->childNode[$firstChar], $remainingString); } public function commonPrefix() { $commonPrefix = ''; $this->commonPrefixRecursive($this->root, $commonPrefix); return $commonPrefix; } private function commonPrefixRecursive($node, &$commonPrefix) { if (count($node->childNode) !== 1 || $node->endOfString) { return; } $firstChar = array_key_first($node->childNode); $commonPrefix .= $firstChar; $this->commonPrefixRecursive($node->childNode[$firstChar], $commonPrefix); } } // Example usage $trie = new Trie(); $trie->insert("/home/texai/www/app/application/cron/logCron.log"); $trie->insert("/home/texai/www/app/application/jobs/logCron.log"); $trie->insert("/home/texai/www/app/var/log/application.log"); $trie->insert("/home/texai/www/app/public/imagick.log"); $trie->insert("/home/texai/www/app/public/status.log"); echo "Common prefix: " . $trie->commonPrefix() . PHP_EOL; ?> ``` Output: Common prefix: /home/texai/www/app/ [Demo][2] [1]: https://en.wikipedia.org/wiki/Trie [2]: https://onecompiler.com/php/428ve5e2h
{"Voters":[{"Id":147356,"DisplayName":"larsks"},{"Id":1394729,"DisplayName":"tink"},{"Id":18157,"DisplayName":"Jim Garrison"}],"SiteSpecificCloseReasonIds":[18]}
I am trying to learn the dataverse API using C#. I am following the code in this github: https://github.com/microsoft/PowerApps-Samples/blob/master/dataverse/orgsvc/C%23-NETCore/GetStarted/ConsoleApp%20(public)/Program.cs I changed the login information and the appID to my app registration's client id and added a redirect URL of http://localhost. The app registration does have API permissions to Dynamics CRM. However, I still get an error > Original exception: AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret' This is my connection string: ``` static string connectionString = $@" AuthType = OAuth; Url = {url}; UserName = {userName}; Password = {password}; AppId = {appId}; RedirectUri = http://localhost; LoginPrompt=Auto; RequireNewInstance = True"; ``` I cannot figure out what the issue is. Any help would be greatly appreciated.
You can use ModuleType: from types import ModuleType a = ModuleType("some") # name of obj a.foo = 123 print(a.foo) print(a.__name__) # some a.__dict__ # {'__name__': 'some', '__doc__': None, '__package__': None, '__loader__': None, '__spec__': None, 'foo': 123}
Adding my own take here because none of the answers were acceptable to me: ```kotlin import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract private fun closeChain(items: List<AutoCloseable>) { if (resources.isEmpty()) return try { resources.last().close() } finally { resources.dropLast(1).also(::closeChain) } } class ResourceInitializationScope { private val itemsToCloseLater = mutableListOf<AutoCloseable>() /** * Adds a resource to be closed later. * * @param resource the resource. */ fun closeLater(item: AutoCloseable) { itemsToCloseLater.add(item) } fun closeNow() = closeChain(itemsToCloseLater) } /** * Begins a block to initialize multiple resources. * * This is done safely. If any failure occurs, all previously-initialized resources are closed. * * @param block the block of code to run. * @return an object which should be closed later to close all resources opened during the block. */ @OptIn(ExperimentalContracts::class) inline fun initializingResources(block: ResourceInitializationScope.() -> Unit): AutoCloseable { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } val scope = ResourceInitializationScope() var success = false try { scope.apply(block) success = true return AutoCloseable { scope.closeNow() } } finally { if (!success) scope.closeNow() } } ``` Example usage: (maybe don't trust the code, other than an example of how to use it, I don't trust it yet) ```kotlin // ... omitting surrounding code ... private val buffers: Array<AudioBuffer> private val device: AudioDevice private val context: AudioContext private val source: AudioSource private val resourcesToClose: AutoCloseable init { resourcesToClose = initializingResources { buffers = Array(BUFFER_COUNT) { AudioBuffer.generate().also(::closeLater) } device = AudioDevice.openDefaultDevice().also(::closeLater) context = AudioContext.create(device, intArrayOf(0)).also(::closeLater) context.makeCurrent() device.createCapabilities() source = AudioSource.generate().also(::closeLater) for (i in 0 until BUFFER_COUNT) { bufferSamples(ShortArray(0)) } source.play() device.detectInternalExceptions() } } override fun close() { resourcesToClose.close() } // ... omitting surrounding code ... ```
[enter image description here][1]I try to use FocusNode() in TextFormField so it will detect when I focus on the TextFormField, the text above will have it's color changed. But it seems not working, what seems to be the problem? ``` import 'package:flutter/material.dart'; class SignIn extends StatefulWidget { const SignIn({Key? key}) : super(key: key); @override _SignInState createState() => _SignInState(); } class _SignInState extends State<SignIn> { bool isPasswordVisible = false; bool _isEmail = true; bool _isPassword = true; TextEditingController emailInput = TextEditingController(); TextEditingController passwordInput = TextEditingController(); FocusNode emailText = FocusNode(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( child: Container( padding: EdgeInsets.all(30.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Sign In to Coinify', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24.0, fontFamily: "Graphik", ) ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Email', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, color: emailText.hasFocus ? Colors.blue : Colors.black, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( focusNode: emailText, controller: emailInput, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red) ), hintText: 'Enter your email', errorText: _isEmail ? null : "Email must not be empty", ), ) ], ), SizedBox(height: 20.0), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Password', style: TextStyle( fontWeight: FontWeight.w600, fontSize: 16.0, fontFamily: "Graphik", ), ), SizedBox(height: 8.0), TextFormField( controller: passwordInput, obscureText: !isPasswordVisible, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), border: OutlineInputBorder(), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.grey) ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.blue) ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red), ), hintText: 'Enter your password', errorText: _isPassword ? null : "Password must not be empty", suffixIcon: GestureDetector( onTap: () { setState(() { isPasswordVisible = !isPasswordVisible; }); }, child: Icon( isPasswordVisible ? Icons.visibility : Icons.visibility_off, ), ), ), ) ], ), SizedBox(height: 50.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/forgot-password'); }, child: Text( 'Forgot password?', style: TextStyle( color: Colors.blue, ) ) ) ), MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Navigator.pushNamed(context, '/privacy-policy'); }, child: Text( 'Privacy policy', style: TextStyle( color: Colors.blue, ) ) ) ), ] ), SizedBox(height: 20.0), ElevatedButton( onPressed: () { setState(() { if(emailInput.text == ""){_isEmail = false;} else{_isEmail = true;} if(passwordInput.text == ""){_isPassword = false;} else{_isPassword = true;} if(_isEmail && _isPassword) {Navigator.pushNamed(context, '/sign-in-code');} }); }, child: Text( "Sign in", style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.normal, color: Colors.white ), ), style: ButtonStyle( shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)) ), minimumSize: MaterialStateProperty.all(Size.fromHeight(60.0)), backgroundColor: MaterialStateProperty.all(Colors.blue), shadowColor: MaterialStateProperty.all(Colors.transparent) ), ) ] ) ), ) ); } } ``` I have tried to change the color in the ternary operator and realized that the Color seems to stuck in false value [1]: https://i.stack.imgur.com/w70Ig.png
I am using `differential_evolution` from `scipy` to do optimization. `likehood` is vectorized to calculate all the populations at once. I have 36 parameters and `popsize=35`. `draws` is also a large matrix `(1000, 112, 7)` for each population, and it is random draws from some distributions. By following the [pytorch tutorial][1] I am now able to use multiple gpus. I want to use `DataLoader` to parallel taking draws. This works when I run it without using multiple gpu. If I run it together like the following code, I get an error. I don't know how to understand this error, as this part of code is actually run on cpu not gpu? And I set `num_workers=4` but it actually only has 2 processes, which I guess is expected because I set `world_size=2`, but how can use use for example, 2 gpu processes and at the same time each uses multiple cpus to do some parallel work? ``` class MapDataset(torch.utils.data.Dataset): def __init__(self, b, L): self.b = b self.L = L def __len__(self): return self.b.shape[1] def __getitem__(self, idx): b = self.b[:, idx] L = self.L[idx, :] obs = np.vstack((b, L)) return obs class Mymodel: def convert_draws(): # using DataLoader to parallelly taking draws return draws def li(draws, params): # using pytorch and gpu return li.cpu().numpy() def collate_fn(self,data): worker_info = torch.utils.data.get_worker_info() data = np.array(worker_info.dataset) worker_id = worker_info.id num_workers = worker_info.num_workers data_chunk = np.split(data, num_workers)[worker_id] b = data_chunk[:, 0, :] L = data[:, 1:, :] draw_list = [] for i in range(b.shape[0]): draws = self.convert_draws(b[i, :], L[i, :]) draw_list.append(draws) data = torch.tensor(np.array(draw_list)) return data def likelihood(params): popinit_data = MapDataset(b, L) draws = DataLoader(popinit_data, batch_size=None, shuffle=False,sampler=None,batch_sampler=None, num_workers=4,collate_fn=self.collate_fn,worker_init_fn=None,prefetch_factor=1,generator=torch.Generator().manual_seed(1)) draws = torch.vstack(list(draws)) li = self.li(drass, params) ll = np.log(li).sum() return -ll def min_de(rank,world_size): model=Mymodel() results = differential_evolution(model.likelihood) import torch.multiprocessing as mp if __name__ == '__main__': world_size = int(sys.argv[1]) processes = [] mp.set_start_method("spawn") for rank in range(world_size): p = mp.Process(target=init_processes,args=(rank,world_size,min_de,'ncll')) p.start() processes.append(p) for p in processes: p.join() ``` [1]: https://github.com/seba-1511/dist_tuto.pth/blob/gh-pages/train_dist.py ``` Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/multigpu.py", line 446, in init_processes fn(rank, size) File "/multigpu.py", line 446, in init_processes fn(rank, size) File "/multigpu.py", line 473, in min_de model.test(x0=popinit.T) File "/multigpu.py", line 473, in min_de model.test(x0=popinit.T) File "/multigpu.py", line 389, in test print("test",self.likelihood(x0)) File "/multigpu.py", line 389, in test print("test",self.likelihood(x0)) File "/multigpu.py", line 344, in likelihood draws = torch.vstack(list(draws)) File "/multigpu.py", line 344, in likelihood draws = torch.vstack(list(draws)) File "/Library/Python/3.9/site-packages/torch/utils/data/dataloader.py", line 439, in __iter__ return self._get_iterator() File "/Library/Python/3.9/site-packages/torch/utils/data/dataloader.py", line 439, in __iter__ return self._get_iterator() File "/Library/Python/3.9/site-packages/torch/utils/ File "/Library/Python/3.9/site-packages/torch/utils/data/dataloader.py", line 387, in _get_iterator return _MultiProcessingDataLoaderIter(self) data/dataloader.py", line 387, in _get_iterator return _MultiProcessingDataLoaderIter(self) File "/Library/Python/3.9/site-packages/torch/utils/data/dataloader.py", line 1040, in __init__ w.start() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/process.py", line 121, in start self._popen = self._Popen(self) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "/Library/Python/3.9/site-packages/torch/utils/data/dataloader.py", line 1040, in __init__ w.start() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/context.py", line 284, in _Popen return Popen(process_obj) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 32, in __init__ super().__init__(process_obj) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_fork.py", line 19, in __init__ self._launch(process_obj) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/popen_spawn_posix.py", line 47, in _launch reduction.dump(process_obj, fp) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) File "/Library/Python/3.9/site-packages/torch/multiprocessing/reductions.py", line 557, in reduce_storage metadata = storage._share_filename_cpu_() File "/Library/Python/3.9/site-packages/torch/storage.py", line 294, in wrapper return fn(self, *args, **kwargs) File "/Library/Python/3.9/site-packages/torch/storage.py", line 368, in _share_filename_cpu_ return super()._share_filename_cpu_(*args, **kwargs) RuntimeError: _share_filename_: only available on CPU ``` UPDATE: I guess I should not use `gloo` when testing in in m1. It works in linux using `nccl`.
{"Voters":[{"Id":6119582,"DisplayName":"sweenish"},{"Id":12002570,"DisplayName":"user12002570"},{"Id":5494370,"DisplayName":"Alan Birtles"}]}
I want to add a local image to the array products like this (https://i.stack.imgur.com/Mckgm.png) I've tried to do like chatpgt said but I still can't do it This is the coding that chatgpt gave me ``` //This is in component uploadImg(event){ const image = event.target.files[0]; this.addImage(image).then((imageUrl) => { this.product.image = imageUrl; }); }, //This is in mutations.js SET_IMAGE(state, image) { state.products.image = image; }, //This is in actions.js addImage({ commit }, image) { commit('SET_IMAGE', image); }, ```
Failed to connect to your instance after deploying mern app on aws ec2 instance when i try to access frontend
|amazon-web-services|docker|amazon-ec2|docker-compose|
As of Angular 15, [tick](https://angular.io/api/core/testing/tick) and [flush](https://angular.io/api/core/testing/flush) call Zone.js's [FakeAsyncTestZoneSpec](https://github.com/angular/angular/blob/67f0cf5fc8a2be4a48c6cd15db53ce9c9c4cd014/packages/core/testing/src/fake_async.ts#L127). - `tick` and `flush` [flush all microtasks first](https://github.com/angular/zone.js/blob/b11bd466c20dc338b6d4d5bc3e59868ff263778d/lib/zone-spec/fake-async-test.ts#L400), e.g. `Promise.then` and `queueMicrotask`. - `tick` has a [default tick count of 0](https://github.com/angular/angular/blob/67f0cf5fc8a2be4a48c6cd15db53ce9c9c4cd014/packages/core/testing/src/fake_async.ts#L122), defined by Angular in milliseconds. It executes macrotasks, including periodic tasks like `setInterval`, [scheduled up to the current time plus the tick count](https://github.com/angular/zone.js/blob/b11bd466c20dc338b6d4d5bc3e59868ff263778d/lib/zone-spec/fake-async-test.ts#L135). - Therefore, by default `tick` only executes the tasks scheduled up to but not at the current time. - `flush` has a [default turn count of 20](https://github.com/angular/angular/blob/67f0cf5fc8a2be4a48c6cd15db53ce9c9c4cd014/packages/core/testing/src/fake_async.ts#L143), defined by the Zone.js fake async test scheduler. It executes macrotasks, but not periodic tasks, [up to the turn count number of tasks (which is treated as the limit) or the first periodic task](https://github.com/angular/zone.js/blob/b11bd466c20dc338b6d4d5bc3e59868ff263778d/lib/zone-spec/fake-async-test.ts#L187). - Therefore, by default `flush` executes macrotasks up until the first periodic task or a maximum of 20. - If there are more than the limit number of tasks, `flush` throws an error. See [async.spec.ts](https://github.com/TrevorKarjanis/angular-async-test-specs?tab=readme-ov-file) for a complete set of example tests. ```typescript it('tick executes all microtasks and macrotasks', fakeAsync(() => { const spy = jasmine.createSpy('interval'); zone.runTask(() => queueMicrotask(() => { })); zone.runTask(() => setInterval(spy, 1)); zone.runTask(() => queueMicrotask(() => { })); expect(zone.hasPendingMicrotasks).toBeTrue(); expect(zone.hasPendingMacrotasks).toBeTrue(); tick(1); expect(zone.hasPendingMicrotasks).toBeFalse(); expect(zone.hasPendingMacrotasks).toBeTrue(); expect(spy).toHaveBeenCalledOnceWith(); discardPeriodicTasks(); })); it('flush executes all microtasks and non-periodic macrotasks', fakeAsync(() => { const spy = jasmine.createSpy('interval'); zone.runTask(() => queueMicrotask(() => { })); zone.runTask(() => setTimeout(spy)); zone.runTask(() => queueMicrotask(() => { })); expect(zone.hasPendingMicrotasks).toBeTrue(); expect(zone.hasPendingMacrotasks).toBeTrue(); flush(); expect(zone.hasPendingMicrotasks).toBeFalse(); expect(spy).toHaveBeenCalledOnceWith(); })); ```
I encountered a error ``` PS C:\\Users\\91789\\Desktop\\Underwater-Image-Enhancement\\WPFNet\> python Underwater_test.py C:\\Users\\91789\\Desktop\\input C:\\Users\\91789\\Desktop\\New folder ./checkpoint/generator_600.pth C:\\Users\\91789\\AppData\\Local\\Programs\\Python\\Python312\\python.exe: can't open file 'C:\\\\Users\\\\91789\\\\Desktop\\\\Underwater-Image-Enhancement\\\\WPFNet\\\\Underwater_test.py': \[Errno 2\] No such file or directory ``` How can i solve it and run it and [this][1] is the github link. [1]: https://github.com/LiuShiBen/WPFNet.git
{"OriginalQuestionIds":[59762996],"Voters":[{"Id":7329832,"DisplayName":"jps"},{"Id":874188,"DisplayName":"tripleee","BindingReason":{"GoldTagBadge":"python"}}]}
A quick and easy way to do that is to overwrite the current contents with an empty string from a Bash console. Let's say that the log you want to clear is `/var/log/someusername.pythonanywhere.com.error.log` -- with that you would run this command: echo > /var/log/someusername.pythonanywhere.com.error.log
Figured it out, though I've no idea why this is what it takes to make it work (if anyone could explain I'd really appreciate it!): First, adding `DT::datatable(matrix())` before reading in the data - without doing this, or adding it somewhere after reading in the data, doesn't seem to help at all. Then when it comes to the actual loop: ``` for (i in 1:length(test_list)){ cat(sprintf("\n#### %s\n", attributes(test_data[[names(test_list[[i]])[1]]])$label)) print(htmltools::tagList(DT::datatable(test_list[[i]], rownames = F, escape = F))) } ```
I have an Admin area in my asp.net core MVC app and when I try to reach to /Admin/Category/Add it says No webpage was found for the web address: https://localhost:7002/Category/Add?area=Admin. My routing in program.cs: ``` app.MapDefaultControllerRoute(); app.MapAreaControllerRoute( name: "Admin", areaName: "Admin", pattern: "Admin/{controller=Home}/{action=Index}/{id?}" ); ``` My view: ``` @model List<Category> @{ ViewData["Title"] = "Index"; Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml"; } <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-body"> <a asp-area="Admin" asp-controller="Category" asp-action="Update" class="btn mb-1 btn-primary">Add Category</a> <div class="card-title"> <h4>Table Basic</h4> </div> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Name</th> <th>Created By</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@item.Name</td> <td>@item.CreatedBy</td> <td>@item.IsDeleted</td> <td> <a asp-area="Admin" asp-controller="Category" asp-action="Update" asp-route-id="@item.Id"> <button type="button" class="btn mb-1 btn-warning">Update</button> </a> <a asp-area="Admin" asp-controller="Category" asp-action="Delete" asp-route-id="@item.Id"> <button type="button" class="btn mb-1 btn-danger">Delete</button> </a> </td> </tr> } </tbody> </table> </div> </div> </div> </div> </div> ``` My controller: ``` namespace AnimeUI.Areas.Admin.Controllers { [Area("Admin")] public class CategoryController : Controller { private readonly ICategoryService categoryService; private readonly IValidator<Category> validator; private readonly IMapper mapper; public CategoryController(ICategoryService categoryService, IValidator<Category> validator, IMapper mapper) { this.categoryService = categoryService; this.validator = validator; this.mapper = mapper; } public async Task<IActionResult> Index() { var categories = await categoryService.GetAllCategoriesNonDeletedAsync(); return View(categories); } [HttpGet] public IActionResult Add() { return View(); } [HttpPost] public async Task<IActionResult> Add(AddCategoryDto addCategoryDto) { var category = mapper.Map<Category>(addCategoryDto); var result = validator.Validate(category); var exists = await categoryService.Exists(category); if (exists) result.Errors.Add(new ValidationFailure("Name", "This category name already exists")); if (result.IsValid) { await categoryService.CreateCategoryAsync(addCategoryDto); return RedirectToAction("Index", "Category", new { Area = "Admin" }); } result.AddToModelState(this.ModelState); return View(addCategoryDto); } } } ``` I have been searching for whole day, yet couldn't find a valid solve to this annoying problem. For some reason my url is being generated like this: https://localhost:7002/Category/Add?area=Admin instead of https://localhost:7002/Admin/Category/Add. I tried to change my port, add different routing syntax. I am currently using visual studio 2022 and my project is .NET 8.0 PS: My problem only occurs when I need to use go to the pages of Admin.
No webpage was found for the web address: https://localhost:7002/Category/Add?area=Admin. Why is my URL generated like ?area=Admin instead of /Admin/
|c#|asp.net-mvc|asp.net-core|model-view-controller|
null
|javascript|reactjs|
I have developed an Android application that includes a background service (MainService) designed to run automatically after the device restarts. To achieve this functionality, I have implemented a BootReceiver class and added it to the AndroidManifest.xml file to handle the ACTION_BOOT_COMPLETED intent. However, despite these efforts, the MainService is not starting automatically after the device restarts. I have created a BroadcastReceiver class named BootReceiver and added it to my AndroidManifest.xml file to start a background service (MainService) after the device restarts. However, the service is not starting automatically after the device restarts. Below are the relevant parts of my code: BootReceiver.java: ``` package com.sithum.mediatracker; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { // Start your service here Intent serviceIntent = new Intent(context, MainService.class); context.startService(serviceIntent); } } } ``` AndroidManifest.xml: ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <!-- Permissions and other declarations --> <receiver android:name=".BootReceiver" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.QUICKBOOT_POWERON" /> </intent-filter> </receiver> <service android:name=".MainService" android:enabled="true" android:exported="false" android:foregroundServiceType="dataSync|location|mediaPlayback" android:permission="android.permission.BIND_JOB_SERVICE"> <!-- Intent filter if needed --> <intent-filter> <action android:name="com.sithum.mediatracker.ACTION_START_SERVICE" /> </intent-filter> </service> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </manifest> ``` I have also declared the necessary permissions in the manifest file. And I tested this in android 9 and 11. What could be causing the background service not to start automatically after device restart, and how can I resolve this issue?
When knitting the below `Rmd` **with a landscape page** and viewing the word output produced by it, it becomes apparent that **page two seems to be missing**. Also, page numbering in the footer of the page only starts after the landscape page has been included. Conversely, when knitting the below `Rmd` **without a landscape page** there are **no such issues**. Why is that and how can I make the document with landscape pages behave like the one without? ***With landscape page:*** ````yaml --- output: officedown::rdocx_document --- ```{r setup, include=FALSE} library(officedown) # 0.3.0 ``` <!---BLOCK_TOC---> # Chapter 1 # Chapter 2 <!---BLOCK_LANDSCAPE_START---> # Chapter 3 <!---BLOCK_LANDSCAPE_STOP---> # Chapter 4 \newpage # Chapter 5 \newpage # Chapter 6 ```` ***Without landscape page:*** ````yaml --- output: officedown::rdocx_document --- ```{r setup, include=FALSE} library(officedown) # 0.3.0 ``` <!---BLOCK_TOC---> # Chapter 1 # Chapter 2 # Chapter 3 # Chapter 4 \newpage # Chapter 5 \newpage # Chapter 6 ````
Why are landscape pages causing issues with page numbers/section headers in officeverse?
|r|r-markdown|officer|officedown|
The `location` object is available only in the browser's environment. If your code relies on `location` for server-side rendering in Next.js, you'll encounter errors during the build or prerendering phases because `location` is undefined in Node.js. Wrap any code using `location` in a condition that checks if `window` or `location` is defined. This prevents the server from executing code that relies on these objects. ```js if (typeof window !== "undefined") { // Safe to use window or location here } ``` The `Element` object is part of the Web APIs provided by browsers and is not available in Node.js. This error usually occurs when your code or a library you use tries to access DOM elements during SSR. For components or libraries using `Element` or other browser-specific APIs, consider importing them dynamically with `{ ssr: false }` to ensure they are only loaded client-side. ```js import dynamic from 'next/dynamic'; const MyComponent = dynamic( () => import('../components/MyComponent'), { ssr: false } ); ```
{"OriginalQuestionIds":[902408],"Voters":[{"Id":5320906,"DisplayName":"snakecharmerb","BindingReason":{"GoldTagBadge":"python"}}]}
|ITEM | OPEN BAL | IN | OUT | CLOS BAL | |---- | -------- | --- | --- | -------- | |A | 10 | 10 | 0 | 20 | |B |200 | 200|300 |100 | |C |50 |100 |100 |50 | |D |20 |20 |40 |0 | |E |100 |0 |50 |50 | |B | | | | | |D | | | | | |E | | | | | |A | | | | | |C | | | | | In the above Table CLOS BAL is = (OPEN BAL + IN - OUT) for each item. But when the Item appears again below then the OPEN BAL should be the CLOS BAL for that Item. How can I insert the same. I did the counting about the number of times each item appears and put an Array to identify the item to the corresponding closing balance but could not include the same in the opening balance column.
I have a website created with ReactJS and React Router Dom. I use `createBrowserRouter` for routing pages. However, when I refresh any page, I encounter a 404 error ("page not found"). This issue arises when I deploy the project on server platforms like Domain.com. Does anyone have a solution? I've tried using `createHashRouter`, but I dislike the "#" in the URL.
null
I encountered a error ``` PS C:\\Users\\91789\\Desktop\\Underwater-Image-Enhancement\\WPFNet\> python Underwater_test.py C:\\Users\\91789\\Desktop\\input C:\\Users\\91789\\Desktop\\New folder ./checkpoint/generator_600.pth C:\\Users\\91789\\AppData\\Local\\Programs\\Python\\Python312\\python.exe: can't open file 'C:\\\\Users\\\\91789\\\\Desktop\\\\Underwater-Image-Enhancement\\\\WPFNet\\\\Underwater_test.py': \[Errno 2\] No such file or directory ``` How can I solve it and run it. [LiuShiBen/WPFNet.git][1] is the GitHub repo. [1]: https://github.com/LiuShiBen/WPFNet.git
I created an .env.development file in order to store my api key and other environment variables. I got an issue that when i use my api key defined in .env.development file and retrieved with the help of dotenvx dependencies, the website failed to load resources with a status of 401. However, if i used my api key directly without the need of retrieving from the .env.development file, the website fetched normally without any trouble. My api key works fine so dont need to worry about that. > **Note**: I also want to mention that the API key I obtained is from TMDB, an external API. Other environment variables that i defined are working fine in the backend with dotenvx package. .env.development: ``` API_KEY="my_api_key" ``` api-config.js: ```javascript const apiKey = process.env.API_KEY; const apiUrl = "my_api_url"; const apiKeyParams = `my_api_params`; ``` error: [![Error from fetching with the external api key](https://i.stack.imgur.com/KWVol.png)](https://i.stack.imgur.com/KWVol.png) I have tried manually with cli bash: ``` $ dotenvx run -- npm run start ``` and i have tried preload with npx: ``` "scripts": { "start": "npx dotenvx run --env-file=.env.development -- react-scripts start" } ``` it all injected environment variables successfully but it still doesnt work.