React Js and Laravel upload multiple images Posted: 16 Aug 2021 08:08 AM PDT I want to save a product with multiple images but something is not working. Below is the code in react js: const [file, setFiles] = useState([]) const handleChangeFiles = (e) => { setFiles(e.target.files) } const form_data = new FormData() form_data.append('name', name) form_data.append('file', file) storeProduct(form_data).then(res => { toastr.success('Product stored!') }) <input accept="image/*" multiple onChange={handleChangeFiles} type="file" className="form-control" /> and this is the code in laravel: $createdProduct = Product::create([ 'name' => $request->name, ]); if($request->hasFile('file')){ $images = $request->file; foreach($images as $image){ $strRandom = Str::random(32); $generateImageName = $createdProduct->slug . '-' .$strRandom; $destinationPath = public_path('/img-products'); $image->move($destinationPath, $generateImageName); ImageProduct::create([ 'product_id' => $createdProduct->id, 'file' => $generateImageName ]); } } The product is being stored but not the images. Can someone tell me what am I doing wrong? |
How do I change labels on y scale of a scatterplot using characters? Posted: 16 Aug 2021 08:08 AM PDT An example of my data is: df <- data.frame(Percent.diff=c(6.3,7.78,12.22,4.81,5.93,8.89), modal.response=c(1,2,3,1,1,1.5), Gr=c("R","G","B"), Sub=c("Plant","Animal","Water")) I have a scatterplot with a continuous variable (Percent.diff) on the x axis. Although the y axis is numeric (modal.response on a survey question), it relates to categories of responses (ie 0-"The same", 1-"Slightly worse", 2-"Moderately worse",3-"Significantly worse", but there are also responses options in between, eg 1.5). I have made other bar charts with the same data but for this chart specifically I want to make a scatterplot. My only issue is that I want to change the labels of the points on my y axis, so that instead of it simply showing 0-3, I want it to show 0-"The same", 1-"Slightly worse", 2-"Moderately worse",3-"Significantly worse". I have tried making the variable into a factor, but this doesn't work because I think it needs to be a continuous scale and I get the error message "Error: Discrete value supplied to continuous scale". This is the code I'm using for my plot: ggplot(df, aes(x=Percent.diff, y=modal.response, color=Sub)) + geom_point()+ geom_smooth(method=lm, se=FALSE)+ geom_point(aes(shape=Gr, fill=Sub), size=3)+ scale_shape_manual(values=c(3, 8, 21:25)) Thank you |
Delete oldest file from ftp via windows command Posted: 16 Aug 2021 08:07 AM PDT I got a batch script where I automatically upload the newest file from a directory to the FTP-Server. There it is used for further stuff. Since these files have different names, they all stay on the directory, which isn't good for the further stuff. So I need to delete the old/oldest file from the same FTP Server, so there is only one file in this directory. My code so far: @echo off set FTP=ftp-script.dat set SRV=XXX set USR=XXX set PAS=XXX FOR /F "delims=|" %%I IN ('DIR "X.csv" /B /O:D') DO SET NewestFile=%%I echo open %SRV% > %FTP% echo %USR%>> %FTP% echo %PAS%>> %FTP% echo bin >> %FTP% echo cd /X >> %FTP% echo lcd T:/X >> %FTP% echo put %NewestFile% >> %FTP% echo close >> %FTP% echo quit >> %FTP% ftp -s:%FTP% cmd /k How can I select the oldest file and delete it, once the new is uploaded? |
Count product selled in a day for each type of product Posted: 16 Aug 2021 08:07 AM PDT I have a problem in my query. Imagine i have 10 product (product1, product2, product3), and today (08/16/2021), i'm selling 15 "product1, 2 product2 and 5 product3. I need to now every day how many product i sold, and be able to get all of them for each day. Tell me if my class are good enough, and what query or code can i use. @Entity(tableName = "stock_products") data class StockProducts ( @PrimaryKey(autoGenerate = false) val id: String, @ColumnInfo(name = "timestamp") val timestamp: String, @ColumnInfo(name = "productName") val orderList: List<ProductInfo> ) |
ZFS pool with altroot or "-R" does not automount Posted: 16 Aug 2021 08:07 AM PDT When i do sudo zpool create -R /zpools zpool1 /dsk/test and after that zpool list it shows me the new pool. But when i reboot the system it does not show up when "zpool list". Same with zpool create -o altroot=/zpools zpool1 /dsk/test When creating pool without altroot or -R it does automount. So how can i change the root folder and have automount at the same time? |
ReactJS - How to print all the content of a Scrollable elment with react-to-print Posted: 16 Aug 2021 08:07 AM PDT I have a <div> tag that has a list of elements, the list can be long so I gave a fixed height to the <div> tag and overflow:auto property to have scrollable list in case of overflow. Now I have a button at the bottom of this <div> to print the content of <div> . I am using react-to-print library as it seemed most easiest way to print the contents of my <div> along with the CSS. The problem is that, the print preview is showing only the elemnts present in the view port, but I want all the elements in the <div> to print. I can not use overflow:visible property on my <div> as I definitely need the <div> to be a scrollable element also I can not place the button to print the list inside my <div> as users cant keep scrolling to the end of list to print it. Here is a sandbox to playaround: https://codesandbox.io/s/material-demo-forked-wifyd?file=/demo.js:337-341 Any help is highly Appreciated!! |
AngularJS Dynamic Youtube Videos with Bootstrap Posted: 16 Aug 2021 08:07 AM PDT I just started working at a small Software Developer Company as a Front-end Developer after graduation. I never used any frameworks before and here we use AngularJs yet ( planning to change into Angular in the future). My tutors are very busy at the moment, so I am looking for external help, with my coding issues. The issue that I would like to share is: I am trying to make a Bootstrap Modal Popup that would play Dynamic Youtube videos from another page. Without Bootstrap modal popup it works (but ugly) Dynamically, and I was able to use Bootstrap Modal but only with Static Youtube Links. Explanation: We have bootstrap cards, Which contains a youtube video play button if a youtube video is connected to it. The video should be able to be played if it appears, but it is not there. The Youtube video Embeds are in an SQL, and a C# file gives it to the View. How could I change my code to make it work (Included other tries too, might someone will have a good idea with them)? Unfortunately, I can't share everything, but I try to explain it as much as possible. Used Technologies: ASP.Net, C#, AngularJs, BootStrap. The Code that I want to change: <div ng-repeat="man in manuals"> <div class="Title text-info"> {{man.GroupName}} </div> <div class="row"> <div class="col-sm-6 col-md-6 col-lg-4 col-xl-3 mb-3 mh-100" ng-repeat="m in man.Items"> <div class="card bg-dark shadow-sm" style="height:250px;"> <div class="card-body ebp-bg-cover" style="background-image: url('../../Content/Image/BackGrounds/doc_bg_{{manuals.indexOf(man)%4+1}}B.jpg');"> <h4 class="font-weight-bold">{{m.Name}} <span ng-if="m.NewDocument" class="text-warning float-right">@OMFPage.New</span> </h4> //Text from a .resx file </a> @* // Working but it is not Pop-Up <a ng-href="{{m.YouTubeVideo}}" ng-show="m.YouTubeVideo!=undefined"> <img src="~/Content/Image/Logos/eniac_play.png" class="ebp_UserManuals_youtube" /> </a>*@ /*Shows the icon only if the field contains value */ <div ng-show="m.YouTubeVideo!=undefined"> <img class="ebp_UserManuals_youtube" src="~/Content/Image/Logos/playbutton.png" data-toggle="modal" data-target="#e_YoutbeVideoModal" title="Play Video" /></div> <div class="modal fade" id="ebp_YoutbeVideoModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content" style="padding: 0px; border:none; "> <div class="modal-header bg-dark"> <h5 class="modal-title" id="exampleModalLabel">YT video</h5> <button type="button" class="close text-light" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body bg-dark"> @*<iframe class="e-youtube-player" id="ebp_Youtube" width="560" height="315" ng-src="{{m.YouTubeVideo}}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>*@ <div ng-controller="MainCtrl"> @*Dont leave two controllers in it*@ <youtube-player video="{{m.YouTubeVideo}}" header="Url Description"> </youtube-player> </div> <script> app.controller('MainCtrl', function($scope) { }); app.filter('trustUrl', function($sce) { return function(url) { return $sce.trustAsResourceUrl(url); }; }); app.directive('youtubePlayer', function() { return { restrict: 'E', scope: { header: '@@', video: '@@' }, transclude: true, replace: true, template: '<iframe ng-src="{{video | trustUrl}}"></iframe>', link: function(scope, element, attrs) { scope.header = attrs.header; } }; }); </script> If you have any question feel free to ask it, and I will extend the description with it. |
append certain values to a dataset based on a condition (Python) Posted: 16 Aug 2021 08:07 AM PDT I have two datasets. I would like to append columns that contain certain values to one of the datasets based on specific matching criteria. Data df1 source pw count date leaving aa 20 2 q122 aa 10 1 q322 6 2 q422 bb df2 id date other aa q1 22 1 aa q2 22 1 aa q3 22 1 bb q1 22 1 bb q2 22 11 bb q3 22 2 bb q4 22 2 Desired id date other source pw count date leaving aa q1 22 1 aa 20 2 q122 aa q2 22 1 aa q3 22 1 aa 10 1 q322 bb q1 22 1 bb q2 22 11 bb q3 22 2 bb q4 22 2 6 2 q422 bb Logic Append the source column to df2 if the source column value matches the id column as well if the date column in df1 matches the date column in df2. Same logic with the 'leaving' column Doing possible mapping df2['source']=df2['aa'].map({ 'q1 22':'' }) concat pd.concat([df1,df2], axis=1) Any suggestion is appreciated |
Input XML SOAP request Posted: 16 Aug 2021 08:07 AM PDT Passing an XML input to WebMethods via a SOAP request. Other XML inputs work fine, but for a particular XML input I get this error in SOAP UI. I don't have any spaces in input parameters and from the java code, gets a response. Very little documentation is on the internet on this error. Any pointers would be appreciated. regards, R |
Count co-occurences across groups Posted: 16 Aug 2021 08:07 AM PDT I would like to count co-occurences of a variable across groups. I'm sure there's an easy {dplyr}/{tidyr} solution with count or pivot_ but I'm stuck. Thank you for your help! Below is a reprex of my input and potential output (I don't care about the format of the output, could also be a contingency table). Note that order of the variable does not matter, i.e., "green" then "blue" is the same as "blue" then "green". library(dplyr) df_in <- tribble( ~id, ~color, 1, "green", 1, "blue", 2, "blue", 2, "green", 3, "blue", 3, "red" ) df_out <- tribble( ~colors, ~n, "blue-green", 2, "blue-red", 1 ) Or as a contingency table: | | blue |green|red| | ----- | - | - | - | | blue | - | 2 | 1 | | green | 2 | - | 0 | | red | 1 | 0 | - | |
AWS Lambda get-layer-version-by-arn: ValidationException when calling the GetLayerVersionByArn operation Posted: 16 Aug 2021 08:07 AM PDT I'm trying to use get-layer-version-by-arn : aws lambda get-layer-version-by-arn --arn=aws:lambda:us-west-2:113088814899:layer:Klayers-python37-packaging:1 But I'm getting this error: An error occurred (ValidationException) when calling the GetLayerVersionByArn operation: 1 validation error detected: Value 'aws:lambda:us-west-2:113088814899:layer:Klayers-python37-packaging:1' at 'arn' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+ I know I have to specify the correct region, I've probably done it incorrectly. Any ideas? |
When running the flask app locally, did not found module reference Posted: 16 Aug 2021 08:07 AM PDT I am doing an example app in python with flask to run locally, and deploying in google cloud functions My directory structury are this: venv\ scripts\ src\ search\ search.py main.py app.py I'm deploying main.py to google cloud main.py from markupsafe import escape from search import lerolero def HelloWorld(request): request_args = request.args if request_args and "name" in request_args: name = request_args["name"] else: name = "World" name = lerolero.search(name) return "Hello {}!".format(escape(name)) search.py def search(arg): print(arg) return arg + " !!!" But when I'm trying to run app.py locally with flask, I'm get an error from search import lerolero ModuleNotFoundError: No module named 'search' app.py import flask from src import main app = flask.Flask(__name__) @app.route("/") def productSearch(): return main.HelloWorld(flask.request) If I remove my search reference from main.py, I can import to google cloud and run locally. It's possible to configure my app.py to run locally when my main.py have multiple references? |
Export DAX ( power query ) query result to csv Posted: 16 Aug 2021 08:07 AM PDT Basically I have about 50 excels worksheets with information to process. Every worksheet has a power query script inside to clean the information. I need to automate this process by any way possible. I've downloaded power query SDK, in visual studio I run the .pq file and it works, but i cant find a way to write the query result to a file (or insert it directly to a sql server table). I've tried this approach and it works (using R on a power BI book to export it to a file with the write.table command). The problem is that I dont know how to trigger the refresh without opening the book. (so I can add it to the job list). The refresh every X time option in power BI is not useful here, I need to trigger the refresh after part of the sql jobs are done. So I need to trigger by some type of API. Any type of solution is welcome. |
Type 'string | number' is not assignable to type 'never' in switch statement Posted: 16 Aug 2021 08:08 AM PDT I have an interface that describe the data structure from BE, and a class has method for transforming that BE data structure to our FE data structure and vice versa,but during that typescript throw Type 'string | number' is not assignable to type 'never'. Type 'string' is not assignable to type 'never' error. How do i resolve it, and why it happen ? interface BEStructure { a?: string; b?: number; ... } class FEStructure { a: string = null; b: number = null; ... static convertToBE(fe: FEStructure): BEStructure { const be: BEStructure = {}; Object.keys(fe).forEach(key => { switch (key) { case 'a': case 'b': // My others logic // ERROR HERE be[key] = fe[key]; break; default: be[key] = fe[key]; } }); return be; } } |
How to merge cells with list datatypes from different dataframes in Python Pandas? Posted: 16 Aug 2021 08:07 AM PDT I currently am trying to merge lists together from two different dataframes using pandas. I am trying to get each cell in df1 merged all the cells in df2. So as an example I have the following two dataframes: >>> df1 0 [This, is, a, sentence] 1 [this, is, another, sentence] >>> df2 0 [this, is, also, a, sentence] 1 [this, too, is, a, sentence] 2 [this, is, very, different] 3 [another, sentence, is, this] 4 [not, much, of, anything] I am trying to have the two cells in df1 merge with the cells in df2, to give the following output: >>> df_merged 0 [this, is, also, a, sentence, This, is, a, sentence] 1 [this, too, is, a, sentence, This, is, a, sentence] 2 [this, is, very, different, This, is, a, sentence] 3 [another, sentence, is, this, This, is, a, sentence] 4 [not, much, of, anything, This, is, a, sentence] >>> df2_merged 0 [this, is, also, a, sentence, This, is, another, sentence] 1 [this, too, is, a, sentence, This, is, another, sentence] 2 [this, is, very, different, This, is, another, sentence] 3 [another, sentence, is, this, This, is, another, sentence] 4 [not, much, of, anything, This, is, another, sentence] Any ideas on how I could achieve this? They don't necessarily need to be split up into different dataframes, they could be in different columns in the same dataframe etc |
React Native App - add buttons that trigger specific screen function on both header and tab navigator Posted: 16 Aug 2021 08:08 AM PDT I'm building an app using React-Native and I'm stuck with the following problem: I need to create a screen with custom Header and Bottom Tabs (Header should have 2 buttons: Go back and Review) and bottom tabs should have 2 buttons as well ( Import and Proceed ). I've tried the following approach for the header as seen below, but I get an error (undefined is not an object) whenever I click on any of the 2 buttons. Also, I don't know if I pass props correctly in the Review screen (I need to pass props of New.js Screen, and the piece of code below is in App.js) <Stack.Screen name="New" component={New} navigation={this.props.navigation} options={{ headerRight: () => ( <Button onPress={() => this.navigation.navigate('Review', { name: name, data: data })} title="Review" /> ), headerLeft: () => ( <Button onPress={() => this.navigation.goBack()} title="Back" /> ), }} /> And the for the bottom tabs, I couldn't find a way to make it work for my scenario. I tried making this work with an Empty component because that way, it will not pass the overall app bottom tabs, because I need a specific one here (with 2 buttons only) const EmptyContainer = () => { return(null) }; //..... <Tab.Screen name="NewContainer" component={EmptyContainer} listeners={({navigation}) => ({ tabPress: event => { event.preventDefault(); navigation.navigate('New'); } })} options ={{ tabBarIcon: ({color, size}) => ( <MaterialCommunityIcons name="plus-box" color ={color} size={12}/> ) }} /> |
Discord bot is not replying to messages Posted: 16 Aug 2021 08:07 AM PDT I have been trying to set up a discord bot and by following the docs, I have been able to set up a slash command but have not been able to get the bot to reply to messages on the server. Here is the code I used to set up slash command from docs. const { REST } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v9'); const commands = [{ name: 'ping', description: 'Replies with Pong!' }]; const rest = new REST({ version: '9' }).setToken('token'); (async () => { try { console.log('Started refreshing application (/) commands.'); await rest.put( Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands }, ); console.log('Successfully reloaded application (/) commands.'); } catch (error) { console.error(error); } })(); After this I set up the bot with this code const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS] }); client.once('ready', () => { console.log('Ready!'); console.log(`Logged in as ${client.user.tag}!`); }); client.on('interactionCreate', async interaction => { // console.log(interaction) if (!interaction.isCommand()) return; if (interaction.commandName === 'ping') { await interaction.reply('Pong!'); // await interaction.reply(client.user + '💖'); } }); client.login('BOT_TOKEN'); Now I am able to get a response of Pong! when I say /ping. reply image But after I added the following code from this link I didn't get any response from the bot. client.on('message', msg => { if (msg.isMentioned(client.user)) { msg.reply('pong'); } }); I want the bot to reply to messages not just slash commands. Can someone help with this. Thanks!!🙂 |
Angular: Unittest with async input pipe + mock service with HttpClient Posted: 16 Aug 2021 08:07 AM PDT I try to create a unittest for my angular component. The test case should do the following: - Manipulate the input with "The"
- Check if the loading indicator is shown
- Return a mocked value from the service (which would normaly create a HttpRequest)
- Check if the loading indicator is hidden
- Check if the options of the response from the mocked service are shown
- [optional] Select an option and check the formControl value
First of all my component.ts : @Component({ selector: 'app-band', templateUrl: './band.component.html', styleUrls: ['./band.component.scss'] }) export class BandComponent implements OnInit { loading?: boolean; formControl = new FormControl('', [Validators.minLength(3)]); filteredOptions: Observable<Band[]> | undefined; @Output() onBandChanged = new EventEmitter<Band>(); constructor(private bandService: BandService) { } ngOnInit(): void { this.filteredOptions = this.formControl.valueChanges .pipe( startWith(''), tap((value) => { if (value) this.loading = true; }), debounceTime(300), distinctUntilChanged(), switchMap(value => { if (!value || value.length < 3) { return of([]); } else { return this.bandService.searchFor(value).pipe(map(value => value.bands)) } }), tap(() => this.loading = false), ); } getBandName(band: Band): string { return band?.name; } } The HTML file: <mat-form-field class="input-full-width" appearance="outline"> <mat-label>Band</mat-label> <input matInput placeholder="e. G. Foo Fighters" type="text" [formControl]="formControl" [matAutocomplete]="auto"> <span matSuffix *ngIf="loading"> <mat-spinner diameter="24"></mat-spinner> </span> <mat-autocomplete #auto="matAutocomplete" [displayWith]="getBandName"> <mat-option *ngFor="let option of filteredOptions | async" [value]="option"> {{option.name}} </mat-option> </mat-autocomplete> <mat-error *ngIf="formControl.hasError('minlength')"> error message </mat-error> </mat-form-field> Here is my current unittest. I was not able to find an example for my usecase. I tried to implement the test, like they did it in the angular docs. I also tried the fixture.debugElement.query(By.css('input')) to set the input value and used the nativeElement , inspired by this post, neither worked. I am not so familiar with angular unittests. In fact I might not have understood some base concepts or principles. beforeEach(() => { bandService = jasmine.createSpyObj('BandService', ['searchFor']); searchForSpy = bandService.searchFor.and.returnValue(asyncData(testBands)); TestBed.configureTestingModule({ imports: [ BrowserAnimationsModule, FormsModule, ReactiveFormsModule, HttpClientTestingModule, MatAutocompleteModule, MatSnackBarModule, MatInputModule, MatProgressSpinnerModule ], providers: [{ provide: BandService, useValue: bandService }], declarations: [BandComponent], }).compileComponents(); fixture = TestBed.createComponent(BandComponent); component = fixture.componentInstance; loader = TestbedHarnessEnvironment.loader(fixture); fixture.detectChanges(); }); it('should search for bands starting with "The"', fakeAsync(() => { fixture.detectChanges(); component.ngOnInit(); tick(); const input = loader.getHarness(MatInputHarness); input.then((input) => { input.setValue('The'); fixture.detectChanges(); expect(component.loading).withContext('Showing loading indicator').toBeTrue(); tick(300); searchForSpy.and.returnValue(asyncData(testBands)); }).finally(() => { const matOptions = fixture.debugElement.queryAll(By.css('.mat-option')); expect(matOptions).toHaveSize(2); }); })); |
THREE.Object3D.add: object not an instance of THREE.Object3D. in Threejs Posted: 16 Aug 2021 08:08 AM PDT I have been trying to add skeleton arms to my haunted house project from threejs journey by Bruno simon. I followed this stackoverflow answer to create a skeleton arm -> three.js basic skeleton for animation But this is giving me an error of Object3D and I even tried one according to the threejs documentation but it gave the same error. Here is my source code GitHub link for my code, can someone help me out over here? Error Screen Error in Console |
TextField input doubled Posted: 16 Aug 2021 08:07 AM PDT In a Flutter desktop for Windows project I have a TextField widget in a statefulWidget with a controller attached to it. late TextEditingController searchController; @override void initState() { super.initState(); searchController = TextEditingController(); } @override void dispose() { searchController.dispose(); super.dispose(); } TextField( keyboardType: TextInputType.text, controller: searchController, decoration: defaultTextFieldDecoration.copyWith(hintText: "Type to Search"), style: textFieldStyle, onChanged: (value) {}, ), Now when I type something into the textfield like "abc" every key gets input twice like "aabbcc" and I can't figure out why. I have used TextFields many times and that never happended. It is also not a problem with my keyboard since I can type this without problems :D Edit: Here is a full example to reproduce this problem. import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: Main())); } class Main extends StatefulWidget { const Main({Key? key}) : super(key: key); @override _MainState createState() => _MainState(); } class _MainState extends State<Main> { @override Widget build(BuildContext context) { return const Scaffold( body: Center( child: TextFieldTestWidget(), ), ); } } class TextFieldTestWidget extends StatefulWidget { const TextFieldTestWidget({Key? key}) : super(key: key); @override _TextFieldTestWidgetState createState() => _TextFieldTestWidgetState(); } class _TextFieldTestWidgetState extends State<TextFieldTestWidget> { TextEditingController controller = TextEditingController(); @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SizedBox( width: 300, height: 100, child: TextField( controller: controller, ), ); } } Edit: Added Image Edit again: Found that it has something to do with the initial text value... I just dont't get what exactly. When i change the TextEditingController to TextEditingController(text:"") it works somehow. I think instancing TextEditingControllers is somehow broken. |
Truncation erros in python Posted: 16 Aug 2021 08:08 AM PDT Try to calculate: by storing 1/N and X as float variable. Which result do you get for N=10000, 100000 and 1000000? Now try to use double variables. Does it change outcome? In order to do this I wrote this code: #TRUNCATION ERRORS import numpy as np #library for numerical calculations import matplotlib.pyplot as plt #library for plotting purposes x = 0 n = 10**6 X = [] N = [] for i in range(1,n+1): x = x + 1/n item = float(x) item2 = float(n) X.append(item) N.append(item2) plt.figure() #block for plot purpoes plt.plot(N,X,marker=".") plt.xlabel('N') plt.ylabel('X') plt.grid() plt.show() The output is: This is wrong because the output should be like that (showed in the lecture): |
Excel Visual Basic SpinButton1 does not work on second search Posted: 16 Aug 2021 08:07 AM PDT I have a table with name and age and a command button, this button opens the customer search screen. When I search for the name Andrew brings me 3 results, I go to page 3 of 3 and perform a new search, so the arrow doesn't work, do you know where the error might be? Public MatrizResultados As Variant Public Total_Ocorrencias As Long Private Sub btn_Procurar_Click() If Me.txt_Procurar.Text = "" Then MsgBox "Enter a name" Else Call ProcuraPersonalizada(Me.txt_Procurar.Text) End If End Sub Private Sub Label6_Click() End Sub Private Sub Label7_Click() End Sub Private Sub SpinButton1_Change() Dim Linha As Long Dim TotalOcorrencias As Long TotalOcorrencias = SpinButton1.Max + 1 Linha = MatrizResultados(SpinButton1.Value) Label_Registros_Contador.Caption = SpinButton1.Value + 1 & " de " & TotalOcorrencias TextBox1.Text = Plan1.Cells(Linha, 1).Value TextBox2.Text = Plan1.Cells(Linha, 2).Value End Sub Private Sub ProcuraPersonalizada(ByVal TermoPesquisado As String) Dim Busca As Range Dim Primeira_Ocorrencia As String Dim Resultados As String 'perform the search Set Busca = Plan1.Cells.Find(What:=TermoPesquisado, After:=Range("A1"), LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not Busca Is Nothing Then Primeira_Ocorrencia = Busca.Address Resultados = Busca.Row Do Set Busca = Plan1.Cells.FindNext(After:=Busca) If Not Busca.Address Like Primeira_Ocorrencia Then Resultados = Resultados & ";" & Busca.Row End If Loop Until Busca.Address Like Primeira_Ocorrencia MatrizResultados = Split(Resultados, ";") SpinButton1.Max = UBound(MatrizResultados) SpinButton1.Enabled = True Label_Registros_Contador.Caption = "1 de " & UBound(MatrizResultados) + 1 TextBox1.Text = Plan1.Cells(MatrizResultados(0), 1).Value TextBox2.Text = Plan1.Cells(MatrizResultados(0), 2).Value Else SpinButton1.Enabled = False Label_Registros_Contador.Caption = "" TextBox1.Text = "" TextBox2.Text = "" MsgBox "No results for '" & TermoPesquisado & "' was found." End If txt_Procurar.Text = "" txt_Procurar.SetFocus End Sub Private Sub TextBox2_Change() End Sub Private Sub UserForm_Initialize() SpinButton1.Enabled = False Label_Registros_Contador.Caption = "" End Sub |
How can I return a value to my ViewModel from CoroutineScope? Posted: 16 Aug 2021 08:07 AM PDT My activity wants to insert a new element on my database using Room, so the activity delegate this task to a ViewModel class passing the Entity object. The activity wants the value back of the id autogenerated by the database so the object can be updated in real-time. So, the ViewModel class wants to launch a coroutine on the IO pool thread that uses an insert Dao method that returns the new id value. Finally, my question is: how can I return the value from the coroutine to the ViewModel method? This is my code into the ViewModel class: //return autogenerated id fun insert(fiscalcode: Fiscalcode): Int { CoroutineScope(Dispatchers.IO).launch { db.fiscalcodeDao().insert(fiscalcode) //return autogenerated id } } |
Tomcat 9.0.52 crashes with "java.util.zip.ZipException: invalid LOC header (bad signature)" when started in debug mode - any work-around? Posted: 16 Aug 2021 08:07 AM PDT When trying to start Tomcat (9.0.52) in debug mode ("Debug on Server") from Eclipse (v2020-12 (4.18.0) / Build id: 20201210-1552) I get the following error (see full stacktrace further below): 16-Aug-2021 13:52:14.019 SEVERE [main] org.apache.catalina.core.ContainerBase.startInternal A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@61322f9d] at java.util.concurrent.FutureTask.report(FutureTask.java:122) ... Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@61322f9d] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) ... Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature) at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:143) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) ... 33 more Caused by: java.util.zip.ZipException: invalid LOC header (bad signature) at java.util.zip.ZipFile.read(Native Method) ... Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature) at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:143) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) ... 33 more Caused by: java.util.zip.ZipException: invalid LOC header (bad signature) While the reasons seems clear - there is some issue reading a .jar file - the question I have is: How can I find out, WHICH .jar is causing this issue? Is there some option to get more info on the root cause: which library (either from Tomcat or which application-jar?) that it tries to read is causing this? The odd thing is: When I start this up in normal "run" mode in Eclipse or as a Windows Service, then Tomcat as well as the application start up fine. This zip-file problem only happens when I try to start it in debug mode! And - when starting Tomcat from Eclipse - then no .war-file is created but rather Tomcat's classpath is adjusted such, that the class files are used in-situ (i.e. directly from the target directory where they have been compiled to). So there is no additional .jar file created compared to the non-debug mode (which is why I am puzzled why this happens only in debug mode). Eclipse uses Java 14 (if I am correct) but is configured to compile to 1.8 compatibility and the runtime (i.e. Tomcat and our application) uses Java 1.8 (I have installed the "almost latest" AdoptOpenJDK v1.8 / jdk-8.0.292.10-hotspot). Tomcat's download page (https://tomcat.apache.org/whichversion.html) claims, that Tomcat 9.0.52 runs with Java "8 and later", so IMHO I should be OK in terms of prereq's. Any idea how to get the above setup starting up/working in debug mode? Full stacktrace: ... 16-Aug-2021 13:52:11.275 INFO [main] org.apache.catalina.startup.Catalina.load Server initialization in [1232] milliseconds 16-Aug-2021 13:52:11.343 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service [Catalina] 16-Aug-2021 13:52:11.343 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet engine: [Apache Tomcat/9.0.52] 16-Aug-2021 13:52:11.866 INFO [main] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 16-Aug-2021 13:52:13.860 WARNING [main] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1,954] milliseconds. 16-Aug-2021 13:52:14.019 SEVERE [main] org.apache.catalina.core.ContainerBase.startInternal A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@61322f9d] at java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.util.concurrent.FutureTask.get(FutureTask.java:192) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:926) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.startup.Catalina.start(Catalina.java:772) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:476) Caused by: org.apache.catalina.LifecycleException: Failed to initialize component [org.apache.catalina.webresources.JarResourceSet@61322f9d] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:139) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:173) at org.apache.catalina.webresources.StandardRoot.startInternal(StandardRoot.java:726) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4885) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5023) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) ... 21 more Caused by: java.lang.IllegalArgumentException: java.util.zip.ZipException: invalid LOC header (bad signature) at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:143) at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:136) ... 33 more Caused by: java.util.zip.ZipException: invalid LOC header (bad signature) at java.util.zip.ZipFile.read(Native Method) at java.util.zip.ZipFile.access$1400(ZipFile.java:60) at java.util.zip.ZipFile$ZipFileInputStream.read(ZipFile.java:734) at java.util.zip.ZipFile$ZipFileInflaterInputStream.fill(ZipFile.java:434) at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158) at sun.misc.IOUtils.readNBytes(IOUtils.java:180) at sun.misc.IOUtils.readAllBytes(IOUtils.java:116) at java.util.jar.JarFile.getBytes(JarFile.java:426) at java.util.jar.JarFile.getManifestFromReference(JarFile.java:193) at java.util.jar.JarFile.getManifest(JarFile.java:180) at org.apache.catalina.webresources.AbstractSingleArchiveResourceSet.initInternal(AbstractSingleArchiveResourceSet.java:141) ... 34 more Later addition: I also tried the entire setup using a Java 11 VM for Tomcat but with the same result. So, this issue with some .jar-file having an invalid header or signature is apparently NOT a Java<=1.8 vs. Java >=v1.9 issue. |
Edit Table Using Angular reactive Forms Posted: 16 Aug 2021 08:07 AM PDT Click here expected form data { "contractProperties": [ { "name": "agentagentcode", "label": "agentagentcode", "defaultvalues": "sample1" }, { "name": "agentcity", "label": "agentcity", "defaultvalues": "sample1" } ], "templateTCSections": [ { "number": 1, "title": "Service", "templateTCText": [ number:1, requiresspecialbid:'true', title:'xxxxxxxxxxxxxxxxxxxx' ] }, { "number": 2, "title": "Service Description", "templateTCText": [ number:2, requiresspecialbid:false, title:'yyyyyyyyy' ] }, { "number": 3, "title": "Eligibility for Consolidations and Changes to a CS", "templateTCText": [ null ] }, { "number": 4, "title": "Currency Conversion, Billing and Payment", "templateTCText": [ null ] }, { "number": 5, "title": "Customer Responsibilities", "templateTCText": [ null ] }, { "number": 6, "title": "Overdue Payments", "templateTCText": [ null ] }, { "number": 7, "title": "Termination", "templateTCText": [ null ] } ] } i want to edit the third table as first two tables, but I'm unable to push the data to Terms & Conditions - Paragraphs table which is a nested form array present inside another form array, eventhough i placed input tags and form controls inside thirdtable im unable to edit the last table can anyone please help me where i messed the code |
Pre_process a column of tweets and make a dataframe Posted: 16 Aug 2021 08:08 AM PDT I have a CSV file that includes 2319 tweets and their labels. I read it in a dataframe and it looks like the following: I want to read each tweet and do the following: Remove stopwords, Remove links, Remove # , Remove punctuations, Remove @(mentions), lowercasing, Tokenization, Also remove emojies And then store each processed tweet in a new column of data frame(Lets say Processed Text). Therefore the previous dataframe will be changed to something like following: I wrote the following code in Jupyter: But I have two problems: first: after running my code, I see still I have stopwords or punctuations. this code creat list of lists, not dataftrame. I need my ouptput is a dayaframe with 3 columns: Text, label, Processed Text |
Unable to install Citrix VDA agent using ansible Posted: 16 Aug 2021 08:08 AM PDT I am trying to install Citirx VDA agent using ansible, but it is failing after reboot. ansible --version ansible 2.9.9 config file = /etc/ansible/ansible.cfg configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /bin/ansible python version = 2.7.5 (default, Aug 13 2020, 02:51:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] installvda.yml - name: Install VDA agent win_package: path: \\winshare\servers$\citrix\CVAD-1912-LTSR\CVAD_1912_U3\x64\XenDesktop Setup\XenDesktopVDASetup.exe arguments: /controllers "svddc025.mobilebelgium.be svddc026.mobilebelgium.be" /quiet /enable_remote_assistance /virtualmachine /optimize /components vda state: present expected_return_code: [0, 3, 3010] creates_service: BrokerAgent vars: ansible_become: yes ansible_become_user: MOBISTAR\_srv_storageansi_win ansible_become_password: ********* ansible_become_flags: logon_type=new_credentials logon_flags=netcredentials_only - name: Wait 180 seconds, but only start checking after 60 seconds wait_for_connection: delay: 60 timeout: 180 Error: { "msg": "Unexpected failure during module execution.", "exception": "Traceback (most recent call last):\n File \"/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py\", line 146, in run\n res = self._execute()\n File \"/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py\", line 645, in _execute\n result = self._handler.run(task_vars=variables)\n File \"/usr/lib/python2.7/site-packages/ansible/plugins/action/normal.py\", line 46, in run\n result = merge_hash(result, self._execute_module(task_vars=task_vars, wrap_async=wrap_async))\n File \"/usr/lib/python2.7/site-packages/ansible/plugins/action/__init__.py\", line 923, in _execute_module\n res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)\n File \"/usr/lib/python2.7/site-packages/ansible/plugins/action/__init__.py\", line 1075, in _low_level_execute_command\n rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)\n File \"/usr/lib/python2.7/site-packages/ansible/plugins/connection/winrm.py\", line 548, in exec_command\n result = self._winrm_exec(cmd_parts[0], cmd_parts[1:], from_exec=True, stdin_iterator=stdin_iterator)\n File \"/usr/lib/python2.7/site-packages/ansible/plugins/connection/winrm.py\", line 509, in _winrm_exec\n self.protocol.cleanup_command(self.shell_id, command_id)\n File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/winrm/protocol.py\", line 372, in cleanup_command\n res = self.send_message(xmltodict.unparse(req))\n File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/winrm/protocol.py\", line 234, in send_message\n resp = self.transport.send_message(message)\n File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/winrm/transport.py\", line 256, in send_message\n response = self._send_message_request(prepared_request, message)\n File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/winrm/transport.py\", line 261, in _send_message_request\n response = self.session.send(prepared_request, timeout=self.read_timeout_sec)\n File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/requests/sessions.py\", line 646, in send\n r = adapter.send(request, **kwargs)\n File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/requests/adapters.py\", line 516, in send\n raise ConnectionError(e, request=request)\nConnectionError: HTTPSConnectionPool(host='svapp705', port=5986): Max retries exceeded with url: /wsman (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f019b431590>: Failed to establish a new connection: [Errno 111] Connection refused',))\n", "_ansible_no_log": false, "stdout": "" } Please let me know if you need any more details to investigate the issue. |
Discord.py How to make clean dialog trees? Posted: 16 Aug 2021 08:08 AM PDT My goal is to clean up my code so that I can more easily make dialog trees without constant copied pieces that don't have to be there. I can do it cleanly in python, but discord.py seems to have different requirements. Here is a sample of my current, very redundant code: if 'I need help' in message.content.lower(): await message.channel.trigger_typing() await asyncio.sleep(2) response = 'Do you need help' await message.channel.send(response) await message.channel.send("yes or no?") def check(msg): return msg.author == message.author and msg.channel == message.channel and msg.content.lower() in ["yes", "no"] msg = await client.wait_for("message", check=check) if msg.content.lower() == "no": await message.channel.trigger_typing() await asyncio.sleep(2) response = 'okay' await message.channel.send(response) if msg.content.lower() == "yes": await message.channel.trigger_typing() await asyncio.sleep(2) response = 'I have something. Would you like to continue?' await message.channel.send(response) await message.channel.send("yes or no?") def check(msg): return msg.author == message.author and msg.channel == message.channel and msg.content.lower() in ["yes", "no"] msg = await client.wait_for("message", check=check) if msg.content.lower() == "no": await message.channel.trigger_typing() await asyncio.sleep(2) response = 'Okay' await message.channel.send(response) I've tried to make functions to handle the repeating code, but haven't been successful. For example, using: async def respond(response, channel): await channel.trigger_typing() await asyncio.sleep(2) await channel.send(response) ... await respond(response, message.channel) Ideally, I'd like to be able to do something like this for the tree dialog itself, as I can in python: if __name__=='__main__': hallucinated = { 1: { 'Text': [ "It sounds like you may be hallucinating, would you like help with trying to disprove it?" ], 'Options': [ ("yes", 2), ("no", 3) ] }, 2: { 'Text': [ "Is it auditory, visual, or tactile?" ], 'Options': [ ("auditory", 4), ("visual", 5), ("tactile", 6) ] } } |
Reading from request body in an authorization requirement handler breaks routing Posted: 16 Aug 2021 08:08 AM PDT I have a custom handler for security and an endpoint. It works as supposed to. protected override Task HandleRequirementAsync( AuthorizationHandlerContext context, AwoRequirement requirement) { HttpRequest request = Accessor.HttpContext.Request; string awo = request.Headers .SingleOrDefault(a => a.Key == "awo").Value.ToString(); ... bools authorized = ...; if (authorized) context.Succeed(requirement); else context.Fail(); return Task.CompletedTask; } [Authorize(Policy = "SomePolicy"), HttpPost("something")] public async Task<IActionResult> Something([FromBody] Thing dto) { ... } Now, I need to check the contents of the body, so I'm reading it in and analyze the contents. However, I noticed that with this addition, the endpoint isn't reached anymore. No exception or anything, just simply no hit, like if the route doesn't match. While debugging, I saw that the stream is used up so breakpointing the flow and reading again produces an empty string. protected override Task HandleRequirementAsync( ... ) { HttpRequest request = Accessor.HttpContext.Request; ... using StreamReader stream = new StreamReader(Accessor.HttpContext.Request.Body); string body = stream.ReadToEndAsync().Result; Thing thing = JsonSerializer.Deserialize<Thing>(body); if (thing.IsBad()) authorized &= fail; ... return Task.CompletedTask; } According to this answer I should rewind seeking zero point of the stream, this one suggests enabling of buffering too. (There's also suggestion here but there's no await in the sample, which is required on my system, so I couldn't try it out properly.) Based on that, I landed in the following. protected override Task HandleRequirementAsync( ... ) { HttpRequest request = Accessor.HttpContext.Request; ... Accessor.HttpContext.Request.EnableBuffering(); using StreamReader stream = new StreamReader(Accessor.HttpContext.Request.Body); string body = stream.ReadToEndAsync().Result; Thing thing = JsonSerializer.Deserialize<Thing>(body); if (thing.IsBad()) authorized &= fail; ... return Task.CompletedTask; } Now, going back and rerunning the code does read in from the stream again. However, the endpoint isn't found anymore still, just like before adding the above. It is reached if I remove the reading from the stream, though, so I sense that I'm still affecting the body reading somehow. |
Fastest way to list all primes below N Posted: 16 Aug 2021 08:07 AM PDT This is the best algorithm I could come up. def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)', setup='import get_primes').timeit(1) 1.1499958793645562 Can it be made even faster? This code has a flaw: Since numbers is an unordered set, there is no guarantee that numbers.pop() will remove the lowest number from the set. Nevertheless, it works (at least for me) for some input numbers: >>> sum(get_primes(2000000)) 142913828922L #That's the correct sum of all numbers below 2 million >>> 529 in get_primes(1000) False >>> 529 in get_primes(530) True |
No comments:
Post a Comment