Sql query to determine income statement Posted: 24 Nov 2021 11:28 AM PST I wrote a Python script to insert data from a Excel file to a MySQL database. I am looking for a query to measure each branch and division its profitability. I have e.g. the following data: Ledger account Name Debit Credit Branch Division 610020 Rent building 150 BXL WPL 615200 Telephone 250 BXL WPL 700100 Turnover parts 1050 BXL WPL 700100 Turnover parts 50 BXL WPL 700110 Work hours 500 BXL WPL 700110 Work hours 300 BXL WPL I would like to get an income statement for the branch and division involved. For each ledger account I would like to know its total debit or credit amount. This I what I would like to see for branch 'BXL' and division 'WPL' by using SQL: Debit Credit 610020 Rent building 150,00 615200 Telephone 250,00 700100 Turnover parts 1.000,00 700110 Work hours 800,00 Any help would be appreciated. |
Coloring Row in QTableView instead of Cell Posted: 24 Nov 2021 11:27 AM PST Backstory: Using an imported UI, I place my table onto a QTableView. I also make use of alternating row colors to better differentiate rows. Problem: I'm looking to color the row of a table that contains a True value in one of the columns. I am able to color the cell, but have not found a way to color the entire row. I use a PandasModel class to format the tables: class PandasModel(QtCore.QAbstractTableModel): def __init__(self, data, parent=None): QtCore.QAbstractTableModel.__init__(self, parent) self._data = data def rowCount(self, parent=None): return len(self._data.values) def columnCount(self, parent=None): return self._data.columns.size def data(self, index, role=QtCore.Qt.DisplayRole): if index.isValid(): if role == QtCore.Qt.DisplayRole: return str(self._data.values[index.row()][index.column()]) if role == QtCore.Qt.BackgroundRole: row = index.row() col = index.column() if self._data.iloc[row,col] == True: return QtGui.QColor('yellow') if self._data.iloc[row,col] == False: pass return None def headerData(self, col, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return self._data.columns[col] return None I've look through numerous examples, and I am aware there may be multiple ways to color a table using QBrush or QColor, but so far the best I am able to do is simply color the cell that contains the True value. Splicing in code from other examples, I thought it was possible that the col = index.column() was getting in the way, as maybe it was limiting it to the cell, however, when I remove this it becomes ambiguous. Important: I am wanting to keep the alternating row colors that I set elsewhere in the script, so please keep that in mind! I am only looking to color the specifics rows that contain any True value (note the if "" == false: Pass ). |
correct using get_or_create? Posted: 24 Nov 2021 11:27 AM PST To my code, which records a contact from the form and adds it to the db, need to add get_or_create, or write another condition (if there is a contact with such a phone — update, no - add), but i'm do it for the first time, please, I'll be glad to read solution to my problem and a brief explanation ♡ views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib import messages from .forms import Forms def main(request): form = Forms if request.method == "POST": form = Forms(request.POST) if form.is_valid(): form.save() messages.success(request, 'Form has been submitted') return redirect('/') return render(request, 'app/main.html', { 'form':form } ) forms.py from django.forms import ModelForm from .models import Form class Forms(ModelForm): class Meta: model = Form fields = '__all__' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) models.py from django.db import models class Form(models.Model): name = models.CharField(max_length=30) phone = models.CharField(max_length=30) admin.py from django.contrib import admin from .models import Form '''from django.contrib.admin.models import LogEntry LogEntry.objects.all().delete()''' '''for delete actions in admin_panel''' admin.site.register(Form) apps.py from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTE-8"> <meta name="viewport" content="width, initial-scale=1.0"> <title>CHECK DATA</title> </head> <body> {% for message in messages %} <p>{{message}}</p> {% endfor %} <form action="" method="post"> {% csrf_token %} <table> {{form.as_table}} <tr> <td colspan="2"> <input type="submit"/> </td> </tr> </table> </form> </body> </html> |
Getting "TypeError: Cannot read properties of undefined" when trying to access properties of an object Posted: 24 Nov 2021 11:27 AM PST I have a function that grabs data from a local JSON file and renders it. Simple stuff. I do the fetch request within the useEffect hook to fire it only on the first render. Once the data is fetched, it sets it in employees . Once in employees , I use another useEffect to set some other states with data from employees . const [employees, setEmployees] = useState<any>([]); useEffect(() => { fetch("data.json", { headers: { "Content-Type": "application/json", Accept: "application/json", }, }) .then(function (response) { return response.json(); }) .then(function (data) { setEmployees(data["employees"]); }); }, []); useEffect(() => { console.log(employees) /* set some other state */ }, [employees]); /*render list of employees*/ My problem is, I can't actually access the properties within employees . When I console.log the contents of employees , this is what I see, an array of objects [ { "first_name": "John", "last_name": "Doe", }, { "first_name": "Jane", "last_name": "Doe", }] So to access the properties of the object, i've tried this employees[0]["first_name"] employees[0]."first_name" employees[0][first_name] employees[0].first_name In the first two, I get this error TypeError: Cannot read properties of undefined (reading 'first_name') While in the last 2 I get this error Cannot find name 'first_name' If someone could tell me how to properly access my data it would be much appreciated! |
WebRTC with android WebView GRALLOC error Posted: 24 Nov 2021 11:27 AM PST I am trying to implement WebRTC in android WebView and it works fine but on some devices, I keep receiving this error: I/GRALLOC: LockFlexLayout: baseFormat: 11, uOffset: 307200, vOffset: 307200,uStride: 640 In devices that receive this error (Huawei), the camera won't be available in other activities even after closing WebView and the error keeps showing endlessly. Manifest file <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.CAPTURE_SECURE_VIDEO_OUTPUT" tools:ignore="ProtectedPermissions" /> <uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" tools:ignore="ProtectedPermissions" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" tools:ignore="ProtectedPermissions" /> <uses-feature android:name="android.hardware.camera.autofocus" android:required="true" /> <uses-feature android:name="android.hardware.camera.front" android:required="true" /> <uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-feature android:name="android.hardware.camera.level.full" android:required="true" /> <uses-feature android:name="android.hardware.camera.capability.raw" android:required="true" /> <uses-feature android:name="android.hardware.camera.any" android:required="true" /> <uses-feature android:name="android.hardware.microphone" android:required="true" /> <uses-feature android:name="android.hardware.camera2" android:required="true" /> <uses-feature android:name="android.hardware.camera" android:required="true" /> MainActivity.java public class MainActivity extends AppCompatActivity { WebView webView; @SuppressLint("SetJavaScriptEnabled") @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = new WebView(this); setContentView(webView); // webView = findViewById(R.id.webView); WebSettings MyWebviewSettings = webView.getSettings(); MyWebviewSettings.setAllowFileAccessFromFileURLs(true); MyWebviewSettings.setAllowUniversalAccessFromFileURLs(true); MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true); MyWebviewSettings.setJavaScriptEnabled(true); MyWebviewSettings.setDomStorageEnabled(true); MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true); MyWebviewSettings.setBuiltInZoomControls(true); MyWebviewSettings.setAllowFileAccess(true); MyWebviewSettings.setMediaPlaybackRequiresUserGesture(false); MyWebviewSettings.setSupportZoom(true); webView.setWebChromeClient(new WebChromeClient(){ @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onPermissionRequest(PermissionRequest request) { request.grant(request.getResources()); } }); webView.loadUrl("file:///android_asset/test.html"); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, 1); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Granted", Toast.LENGTH_SHORT).show(); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show(); } return; } // other 'case' lines to check for other // permissions this app might request } } } |
Merging Python Plots From many CITIfile's Posted: 24 Nov 2021 11:27 AM PST The following code creates 20 plots with a specific title. I would like to find a way to merge plots that contain the same title. For example when I run this code, I will obtain a sequence of graphs that are titled S11 Log Magnitude, S21 Log Magnitude, S12 Log magnitude, S22 Log magnitude. Then, it will move on to the next CITI file and produce separate plots following the same sequence. How can I edit this code so that I can merge all the plots with the title S11 Log Magnitude into one plot? And do the same with the other plots. At the end, my goal is to produce only 4 plots that contain similar data instead of 20 separate plots. # modified based on https://github.com/feph/citidata # datalist contains all data np arrays import citidata import glob import numpy as np from numpy import * import matplotlib.pyplot as plt keyslist = [] # data name datalist = [] # data arrays M = N = 0 all_my_files = glob.glob("*.citi") for filename in all_my_files: M += 1 print("=== %s ===" % filename) citi_file = citidata.genfromfile(filename) for package in citi_file.packages: print(package) print(package.indep) #print(package.deps) # suppress screen output for key in package.deps: N += 1 value = package.deps[key] # get data print(value) keyslist.append(key) # append key datalist.append(value['data']) # append np array data #(datalist) name_dict = { 0: "S11 Log Magnitude", 1: "S21 Log Magntitude", 2: "S12 Log Magnitude", 3: "S22 Log magnitude", 4: "S11 Log Magnitude", 5: "S21 Log Magntitude", 6: "S12 Log Magnitude", 7: "S22 Log magnitude", 8: "S11 Log Magnitude", 9: "S21 Log Magntitude", 10: "S12 Log Magnitude", 11: "S22 Log magnitude", 12: "S11 Log Magnitude", 13: "S21 Log Magntitude", 14: "S12 Log Magnitude", 15: "S22 Log magnitude", 16: "S11 Log Magnitude", 17: "S21 Log Magntitude", 18: "S12 Log Magnitude", 19: "S22 Log magnitude" } #print('\n ', M, 'files read;', N, 'datasets recorded.') #print('dataset : name') #plt.figure(0) w = [] x = np.linspace(8, 12, 201) for i in range(N): fig = plt.figure(i) # print(i, ':', keyslist[i]) y = datalist[i] # data # print(y) test = np.abs(y) f = sqrt(test) mag = 20*log10(f) # print(mag) # [S11, S21, S12,S22] # y = np.append(mag) plt.xlabel('Frequancy (Hz') plt.ylabel('Log Magnitude (dB') plt.plot(x, mag) plt.title(name_dict[i]) |
Select a single element from a complex ID Posted: 24 Nov 2021 11:26 AM PST I have IDs such as "3_K97_T12_High_2_Apples". I want to select just "T12" and store it in a character vector (Tiles) so I can call it in text() when I label my points in the plot() with label = Tiles. I want to label each point with just the 3rd element of the ID (i.e T12). How can I do this? Thank you in advance! |
how can i rewrite this into a single query - sql optimization Posted: 24 Nov 2021 11:26 AM PST how can i optimize the following query? I'm not sure how to rewrite them into a single query, combine all the joins. other_publisher_views AS ( SELECT clv.date, clv.streeteasy_page_views, clv.trulia_page_views, clv.zillow_page_views, clv.realtor_page_views FROM agent_insights_lt.agent_insights__combined_listing_views AS clv JOIN listing_info_raw ON clv.property_id_sha = listing_info_raw.property_id_sha ), other_publisher_views_by_period AS ( SELECT is_current_period, start_date, end_date, coalesce(sum(streeteasy_page_views), 0) AS streeteasy_page_views, coalesce(sum(trulia_page_views), 0) AS trulia_page_views, coalesce(sum(zillow_page_views), 0) AS zillow_page_views, coalesce(sum(realtor_page_views), 0) AS realtor_page_views FROM periods LEFT JOIN other_publisher_views ON other_publisher_views.date BETWEEN periods.start_date AND periods.end_date |
How to access the final parent StatefulWidget class variables from its extended class? Posted: 24 Nov 2021 11:26 AM PST I've ExperienceCardFront a StatefulWidget class which extends _ExperienceCardFrontState . I'm trying to access the variables (marked as final and required) in ExperienceCardFront from its state, _ExperienceCardFrontState . This is my ExperienceCardFront : class ExperienceCardFront extends StatefulWidget { const ExperienceCardFront( {Key? key, required this.title, required this.image}) : super(key: key); //the 2 variables I want to get access to from the extended class final String title; final String image; @override _ExperienceCardFrontState createState() => _ExperienceCardFrontState(); } And this is my _ExperienceCardFrontState : class _ExperienceCardFrontState extends State<ExperienceCardFront> { @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Container( //here I want to get access to the title (or image) variable from ExperienceCardFront child: Text(title), ); } } The following error is thrown: Undefined name 'title' , when I try to run this code. |
Java: can not assign the same variable to different objects Posted: 24 Nov 2021 11:26 AM PST I was trying to practise inheritence on Java by writing a code that consist of Parent class that is called Person that has two child classes of SuperPerson and Civil, and the SuperPerson class which is a child class of Person class has two classes called Hero and Villian. I was trying to implement a method called Protect which is used only by the Hero class that can only works on the Civil class as a target. So, the main issue here when i run the code, it doesn's show the protector name in the case of a different hero trying to protect a civil who's already under another hero's protection and in the case of a villian trying to attack a civil who's under hero's protection The parent class: public class SuperPerson extends Person { String protector;} The first child (Hero) class that has the protect method: void protect(Person target) { if(target.type == "Super Villian") { System.out.println("You can not protect a villian!"); } else { if(target.health != 0) { if(target.protection == false) {//to protect target.protection = true; this.protector = this.name; System.out.println(target.name + " is under " + this.protector + "'s proction."); } else { if(this.protector != this.name) {//under someone else protection so can not unprotect System.out.println(target.name + " is already under " + protector + "'s protection"); } else {//to unprotect target.protection = false; System.out.println(target.name + " is no longer under " + this.name + "'s protection"); } } } else { System.out.println("Target is already dead."); } } } the other child (Villian) class: int attack(Person target) { if(target.type == this.type) { System.out.println("Invalid target!"); return 0 ; } else { if(target.protection == true) { System.out.println("The target is under " + protector + "'s protection"); return 0; } else { return super.attack(target); } } } The main method: Hero h1 = new Hero("Spiderman", 25,"Male", "Web"); Hero h2 = new Hero("Batman", 35, "Male","Wealth"); SuperPerson v1 = new Villian("Goblin", 47,"Male", "Goblin Power"); Person c3 = new Civil("Mary", 24,"Female"); h1.protect(c3); h2.protect(c3); v1.attack(c3); The outcome: Mary is under Spiderman's proction. Mary is already under null's protection //Bug here The target is under null's protection //Bug here |
Is there a way to constantly update a graph figure while a switch is on in Dash Plotly Python? Posted: 24 Nov 2021 11:26 AM PST I have a function that updates the figure of a graph using an algorithm, and a callback function to return the graph's figure (among many other things). This is the basic idea: for i in range(0,5): time.sleep(0.1) randomfunction(i) return plot How can I update the graph without breaking the loop? I've tried using yield instead of return to no avail as the callback does not expect a generator class to be output. |
Use Brew Gcc and Python Compilers on Mac | Usr/local/bin appearing as a file Posted: 24 Nov 2021 11:26 AM PST I have installed Gcc compiler and python, using Homebrew on my Mac (Monterey, version 12.0.1). However, the default compilers used are still the inbuilt ones (clang and python 2.8). I wanted to change this. Solutions on the web require me to move some file to the 'folder' usr/local/bin. However, in my laptop, usr/local/bin is actually a file. How should I proceed? Thanks ! |
How to input shortcode in query_filter using Wordpress Posted: 24 Nov 2021 11:25 AM PST I'm using Domain Mapping and created a short code as per (URL: https://wordpress.org/support/topic/create-shortcode-based-on-multiple-domain-settings/). I'm trying to only display posts where the value of the shortcode, [multiple_domain_email] matches the 'author_email' meta key, built with Advanced Custom Fields. To do this, I'm trying to create a query_filter (as below), but can't seem to get it to work. function my_super_filter_function($query_args){ $query_args['meta_key'] = 'author_email'; $query_args['meta_value'] = [multiple_domain_email]; return $query_args; } add_filter('my_super_filter', 'my_super_filter_function'); |
JSON Serializing Scala Case Class to only strings and ints Posted: 24 Nov 2021 11:25 AM PST I have a need to serialize a handful of case classes to only strings and ints. Meaning, if there's a nested type, it gets serialized as the stringified version of a JSON object, not a JSON object. Example: case class Deepest(someNum: Int) case class Inner(superDeep: Deepest) case class Outer(aValue: Int, aNestedValue: Inner) Serializing an instance of Outer Would result in (or something similar) { "Outer": { "aValue": 5, "aNestedValue": "{ \"superDeep\": .... }" } } Is this possible? |
How many ICE candidates to exchange for video call? Posted: 24 Nov 2021 11:26 AM PST Suppose there are 2 users user 1: 10 Ice candidates generated user 2: 5 Ice candidates generated And I know only 1 candidate is required to establish a connection. So any of the above user sends candidates to other user and the connection gets established. My question is they should exchange all candidates, In order to agree on best connection route ? If they exchange all candidates , all I have to do is feed all Ice candidates to my peerConnection as shown in dart code below, Am I right ? RTCPeerConnection _peerConnection; await _peerConnection.addCandidate(candidate); |
How to assert that the request happened when mocking an API concurrently? Posted: 24 Nov 2021 11:28 AM PST Followup question to: How do I guarantee that the request happened correctly when mocking an API? main.go package main import ( "fmt" "net/http" ) func SomeFeature(host, a string) error { if a == "foo" { resp, err := http.Get(fmt.Sprintf("%v/foo", host)) if resp.StatusCode != http.StatusOK { return fmt.Errorf("SomeFeature: error status %q", resp.StatusCode) } if err != nil { return fmt.Errorf("SomeFeature: %w", err) } } if a == "bar" { resp, err := http.Get(fmt.Sprintf("%v/baz", host)) if resp.StatusCode != http.StatusOK { return fmt.Errorf("SomeFeature: error status %q", resp.StatusCode) } if err != nil { return fmt.Errorf("SomeFeature: %w", err) } } // baz is missing, the test should error! return nil } main_test.go package main import ( "net/http" "net/http/httptest" "testing" ) func TestSomeFeature(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })) testCases := []struct { name string variable string }{ { name: "test 1", variable: "foo", }, { name: "test 2", variable: "bar", }, { name: "test 3", variable: "baz", }, } for _, tc := range testCases { tc := tc t.Run(tc.name, func(t *testing.T) { t.Parallel() err := SomeFeature(server.URL, tc.variable) if err != nil { t.Error("SomeFeature should not error") } }) } } - GO Playground: https://go.dev/play/p/EFanSSzgnbk
- How to do I assert that each test case send a request to the mocked server?
- How can I assert that a request wasn't sent?
- "test 3" should fail since it didn't trigger a http call.
- "test 2" should fail because it didn't call the right URL.
All while keeping the tests parallel/concurrent? |
Python program - returning every response from a loop instead of just the desired one Posted: 24 Nov 2021 11:28 AM PST I have the following Python program and want the program to simply return the price of the corresponding item in the list 'items'. Instead, as you can see, it doesn't work correctly and either breaks or returns "There is no such item" and then the number. I have tried various things and can't get the sequence of output right. https://trinket.io/python/77909a6574 Desired output: User enters: Chicken Wings Output: 5 User enters: Jollof Rice Output: 7 and so on. Can anyone suggest a fix as well as best practice for using an if statement inside a for loop and breaking out at the right time. def salestracker(): print("---Sales Tracker---") print("---MENU---") print(""" 1. Find the price of an item 2. Enter sales of an item 3. Find total of the day """) items=["Chicken Wings","Jollof Rice", "Thai fried rice", "Dumplings"] price=[5,7,8,5] findprice(items,price) def findprice(items,price): print("---Find Price---") item=input("Enter Item:") for i in range(len(items)): if item==items[i]: print(price[i]) break else: break print("There is no such item") salestracker() |
[: too many arguments (Linux script) Posted: 24 Nov 2021 11:26 AM PST I'm fairly new to Linux and I'm working my way though a course of learning. I've been working on a script to create a new group, which checks for duplicates and then also does the same for a new user and configures some parameters for the user. I've gotten so far, but I suspect, I'm either over-complicating it, or just too much of a noob. Here's my script: #!/bin/bash # Challenge Lab B: Bash Scripting # Script settings in OS: # 1. set user owner to root # 2. set group owner to root # 3. set permission to include setuid (4755) # 4. run script with sudo echo -n 'Enter new group: ' read group_name echo 'checking for duplicates...' while [ grep -q "$group_name" /etc/group == 0 ] do echo 'group already exists; try another.' if [ grep -q "$group_name" /etc/group == 1 ]; then break fi done echo 'group does not exist.'; echo 'creating group.'; groupadd $group_name; echo "$group_name group created"; echo -n 'Enter new user: ' read user_name while [ grep -q "$user_name" /etc/passwd == 0 ] do echo 'user already exists; try another.' if [ grep -q "$user_name" /etc/passwd == 1 ]; then break fi done echo 'user does not exist.'; echo 'creating user directory.'; mkdir /$user_name; echo 'creating user.'; useradd -s /bin/bash -g $group_name $user_name; echo "changing home directory user and group ownership to $user_name"; chown $user_name:$group_name /$user_name; echo 'changing user and group mode to RWX and setting sticky bit'; chmod 1770 /$user_name echo "Process complete" And here's the result: Enter new group: test1 checking for duplicates... ./test_sc: line 25: [: too many arguments group does not exist. creating group. test1 group created Enter new user: user1 ./test_sc: line 57: [: too many arguments user does not exist. creating user directory. creating user. changing home directory user and group ownership to user1 changing user and group mode to RWX and setting sticky bit Process complete Clearly, it kind of works, but I'm sure the low-level handling of the duplicate isn't working based upon the result. I'm sure many will look upon my work as terrible, but this is my first one, so please bear that in mind. Cheers, S |
Memory effective way to monitor change of Kubernetes objects in a namespace Posted: 24 Nov 2021 11:26 AM PST I am working with kubernetes and kubectl commands, and am able to get a list of namespaces, and then can get the resources inside those namespaces. Question is, is there an effective way to monitor all resources (CRDs especially) in a certain namespace for changes? I know I could do this: kubectl get myobjecttype -n <user-account-1> and then check timestamps with a separate command, but that seems resource-taxing. |
Where can i find these symbols? Posted: 24 Nov 2021 11:27 AM PST Can someone help me? Where can i find these symbols? Symbols |
Why does task manager say my GPU usage is low, while "CUDA" is nearly maxed out in task manager? Posted: 24 Nov 2021 11:27 AM PST I'm a novice to deep learning, working on a project for school, and have not yet been able to find an answer for this question. My GPU usage, as shown in the picture attached, barely increases (from 0% to ~5%) when training my neural network. However, when I open a display of the "CUDA" usage, it shows that I am nearly maxing out whatever this is measuring, as well as the dedicated GPU memory. A couple of questions Here is a screenshot of my task manager that shows what I'm talking about Before I was having an issue getting my GPU to be loaded at all, since I had a very small network. This leads me to a couple of questions: - Why is it that a larger width network results in my GPU working harder? Is this because the operations on each neuron can be performed by individual GPU cores?
- Why is task manager showing that my GPU utilization is about 5% while CUDA is showing ~90%? Are these fundamentally different metrics?
- Is there any more performance I can squeeze out of my graphics card or am I right at the limit here? Generally, what can I look at to improve training time?
Thank you! |
Duplicating values from matrix next to the original value in R Posted: 24 Nov 2021 11:27 AM PST I have a matrix including simulated data. The data concern a repeated measurements situation, and for one variable I would like to duplicate the simulated values. The current matrix looks like this: [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1.647 1.125 0.559 1.614 1.578 0.377 [2,] 0.555 0.395 1.090 0.896 2.135 1.184 [3,] 0.269 2.022 -0.184 0.614 1.128 1.036 The columns represent the repeated measurements, the rows indicate the individual. It is important that the duplicate value is next to the original value, so that it looks like this (for the first line): [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,] 1.647 1.647 1.125 1.125 0.559 0.559 1.614 1.614 1.578 1.578 0.377 0.377 I tried some ways, but that resulted in getting the sequence of duplicates starting from column 7. Is there any way to (easily) obtain this result? Thanks in advance. |
how to write pytest for pymssql? Posted: 24 Nov 2021 11:27 AM PST I am trying to write pytest to test the following method by mocking the database. How to mock the database connection without actually connecting to the real database server.I tried with sample test case. I am not sure if that is right way to do it. Please correct me if I am wrong. //fetch.py import pymssql def cur_fetch(query): with pymssql.connect('host', 'username', 'password') as conn: with conn.cursor(as_dict=True) as cursor: cursor.execute(query) response = cursor.fetchall() return response //test_fetch.py import mock from unittest.mock import MagicMock, patch from .fetch import cur_fetch def test_cur_fetch(): with patch('fetch.pymssql', autospec=True) as mock_pymssql: mock_cursor = mock.MagicMock() test_data = [{'password': 'secret', 'id': 1}] mock_cursor.fetchall.return_value = MagicMock(return_value=test_data) mock_pymssql.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor x = cur_fetch({}) assert x == None The result is: AssertionError: assert <MagicMock name='pymssql.connect().__enter__().cursor().__enter__().fetchall()' id='2250972950288'> == None Please help. |
How to getObject from S3 protocol url using AWS SDK JS v3? Posted: 24 Nov 2021 11:25 AM PST I have a URL that looks like: s3://mybucket/data.txt . I'm trying to retrieve that item using the AWS SDK JS v3 library (@aws-sdk/client-s3 ). When using the getObject command, it requires a Bucket and Key. How can I pass in the S3 protocol URL into the S3 client to get the object based on that URL? |
regex to match a specific pattern Posted: 24 Nov 2021 11:26 AM PST I have some data like below (abc 12;efg 34; hij 22) (abc 34; efg 22) (abc 22) I need to extract first word before each semicolon if exists in to 3 different fields and ignore any numbers |
Not showing font awesome icons Posted: 24 Nov 2021 11:26 AM PST i'm new here, been redirected here form the support team of font awesome. I have a problem with some icons i have set on a wordpress site, they only appear visible with my wordpress user logged, can't see them on logged out, or even in any other explorers.. i have runed a troubleshoot test and got this link here: https://use.fontawesome.com/releases/v5.15.4/css/all.css Anyone may give some light in to this? |
Error mail.smtp.SMTPSendFailedException: SendAsDenied; send as nobody@nowhere [closed] Posted: 24 Nov 2021 11:25 AM PST I want to configure my Jenkinsfile to send notifications by mail from office 365, corporate mail. I get this error when executing the job. |
Flutter mobile app login via azure Active directory from web app that already implemented Azure Ad Posted: 24 Nov 2021 11:27 AM PST I have a web app that already configured with Azure Ad, once user login the web app via azure ad, they web app will redirect it to identity server and then successfully logged in to the website. However, currently we have to implement the azure ad login in our flutter mobile app also. For calling the web app API, we have to get access token generated from the web app identity server. So the problem is that is there a solution to directly allow my mobile app to login through the azure ad page configured for my web app and get access token directly in my flutter app? Or is there other suggestions? |
Google map ground overlay flutter Posted: 24 Nov 2021 11:25 AM PST I would like to display an image in overlay at given lat-log positions on Google map using Flutter . I am using flutter package google_maps_flutter: 0.5.32 , at present the package does not provide to implement the feature . |
What tag should be used for a logo element if the logo is text? Posted: 24 Nov 2021 11:26 AM PST I have read that an <h1> tag is inappropriate for a logo. But if your logo is plain text, what should you use? I feel like <p> and <span> are also unsuitable. Here's a sample: <header> <nav> <a id="logo" href="."> <span>Company Name</span> </a> <a id="linkOne" href="#thingOne"> <img src="…"> </a> <a id="linkTwo" href="#thingTwo"> <img src="…"> </a> <a id="linkThree" href="#thingThree"> <img src="…"> </a> </nav> </header> Thanks! |
No comments:
Post a Comment