text
stringlengths
15
59.8k
meta
dict
Q: Street view panorama doesn't work in a div I'm trying to embed a street view panorama on a website as explained here. It works well when I do that : <body> <div id="map"></div> </body> but it doesn't work when i put the #map in a other div, like that : <body> <div> <div id="map"></div> </div> </body> Do you have any idea why ? A: Can you add width and height map div? If you have blank page instead map, it's probably missing css.
{ "language": "en", "url": "https://stackoverflow.com/questions/36794509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installation of tools in Azure virtual machine I have a requirement to install tools like Nagios, BigFix and other tools inside an Azure virtual machine once it gets provisioned and joined to the domain. Currently, I have written PowerShell scripts for a remote installation of these tools via Jumpbox once the VM is domain joined. Is there any other way this can be achieved?
{ "language": "en", "url": "https://stackoverflow.com/questions/48926870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I change the select option from the component in Angular2? I have a dropdown like below html <mat-form-field> <mat-select placeholder="Team" [(ngModel)]="selectedTeam" name="team" (change)="mainValuesChanged('team',$event,t.value)" #t> <mat-option *ngFor="let team of teams" [value]="team.value" > {{ team.viewValue }} </mat-option> </mat-select> </mat-form-field> ts selectedTeam="team1" teams = {"value":"t1","viewValue":"team1", "value":"t2","viewValue":"team2", "value":"newTeam",""viewValue":"Create Team"} What I'd like to do is when the user clicks on 'Create Team' the previous values(t1:team1 or t2:team2) remain same, while I create a new team by form, etc. How do I get reference to the select element so that I can change [value] to the previous value? So far I have this: mainValuesChanged(term,event:MatSelectChange,tValue){ if (event.value==="newTeam"){ this.selectedTeam = getPrevTeamNamefromAService(); #hack, hack } } If I could only reference the select element and set the [value] to selectedTeam or just change the selected value from the component without a direct reference, I would be able to do this. How do I achieve this? A: If you take a look at the API docs for the select, you can see that MatSelect is exported as matSelect. This means that you can get a reference to the select in the template by writing #t="matSelect". If you then pass this #t into your function, you can update the select's value like this: mainValuesChanged(term, event:MatSelectChange, select: MatSelect){ if (event.value==="newTeam"){ select.writeValue(getPrevTeamNamefromAService()); } } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/48857345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: merging two xmls of same number of nodes I have merged two xml files using java dom parser: a.xml <config> <category name="mimetypes"> <!-- application mime types --> <mime-type type=1></mime-type> <!-- eps --> <mime-type type=2></mime-type> <!-- octet-stream --> <mime-type type=3></mime-type> </category> </config> b.xml: <config> <category name="mimetypes"> <!-- application mime types --> <!-- eps --> <mime-type type=2></mime-type> <!-- octet-stream --> <mime-type type=3></mime-type> <mime-type type=4></mime-type> </category> </config> the output I get <config> <category name="mimetypes"> <!-- application mime types --> <mime-type type=1></mime-type> <!-- eps --> <mime-type type=2></mime-type> <!-- octet-stream --> <mime-type type=3></mime-type> </category> <mime-type type=2></mime-type> </config> Expected: <config> <category name="mimetypes"> <!-- application mime types --> <mime-type type=1></mime-type> <!-- eps --> <mime-type type=2></mime-type> <!-- octet-stream --> <mime-type type=3></mime-type> <mime-type type=4></mime-type> </category> </config> Code I have tried: public class MergeXmlDemo { public static void main(String args[]){ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; Document doc = null; Document doc2 = null; db = dbf.newDocumentBuilder(); doc = db.parse(new File("second.xml")); doc2 = db.parse(new File("first.xml")); NodeList ndListFirstFile = doc.getElementsByTagName("config"); Node nodeArea = doc.importNode(doc2.getElementsByTagName("mime-type").item(0), true); ndListFirstFile.item(0).appendChild(nodeArea); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); //StreamResult result = new StreamResult(new StringWriter()); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } merging two xml files with same number of nodes is giving the file with same number of nodes and type=4 is missing from the output. Any help is appreciated
{ "language": "en", "url": "https://stackoverflow.com/questions/61101181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to extend the prime membership of user from one month to 3 or 6 month using stripe I'am working on an application where user subscribe the premium membership using stripe. The subscription function is working properly with one month of billing cycle. Now I have to update the prime membership of user to 3 or 6 months. Please help me for this. I have implemented the stripe using spring boot REST api. A: Stripe has a guide to upgrading or downgrading Subscriptions that covers what you're asking about. The high-level steps are: * *Create a new Price representing the new billing period under the Product you already have *Update the Subscription using the new Price
{ "language": "en", "url": "https://stackoverflow.com/questions/68756767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AS/400 QSYRUSRI API parameters I'm trying to use the QYSRUSRI api to retrieve the number of supplemental groups in an Iseries user profile. There is an offset pointer to the beginning of the array holding this data. The spec for format USRI0300 mentions this as starting in position 585 of the receiver variable but in my implementation that subfield (suppGrpIdx) contains zero even though the subfield for the number of supplemental groups (suppGrp) contains 6, which is correct for the profile I am analysing. See below for my DS specifications for the received data. Any ideas what I'm missing? D USRI0300 DS based(p_usrData) qualified D name 10a overlay(USRI0300:9) D prevSign 6a overlay(USRI0300:20) D signTries 10i 0 overlay(USRI0300:33) D status 10a overlay(USRI0300:37) D changed 8a overlay(USRI0300:47) D expires 8a overlay(USRI0300:61) D special 15a overlay(USRI0300:84) D groupprf 10a overlay(USRI0300:99) D owner 10a overlay(USRI0300:109) D authority 10a overlay(USRI0300:119) D initmenu 20a overlay(USRI0300:149) D initpgm 20a overlay(USRI0300:169) D jobd 20a overlay(USRI0300:290) D text 50a overlay(USRI0300:199) D suppGrpIdx 10i 0 overlay(USRI0300:585) D suppGrp 10i 0 overlay(USRI0300:589) Here is my Prototype:- D QSYRUSRI PR ExtPgm('QSYRUSRI') D RcvVar 32767a options(*varsize) D RcvVarLen 10i 0 const D Format 8a const D UsrPrf 10a const D ErrCode 32767a options(*varsize) A: I tried your code, and I put %SIZE(USRI00300) as the second parameter, and I got zero for suppGrpIdx too. As Charles and Mark Sanderson implied, you have to make the receiver big enough to give all the information and also tell the API how big the receiver is. I'm guessing that since you defined your data structure as based, that you are setting p_usrData to some larger storage. If so, give the length of the larger storage instead of the size of USRI0300. When I set p_usrData to point to a 32767-length buffer, and put %size(buffer) as the second parameter, I got 722 for suppGrpIdx.
{ "language": "en", "url": "https://stackoverflow.com/questions/64750917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to display corresponding record from access based on other column in Datagrid in vb6 I am using Vb6 ! I have one datagrid named "Datagrid1" and i display certain contents such as subjectname, subjectcode, theory_practical from the table named "subjectcode" in Datagrid1 from access database. And i have another table named "feedetail". My doubt is, if the "theory_practical" value is theory means, then it should display the theoryfee from the table named feedetail or if "theroy_practical" value is practical means, then it should display practical fee in the new column named "Fee" in datagrid1. I am having confusion with the sql statement and displaying in datagrid ! here is my code that i used! I want to display the corresponding fee in the next column to the Theory_Practical heading ! I can't attach a screenshot file n it shows error! so here is the link of the screenshot file! Thanks in advance ! Public con As New ADODB.Connection Public rs As New ADODB.Recordset Public rs2 As New ADODB.Recordset Private Sub Command1_Click() Dim semesternew As String semesternew = semester.Caption Select Case semesternew Case "I" semester1 = 1 Case "II" semester1 = 2 Case "III" semester1 = 3 Case "IV" semester1 = 4 Case "V" semester1 = 5 Case "VI" semester1 = 6 End Select DataGrid1.ClearFields rs.Open "select Subjectcode,Subjectname,Theory_Practical from subjectcode as s where s.Degree='" & Degree & "' and s.Branch='" & course & "' and s.Year1='" & year1 & "' and s.Year2='" & year2 & "' and s.Semester='" & semester1 & "' ", con, 1, 3 Set DataGrid1.DataSource = rs End Sub Private Sub Command2_Click() examfee2.Hide examfee1.Show End Sub Private Sub Command4_Click() If rs!Theory_Practical = "theory" Then rs2.Open "select Theoryfee from Degreelevel", con, 1, 3 Set DataGrid2.DataSource = rs2 ElseIf rs!Theory_Practical = "practical" Then rs2.Open "select Practicalfee from Degreelevel", con, 1, 3 Set DataGrid2.DataSource = rs2 End If End Sub Private Sub Form_Load() Set con = New ADODB.Connection con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\college.mdb;Persist Security Info=False" con.CursorLocation = adUseClient Set rs = New ADODB.Recordset End Sub Fee table: Heading(Year1,Year2,Theoryfee,Practicalfee) values (2001,2003,440,320) All other values like this only with different values ! subjectcode table : Heading(Year1,Year2,Subjectcode,Subjectname,Theory_Practical) values (2001,2003,RCCS10CS1,C programming, Theory) A: You can use a query like so: SELECT subjectcode.Year1, subjectcode.Year2, subjectcode.Subjectcode, subjectcode.Subjectname, subjectcode.Theory_Practical, q.fee FROM subjectcode INNER JOIN ( SELECT fees.Year1, fees.Year2, "Theory" As FeeType, fees.Theoryfee As Fee FROM fees UNION ALL SELECT fees.Year1, fees.Year2, "Practical" As FeeType, fees.Practicalfee As Fee FROM fees) AS q ON (subjectcode.Theory_Practical = q.FeeType) AND (subjectcode.Year2 = q.Year2) AND (subjectcode.Year1 = q.Year1) However, you would be much better off redesigning your fees table to match the data returned by the inner sql, that is, a different line for theory and practical fees: Year1 Year2 FeeType Fee 2001 2003 Theory 440 2001 2003 Practical 320
{ "language": "en", "url": "https://stackoverflow.com/questions/14302832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJS - convert json to Model I have a json string that I need to map into a Model, I've been checking this json reader, Ext.data.reader.JsonView, but it seems that it only wokrs with a proxy, I need to pass a string (which contains the json) and map it to my model. Is that possible? Thanks, Angelo. A: Take a look on the Ext.data.model's constructor. http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.data.Model-method-constructor You can pass your data into it and it will map it to your model's fields. So you can do something like: var model = new Ext.data.model(Ext.decode(<yourJsonString>)); Ext.data.model can be replaced with your model class.
{ "language": "en", "url": "https://stackoverflow.com/questions/30182026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django pagination giving error: Caught TypeError while rendering: 'Page' object is not iterable I am using django pagination, as told in documentation: view part is : def list(request): job_list = Job.objects.all() paginator = Paginator(job_list, 25) # Show 25 jobs per page page = request.GET.get('page',1) try: jobs = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. jobs = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. jobs = paginator.page(paginator.num_pages) return render_to_response('jobs/list.html', {"jobs": jobs}) and template is: <div> {% for job in jobs %} {# Each "contact" is a Contact model object. #} {{ job.title|upper }}<br /> {% endfor %} <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?page={{ contacts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. </span> {% if contacts.has_next %} <a href="?page={{ contacts.next_page_number }}">next</a> {% endif %} </span> </div> </div> But it gives the error saying: In template d:\programming\django_projects\kaasib\templates\jobs\list.html, error at line 32 Caught TypeError while rendering: 'Page' object is not iterable I am new in django and this error seems general but very strange. Because in loop there is some other variable, not job. So please tell if anyone have any idea about it. thanks A: The error should be clear - the variable you've called jobs actually contains a Page object from the paginator. Which is as it should be, as you assigned jobs to paginator.page(x). So obviously, it contains a Page. The documentation shows what to do: {% for job in jobs.object_list %} etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/8512743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the first and last value that match condition in Google Sheets? I have a table in this format: I would like to get the first and last date (column A) that hasn't been invoiced (column E) so I can later concatenate: ="Invoice for items between " & FIRST_DATE & " and " & LAST_DATE I've tried using VLOOKUP but it appears that "" isn't interpreted as an empty match. A: I would think this would work. =TEXT(MIN(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd") and =TEXT(MAX(FILTER(1*LEFT(A2:A;10);A2:A<>"";E2:E=""));"yyyy-mm-dd") Your timestamps are coming from a system other than GoogleSheets. They need to be "forced" into numbers before they can be MIN()'d and MAX()'d. That's what 1* LEFT(... , 10) does. Then they need to get turned back into text before they're concatenated in a text string like your plan. That's what TEXT(... ,"yyyy-mm-dd") does.
{ "language": "en", "url": "https://stackoverflow.com/questions/67233562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Matplotlib drawing a line with a hint through a plot I have a pcolor in matplotlib where I would like to draw a horizontal line with a caption. So in a way, as it is drawn on the following picture: Is there a way to do that?
{ "language": "en", "url": "https://stackoverflow.com/questions/58407072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails engine extending views, not overriding I am aware that I can override an applications view from within an engine by simply creating the same file within the engine and removing it from the application (eg: 'users/show.html.erb'). However, what I want is to be able to extend the applications view, not override. Lets say I have a yield inside 'users/show.html.erb' of the main application: yield :foo What I want is for the engine to specify the same file 'users/show.html.erb' and to have a content_for block content_for :foo {} Thereby, injecting some template data from the engines view, into the applications view. Obviously, the above won't work as once it has found the template file in the application, it won't look for one in the engine. Is there a way to make this work? A: There is no way to extend views that way in Rails. You can however, accomplish this by using partials. In your engine, write a partial view file users/_show.html.erb and then render it in your app's view: # app/views/users/show # will look for a partial called "_show.html.erb" in the engine's and app's view paths. render partial: 'show' It's just as easy as your suggestion. This gem tries to implement partial extension of views, but it works similarly to what I just described: https://github.com/amatsuda/motorhead#partially-extending-views-in-the-main-app
{ "language": "en", "url": "https://stackoverflow.com/questions/44285307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Emulate Excel AverageIFs with Pandas I am trying to emulate Excel's AVERAGEIFs function in Pandas on a date range, and so far have been unsuccessful. I understand that I need to use apply and groupby, but I obviously don't have the syntax correct as I receive this error: TypeError: can only concatenate list (not "Timedelta") to list I am using test data at the moment while I try to figure out the syntax, and the data is below: For each 'Avg' column I am trying to return the average quantity for the previous 180 days as grouped by 'A' and 'B'. Therefore, I would expect the 'Avg' column in row 1 to be 1.5 ( (1+2)/2, while leaving out row 5 which is a match but is > 180 days prior). Here is the code I have at present, which does not work: import pandas as pd #Importing the dataset df = pd.read_excel('Test.xlsx', sheet_name='Sheet1') df = pd.concat([df, pd.DataFrame(columns=['Avg Qty'])], axis=1) df['Avg Qty'] = df.apply(df.groupby([(['Date'] <= (['Date']+pd.Timedelta(-1, unit='d')) >= (['Date']+pd.Timedelta(-180, unit='d'))), 'A', 'B']))['Qty'].mean() print(df.head) Any help would be greatly appreciated. A: IIUC, I think you want something like this: df['Avg Qty'] = (df.groupby([pd.Grouper(freq='180D', key='Date'),'A','B'])['Qty'] .transform('mean')) Output: Date A B Qty Cost Avg Qty 0 2017-12-11 Cancer Golf 1 100 1.5 1 2017-11-11 Cancer Golf 2 200 1.5 2 2017-11-11 Cardio Golf 2 300 2.0 3 2017-10-11 Cardio Baseball 3 600 3.0 4 2017-04-11 Cancer Golf 4 150 4.0 5 2016-01-01 Cancer Football 5 200 5.0 Edit: df = df.set_index('Date') df.groupby(['A','B']).apply(lambda x: x.sort_index().rolling('180D')['Qty'].mean()).reset_index()\ .merge(df.reset_index(), on=['Date','A','B'], suffixes=('_avg','')) Output: A B Date Qty_avg Qty Cost 0 Cancer Football 2016-01-01 5.0 5 200 1 Cancer Golf 2017-04-11 4.0 4 150 2 Cancer Golf 2017-11-11 2.0 2 200 3 Cancer Golf 2017-12-11 1.5 1 100 4 Cardio Baseball 2017-10-11 3.0 3 600 5 Cardio Golf 2017-11-11 2.0 2 300
{ "language": "en", "url": "https://stackoverflow.com/questions/47775512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Laravel - additional condition in a join using DB::raw() query I want to add an "OR" conditional to the DB::raw query join I have this query: $billings = DB::table("billings") ->select("billings.plan", "billings.email",DB::raw("COUNT(billings.plan) as total_plans") ,DB::raw("SUM(billings.amount) as total_amount")) ->join("users","users.email","=","billings.email") ->groupBy("billings.plan") ->orderByRaw('billings.plan ASC'); In it I have: ->join("users","users.email","=","billings.email") I want to use an "OR" condition: ->join("users","users.email","=","billings.email") or ->join("users","users.phone","=","billings.phone") A: try below: $billings = DB::table("billings") ->select("billings.plan", "billings.email", DB::raw("COUNT(billings.plan) as total_plans"), DB::raw("SUM(billings.amount) as total_amount")) ->join("users", function ($join) { $join->on("users.email", "=", "billings.email") ->orOn("users.phone", "=", "billings.phone") }) ->groupBy("billings.plan") ->orderByRaw('billings.plan ASC'); A: $billings = DB::table("billings") ->select("billings.plan", "billings.email",DB::raw("COUNT(billings.plan) as total_plans") ,DB::raw("SUM(billings.amount) as total_amount")) ->join("users",function($join){ $join->on("users.email","=","billings.email"); $join->orOn("users.phone","=","billings.phone"); }) ->groupBy("billings.plan") ->orderByRaw('billings.plan ASC'); A: I think for this u need to use advanced join clause. Something like this:- DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id')->orOn(...); }) ->get();
{ "language": "en", "url": "https://stackoverflow.com/questions/56477091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iTextSharp pdf Listbox form control looses right alignment I have a pdf form, and I am using pdfStamper to manipulate the values of listbox. form.SetListOption("fieldname",String[]{"one","two","three"}); form.SetListSelection("fieldname",String[]{"","",""}); The listbox alignment is set to "right". If I use a PDF editor and change the values myself, it displays correctly. If I run it through iTextSharp, the listbox is left aligned. Is this a bug, or do I need to do something else?
{ "language": "en", "url": "https://stackoverflow.com/questions/19009195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to distinguish the WM_LBUTTONUP message in a single-click event and a double-click event I want to do something when I receive the WM_LBUTTONUP message in the single-click event, but the WM_LBUTTONUP message in the double-click event should not do these things. How can I ignore it in the function OnLButtonUp() that processes the message? A: Your computer doesn't have clairvoyant super powers and thus cannot reliably predict whether any observed WM_LBUTTONUP is or isn't followed up by any WM_LBUTTONDBLCLK message. What you could do is start a timer in your WM_LBUTTONDOWN message handler with a timeout of GetDoubleClickTime, and build up a complex state machine that moves between states on WM_TIMER, WM_LBUTTONUP, and WM_LBUTTONDBLCLK messages. That's doable, but a lot more complex than you'd expect. Plus, it will necessarily introduce a delay between the user releasing the left mouse button and the action they intended to trigger starting. What you should be doing instead is solving your UX issue. If you make your single click action unrelated to your double click action, then that is the bug that needs to be addressed. Logical consequences of the way Windows converts single-clicks into double-clicks goes into much more detail, and arrives at the same conclusion: Don't, just don't do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/68540296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Android Wear emulator goes into Ambient Mode automatically I've been absent for some times from WearOS development. Now I am back and I have one annoying issue with the latest emulator - it goes automatically in Ambient Mode after few seconds. Not just my app, but the OS itself. I Checked into the settings, tried clicking on the top of the window, but no luck - is there a settings for this or I should file a bug? A: * *Set the emulator to be charging. *Make sure Settings - Developer options - Stay awake when charging is enabled.(default) PS: Click Settings - System - About - Build number quickly to enable Developer options.
{ "language": "en", "url": "https://stackoverflow.com/questions/58534295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent node.js from reading node_modules besides immediate folder Say I have this situation: node_modules/ muh_project/ node_modules/ index.js say I do this: cd muh_project && node index.js How can I prevent the node.js runtime from reading node_modules anywhere but the immediate node_modules folder? By default, Node.js will walk up the filesystem looking for node_modules until it reaches $HOME. But for a certain use case (for testing) I want to prevent that behavior. The only thing I can think of is something like this: mv_all_node_modules_dirs node muh_project mv_all_node_modules_dirs_back_to_original_name The renaming solution seems really bad, is there another way? Update: An additional constraint - I am running someone else's program with bash, so whatever I change has to be external to their program, either an env variable or changing directory names, or whatever. Modifying require() or whatnot won't work so good. A newer idea - I could change permissions, so that the program doesn't have permissions to any files below the current dir? Last time I checked *nix can't really do this (which is super lame). Here is my rename script, so you get the idea: 'use strict' const fs = require('fs'); const path = require('path'); let current = path.dirname(process.cwd()); const home = process.env.HOME; let renameThisDir = 'node_modules'; let renameTo = 'r2g_nodemodules' if(process.argv[2] === 'undo'){ // swap the variables [renameTo, renameThisDir] = [renameThisDir, renameTo]; } while (current.length >= home.length) { let nm = path.resolve(current, renameThisDir) let renamed = path.resolve(current, renameTo) fs.stat(nm, (err, stats) => { if (!(stats && stats.isDirectory())) { return; } fs.rename(nm, renamed, err => { err && console.error(err.message); }); }); current = path.join(current, '..'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/53111053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Laravel 7 change where file uploads to I have a file upload form in on of my blade files. However when I upload the file I see its saving the file to /storage//Applications/MAMP/tmp/php/phpIVfP2L.mp4 how do I set this upload to be saved to a specific location like I want them saved in the Laravel public folder that is in the Laravel root directory so the path would be /public/trainingvideos Below is my controller code where my file upload code is public function addtraining(Request $req) { //Save to a mysql database //print_r($req->input()); $pwdata = new AddTraining; $pwdata->userid = $req->userid; $pwdata->video_title = $req->trainingtitle; $pwdata->video_description = $req->trainingdesc; $pwdata->video_url = $req->trainingvideo; if($req->hasFile('trainingvideo')) { // Let's do everything here if($req->file('trainingvideo')->isValid()) { // $validated = $req->validate([ 'trainingvideo' => 'mimes:mp4,mov|max:10000', ]); $extension = $req->trainingvideo->extension(); $req->trainingvideo->storeAs('public_path()/public/trainingvideos', $req->trainingvideo.".".$extension); $url = Storage::url($req->trainingvideo.".".$extension); $pwdata->video_url = $url; //Session::flash('success', "Success!"); } } //abort(500, 'Could not upload video :('); $pwdata->save(); A: The /tmp directory is where files are temporarily stored when uploaded. In your controller you need to go about actually storing that file, the docs cover this in depth; https://laravel.com/docs/7.x/requests#storing-uploaded-files It's worth mentioning that if you leave the files in your tmp directory, they will be garbage collected at some point and so this is not a safe location to store files.
{ "language": "en", "url": "https://stackoverflow.com/questions/63368136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Only allow ajax request to fire once (like button) I have a button that on click adds 1 to a table value in my database (i.e a like button). When the user clicks the button: var button_id = $(e.target).closest('div').attr('id'); var id = button_id.substring(12); $.ajax({ method: 'POST', url: 'update_like.php', data: {id:id}, success: function(){ // }, error: function(){ // } }) update_like.php $id = mysqli_real_escape_string($conn,$_POST['id']); if (!empty($_POST)){ mysqli_query($conn,"UPDATE posts SET likes=likes+1 WHERE id='$id'"); } Q: What way can it check if they already liked it, so that they can only like the post once? I just thought of something like this: Have a column called "likers" or something similar, with a long list of user IDs who've liked the post. i.e. 5 217 16 31893 ... <-- user IDs In update_like.php, check if the user who's logged in's ID can be found within that string. Something like: $id = mysqli_real_escape_string($conn,$_POST['id']); $result = mysqli_query($conn,"SELECT likers FROM posts WHERE id='$id'"); $likers = mysqli_fetch_assoc($result); $user_id = $_SESSION['id']; // user ID if (!empty($_POST)){ if (!(preg_match("/\b$user_id\b/", $likers))){ mysqli_query($conn,"UPDATE posts SET likes=likes+1 WHERE id='$id'"); } } Is this feasible? A: You can try this: var button_id = $(e.target).closest('div').attr('id'); var id = button_id.substring(12); var idArray = []; if (idArray.indexOf(id) === -1) { ajaxCall = $.ajax({ method: 'POST', url: 'update_like.php', data: {id:id}, success: function(){ // idArray.push(id); }, error: function(){ // } }); } On server side you can try this: Assuming ID to be a comma separated list. UPDATE posts SET likes = likes+1 WHERE id = '$id' AND FIND_IN_SET('$id', listofuserid) = 0
{ "language": "en", "url": "https://stackoverflow.com/questions/30679978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Awk/Sed Solution for English/Chinese Text? I have a text file. There are hundreds of lines. Each line is either in English or in Chinese characters, but not both (there are a few exceptions but perhaps less than <10, so these are discoverable and manageable). A single line may contain multiple sentences. What I would like to end up with is two files; one in English; the other in Chinese. The lines tend to alternate languages, but not always. Sometimes there might be two lines in English, followed by one line in Chinese. Is there a way to use Sed or Awk to divide the languages into two different text files? A: This one-liner might help: awk '/[^\x00-\x7f]/{print >"cn.txt";next}{print > "en.txt"}' file It will generate two files cn.txt and en.txt. It checks if the line contains at least one non-ascii character, if found one, the line would be considered as Chinese line. Little test: kent$ cat f this is line1 in english 你好 this is line2 in english 你好你好 this is line3 in english this is line4 in english 你好你好你好 kent$ awk '/[^\x00-\x7f]/{print >"cn.txt";next}{print > "en.txt"}' f kent$ head *.txt ==> cn.txt <== 你好 你好你好 你好你好你好 ==> en.txt <== this is line1 in english this is line2 in english this is line3 in english this is line4 in english
{ "language": "en", "url": "https://stackoverflow.com/questions/32089295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use allow: options with eslintrc.js I am having the following eslintrc.js: module.exports = { extends: ['airbnb-typescript/base'], parserOptions: { project: './tsconfig.json', sourceType: 'module', }, ignorePatterns: ['*.js'], rules: { 'no-underscore-dangle': 0, ... } }; And I'd like to include some exceptions with allow: [ /** */ ]. But each time when I am adding this as a key: value property in my file, ESLint returns me an error with the following text: unable to use allow on top level. So the question is, how to achieve such results, with allow? Long story short, I am unable to use my set of rules with MongoDB _id naming, so I have ESLint just to ignore only _id in variable naming, instead of disabling the naming-convention rule itself. Is there any way to solve this problem? A: It works for me: "no-underscore-dangle": ["error", { allow: ["_id"] }] If you are using the @typescript-eslint/naming-convention rule, you may also need to add this: "@typescript-eslint/naming-convention": [ "error", { selector: ["variable"], format: ["strictCamelCase", "PascalCase", "UPPER_CASE"], filter: { regex: "^_id$", match: false, }, }, ],
{ "language": "en", "url": "https://stackoverflow.com/questions/68563727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Workarounds for the forward-declared class enumeration problem? I am maintaining a large code base and am using a combination of forward declarations and the pImpl idiom to keep compile times down and reduce dependencies (and it works really well,) The problem I have is with classes that contain public enumerations. These enumerations cannot be forward declared so I am left with no option but to include the class header. For example: // Foo.h class Foo { public: enum Type { TYPE_A, TYPE_B, }; ... }; // Bar.h #include "Foo.h" // For Foo::Type class Bar { public: void someFunction(Foo::Type type); ... }; So, I'm looking for ways to avoid this and can only think of the following: Move the class enumerations to a separate 'types' namespace // FooTypes.h namespace FooTypes { enum Type { TYPE_A, TYPE_B, }; } // Bar.h #include "FooTypes.h" class Bar { public: void someFunction(FooTypes::Type type); ... }; Use int instead of the enumeration // Bar.h class Bar { public: void someFunction(int type); ... }; What have I missed? How do other people get around this limitation (not being able to forward declare enumerations.) A: Put the enumeration in the class containing the PIMPL. A: Put the enumeration into its own type: struct FooEnum { enum Type { TYPE_A, TYPE_B, }; }; Then Foo and Bar can both access FooEnum::Type and Bar.h doesn't need to include Foo.h. A: I'd argue that enums are a bad idea to start with, but in general for constants/the many things like constants in C++ none of which are quite constants and all of which have issues. I like to put it into a struct then have the classes using it inherit from the struct. I'd also argue that the pimpl idiom is bad. Actually I am sure it's a poor way to do things. It's something that works but is awkward and a bit silly. It's also easy to avoid, and the only reason it comes about is due to people using yet other bad design choices. Usually someone just tacks on OOP stuff to a class they designed to be concrete. Then you get the mixed inheritance case and the plethora of issues it causes such as super slow compile time. Instead, consider pure virtual base classes, then writing your libs to that to avoid templates and avoid the forward declaration problem. Not for everything, but definitely for the cases where you are generating code for lots of classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/1861837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to install turtlegraphics in python I'm trying my hands on Turtle but I can't get the module installed. I have searched a lot and people seems to imply that it is included in the Python standard library with Tkinter but this doesn't seem to be the case for me. when I do: import Tkinter everything seems ok. But when I try t1 = Turtle() I get the error NameError: name 'Turtle' is not defined As per the tutorial I'm suppose to import like this: from turtlegraphics import Turtle But no matter what I've tried I cant find how I can get the library installed. A: You need to import it from the turtle module. from turtle import Turtle t1 = Turtle() t1.forward(100) A: Try to check within the library files whether there is a file called turtle in it . I had the same problem and i found the library file and opened it. So check it and see if it will fix your problem. Most probably turtle library file will be in Lib folder. A: Nothing here worked for me. This is what I did: I checked what configuration I had (in the upper right hand corner). I changed it so it was the python version that ran through the project and not just plain python. Then you also have to go to script path (also a setting in the configuation) and set it to the .py that you are working on :) A: hey all of you guys just check importing that module ,you dont get any errors its already in standard libraray
{ "language": "en", "url": "https://stackoverflow.com/questions/21476627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FireFox SDK Addon - "Detach content script" on disable/unload? I am having some issues trying to figure out how to handle the detach event when the addon is disabled and uninstalled. In main.js and my content script, I am capturing the "detach" event which fires in both cases, but the content script is not actually removed from the tab. As a result, my listeners and observers continue to fire after the addon is disabled. My understanding is that destroy() is fired and that should remove the content script, but if I look in the debugger in dev tools, the script is still listed after I disable. I can remove the listeners and the observers when handling the detach event, but my understanding was that the content script is removed during the detach so the listeners, should be removed? I also thought to just remove the content script from the DOM, but the content script is not listed if you do something like: var scripts = document.getElementsByTagName("script"); for (i=0;i<scripts.length;i++){ if(scripts[i].src == "content-script.js"){ console.log("content script found"); } } When you do the detach do you need to need to make another call to something to let it know you finished your cleanup? Anytime I capture the detach event in the main.js or my content script, it hangs when rung using cfx? Is this why its not completing the removal? A: My understanding is that destroy() is fired and that should remove the content script, but if I look in the debugger in dev tools, the script is still listed after I disable. I can remove the listeners and the observers when handling the detach event, but my understanding was that the content script is removed during the detach so the listeners, should be removed? This is a very good question. The detach event is event is meant to let you know it's time to clean your content script. Event listeners need to be removed, anything added to the window scope should also be removed, You don't need to let the main.js script know when you are done.
{ "language": "en", "url": "https://stackoverflow.com/questions/28127443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SBT maven local repository is not searched I want to load some library from local maven repostory. I have configured .sbt/0.13/plugins/plugins.sbt: resolvers += Resolver.sonatypeRepo("snapshots") resolvers += Resolver.mavenLocal addSbtPlugin("org.ensime" % "ensime-sbt" % "0.1.5-SNAPSHOT") In my project I have set this lines in build.sbt: name := "hello" version := "1.0" scalaVersion := "2.10.4" libraryDependencies += "opencv" % "opencv" % "2.4.9" libraryDependencies += "opencv" % "opencv-native" % "2.4.9" And I can't figure out why it is not working. After running sbt compile in project it logs this: [info] Resolving opencv#opencv;2.4.9 ... [info] Resolving opencv#opencv;2.4.9 ... [warn] module not found: opencv#opencv;2.4.9 [warn] ==== local: tried [warn] C:\Users\Una\.ivy2\local\opencv\opencv\2.4.9\ivys\ivy.xml [warn] ==== public: tried [warn] https://repo1.maven.org/maven2/opencv/opencv/2.4.9/opencv-2.4.9.pom [info] Resolving opencv#opencv-native;2.4.9 ... [info] Resolving opencv#opencv-native;2.4.9 ... [warn] module not found: opencv#opencv-native;2.4.9 [warn] ==== local: tried [warn] C:\Users\Una\.ivy2\local\opencv\opencv-native\2.4.9\ivys\ivy.xml [warn] ==== public: tried [warn] https://repo1.maven.org/maven2/opencv/opencv-native/2.4.9/opencv-native -2.4.9.pom [info] Resolving org.scala-lang#scala-compiler;2.10.4 ... [info] Resolving org.scala-lang#scala-reflect;2.10.4 ... [info] Resolving org.scala-lang#jline;2.10.4 ... [info] Resolving org.fusesource.jansi#jansi;1.4 ... [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: opencv#opencv;2.4.9: not found [warn] :: opencv#opencv-native;2.4.9: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: Why it could be not looking in .m2/repository as said in plugins.sbt? I have no experience with scala and sbt. A: Move maven local resolver out of plugins.sbt and into build.sbt. If you want that listed plugin to come from the snapshot resolver listed leave that in plugins.sbt otherwise remove that one as well and move to build.sbt.
{ "language": "en", "url": "https://stackoverflow.com/questions/27646685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to convert pandas str.split call to to dask I have a dask data frame where the index is a string which looks like this: 12/09/2016 00:00;32.0046;-106.259 12/09/2016 00:00;32.0201;-108.838 12/09/2016 00:00;32.0224;-106.004 (its basically a string encoding the datetime;latitude;longitude of the row) I'd like to split that while still in the dask context to individual columns representing each of the fields. I can do that with a pandas dataframe as: df['date'], df['Lat'], df['Lon'] = df.index.str.split(';', 2).str But that doesn't work in dask for several of the attempts I've tried. If I directly substitute the df for a dask df I get the error: 'Index' object has no attribute 'str' If I use the column name instead of index as: forecastDf['date'], forecastDf['Lat'], forecastDf['Lon'] = forecastDf['dateLocation'].str.split(';', 2).str I get the error: TypeError: 'StringAccessor' object is not iterable Here is an runnable example of this working in Pandas import pandas as pd df = pd.DataFrame() df['dateLocation'] = ['12/09/2016 00:00;32.0046;-106.259','12/09/2016 00:00;32.0201;-108.838','12/09/2016 00:00;32.0224;-106.004'] df = df.set_index('dateLocation') df['date'], df['Lat'], df['Lon'] = df.index.str.split(';', 2).str df.head() Here is the error I get if I directly convert that to dask import dask.dataframe as dd dd = dd.from_pandas(df, npartitions=1) dd['date'], dd['Lat'], dd['Lon'] = dd.index.str.split(';', 2).str >>TypeError: 'StringAccessor' object is not iterable A: forecastDf['date'] = forecastDf['dateLocation'].str.partition(';')[0] forecastDf['Lat'] = forecastDf['dateLocation'].str.partition(';')[2] forecastDf['Lon'] = forecastDf['dateLocation'].str.partition(';')[4] Let me know if this works for you! A: First make sure the column is string dtype forecastDD['dateLocation'] = forecastDD['dateLocation'].astype('str') Then you can use this to split in dask splitColumns = client.persist(forecastDD['dateLocation'].str.split(';',2)) You can then index the columns in the new dataframe splitColumns and add them back to the original data frame. forecastDD = forecastDD.assign(Lat=splitColumns.apply(lambda x: x[0], meta=('Lat', 'f8')), Lon=splitColumns.apply(lambda x: x[1], meta=('Lat', 'f8')), date=splitColumns.apply(lambda x: x[2], meta=('Lat', np.dtype(str)))) Unfortunately I couldn't figure out how to do it without calling compute and creating the temp dataframe.
{ "language": "en", "url": "https://stackoverflow.com/questions/45428292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Random variable not changing in "for" loop in windows batch file I'm trying to print out a Random number multiple times but in the for loop I use, it doesn't reset the variable. Here's my code. @echo off for %%i in (*.txt) do ( set checker=%Random% echo %checker% echo %%i% >> backupF ) echo Complete There are 5 text files and so I want it to print 5 different random numbers but it just prints the same random number 5 times. Any help would be greatly appreciated. Thanks! A: I'm not sure how you've been able to have it print even one random number. In your case, %checker% should evaluate to an empty string, unless you run your script more than once from the same cmd session. Basically, the reason your script doesn't work as intended is because the variables in the loop body are parsed and evaluated before the loop executes. When the body executes, the vars have already been evaluated and the same values are used in all iterations. What you need, therefore, is a delayed evaluation, otherwise called delayed expansion. You need first to enable it, then use a special syntax for it. Here's your script modified so as to use the delayed expansion: @echo off setlocal EnableDelayedExpansion for %%i in (*.txt) do ( set checker=!Random! echo !checker! echo %%i% >> backupF ) endlocal echo Complete As you can see, setlocal EnableDelayedExpansion enables special processing for the delayed expansion syntax, which is !s around the variable names instead of %s. You can still use immediate expansion (using %) where it can work correctly (basically, outside the bracketed command blocks). A: Try by calling a method. @echo off pause for %%i in (*.txt) do ( call :makeRandom %%i ) echo Complete pause :makeRandom set /a y = %random% echo %y% echo %~1 >> backupF A: on my system I have to write set checker=Random instead of set checker=!Random!
{ "language": "en", "url": "https://stackoverflow.com/questions/6500217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Issue with NSNumber -initWithDouble and resulting values I'm using NSNumber to store various values, but sometimes run into issues when doing calculations with the values and initializing new NSNumber objects for the results. I've figured out how to overcome it, but I couldn't for the life of me explain why it works and since my grasp on numerical values in computer environments (doubles, floats, etc) is weak I'd like to ask this question to learn. :-) First example is when I am converting between different units of measurement, in this particular case it's between mmol/L and mg/dl. Getting an NSNumber which represents a mmol/L value, I extract its double value and perform the calculation. Then I create a new NSNumber with -initWithDouble and return the result. However, I get odd quirks. If the mmol/L value is 10.0, the corresponding mg/dl value is 180.0 (the rate, obviously, is simply 18). But when I later need to let the user select a new value in a picker view and use the NSNumber -intValue to get the integer digits of the current value (using my own extension for getting the fractional digits), the int is 179! I've checked all the intermediate double values during calculation as well as the new NSNumber's double value and all is fine (180.00000 is the result). Interestingly, this doesn't happen for all values, just some (10.0 being one real example). The second example is when I retrieve double values from an Sqlite3 database and store them in NSNumbers. Again, most values work fine, but occasionally I get weird stuff back. For instance, if I save 6.7 in the database (checking when it is saved that that is in fact the value), what my NSNumber will show after retrieval is 6.699999. (I can't actually remember at the moment of writing if that's what's in the database as well, but I think it is - I can check later.) Both of these instances can be circumvented by using an intermediate float value and NSNumber initWithFloat instead of initWithDouble. So in my conversion, for example, I just do a float resultAsFloat = resultAsDouble and use initWithFloat for the new NSNumber. Apologies for the long-winded question and if it's just my own knowledge about working with numerical values that is lacking, but I would really appreciate if someone could explain this to me! Thanks, Anders * EDIT 1 * Code for the unit conversion example: -(NSNumber *)convertNumber:(NSNumber *)aNumber withUnit:(FCUnit *)aUnit { // if origin unit and target unit are the same, return original number if ([aUnit.uid isEqualToString:self.target.uid]) return aNumber; // determine if origin unit and target unit are comparable if (aUnit.quantity != self.target.quantity) return nil; // if so, convert the number... // get bases double originBase; double targetBase; if (aUnit.metre != nil) { originBase = [aUnit.metre doubleValue]; targetBase = [self.target.metre doubleValue]; } else if (aUnit.kilogram != nil) { originBase = [aUnit.kilogram doubleValue]; targetBase = [self.target.kilogram doubleValue]; } else if (aUnit.second != nil) { originBase = [aUnit.second doubleValue]; targetBase = [self.target.second doubleValue]; } else if (aUnit.quantity == FCUnitQuantityGlucose) { // special case for glucose if ([aUnit.uid isEqualToString:FCKeyUIDGlucoseMillimolesPerLitre]) { // mmol/L -> mg/dl originBase = 1; targetBase = 0.0555555555555556; // since 1 / 0.0555555555555556 = 18 } else if ([aUnit.uid isEqualToString:FCKeyUIDGlucoseMilligramsPerDecilitre]) { // mg/dl -> mmol/L originBase = 0.0555555555555556; targetBase = 1; } } // find conversion rate double rate = originBase / targetBase; // convert the value double convert = [aNumber doubleValue] * rate; // TMP FIX: this fixes an issue where the intValue of convertedNumber would be one less // than it should be if the number was created with a double instead of a float. I have // no clue as to why... float convertAsFloat = convert; // create new number object and return it NSNumber *convertedNumber = [[NSNumber alloc] initWithFloat:convertAsFloat]; [convertedNumber autorelease]; return convertedNumber; } A: Try using NSDecimalNumber. There's a good tutorial here: http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/ A: If I'm not wrong and if I well remember the appropriate course at college i think it's a matter of conversion from reality (where you have infinite values) to virtual (where you have finite values even if you have a lot): so you can't actually represent ALL the numbers. You also have to face with operations you're making: multiplications and divisions generate a lot of this troubles, because you'll have a lot of decimal numbers and, in my opinion, C-Based languages are not the best around to manage this kind of matter. Hoping this will point you to a better source of information :).
{ "language": "en", "url": "https://stackoverflow.com/questions/3728213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSNotifications from web Is it possible create NSNotifications in app and then from any form (apple.com) send push notifications to apps users? How can I do it? A: To push notification to users, you need a your backend environment with your certificates. You also have to receive the user device token needed to send the push notification. Here there is a complete tutorial to make all the necessary for push notifications: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1 NSNotification is another thing and is local..in your app. You can use that to generate notification in your app at certain time or when a certain event happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/23702591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google analytics: dataLayer.push not working with array of variables? I wonder why gtag.js doesn't work when push to dataLayer array of variables instead of 'arguments'? Here is some code example: window.dataLayer = window.dataLayer || [] function gtag(first: any, second: any) { window.dataLayer.push([first, second]) } gtag('js', new Date()) gtag('config', trackingCode) This only works when I replace '[first, second]' with 'arguments' A: We don't know what you're trying to achieve by overwriting the gtag function so we can't answer the specific question as to what "works" and what doesn't. What can be said: arguments is an Object and GTM expects an object from dataLayer.push, hence why this follows the intended design (whereas [first, second] is an Array and thus does not). Note that the push call in itself "works": However you won't be able to read that data via GTM which as explained above expects .push to pass Objects. If you want to use the dataLayer in a compeltely free way, you can use the GTM dataLayer helper: https://github.com/google/data-layer-helper This does support the array syntax via Meta commands: dataLayer.push(['abc.push', 4, 5, 6]); However GTM by default doesn't support reading this data (once again GTM expects an Object so it can extract values based on the object properties), so to read that data via GTM you would need to use the dataLayer helper within GTM tags and variables. A: So, at the end, this version of the code works fine for me, without linter errors: window.dataLayer = window.dataLayer || [] function gtag(..._args: unknown[]) { window.dataLayer.push(arguments) } gtag('js', new Date()) gtag('config', trackingCode)
{ "language": "en", "url": "https://stackoverflow.com/questions/60400130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i convert chr to ord? - Python in my python program i generate a list of numbers which looks like this: gen1=(random.sample(range(33,126), 8)) conv=(gen1[0:]) then that list is converted to chr like this: chr="".join([chr(i) for i in conv]) the printed result for example would look like this: `&+hs,DY Now my question is, how do i convert it back to how it was in 'conv' later on in my program, the user enters the generated key and my program need to reverse engineer it back to calculate something, i tried this: InPut=input("Please enter the key you used to encrypt the above text: ") ord_key="".join([ord for d in InPut]) but that doesnt work if there is numbers in the key that was generated earlier please help me A: You are not calling ord properly, this should do: InPut=input("Please enter the key you used to encrypt the above text: ") ord_key="".join(map(str,[ord(d) for d in InPut])) if you want to reverse the stringfied '&+hs,DY just map chr to it: reversed = map(chr, "`&+hs,DY") If you are using python 3.x transform it to a list: reversed = list(map(chr, "`&+hs,DY"))
{ "language": "en", "url": "https://stackoverflow.com/questions/34106713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Not connection with SLComposeViewController - Not share Screenshot with Facebook My code for share screenshot of my App in Facebook always shows alertView and never posts in Facebook: - (UIImage *) screenshot { AppDelegate* app = (((AppDelegate*)[UIApplication sharedApplication].delegate)); UIGraphicsBeginImageContextWithOptions(app.navController.view.bounds.size, NO, [UIScreen mainScreen].scale); [app.navController.view drawViewHierarchyInRect:app.navController.view.bounds afterScreenUpdates:YES]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } -(void)btnSharedFacebookTapped:(id)sender { [[AudioManager sharedAudioManager]playSoundEffect:kSoundGrilloMenu]; // Take screenshot if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) { AppDelegate* app = (((AppDelegate*)[UIApplication sharedApplication].delegate)); SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result) { if (result == SLComposeViewControllerResultCancelled) { NSLog(@"Cancelled"); } else { NSLog(@"Done"); } [app.navController dismissViewControllerAnimated:YES completion:Nil]; }; controller.completionHandler =myBlock; //Adding the Text to the facebook post value from iOS [controller setInitialText:@"Checkout this app xxxxxx”]; [controller addImage:[self screenshot]]; //Adding the URL to the facebook post value from iOS [controller addURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/xxxxxxx/id[xxx]?mt=8‎"]]; [app.navController presentViewController:controller animated:YES completion:Nil]; } else{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"You can't send a post right now, make sure your device has an internet connection and you have at least one Facebook account setup." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; } } A: I have created one demo APP for this. In this APP, i am posting status and uploading photo but i have never got fail error. - (IBAction)btnSocialSharing:(id)sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Social Media" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook", @"Twitter" ,nil]; // actionSheet.tag = 100; [actionSheet showInView:self.view]; } -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *buttonTitle=[actionSheet buttonTitleAtIndex:buttonIndex]; // NSString *image=[UIImage imageNamed:chooseImage]; if ([buttonTitle isEqualToString:@"Facebook"]) { SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){ if (result == SLComposeViewControllerResultCancelled) { NSLog(@"Cancelled"); } else { NSLog(@"Done"); } [controller dismissViewControllerAnimated:YES completion:nil]; }; controller.completionHandler =myBlock; [controller setInitialText:self.txtStatus.text]; [controller addImage:chooseImage]; [self presentViewController:controller animated:YES completion:nil]; } else if ([buttonTitle isEqualToString:@"Twitter"]) { SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){ if (result == SLComposeViewControllerResultCancelled) { NSLog(@"Cancelled"); } else { NSLog(@"Done"); } [controller dismissViewControllerAnimated:YES completion:nil]; }; controller.completionHandler =myBlock; [controller setInitialText:self.txtStatus.text]; [controller addImage:chooseImage]; [self presentViewController:controller animated:YES completion:nil]; } } - (IBAction)btnSelectPhoto:(id)sender { NSLog(@"Select Photos button"); UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:picker animated:YES completion:NULL]; } //Image Picker Delegate Methods - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { chooseImage = info[UIImagePickerControllerEditedImage]; [picker dismissViewControllerAnimated:YES completion:NULL]; [self displayImage]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:NULL]; } -(void)displayImage { self.viewImage.image = chooseImage; }
{ "language": "en", "url": "https://stackoverflow.com/questions/30381538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Real world example of application of the command pattern Command pattern can be used to implement Transactional behavior (and Undo). But I could not find an example of these by googling. I could only find some trivial examples of a lamp that is switched on or off. Where can I find a coding example (preferably in Java)of this/these behaviors implemented using the Command Pattern? A: public final class Ping implements Callable<Boolean> { private final InetAddress peer; public Ping(final InetAddress peer) { this.peer = peer; } public Boolean call() { /* do the ping */ ... } } ... final Future<Boolean> result = executorService.submit(new Ping(InetAddress.getByName("google.com"))); System.out.println("google.com is " + (result.get() ? "UP" : "DOWN")); A: In one of our projects, we have the following requirement: * *Create a record in DB. *Call a service to update a related record. *Call another service to log a ticket. To perform this in a transactional manner, each operation is implemented as a command with undo operation. At the end of each step, the command is pushed onto a stack. If the operation fails at some step, then we pop the commands from the stack and call undo operation on each of the command popped out. The undo operation of each step is defined in that command implementation to reverse the earlier command.execute(). Hope this helps. A: Command Patterns are used in a lot of places. * *Of course what you see everywhere is a very trivial example of GUI Implementation, switches. It is also used extensively is game development. With this pattern the user can configure his buttons on screen as well. *It is used in Networking as well, if a command has to be passed to the other end. *When the programmers want to store all the commands executed by the user, e.g. sometimes a game lets you replay the whole level. *It is used to implement callbacks. Here is a site which provides as example of command pattern used for callback. http://www.javaworld.com/article/2077569/core-java/java-tip-68--learn-how-to-implement-the-command-pattern-in-java.html?page=2 *Here's another link which shows command pattern with database. The code is in C#. http://www.codeproject.com/Articles/154606/Command-Pattern-at-Work-in-a-Database-Application A: You have to define undo(), redo() operations along with execute() in Command interface itself. example: interface ChangeI { enum State{ READY, DONE, UNDONE, STUCK } ; State getState() ; void execute() ; void undo() ; void redo() ; } Define a State in your ConcreteCommand class. Depending on current State after execute() method, you have to decide whether command should be added to Undo Stack or Redo Stack and take decision accordingly. abstract class AbstractChange implements ChangeI { State state = State.READY ; public State getState() { return state ; } public void execute() { assert state == State.READY ; try { doHook() ; state = State.DONE ; } catch( Failure e ) { state = State.STUCK ; } catch( Throwable e ) { assert false ; } } public void undo() { assert state == State.DONE ; } try { undoHook() ; state = State.UNDONE ; } catch( Failure e ) { state = State.STUCK ; } catch( Throwable e ) { assert false ; } } public void redo() { assert state == State.UNDONE ; try { redoHook() ; state = State.DONE ; } catch( Failure e ) { state = State.STUCK ; } catch( Throwable e ) { assert false ; } } protected abstract void doHook() throws Failure ; protected abstract void undoHook() throws Failure ; protected void redoHook() throws Failure { doHook() ;} ; } Have a look at this undo-redo command article for better understanding.
{ "language": "en", "url": "https://stackoverflow.com/questions/12153708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Convert a in a My code has <input class="menu_button" type="submit" value="Log in"> <a href="register.php" class="menu_button">Register</a> The a href is styled perfectly in my css while the input button with type = submit DOES NOT... How could I change Into a a href? Here is a jsfiddle. http://jsfiddle.net/26tyd/ SEE HOW THE BUTTONS LOOK different. one higher up and smaller the other is perfect. Please help me figure out how to fix this issue. A: Add this to your css: input[type=submit]{ height: 22px; line-height: 18px; cursor: pointer; } A: Instead of using height and width like you are currently doing you should use padding because then the text is vertically centred. The reason that the is not being sent is because you are not currently using a form so you need to add a form tag around the stuff that you want in the form so you could use this: <form action='#' method='get'> <input class="menu_button" type="submit" value="Log in" /> </form> Here is a working fiddle: http://jsfiddle.net/Hive7/26tyd/3/ A: You just need to add below code in your code: box-sizing: border-box; -moz-box-sizing: border-box; And to adjust the hight and with I would sugegst you to play with "min-width" and "padding". As giving "Width" and "Height" can limit your button and if you have more test or padding the height and width will not let the background increase. Please see the updated code:- .menu_button { -moz-box-shadow:inset 0px -1px 0px 0px #000000; -webkit-box-shadow:inset 0px -1px 0px 0px #000000; box-shadow:inset 0px -1px 0px 0px #000000; background-color:#000000; -webkit-border-top-left-radius:0px; -moz-border-radius-topleft:0px; border-top-left-radius:0px; -webkit-border-top-right-radius:0px; -moz-border-radius-topright:0px; border-top-right-radius:0px; -webkit-border-bottom-right-radius:0px; -moz-border-radius-bottomright:0px; border-bottom-right-radius:0px; -webkit-border-bottom-left-radius:0px; -moz-border-radius-bottomleft:0px; border-bottom-left-radius:0px; text-indent:0; border:1px solid #fa1e0f; display:inline-block; color:#ffffff; font-family:Arial; font-size:12px; font-weight:normal; font-style:normal; text-decoration:none; text-align:center; text-shadow:1px 1px 0px #33302f; box-sizing: border-box; /*ADDED*/ -moz-box-sizing: border-box; /*ADDED*/ padding:5px; } Hope this helps! A: Try margin: 0; padding: 0; white-space: normal; box-sizing: content-box; The input tags are styled different by the user agent stylesheet than a tags. A: As I understand you need to style both elements the same? Here's one solution: JSFIDDLE DEMO .menu_button { -moz-box-shadow:inset 0px -1px 0px 0px #000000; -webkit-box-shadow:inset 0px -1px 0px 0px #000000; box-shadow:inset 0px -1px 0px 0px #000000; background-color:#000000; text-indent: 0; border: 1px solid #fa1e0f; display: inline-block; color: #fff; font: normal 12px/1 Arial; width: 58px; text-decoration: none; text-align: center; vertical-align: top; text-shadow: 1px 1px 0px #33302f; padding: 5px 0; ouotline: 0 none; margin: 0; } /*this is needed for firefox and buttons */ .menu_button::-moz-focus-inner { border: 0; padding: 0; outline: none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/19054666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Azure notification hub Cannot read property 'name' of undefined Scenario I have created azure notification hub on my Visual Studio Enterprise subscription and new namespace in the azure portal according to this tutorial Problem After resources are created, I go into overview section of my notification hub in azure portal and I see error Cannot read property 'name' of undefined
{ "language": "en", "url": "https://stackoverflow.com/questions/68066870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I need to convert a Node object to a string in C I am having trouble with a homework assignment. I finished most of it, but I'm stuck at this one part. If you look at the header file, you will see a comment that says: Convert a Node object to a string. We require a pointer to the Node object so that we can display the address of the object for further reference I did as much as I could, but I don't know where to go from here. The output from this test program looks like: <0x0022ff40>[value: 2, left: 0x00000000, right: 0x00000000] <0x0022ff30>[value: 3, left: 0x00000000, right: 0x00000000] <0x0022ff20>[value: 4, left: 0x00000000, right: 0x00000000] <0x0022ff10>[value: *, left: 0x0022ff30, right: 0x0022ff20] <0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff10] Tree evaluation: 14 <0x0022ff00>[value: +, left: 0x0022ff40, right: 0x0022ff30] <0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20] Tree evaluation: 20 <0x0022ff00>[value: ., left: 0x0022ff40, right: 0x0022ff30] <0x0022ff10>[value: *, left: 0x0022ff00, right: 0x0022ff20] invalid operator: . This is my main(): #include <stdio.h> #include "TreeNode.h" int main(void) { Node n2, n3, n4, times, plus; setNode(&n2, 2, NULL, NULL, true); setNode(&n3, 3, NULL, NULL, true); setNode(&n4, 4, NULL, NULL, true); printf("\n"); setNode(&times, '*', &n3, &n4, true); setNode(&plus, '+', &n2, &times, true); printf(" Tree evaluation: %d\n\n", eval(&plus)); setNode(&plus, '+', &n2, &n3, true); setNode(&times, '*', &plus, &n4, true); printf(" Tree evaluation: %d\n\n", eval(&times)); setNode(&plus, '.', &n2, &n3, true); setNode(&times, '*', &plus, &n4, true); printf(" Tree evaluation: %d\n\n", eval(&times)); return 0; } This is my header: #include <stdio.h> #ifndef TREE_NODE #define TREE_NODE typedef struct Node_t { int value; struct Node_t *left; struct Node_t *right; } Node, *Node_p; typedef char* String; typedef enum {false, true} bool; /* * Convert a Node object to a string. * * We require a pointer to the Node object so that we can display the * address of the object for further reference. */ String nodeToString(Node_p np) { static char output[0]; sprintf(output, "<0x%d>\n", np, np->value, np->left, np->right); return output; } void setNode(Node_p np, int value, Node_p left, Node_p right, bool display) { np->value = value; np->left = left; np->right = right; if (display) { printf("%s\n", nodeToString(np)); } } int eval(Node_p np){ switch(np->value) { case '+': np->value = eval(np->left) + eval(np->right); return np->value; case '-': np->value = eval(np->left) - eval(np->right); return np->value; case '*': np->value = eval(np->left) * eval(np->right); return np->value; case '/': np->value = eval(np->left) / eval(np->right); return np->value; default: exit(1); } return 0; } #endif A: You are using the same field for operator and value in the struct Node_t. Extend your struct as this: typedef struct Node_t { int value; char op; /*operator*/ struct Node_t *left; struct Node_t *right; } Node, *Node_p; Add a new parameter to the function setNode for the operator (set it to '\0' when Node is a number; you must do the switch of eval over this operator), and add case '\0': return np->value; break; to the switch of eval.
{ "language": "en", "url": "https://stackoverflow.com/questions/23144055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery .change() For some reason this is non functional any help appreciated. <script> $(document).ready(function(){ $('select[name=materialSelect]').change(function(){ alert("Changed"); }); }); </script> <select name="materialSelect" id="materialSelect"> <option value="-1">-----Select Material-----</option> <option value="0">Material</option> </select> A: Your code doesn't have any issue, be careful that you've called your $('select[name=materialSelect]').change(function(){ alert("Changed"); }); after which your html is loaded. For sample binding the document load to a function that called your code. A: There is a on change function of jquery available already you are binding it with body load which means your select doesn't exists when you call the function, you should do this : $(document).on('change', '#materialSelect', function () { alert('changed'); }); A: Your code is fine as long as the HTML element (on which you are binding the event) is present when the binding script is running. To be on safe side, always bind to a parent element (body for example) which will delegate the event it to the child. So, try this, $('body').on('change', 'select[name=materialSelect]', function(){ alert("Changed"); }); Hope it helps. A: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> </head> <body> <select name="materialSelect" id="materialSelect"> <option value="">-----Select Material-----</option> <option value="0">Material</option> </select> <script type="text/javascript"> $(document).ready(function(){ $('select[name=materialSelect]').change(function(){ alert("Changed"); }); }); </script> </body> </html> A: First, I'd look into where jQuery is being loaded. jQuery needs to be loaded before any scripts that use it. Incorrect: <script> $('.something').change(... </script> <script src=""></script><!-- jquery --> Correct: <script src=""></script><!-- jquery --> <script> $('.something').change(... </script> Secondly, you should be using some kind of document on ready function. This will ensure your HTML is rendered before applying your events (eg "onchange") Correct: <script src=""></script><!-- jquery --> <script> $(function () { // DOM is now ready $('.something').change(... }) </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/37552222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does Swagger UI POST form data with Content-Type: undefined? I'm trying to POST form data using Swagger UI, but the request is sent with Content-Type: undefined: How can I configure it so it works? JSON POST works just fine. Here is my API definition: { "swagger": "2.0", "info": { "version": "V1", "title": "Title" }, "paths": { "/api/getcalculation": { "post": { "tags": [ "ArrearsOfPay" ], "operationId": "ApiArrearsOfPayPost", "consumes": [], "produces": [ "application/json" ], "parameters": [ { "name": "InsolvencyDate", "in": "formData", "required": false, "type": "string", "format": "date-time" }, { "name": "DismissalDate", "in": "formData", "required": false, "type": "string", "format": "date-time" }, { "name": "UnpaidPeriodFrom", "in": "formData", "required": false, "type": "string", "format": "date-time" }, { "name": "UnpaidPeriodTo", "in": "formData", "required": false, "type": "string", "format": "date-time" }, { "name": "ApClaimAmount", "in": "formData", "required": false, "type": "number", "format": "double" }, { "name": "PayDay", "in": "formData", "required": false, "type": "integer", "format": "int32" }, { "name": "ShifPattern", "in": "formData", "required": true, "type": "array", "items": { "type": "string" }, "collectionFormat": "multi" }, { "name": "WeeklyWage", "in": "formData", "required": false, "type": "number", "format": "double" }, { "name": "StatutaryMax", "in": "formData", "required": false, "type": "number", "format": "double" }, { "name": "NumberOfDaysWorkedInWeek", "in": "formData", "required": false, "type": "integer", "format": "int32" } ], "responses": { "200": { "description": "Success", "schema": { "$ref": "#/definitions/ArrearsOfPayCalculationResponseModel" } } } } } }, "definitions": { "ArrearsOfPayCalculationResponseModel": { "type": "object", "properties": { "startOfPayWeek": { "format": "date-time", "type": "string" }, "maximumLiability": { "format": "double", "type": "number" }, "employerLiability": { "format": "double", "type": "number" }, "minimumLiability": { "format": "double", "type": "number" } } } } } A: The problem is here: "consumes": [] The consumes keyword specifies the Content-Type header in requests. Since you are POSTing form data, it should be: "consumes": ["application/x-www-form-urlencoded"] Tip: You can paste your spec into http://editor.swagger.io to check for syntax errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/49844464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Remove empty array elements Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this: foreach($linksArray as $link) { if($link == '') { unset($link); } } print_r($linksArray); But it doesn't work. $linksArray still has empty elements. I have also tried doing it with the empty() function, but the outcome is the same. A: function trim_array($Array) { foreach ($Array as $value) { if(trim($value) === '') { $index = array_search($value, $Array); unset($Array[$index]); } } return $Array; } A: $out_array = array_filter($input_array, function($item) { return !empty($item['key_of_array_to_check_whether_it_is_empty']); } ); A: Just want to contribute an alternative to loops...also addressing gaps in keys... In my case, I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.) I was looking for something more like this: http://gotofritz.net/blog/howto/removing-empty-array-elements-php/ The combination of array_filter and array_slice does the trick. $example = array_filter($example); $example = array_slice($example,0); No idea about efficiencies or benchmarks but it works. A: I use the following script to remove empty elements from an array for ($i=0; $i<$count($Array); $i++) { if (empty($Array[$i])) unset($Array[$i]); } A: $my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" "); foreach ($my as $key => $value) { if (is_null($value)) unset($my[$key]); } foreach ($my as $key => $value) { echo $key . ':' . $value . '<br>'; } output 1:5 2:6 A: $myarray = array_filter($myarray, 'strlen'); //removes null values but leaves "0" $myarray = array_filter($myarray); //removes all null values A: foreach($arr as $key => $val){ if (empty($val)) unset($arr[$key]; } A: Just one line : Update (thanks to @suther): $array_without_empty_values = array_filter($array); A: You can just do array_filter($array) array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too. The other option is doing array_diff($array, array('')) which will remove elements with values NULL, '' and FALSE. Hope this helps :) UPDATE Here is an example. $a = array(0, '0', NULL, FALSE, '', array()); var_dump(array_filter($a)); // array() var_dump(array_diff($a, array(0))) // 0 / '0' // array(NULL, FALSE, '', array()); var_dump(array_diff($a, array(NULL))) // NULL / FALSE / '' // array(0, '0', array()) To sum up: * *0 or '0' will remove 0 and '0' *NULL, FALSE or '' will remove NULL, FALSE and '' A: foreach($linksArray as $key => $link) { if($link === '') { unset($linksArray[$key]); } } print_r($linksArray); A: In short: This is my suggested code: $myarray = array_values(array_filter(array_map('trim', $myarray), 'strlen')); Explanation: I thinks use array_filter is good, but not enough, because values be like space and \n,... keep in the array and this is usually bad. So I suggest you use mixture ‍‍array_filter and array_map. array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed. Samples: $myarray = array("\r", "\n", "\r\n", "", " ", "0", "a"); // "\r", "\n", "\r\n", " ", "a" $new1 = array_filter($myarray); // "a" $new2 = array_filter(array_map('trim', $myarray)); // "0", "a" $new3 = array_filter(array_map('trim', $myarray), 'strlen'); // "0", "a" (reindex) $new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen')); var_dump($new1, $new2, $new3, $new4); Results: array(5) { [0]=> " string(1) " [1]=> string(1) " " [2]=> string(2) " " [4]=> string(1) " " [6]=> string(1) "a" } array(1) { [6]=> string(1) "a" } array(2) { [5]=> string(1) "0" [6]=> string(1) "a" } array(2) { [0]=> string(1) "0" [1]=> string(1) "a" } Online Test: http://sandbox.onlinephpfunctions.com/code/e02f5d8795938be9f0fa6f4c17245a9bf8777404 A: Another one liner to remove empty ("" empty string) elements from your array. $array = array_filter($array, function($a) {return $a !== "";}); Note: This code deliberately keeps null, 0 and false elements. Or maybe you want to trim your array elements first: $array = array_filter($array, function($a) { return trim($a) !== ""; }); Note: This code also removes null and false elements. A: use array_filter function to remove empty values: $linksArray = array_filter($linksArray); print_r($linksArray); A: Remove empty array elements function removeEmptyElements(&$element) { if (is_array($element)) { if ($key = key($element)) { $element[$key] = array_filter($element); } if (count($element) != count($element, COUNT_RECURSIVE)) { $element = array_filter(current($element), __FUNCTION__); } return $element; } else { return empty($element) ? false : $element; } } $data = array( 'horarios' => array(), 'grupos' => array( '1A' => array( 'Juan' => array( 'calificaciones' => array( 'Matematicas' => 8, 'Español' => 5, 'Ingles' => 9, ), 'asistencias' => array( 'enero' => 20, 'febrero' => 10, 'marzo' => '', ) ), 'Damian' => array( 'calificaciones' => array( 'Matematicas' => 10, 'Español' => '', 'Ingles' => 9, ), 'asistencias' => array( 'enero' => 20, 'febrero' => '', 'marzo' => 5, ) ), ), '1B' => array( 'Mariana' => array( 'calificaciones' => array( 'Matematicas' => null, 'Español' => 7, 'Ingles' => 9, ), 'asistencias' => array( 'enero' => null, 'febrero' => 5, 'marzo' => 5, ) ), ), ) ); $data = array_filter($data, 'removeEmptyElements'); var_dump($data); ¡it works! A: As per your method, you can just catch those elements in an another array and use that one like follows, foreach($linksArray as $link){ if(!empty($link)){ $new_arr[] = $link } } print_r($new_arr); A: I think array_walk is much more suitable here $linksArray = array('name', ' ', ' 342', '0', 0.0, null, '', false); array_walk($linksArray, function(&$v, $k) use (&$linksArray){ $v = trim($v); if ($v == '') unset($linksArray[$k]); }); print_r($linksArray); Output: Array ( [0] => name [2] => 342 [3] => 0 [4] => 0 ) * *We made sure that empty values are removed even if the user adds more than one space *We also trimmed empty spaces from the valid values *Finally, only (null), (Boolean False) and ('') will be considered empty strings As for False it's ok to remove it, because AFAIK the user can't submit boolean values. A: As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you: print_r(array_filter($linksArray)); Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback: // PHP 7.4 and later print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== '')); // PHP 5.3 and later print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; })); // PHP < 5.3 print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";'))); Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray)); A: You can use array_filter to remove empty elements: $emptyRemoved = array_filter($linksArray); If you have (int) 0 in your array, you may use the following: $emptyRemoved = remove_empty($linksArray); function remove_empty($array) { return array_filter($array, '_remove_empty_internal'); } function _remove_empty_internal($value) { return !empty($value) || $value === 0; } EDIT: Maybe your elements are not empty per se but contain one or more spaces... You can use the following before using array_filter $trimmedArray = array_map('trim', $linksArray); A: The most popular answer on this topic is absolutely INCORRECT. Consider the following PHP script: <?php $arr = array('1', '', '2', '3', '0'); // Incorrect: print_r(array_filter($arr)); // Correct: print_r(array_filter($arr, 'strlen')); Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug. Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean. So, the absolute, definitive, correct answer is: $arr = array_filter($arr, 'strlen'); A: If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function: array_values(array_filter($array)); Also see: PHP reindex array? A: The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here's a thorough explanation: What does empty mean? First of all, we must agree on what empty means. Do you mean to filter out: * *the empty strings only ("")? *the strictly false values? ($element === false) *the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...) *the equivalent of PHP's empty() function? How do you filter out the values To filter out empty strings only: $filtered = array_diff($originalArray, array("")); To only filter out strictly false values, you must use a callback function: $filtered = array_diff($originalArray, 'myCallback'); function myCallback($var) { return $var === false; } The callback is also useful for any combination in which you want to filter out the "falsey" values, except some. (For example, filter every null and false, etc, leaving only 0): $filtered = array_filter($originalArray, 'myCallback'); function myCallback($var) { return ($var === 0 || $var === '0'); } Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default: $filtered = array_filter($originalArray); A: $a = array(1, '', '', '', 2, '', 3, 4); $b = array_values(array_filter($a)); print_r($b) A: For multidimensional array $data = array_map('array_filter', $data); $data = array_filter($data); A: $linksArray = array_filter($linksArray); "If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php A: I had to do this in order to keep an array value of (string) 0 $url = array_filter($data, function ($value) { return (!empty($value) || $value === 0 || $value==='0'); }); A: With these types of things, it's much better to be explicit about what you want and do not want. It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer. Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed. In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values. Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop. <?php $xs = [0, 1, 2, 3, "0", "", false, null]; $xs = array_filter($xs, function($x) { if ($x === null) { return false; } if ($x === false) { return false; } if ($x === "") { return false; } if ($x === "0") { return false; } return true; }); $xs = array_values($xs); // reindex array echo "<pre>"; var_export($xs); Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution. See this example and the inline comments for the output. <?php /** * @param string $valueToFilter * * @return \Closure A function that expects a 1d array and returns an array * filtered of values matching $valueToFilter. */ function filterValue($valueToFilter) { return function($xs) use ($valueToFilter) { return array_filter($xs, function($x) use ($valueToFilter) { return $x !== $valueToFilter; }); }; } // partially applied functions that each expect a 1d array of values $filterNull = filterValue(null); $filterFalse = filterValue(false); $filterZeroString = filterValue("0"); $filterEmptyString = filterValue(""); $xs = [0, 1, 2, 3, null, false, "0", ""]; $xs = $filterNull($xs); //=> [0, 1, 2, 3, false, "0", ""] $xs = $filterFalse($xs); //=> [0, 1, 2, 3, "0", ""] $xs = $filterZeroString($xs); //=> [0, 1, 2, 3, ""] $xs = $filterEmptyString($xs); //=> [0, 1, 2, 3] echo "<pre>"; var_export($xs); //=> [0, 1, 2, 3] Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you. <?php /** * Supply between 1..n functions each with an arity of 1 (that is, accepts * one and only one argument). Versions prior to php 5.6 do not have the * variadic operator `...` and as such require the use of `func_get_args()` to * obtain the comma-delimited list of expressions provided via the argument * list on function call. * * Example - Call the function `pipe()` like: * * pipe ($addOne, $multiplyByTwo); * * @return closure */ function pipe() { $functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo] return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1 return array_reduce( // chain the supplied `$arg` value through each function in the list of functions $functions, // an array of functions to reduce over the supplied `$arg` value function ($accumulator, $currFn) { // the reducer (a reducing function) return $currFn($accumulator); }, $initialAccumulator ); }; } /** * @param string $valueToFilter * * @return \Closure A function that expects a 1d array and returns an array * filtered of values matching $valueToFilter. */ function filterValue($valueToFilter) { return function($xs) use ($valueToFilter) { return array_filter($xs, function($x) use ($valueToFilter) { return $x !== $valueToFilter; }); }; } $filterer = pipe( filterValue(null), filterValue(false), filterValue("0"), filterValue("") ); $xs = [0, 1, 2, 3, null, false, "0", ""]; $xs = $filterer($xs); echo "<pre>"; var_export($xs); //=> [0, 1, 2, 3] A: try this ** **Example $or = array( 'PersonalInformation.first_name' => $this->request->data['User']['first_name'], 'PersonalInformation.last_name' => $this->request->data['User']['last_name'], 'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'], 'PersonalInformation.dob' => $this->request->data['User']['dob'], 'User.email' => $this->request->data['User']['email'], ); $or = array_filter($or); $condition = array( 'User.role' => array('U', 'P'), 'User.user_status' => array('active', 'lead', 'inactive'), 'OR' => $or );
{ "language": "en", "url": "https://stackoverflow.com/questions/3654295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1002" }
Q: Do...while is not working in input verification So I'm trying to do an input verification for my program in java, and I'm trying to do that in this setter: public void setClientName(String clientName) { boolean valid; do{ valid = false; try{ if(clientName.matches("[a-zA-Z]+")){ this.clientName = clientName; }else{ throw new IllegalArgumentException("Invalid client name"); } }catch(Exception e){ System.out.println("Invalid name"); valid = true; } }while(!valid); } But when I call it and put a wrong name, the do...while does not work and the program just continue Here's where I call it public void openAccount(int i){ nCartao = 2021120040 + i; System.out.println("Account Number : " + (nCartao)); System.out.println("Client Name :"); setClientName(sc.next()); // I CALL IT HERE System.out.println("Client Age : "); age = sc.nextInt(); System.out.println("Balance :"); balance = sc.nextInt(); } What am I doing wrong? A: Maybe that's because in your catch you are stating that valid is true when it should be false to repeat the block.
{ "language": "en", "url": "https://stackoverflow.com/questions/72110164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Deedle Frame From Database, What is the Schema? I am new to Deedle, and in documentation I cant find how to solve my problem. I bind an SQL Table to a Deedle Frame using the following code: namespace teste open FSharp.Data.Sql open Deedle open System.Linq module DatabaseService = [<Literal>] let connectionString = "Data Source=*********;Initial Catalog=*******;Persist Security Info=True;User ID=sa;Password=****"; type bd = SqlDataProvider< ConnectionString = connectionString, DatabaseVendor = Common.DatabaseProviderTypes.MSSQLSERVER > type Database() = static member contextDbo() = bd.GetDataContext().Dbo static member acAgregations() = Database.contextDbo().AcAgregations |> Frame.ofRecords static member acBusyHourDefinition() = Database.contextDbo().AcBusyHourDefinition |> Frame.ofRecords "alternative_reference_table_scan", "formula"] static member acBusyHourDefinitionFilterByTimeAgregationTipe(value:int) = Database.acBusyHourDefinition() |> Frame.getRows These things are working properly becuse I can't understand the Data Frame Schema, for my surprise, this is not a representation of the table. My question is: how can I access my database elements by Rows instead of Columns (columns is the Deedle Default)? I Thied what is showed in documentation, but unfortunatelly, the columns names are not recognized, as is in the CSV example in Deedle Website. A: With Frame.ofRecords you can extract the table into a dataframe and then operate on its rows or columns. In this case I have a very simple table. This is for SQL Server but I assume MySQL will work the same. If you provide more details in your question the solution can narrowed down. This is the table, indexed by ID, which is Int64: You can work with the rows or the columns: #if INTERACTIVE #load @"..\..\FSLAB\packages\FsLab\FsLab.fsx" #r "System.Data.Linq.dll" #r "FSharp.Data.TypeProviders.dll" #endif //open FSharp.Data //open System.Data.Linq open Microsoft.FSharp.Data.TypeProviders open Deedle [<Literal>] let connectionString1 = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\userName\Documents\tes.sdf.mdf" type dbSchema = SqlDataConnection<connectionString1> let dbx = dbSchema.GetDataContext() let table1 = dbx.Table_1 query { for row in table1 do select row} |> Seq.takeWhile (fun x -> x.ID < 10L) |> Seq.toList // check if we can connect to the DB. let df = table1 |> Frame.ofRecords // pull the table into a df let df = df.IndexRows<System.Int64>("ID") // if you need an index df.GetRows(2L) // Get the second row, but this can be any kind of index/key df.["Number"].GetSlice(Some 2L, Some 5L) // get the 2nd to 5th row from the Number column Will get you the following output: val it : Series<System.Int64,float> = 2 -> 2 > val it : Series<System.Int64,float> = 2 -> 2 3 -> 3 4 -> 4 5 -> 5 Depending on what you're trying to do Selecting Specific Rows in Deedle might also work. Edit From your comment you appear to be working with some large table. Depending on how much memory you have and how large the table you still might be able to load it. If not these are some of things you can do in increasing complexity: * *Use a query { } expression like above to narrow the dataset on the database server and convert just part of the result into a dataframe. You can do quite complex transformations so you might not even need the dataframe in the end. This is basically Linq2Sql. *Use lazy loading in Deedle. This works with series so you can get a few series and reassemble a dataframe. *Use Big Deedle which is designed for this sort of thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/38667991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom cell in list in Flash AS3 I am no expert in Flash, and I need some quick help here, without needing to learn everything from scratch. Short story, I have to make a list where each cell contains an image, two labels, and a button. List/Cell example: img - label - label - button img - label - label - button As a Java-programmer, I have tried to quicly learn the syntax and visualness of Flash and AS3, but with no luck so far. I have fairly understood the basics of movie clips etc. I saw a tutorial on how to add a list, and add some text to it. So I dragged in a list, and in the code went list.addItem({label:"hello"}); , and that worked ofc. So i thought if I double-clicked the MC of the list, i would get to tweak some things. In there I have been wandering around different halls of cell-renderers etc. I have now come to the point that I entered the CellRenderer_skinUp or something, and customized it to my liking. When this was done, I expected i could use list.addItem(); and get an empty "version" of my cell, with the img, labels and the button. But AS3 expects an input in addItem. From my object-oriented view, I am thinking that i have to create an object of the cell i have made, but i have no luck reaching it.. I tried to go var test:CellRenderer = list.listItem; list.addItem(test); ..But with no luck. This is just for funsies, but I really want to make this work, however not so much that I am willing to read up on ALOT of Flash and AS3. I felt that I was closing in on the prize, but the compiler expected a semicolon after the variable (list.addItem({test:something});). Note: If possible, I do NOT want this: list.addItem({image:"src",label:"text",label"text",button:"text"}); Well.. It actually is what I want, but I would really like to custom-draw everything. Does anyone get what I am trying to do, and has any answers for me? Am I approaching this the wrong way? I have searched the interwebs for custom list-cells, but with no luck. Please, any guiding here is appreciated! Sti A: You could use a Datagrid as well, with each column pointing to the appropriate part of the data source (possibly even the same field, depending on what you're doing). You can then just use the ImageCell as the renderer for the second and third colums. I think you're just not understanding that Adobe, in the own woolly-headed little way, is separating the Model from the View on your behalf. You hand the Model to the View and then get out of the way. The extent of what you can/should change is just telling it what renderer to pop your data into. In fact, the fl.controls don't give you much control at all about how they work--I wouldn't go down the road of trying to create a custom itemRenderer with any signifcant functionality for them if you don't fully understand how the Display List works and if you're not comfortable digging around in the debugger and ferreting out all kinds of undocumented information. For more details (to the extent anyone knows anything about how these work), see http://www.adobe.com/devnet/flash/quickstart/datagrid_pt1.html http://www.adobe.com/devnet/flash/quickstart/datagrid_pt2.htmlhttp://www.adobe.com/devnet/flash/quickstart/datagrid_pt3.html http://www.adobe.com/devnet/flash/quickstart/tilelist_component_as3.html Do you have the option to use the Flex Framework instead of pure Flash? It makes this kind of extension much more satisfying. It's aimed more at application developers, whereas Adobe sees Flash users more as designers.
{ "language": "en", "url": "https://stackoverflow.com/questions/11303795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fragment Missing From Product I created a localization fragment for one of our projects which works nicely when started from the IDE, but not at all when started from the exported product. The fragment itself only really has two files, a MANIFEST.MF: Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: L10N Fragment Bundle-SymbolicName: org.acme.module.nl_xx;singleton:=true Bundle-Version: 3.0.6.qualifier Bundle-Vendor: ACME Fragment-Host: org.acme.module;bundle-version="[1.0.0,2.0.0)" Bundle-RequiredExecutionEnvironment: JavaSE-11 ...and a properties file messages&lowbar;de&lowbar;de&lowbar;xx.properties: Special = Something The product is started with -nl de_DE_XX and -Djava.language=de -Djava.country=DE -Djava.variant=XX. As noted, it works from Eclipse, but not from the finished EXE. Things I tried to debug / fix: * *made sure the exported product contains the fragment *made sure the build.properties / fragment JAR contains the above two files *played around with the country and variant (toggled upper and lower case) *cleared the OSGi instance area (i.e. the application preferences) *made sure the fragment is resolved using the OSGi console *tested it with a messages file for en_UK_XX (which is based on the English localization instead of the German one) *made sure that the files configuration\org.eclipse.equinox.simpleconfigurator\bundles.info and artifacts.xml contain something that looks plausible for the fragment Nothing worked, so I'm out of ideas. What could be the problem? What can I do to debug the application? A: This is an incredible stupid problem. The messages file is supposed to have the name messages&lowbar;de&lowbar;DE&lowbar;XX.properties (note that the last two segments are in upper case). My guess is it works when started from the IDE because Eclipse uses the filesystem and hence the OS standard, which is "ignore casing" for Windows. When started from the finished product however the files are in JARs, where casing is important.
{ "language": "en", "url": "https://stackoverflow.com/questions/58199414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display or get the HTTP header attributes in Rails 4 I have an application developed in Rails and I am trying to see the attributes in the HTTP header. Is there any way to read these attributes? Where are they stored? Someone mentioned request.headers. Is this correct? I am not able to see any attributes inside this array. A: This code solved my question request.env["HTTP_MY_HEADER"]. The trick was that I had to prefix my header's name with HTTP A: I've noticed in Rails 5 they now expect headers to be spelled like this in the request: Access-Token Before they are transformed into: HTTP_ACCESS_TOKEN In Rails. Doing ACCESS_TOKEN will no longer work. A: request.headers does not return a hash, but an instance of ActionDispatch::Http::Headers, which is a wrapper around rack env. ActionDispatch::Http::Headers implements many methods like [] and []= which make it behave like a hash, but it doesn't override the default inspect, hence you can't see the key-value pairs by just p or pp it. You can, however, see the request headers in the rack env: pp request.headers.env.select{|k, _| k =~ /^HTTP_/} Remember that the request headers in rack env are the upcased, underscored and HTTP_ prefixed version of the original http request headers. UPDATE Actually there are a finite set of request headers that are not prefixed HTTP_. These (capitalized and underscored) header names are stored in ActionDispatch::Http::Headers::CGI_VARIABLES. I list them below: AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE GATEWAY_INTERFACE HTTPS PATH_INFO PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE So the full version of listing request headers would be pp request.headers.env.select{|k, _| k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES) || k =~ /^HTTP_/} A: You can see hash of actual http headers using @_headers in controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/32405155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Finding files in list using bash array loop I'm trying to write a script that reads a file with filenames, and outputs whether or not those files were found in a directory. Logically I'm thinking it goes like this: $filelist = prompt for file with filenames $directory = prompt for directory path where find command is performed new Array[] = read $filelist line by line for i, i > numberoflines, i++ if find Array[i] in $directory is false echo "$i not found" export to result.txt I've been having a hard time getting Bash to do this, any ideas? A: First, I would just assume that all the file-names are supplied on standard input. E.g., if the file names.txt contains the file-names and check.sh is the script, you can invoke it like cat names.txt | ./script.sh to obtain the desired behaviour (i.e., using the file-names from names.txt). Second, inside script.sh you can loop as follows over all lines of the standard input while read line do ... # do your checks on $line here done Edit: I adapted my answer to use standard input instead of command line arguments, due to the problem indicated by @rici. A: while read dirname do echo $dirname >> result.txt while read filename do find $dirname -type f -name $filename >> result.txt done <filenames.txt done <dirnames.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/18008147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force browser to display ISO-8859-1 without interpreting as Windows-1252 Historically, a lot of web pages advertising themselves as being in the ISO-8859-1 (Latin-1) encoding actually contained content in the Windows-1252 encoding (which is a strict superset of Latin-1). This was enough of a problem that browsers updated their behaviour to treat all Latin-1 text as if it were Windows-1252. This behaviour was then rationalised into the HTML5 [draft] standard. I'm writing a set of pages on which I want to show the difference between the two encodings, however this seems to be impossible because my Latin-1 page is never actually treated as Latin-1. Is there any way, in any browser, that I can actually force the page encoding to be respected and display the demo? A: I’m afraid there is no direct way. I thought Opera once had an option for this, and its current version has an option (via opera:config) to force a specific encoding, overriding HTTP headers and all, but even there, iso-8859-1 actually means windows-1252. I checked Opera versions 5 and 9 too, no luck. But using the current version of Opera (12.02), you can set the encoding via View → Encoding, and in the “Western” set (where iso-8859-1 means windows-1252 as usual), selecting iso-8859-15 causes the range 130–159 (decimal) of bytes to be effectively ignored in display, not shown as per windows-1252. So this more or less means treating the data as genuinely iso-8859-1 – except of course that the few graphic characters where iso-8859-1 and iso-8859-15 differ, the latter is used. Technically, those bytes represent C1 Controls in iso-8859-1, and in the mode described above, Opera actually treats them that way. They are disallowed in HTML but normally just ignored by browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/13280125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cross browser video autoplay loop I have a copy of a mp4 video which I want to show on my website and I want to know how is it possible with javascript to autoplay and loop for ever the video. I want to make it compatible with all browsers. I want to load the video on load of the page with js Thank you. A: <video autoplay loop> <source src="movie.mp4" type="video/mp4" /> <source src="movie.ogg" type="video/ogg" /> </video> You mean this? A: You’ll need to mute the video (adding the muted attribute on the <video> tag) as videos with sound don’t autoplay in all browsers. Then also add the attributes autoplay and playsinline. Also you can use the videoEnd event and call play() to ensure it loops.
{ "language": "en", "url": "https://stackoverflow.com/questions/55052386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON_QUERY unable to handle NULL I have a table. Few columns are of String, Integer type. And few are JSON type. I am writing a query to form each row as a json object. I have issues with JSON_QUERY(jsondataColumnName). If the column is populated NULL JSON_QUERY fails. I have already written query below. select ( SELECT [customerReferenceNumber] as customerReferenceNumber ,[customerType] as customerType ,[personReferenceNumber] as personReferenceNumber ,[organisationReferenceNumber] as organisationReferenceNumber ,json_query(isnull(product,'')) as product ,json_query(isnull([address],'')) as address FROM [dbo].[customer] FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS customer from [dbo].[customer] P Msg 13609, Level 16, State 1, Line 2 JSON text is not properly formatted. Unexpected character '.' is found at position 0. A: By default, for JSON don't work with NULL VALUES. Use INCLUDE_NULL_VALUES to handle. As Example: JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES) AS customer As reference: https://learn.microsoft.com/en-us/sql/relational-databases/json/include-null-values-in-json-include-null-values-option?view=sql-server-ver15
{ "language": "en", "url": "https://stackoverflow.com/questions/56935361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to display PDFs and images in Firebase Storage I would like to use FirebaeStorage to display PDFs and images. ↓The code below is the code to display the file list (I was able to get the data from Firebase and display the List.) class Gakubu extends StatefulWidget { const Gakubu({Key? key}) : super(key: key); @override State<Gakubu> createState() => _GakubuState(); } class _GakubuState extends State<Gakubu> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('学部'), ), body: Container( child: ListView( children: [ Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('工学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => kougaku(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('情報理工学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => zyouhourikou(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('教育学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => kyouiku(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('獣医学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => zyuui(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('理学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => rigaku(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('生命科学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => seimei(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('生物地球学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => seibutu(), ) ), ), ), Card( child: ListTile( leading: Icon(Icons.folder), trailing: Icon(Icons.chevron_right), title: Text('経営学部'), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => keiei(), ) ), ), ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { //ポップアップメニュー実装 showModalBottomSheet( //モーダルの背景の色、透過 backgroundColor: Colors.transparent, //ドラッグ可能にする(高さもハーフサイズからフルサイズになる様子) isScrollControlled: true, context: context, builder: (BuildContext context) { return Container( margin: EdgeInsets.only(top: 150), decoration: BoxDecoration( //モーダル自体の色 color: Colors.white, //角丸にする borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20), ), ), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( '過去問をアップロード', style: TextStyle( fontSize: 25, color: Colors.black, fontWeight: FontWeight.bold, ), ), Padding( padding: const EdgeInsets.all(8.0), //マージン child: SizedBox( width: double.infinity, height: 50, child: ElevatedButton.icon( icon: Icon(Icons.photo_library), label: Text( 'アルバムから選択', textAlign: TextAlign.left, ), onPressed: () {}, ), ), ), Padding( padding: const EdgeInsets.all(8.0), //マージン child: SizedBox( width: double.infinity, height: 50, child: ElevatedButton.icon( icon: Icon(Icons.camera), label: Text( '写真を撮る', textAlign: TextAlign.left, ), onPressed: () {}, ), ), ), Padding( padding: const EdgeInsets.all(8.0), //マージン child: SizedBox( width: double.infinity, height: 50, child: ElevatedButton.icon( icon: Icon(Icons.folder), label: Text( '複数以上のファイル', textAlign: TextAlign.left, ), onPressed: () => launch( 'https://docs.google.com/forms/d/e/1FAIpQLSda45WF5uVd9mRFs_4nPCiM6bxFqpUKZSApYFWUVlAVtDlg_g/viewform?usp=sf_link')), ), ), Padding( padding: const EdgeInsets.all(8.0), //マージン child: SizedBox( width: double.infinity, height: 50, child: ElevatedButton.icon( icon: Icon(Icons.link), label: Text( 'ドライブなどのURL', textAlign: TextAlign.left, ), onPressed: () => launch( 'https://docs.google.com/forms/d/e/1FAIpQLSdEIS3eOynTihQ3AEk0zrp7mSpmcfqpEGxTOUIDp6Mzi19jqA/viewform?usp=sf_link')), ), ), Text( 'アップロードあざます!', style: TextStyle( fontSize: 20, color: Colors.black, ), ), ], ), ); }); }, child: const Icon(Icons.upload_rounded), ) , ); } } This code is for displaying images and PDFs. (This code can only display PDFs.) class ImagePage extends StatelessWidget { final FirebaseFile file; const ImagePage({ Key? key, required this.file, }) : super(key: key); @override Widget build(BuildContext context) { final isImage = ['.jpeg', '.jpg', '.png'].any(file.name.contains); final isPdf = ['.pdf'].any(file.name.contains); return Scaffold( appBar: AppBar( title: Text(file.name), centerTitle: true, ), body: SfPdfViewer.network( file.url ), ); } } final isImage = ['.jpeg', '.jpg', '.png'].any(file.name.contains); final isPdf = ['.pdf'].any(file.name.contains); Here I would like to have the process change depending on the file extension. for example sfpdfview for PDF imageview for image Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/73081624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ImportError: No module named django.core.wsgi for wsgi server setting I am setting with djano and uwsgi $uwsgi --ini uwsgi.ini My Django root is here /var/www/html/myapp/current It must be quite simple setting however I am not sure the yet. I have these two files /var/www/html/myapp/current/myapp/settings.py /var/www/html/myapp/current/myapp/wsgi.py [uwsgi] chdir=/var/www/html/myapp/current #it success module=myapp.wsgi:application #it success env DJANGO_SETTINGS_MODULE=myapp.settings # it success http-socket = 0.0.0.0:8008 processes = 1 threasds = 1 master = 1 max-requests = 100000 The error is below, but I can't dig the detailed logs. spawned uWSGI worker 1 (pid: 27353, cores: 1) --- no python application found, check your startup logs for errors --- [pid: 27353|app: -1|req: -1/1] 172.17.1.143 () {28 vars in 334 bytes} [Thu Mar 26 17:37:01 2020] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) And this error occurs. *** Operational MODE: single process *** Traceback (most recent call last): File "./myapp/wsgi.py", line 13, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 1705) spawned uWSGI worker 1 (pid: 1706, cores: 1) spawned uWSGI http 1 (pid: 1707) error happens here from django.core.wsgi import get_wsgi_application Also I am using anaconda3 $conda activate py37 then start this command $uwsgi --ini uwsgi.ini A: I solved the problem , the problem was uwsgi itself. My setting file was ok. install uwsgi by conda conda install -c conda-forge libiconv conda install -c conda-forge uwsgi then start uwsgi /home/ubuntu/anaconda3/envs/py37/bin/uwsgi --ini uwsgi.ini
{ "language": "en", "url": "https://stackoverflow.com/questions/60873411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add style to bundled code using webpack GitHub: https://github.com/Chirag161198/react-boilerplate 1 Here is the react boilerplate I’m trying to make from scratch. I have bundled html with the react code but I’m not able to add styles (CSS). I have heard about ExtractTextPlugin but not able to configure it. Please suggest some way to add styles to it. Thank you in advance. A: You need to use style-loader and css-loader in your webpack.config.js First, install these two packages via npm: npm install style-loader, css-loader --dev Then, create a styles.css in your src folder and append the following styles into the file (just for demo purpose, so you know it's working correctly): body { background-color: #ff4444; } Don't forget to import the css file in your src/index.js: import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App.js'; import './styles.css'; // <- import the css file here, so webpack will handle it when bundling ReactDOM.render(<App />, document.getElementById('app')); And use style-loader and css-loader in your webpack.config.js: const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' }, }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', }), ], }; If you don't see the correct output, you might need to restart the webpack dev server again. I have cloned your repo and made the changes like I mentioned above, it works. As for ExtractTextPlugin, you will need this when bundling for a production build, you can learn more from their Repo Hope it helps! A: Hi Chirag ExtractTextPlugin works great but when it comes to caching and bundle hashing. Css bundle becomes 0 bytes. So they introduced MiniCssExtractPlugin which has tackled this issue. It is really important to cache static files as your app size increase by time. import plugin first: var MiniCssExtractPlugin = require("mini-css-extract-plugin"); add these in your webpack config: rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.scss$/, use: [ 'style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'] } ] } plugins: [ new MiniCssExtractPlugin({ filename: 'style.css', }), new HtmlWebpackPlugin({ template: './src/index.html', }), Let me know you the issue still persists. A: first you need to load style-loader and css-loader.Then you will add the following code in "rules" in webpack.config.js file. { test: /\.css$/,use: ['style-loader', 'css-loader']} then import the "style.css" file location into the "index.js" file and for example: import "./style.css"; When you package, "css" codes will be added in "bundle.js".
{ "language": "en", "url": "https://stackoverflow.com/questions/52000497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: MS Access: Report to contain info from third table I'm currently working on a database for a company, for them to use when making production orders. A report is to be made consisting of several things, mainly product number, order number etc etc. A part of the report is to be made up of a list of spare parts needed for the production of the item in question. I have a table with an order number and product number, which needs to look in another table to find the necessary spare parts. However, the name, location and stock of those spare parts are in a third table, and I can't seem to find a way to include these things automatically when the product number is known. I'm pretty new to MS Access, so any help will be greatly appreciated. Thanks! I have a table called Table1, which uses a combobox to automatically fill boxes such as production time, test time etc from a given product number. This data is gathered from the second table StandardTimes, which has as a primary key the product number. Other columns in this table includes production area, standard quantity, average production time, and also includes in several columns, the necessary spare parts needed. In a third table called Inventory, we have the product numbers of the spare parts, their location in storage, and number of items currently in store. I created a report using a query which takes an order number, and creates a report on that order number from Table1. What needs to be included in this report is a list of the spareparts necessary, the location in the storage, and the number of items currently in store. Revised from new user input Your question still does not provide actual columns or data. As a result, it's hard to model your needs. However, based on what I can read, I think that you have are missing some basic design setup items in a relational model. Assuming that you have 3 tables: Table1 (Orders), StandardTimes (Products) and Inventory (SpareParts) In English, every order has one or more products. Every product has one or more spare parts. Really you'd want an orders table, and an order details table which has records for each item as part of that order. But I'm answering it on your setup which I believe is flawed. Orders <-(1:M)-> Products <- (1:M) -> SpareParts You have an OrderID, a ProductID, and a SparePartID. A query such as this would join those 3 tables together with that kind of relationship. SELECT o.OrderNum, o.ProductNum, st.ProductionArea, st.StandardQuality, i.SparePartsNum, i.Location, i.Qty FROM Orders as o INNER JOIN StanardTimes as st on o.ProductNum = st.ProductNum INNER JOIN Inventory as i on i.ProductNum = st.ProductNum A: Some sample data would be helpful to help design the queries. In principal you would need to join the tables together to get the desired result. You would join the productID on tblOrders to the ProductID on tblProducts. This will net you the name of the product etc. This would be an INNER join, as every order has a product. You would then join to tblSpareParts, also using the productID so that you could return the status of the spare parts for that product. This might be a LEFT JOIN instead of an INNER, but it depends on if you maintain a value of 0 for spare parts (e.g. Every product has a corresponding spare parts record), or if you only maintain a spare parts record for items which have spare parts.
{ "language": "en", "url": "https://stackoverflow.com/questions/31166607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cgridveiw to display fetched data via customized query I am a newbei in yii, when a person clicks on a category display him all products under that particular category in a gridview view productcategory <?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'admin-grid', 'dataProvider'=>$model->SelectedCategoryProducts, 'filter'=>$model, 'columns'=>array( 'Name', 'Model', 'Brand', 'Price', array( 'class'=>'CButtonColumn', ), ), )); ?> controller product public function actionProductcategory($id) { $model= Product::model()->SelectedCategoryProducts($id); var_dump($model); $this->render('productcategory',array( 'model'=>$model,'id'=>$id, )); } model product public function SelectedCategoryProducts($id) { $dataProvider=new CActiveDataProvider('Product', array( 'criteria'=>array( 'select'=>'name,model,price,brand', 'condition'=>'category=:category', 'params'=>array(':category'=>$id), ))); var_dump($dataProvider); return $dataProvider; } CException Property "CActiveDataProvider.sellerSelectedCategoryProducts" is not defined. PLEASE HELP! I am losing my mind on this ... not able to display in gridview. A: Hope this might help Controller file public function actionProductcategory($id) { $model=new Product; $this->render('productcategory',array('model'=>$model, 'id'=>$id)); } In View file 'dataProvider'=>$model->SelectedCategoryProducts($id), UPDATE 1 'columns'=>array( 'name', 'model', 'brand', 'price', change them to lowercase which are your original column names A: Pass $id to your view file. $this->render('productcategory',array('model'=>$model,'id'=>$id)); Then pass id to model function in ccgridview function. 'dataProvider'=>$model->SelectedCategoryProducts($id), A: $dataProvider=new CActiveDataProvider('Product', array( 'criteria'=>array( 'select'=>'name,model,price,brand', 'condition'=>'category=:category', 'params'=>array(':category'=>$id), ))); this can retrieve needed data.... first check that data is perfect ... is it right after that take second step....
{ "language": "en", "url": "https://stackoverflow.com/questions/20782979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HyperlinkedRelatedField doesn't work in drf-nested-routers I'm using drf-nested-routers as below calendar_router = DefaultRouter() calendar_router.register(r'calendars', views.CalendarViewSet, base_name='calendars') event_router = routers.NestedSimpleRouter(calendar_router, r'calendars', lookup='calendar') event_router.register(r'events', views.EventViewSet, base_name='events') When I add url field to Calendar serializer, it works well, but when add url field to 'Event' serializer, it just raise below exception Could not resolve URL for hyperlinked relationship using view name "event-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. A: Replace: event_router.register(r'events', views.EventViewSet, base_name='events') with event_router.register(r'events', views.EventViewSet, base_name='event')
{ "language": "en", "url": "https://stackoverflow.com/questions/32291902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run Command Prompt Through Python (Or Vice Versa) I found myself doing a repetitive task and wondered how I can automate it. I can write a function script with python(3), to iterate through each item in a folder, but I'm not sure how I would run that through command prompt. I have sort of looked into how it would be possible, but I think a direct response to my exact question would be more helpful and easier to grasp. My question comes more from a desire to learn than it does from laziness! A: You could use os.system, but subprocess.run is probably better. You should also use glob: import glob import subprocess files = glob.glob('*.wav') for file in files: subprocess.run(['xWMAEncode', file, file.replace('.wav', '.xwm')])
{ "language": "en", "url": "https://stackoverflow.com/questions/54683361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Uncaught TypeError: arr.filter is not a function I have printed arr values in console they are like [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] but when this function gives an error i am not getting any values in arr Uncaught Type Error: arr.filter is not a function I am new to java-script and i don't have any idea what's this error is function filter(arr, criteria) { return arr.filter(function (obj) { return Object.keys(criteria).every(function (c) { return obj[c] == criteria[c]; }); }); } A: Seems like the arr you are sending to the filter function is not an array, which is why the error is saying that arr.filter is not a function. Just tried this and it works, so your function seems ok: function filter(arr, criteria) { return arr.filter(function (obj) { return Object.keys(criteria).every(function (c) { return obj[c] == criteria[c]; }); }); } const arr = [ { name: "David", age: 54 }, { name: "Andrew", age: 32 }, { name: "Mike", age: 54 } ]; const myFilter = {"age": 54}; const result = filter(arr, myFilter); console.log(result);
{ "language": "en", "url": "https://stackoverflow.com/questions/58949216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pyspark - Divide the customers into income buckets How to divide customers into income buckets using pyspark? Assume I've 2 columns named Customer and Income having range 10K to 50K. Now I want to Divide the customers into income buckets 10K -20K, 20K-30K etc using pyspark Data frame. TIA!
{ "language": "en", "url": "https://stackoverflow.com/questions/74094948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I improve my RBX.Lua procedural generation code? This is my first post in stack overflow, and I have no clue whether I can post stuff about roblox development here. But anyways, here I go. I'm making a top-down pixel art survival game, and am procedurally generating "flat" worlds with many different biomes. The code is working fine, it's just that the results look really unnatural, and I don't know what to do about it. Some examples of what I mean: world 1, world 2, world 3 Here is my code: local biomeInfo = require(script.BiomeInfo) local heightSeed = math.random(-2147483640, 2147483640) local moistureSeed = math.random(-2147483640, 2147483640) local heatSeed = math.random(-2147483640, 2147483640) local mapSize = 250 local resolution = 20 local frequency = 15 local amplitude = 95 -- Generate noise maps local grid = {} for x = 1, mapSize do grid[x] = {} for z = 1, mapSize do local heightMap = math.noise(x / resolution * frequency / amplitude, z / resolution * frequency / amplitude, heightSeed) local moistureMap = math.noise(x / resolution * frequency / amplitude, z / resolution * frequency / amplitude, moistureSeed) local heatMap = math.noise(x / resolution * frequency / amplitude, z / resolution * frequency / amplitude, heatSeed) --[[local heightMap = math.noise(x / resolution * 1.2 / 3.2, z / resolution * 1.2 / 3.2, heightSeed) local moistureMap = math.noise(x / resolution * 4 / 5.6, z / resolution * 4 / 5.6, moistureSeed) local heatMap = math.noise(x / resolution * 2.7 / 7, z / resolution * 2.7 / 7, heatSeed)]] grid[x][z] = { ["Height"] = math.clamp(heightMap, -0.5, 0.5) + 0.5, ["Moisture"] = math.clamp(moistureMap, -0.5, 0.5) + 0.5, ["Heat"] = math.clamp(heatMap, -0.5, 0.5) + 0.5, } end end -- Generate blocks for x = 1, mapSize do for z = 1, mapSize do -- Get all available biomes for this block local availableBiomes = {} for name, value in pairs(biomeInfo) do local condition = grid[x][z]["Height"] >= biomeInfo[name]["Height"] and grid[x][z]["Moisture"] >= biomeInfo[name]["Moisture"] and grid[x][z]["Heat"] >= biomeInfo[name]["Heat"] if condition and not availableBiomes[name] then table.insert(availableBiomes, name) end end -- Calculate value differences for all available biomes for this block local valueDiffs = {} for _, biome in pairs(availableBiomes) do valueDiffs[biome] = (grid[x][z]["Height"] - biomeInfo[biome]["Height"]) + (grid[x][z]["Moisture"] - biomeInfo[biome]["Moisture"]) + (grid[x][z]["Heat"] - biomeInfo[biome]["Heat"]) end -- Get the lowest value difference, assign the corresponding biome local lowestValue = 1 local selectedBiome for biome, value in pairs(valueDiffs) do if value < lowestValue then lowestValue = value selectedBiome = biome end end -- Generate the block local block = Instance.new("Part") block.Anchored = true block.Size = Vector3.new(8, 8, 8) block.Position = Vector3.new(x * 8, 0, z * 8) block.Parent = game.Workspace.World if grid[x][z]["Height"] <= 0.2 then -- Water level block.BrickColor = BrickColor.new("Electric blue") elseif selectedBiome == "Grasslands" then block.BrickColor = BrickColor.new("Bright green") elseif selectedBiome == "Taiga" then block.BrickColor = BrickColor.new("Baby blue") elseif selectedBiome == "Desert" then block.BrickColor = BrickColor.new("Cool yellow") elseif selectedBiome == "Swamp" then block.BrickColor = BrickColor.new("Slime green") elseif selectedBiome == "Mountains" then block.BrickColor = BrickColor.new("Dark stone grey") elseif selectedBiome == "Jungle" then block.BrickColor = BrickColor.new("Earth green") elseif selectedBiome == "Snowy tundra" then block.BrickColor = BrickColor.new("White") else block.BrickColor = BrickColor.new("Bright green") end block.Position = Vector3.new(x * 8, 4.5, z * 8) block.Parent = game.Workspace.World end game:GetService("RunService").Heartbeat:Wait() end Note: I'm aware that the many elseif statements is inefficient, this is temporary, please ignore it. The "BiomeInfo" module script: return { ["Grasslands"] = { ["Height"] = 0.27, ["Moisture"] = 0.21, ["Heat"] = 0.25 }, ["Desert"] = { ["Height"] = 0.15, ["Moisture"] = 0.05, ["Heat"] = 0.49 }, ["Taiga"] = { ["Height"] = 0.28, ["Moisture"] = 0.16, ["Heat"] = 0.12 }, ["Swamp"] = { ["Height"] = 0.16, ["Moisture"] = 0.44, ["Heat"] = 0.14 }, ["Mountains"] = { ["Height"] = 0.43, ["Moisture"] = 0.08, ["Heat"] = 0.11 }, ["Jungle"] = { ["Height"] = 0.22, ["Moisture"] = 0.51, ["Heat"] = 0.31 }, ["Snowy tundra"] = { ["Height"] = 0.17, ["Moisture"] = 0.12, ["Heat"] = 0.03 }, } This is my first time working with procedural generation, so I'm not sure if I'm applying the most efficient methods for everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/69529345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to test select html control object using SpecFlow? I have html select on page: <select id="StateName" name="StateName"> <option value=""></option> <option value="value1">value1</option> <option value="value2">value2</option> <option value="value3">value3</option> <option value="value4">value4</option> <option value="value5">value5</option> </select> I've already tried such step definition [When("I select value \"(.*)\" of select object with id \"(.*)\"")] public void ThenSelectValueOfSelect(string value, string selectId) { var select = TestsRunner.Browser.GetElementById(selectId); select.Click(); var item = TestsRunner.Browser.GetElementsByTag(@"option").SingleOrDefault(o => o.GetAttribute("value").Equals(value, StringComparison.OrdinalIgnoreCase)); item.Click(); } As testsrunner browser I use firefox. The problem is select items are dropped down but concrete option isn't selected. A: I think it can be done much shorter/easier. The way I'm selecting values from dropdownboxes: SelectElement dropdown = new SelectElement(Driver.FindElement(By.Id(dropdownID))); dropdown.SelectByValue(valueToBeSelected); It's pretty simple and straight forward and it just works.
{ "language": "en", "url": "https://stackoverflow.com/questions/12443635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating private reminders using iOS API? Does EKEventStore allow the creation of "private" reminders, i.e. reminders that will be visible only to my app (the one that calls against the EventKit -- iOS events API) but not e.g. to Apple's default reminders app (for either iOS or OS X)? A: The EKEventStore provides access to the calendar/reminder resources that are available to the OS that are configured by the user. It is not possible to configure a separate event store for private developer use. Reminders can be made local so they are not synced in the cloud. However, if the device has reminder lists that are synced to the cloud, then it is no longer possible to access the local reminders either by your app or the Reminders app. This same behavior seems to apply to local Calendars where I answered a question about their availability at Local EKCalendar saved with not errors, disappears. The question at Unable to create local EKCalendar (Reminders) if iCloud is set to not sync Reminders seems to support my conclusions and suggests this behavior has been present for at least a couple of years.
{ "language": "en", "url": "https://stackoverflow.com/questions/33706009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using "object" of mainfile, in function saved in other file In my work, I am receiving orders in PDF file, while I need to rewrite them into Excel table. Both Excel file and PDF file have every time exact structure, that does not change, so I have decided to automate this process and create python script that will do it for me. At the moment, I am about to end, I just need to write into excel file last data, but I am having serious issues, so serious, that I might need to rewrite/redesign half of my code (that has about 500 lines atm). The "problem" is, that I have my code split into 3 files: * *main (the one I am executing) *functions (where all complicated logical functions are stored) *config (where constants and configuration is stored) The problem, however is, that I have in main file constructor of xlsxwritter, which creates Excel files and sheets. Exactly this: # Creation of new EXCEL file xlsx_file = 'Red_vyplaty_' + termin_file + '.xlsx' print 'Creating excel file "%s"' % xlsx_file excel_file = xlsxwriter.Workbook(xlsx_file) # Adding sheet, called "Listky_obce_nad_300" obce_nad_300_sheet = excel_file.add_worksheet('Listky_obce_nad_300') print 'Adding data sheet "Listky_obce_nad_300" into "%s"' % (xlsx_file) obce_nad_300_sheet.set_column(0, 0, 2) obce_nad_300_sheet.set_column(1, 1, 2) But, I need(or want is more accurate) to create a function, in functions file that will have one imput, and based on this one imput, it will get data from config-constants file, and write them into this sheet(obce_nad_300_sheet). The problem is, if i create function like: def create_footer(suma_cell, starting_row, flag): """ Function to creade footer of listok flag = 0 / 1 / 2 (data sheet where to write header) """ obce_nad_300_sheet.write(row, 4, 'Test') it will (obviously) throw exception, that global variable obce_nad_300_sheet does not exist, bla bla bla..im sure you all know it :) I know, that I have 2 options how to solve it: * *Move whole creating and adding and writting into worksheet from main.py, into functions.py * *that could do it, but, it would be too much work for me, and most of those new functions will be just calling one xlsxwritter function, so kinda waste of time *Create these new function in main.py file * *while I am not sure if it would work, I am sure, that having some functions in function.py file, and others in main.py file, will be totally ugly and against my rules of clear code. BUT I would like to have 3rd option, that I am not aware of yet and will be both, simple and "nice"??? :) PS: No, xlsxWritter is not able to open/read excel file, it can only create new one, so if i define it inside function, it will rewrite everything I have written into file before. A: I feel that your code is not very well organized. Without entering into too much trouble, I would use obce_nad_300_sheet as an object an move it around. Like this: def create_footer(sheet, suma_cell, starting_row, flag): """ Function to creade footer of listok flag = 0 / 1 / 2 (data sheet where to write header) """ sheet.write(row, 4, 'Test') I don't know how the library works however. Does it "commit" the changes with a call to write or need some sort of a save or commit method after that? Without knowing too much about your situation nor the library, I would probably create an object inheriting from xlsxwriter.Workbook, store the sheets in an attribute of that object (probably a dict of {"sheet_name": WorkSheet}) and write the methods in the object. It could look like this: class MyWorksheet(xlsxwriter.Workbook): def __init__(self, *args, **kwargs): [...] super(MyWorksheet, self).__init__(*args, **kwargs) self.sheets = {} [...] def add_worksheet(self, name): [...] self.sheets[name] = super(MyWorksheet, self).add_worksheet(name) [...] def create_footer(self, sheet_name, suma_cell, starting_row, flag): [...] self.sheets[sheet_name].write(row, 4, "Test") [...] And then in what you call main file do: my_sheet = MyWorksheet() my_sheet.add_worksheet("Listky_obce_nad_300") my_sheet.create_footer("Listky_obce_nad_300", suma, starting, flag)
{ "language": "en", "url": "https://stackoverflow.com/questions/25390710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Deciding which derived class is passed as an argument I'm struggling with my current design and would like to know, if theres a possibility to decide which method to call without using a casting method. Say I've got a base Fence class. And at the moment my workers know how to build wooden fences and how to build barb wire fences. And they can add two fences together... but up to now they only learned how to connect the wooden ones with wooden ones, and the barb wired ones with barb wired ones. But as they probably will learn more, the Fence class has a virtual addFence(const Fence& fence) method. As I wanted to avoid any casting methods, I tried to add special addFence()methods in both classes. Here is an example: class Fence { public: virtual void addFence(const Fence& fence) = 0; ... }; class BarbWireFence : public Fence { public: ... void addFence(const Fence& fence) { //only add such a fence, if it is a barb wired one } void addFence(const BarbWireFence& fence) { //continue the fence with the given one } }; class WoodenFence : public Fence { public: ... void addFence(const Fence& fence) { //only add the fence, if it is a wooden one } void addFence(const WoodenFence& fence) { //continue the fence with the given one } }; Now I would like to do something like Fence *woodenFence1 = new WoodenFence(); Fence *woodenFence2 = new WoodenFence(); woodenFence1->addFence(*woodenFence2); But as it is a runtime decision what sort of fence I've got, I only have the base Fence* pointer and therefore the definition of the base class Fence is used in the last line. So is there a better implementation to decide 'automatically' what sort of fence I've got? Or should I use a completely different design? A: I'm not aware of a general approach in C++ but assuming you have a fixed set of derived classes, you can actually deal with the situation using an extra indirection: class BarbWireFence; class WoodenFence; class Fence { public: virtual void add(Fence& fence) = 0; virtual void add(BarbWireFence& fence) = 0; virtual void add(WoodenFence& fence) = 0; }; class BarbWireFence { void add(Fence& fence) override { fence.add(*this); } void add(BarbWireFence& fence) override; // deal with the actual addition void add(WoodenFence& fence) override; // deal with the actual addition }; class WoodenFence { void add(Fence& fence) override { fence.add(*this); } void add(BarbWireFence& fence) override; // deal with the actual addition void add(WoodenFence& fence) override; // deal with the actual addition }; A: Welcome to the wonderful world of binary methods. There is no satisfactory solution to this problem. You may want to learn about double dispatch and its more formal sibling the Visitor pattern. These two things are basically the same, only presented a bit differently. In the most simplistic scenario you do this: class WoodenFence; class BarbWireFence; class Fence { public: virtual void addFence(const Fence& fence) = 0; virtual void addMe(BarbWireFence& fence) const = 0; virtual void addMe(WoodenFence& fence) const = 0; ... }; class BarbWireFence : public Fence { public: ... void addFence(const Fence& fence) { fence->addMe(*this); } void addMe(BarbWireFence& fence) const { fence->addBarbWireFence(*this); } void addMe(WoodenFence& fence) const { throw error("bad fence combo"); } void addBarbWireFence(const BarbWireFence& fence) { // actually add fence... } }; class WoodenFence : public Fence { public: ... void addFence(const Fence& fence) { fence->addMe(*this); } void addMe(BarbWireFence& fence) const { throw error("bad fence combo"); } void addMe(WoodenFence& fence) const { fence->addWoodenFenceFence(*this); } void addWoodenFence(const WoodenFence& fence) { // actually add fence... } ... }; You can figure out what should happen when you add 10 other fence types. There's a totally different direction one might take, namely, templatize the entire business and get rid of the Fence base class, as it doesn't provide a type-safe interface. class BarbWireFence { public: ... void addSimilarFence(const BarbWireFence& fence) { //continue the fence with the given one } }; class WoodenFence { public: ... void addSimilarFence(const WoodenFence& fence) { //continue the fence with the given one } }; template <typename Fence> void addFence (Fence& f1, const Fence& f2) { f1->addSimilarFence(f2); }
{ "language": "en", "url": "https://stackoverflow.com/questions/26590251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom filename for generated file in Jekyll In my _config.yml file I have defined the permalink like permalink: /posts/:title/ (notice the ending slash). For a post in _posts/my_first_post/2017-05-06-my_first_post.markdown the generated file is _site/posts/my_first_post/index.html. How can I change the filename from index.html to something arbitrary like something.htm? Edit 1: Didn't want to do this, but I ultimately had to look at the Jekyll source code: In the lib/jekyll/page.rb there is this: def destination(dest) path = site.in_dest_dir(dest, URL.unescape_path(url)) path = File.join(path, "index") if url.end_with?("/") path << output_ext unless path.end_with? output_ext path end And in lib/jekyll/document.rb there is this: def destination(base_directory) dest = site.in_dest_dir(base_directory) path = site.in_dest_dir(dest, URL.unescape_path(url)) if url.end_with? "/" path = File.join(path, "index.html") else path << output_ext unless path.end_with? output_ext end path end So the index.html part is hardcoded. This question cannot be answered...unless there is a plugin that does what I want. A: You can adjust the code of Jekyll to your specific requirement. Open lib\jekyll\Page.rb in jekyll folder and update the destination method: module Jekyll class Page def destination(dest) path = site.in_dest_dir(dest, URL.unescape_path(url)) path = File.join(path, "index") if url.end_with?("/") path << output_ext unless path.end_with? output_ext # replace index with title path.sub! 'index', data['title'] if data['title'] path end end end Also update the destination method in lib\jekyll\Document.rb with the same line before returning path A: Create a plugin and monkey patch those classes Create _plugins/_my_custom_index.rb module Jekyll class Page def destination(dest) path = site.in_dest_dir(dest, URL.unescape_path(url)) path = File.join(path, "index") if url.end_with?("/") path << output_ext unless path.end_with? output_ext # replace index with title path.sub! 'index', data['title'] if data['title'] path end end end module Jekyll class Document def destination(base_directory) dest = site.in_dest_dir(base_directory) path = site.in_dest_dir(dest, URL.unescape_path(url)) if url.end_with? "/" path = File.join(path, "index.html") else path << output_ext unless path.end_with? output_ext end # replace index with title path.sub! 'index', data['title'] if data['title'] path end end end A: You can change to permalink /posts/:title/:title.html However, the post will be now accessible via http://server/post/my_first_post/my_first_post.html If you want to change the default behavior, you should modify Jekyll.Page.destination A: You can use permalink: /posts/:title/something:output_ext in the _config.yml or in post front matter
{ "language": "en", "url": "https://stackoverflow.com/questions/43832908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: struts2 s:property tag: Better way to replace value? I have a POJO whose properties I'm displaying on a JSP using Struts2 property tags: public Class message { string messageText; string messageType; //getters and setters, here } Text: <s:property value="messageBean.messageText"/> Type: <s:property value="messageBean.messageType"/> The object is created either by user input, or reading from a database. The "messageType" attribute only ever has integer values in it, which are used as keys for a lookup table within the database. When selecting the "type" values, users are given a radio selection on a previous page, and each option corresponds to an integer. When I'm displaying the values, I'm currently showing just the integer. I'd like to show the text that corresponds to the integer, and I would accomplish this by having a key/value lookup method in the action class, and change the code to appear as follows: //in Action class public String getTranslatedType() { if (messageBean.getMessageType().equals("12")) return "Message for frequent callers."; if (messageBean.getMessageType().equals("17")) return "Message for first time callers."; //etc } Text: <s:property value="messageBean.messageText"/> Type: <s:property value="translatedType"/> Is there a better way to do this? This does not seem to work: Type: <s:property value="Utility.getTranslatedText(messageBean.messageType)"/> Is there a syntax for calling a static utility method from within the property tag? A: I'm not sure exactly what you are trying to achieve. Why would you prefer to use a static call instead of accessing data from the ValueStack (which is where the action properties are accessed from)? It really is best to avoid static calls if possible and stick to the intended design of the framework and access data from the ValueStack/action. If you just wish to separate the logic from your action, you could change your method to: public String getTranslatedType() { return Utility.getTranslatedText(getMessageBean().getMessageType()); } Or are you wishing to have the translated text appear on the page dynamically? If so, perhaps you could use Javascript and JSON to achieve your goal with something along the lines of the following steps: * *Place your messageType integers (as the keys) and your translatedText Strings (as the values) into a map along the lines of messageTypeText.put(12, "Message for frequent callers."); *Convert this to JSON using something like (new JSONObject(messageTypeText)).toString(); *Then expose this to the client by any of a number of ways such as var messageTypeText = <s:property value="messageTypeText"/>; *Bind a javascript method to the messageType radio button that then displays the translated text by accessing it from the javascript map/array using the value of the currently selected radio/messageType. I could give more detail on this approach, but I don't want to waste my time if its not what you're looking for! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/11405282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable zuul decoding encoded slash %2F? I'm using a solution with Spring Cloud Zuul and Eureka. The REST application register itself with Eureka and Zuul provide access to the Service via Eureka Service Discovery. I had to configure the REST application to accept encoded slash in URL with: System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); To accept encoded dash in the Spring Boot REST application, and: @Bean public HttpFirewall allowUrlEncodedSlashHttpFirewall() { DefaultHttpFirewall firewall = new DefaultHttpFirewall(); firewall.setAllowUrlEncodedSlash(true); return firewall; } @Override public void configure(WebSecurity web) throws Exception { web.httpFirewall(allowUrlEncodedSlashHttpFirewall()); } In WebSecurityConfigurerAdapter for the same purpose. And: @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setUrlDecode(false); configurer.setUrlPathHelper(urlPathHelper); } In WebMvcConfigurer to skip decoding url encoded characters. After that, the REST application alone started to answer normally the request with the encoded slash. When I connected the REST application with Zuul, the gateway, the problem happened with slash encoded happens again. I did the same configuration of REST application with Zuul plus the property decode-url: false in application.yml and the combination of Zuul and REST application worked again. When I added the Service Discovery/Service Registration solution with Eureka, the problem begun happen again. I searched a lot, even cloned the Spring Cloud Netflix Eureka Server 2.1.0.RELEASE and Eureka Core 1.9.8 but couldn't find any solution. How to disable the decoding of slash in Eureka encoded in URL? A: The solution is to change Spring Boot version from 2.1.3.RELEASE to 2.1.4.RELEASE in the gateway.
{ "language": "en", "url": "https://stackoverflow.com/questions/56187583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: can not resolve method getProjection() and getMapCenter() i am implementing long click to get latlang on mapview, i referred this tutorial. but i am getting error here is my code: import com.google.android.gms.vision.barcode.Barcode; public class MyCustomMapView extends MapView { public interface OnLongpressListener { public void onLongpress(MapView view, Barcode.GeoPoint longpressLocation); } static final int LONGPRESS_THRESHOLD = 500; private Barcode.GeoPoint lastMapCenter; private Timer longpressTimer = new Timer(); private MyCustomMapView.OnLongpressListener longpressListener; public MyCustomMapView(Context context) { super(context); } public void setOnLongpressListener(MyCustomMapView.OnLongpressListener listener) { longpressListener = listener; } @Override public boolean onTouchEvent(MotionEvent event) { handleLongpress(event); return super.onTouchEvent(event); } private void handleLongpress(final MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // Finger has touched screen. longpressTimer = new Timer(); longpressTimer.schedule(new TimerTask() { @Override public void run() { Barcode.GeoPoint longpressLocation = getProjection().fromPixels((int)event.getX(), (int)event.getY()); <--here --> longpressListener.onLongpress(MyCustomMapView.this, longpressLocation); } }, LONGPRESS_THRESHOLD); lastMapCenter = **getMapCenter()**; } if (event.getAction() == MotionEvent.ACTION_MOVE) { if (!getMapCenter().equals(lastMapCenter)) { longpressTimer.cancel(); } lastMapCenter = getMapCenter();<-- here --> } if (event.getAction() == MotionEvent.ACTION_UP) { longpressTimer.cancel(); } if (event.getPointerCount() > 1) { longpressTimer.cancel(); } } } here my getProjection() and getMapCenter() cant resolve, i want to know why its happening, is this method deprecated, or what method i have to use instead, and i also want to know that why its barcode.GeoPoint, why my program importing import com.google.android.gms.vision.barcode.Barcode; instead of import com.google.maps.GeoPoint; A: You can implement GoogleMap.OnMapClickListener and GoogleMap.OnMapLongClickListener to achieve this public class CreateFenceActiviy extends AppCompatActivity implements GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener{ private GoogleMap mGoogleMap; private SupportMapFragment mMapFragment; private ArrayList<double[]> mLatLongArray =null; private Polygon mPolygon; private PolygonOptions mPolygonOptions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.create_fence_activity); mLatLongArray = new ArrayList<double[]>(); if (mGoogleMap == null) { mMapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_create_fence)); mGoogleMap = mMapFragment.getMap(); mGoogleMap.setOnMapClickListener(this); mGoogleMap.setOnMapLongClickListener(this); mGoogleMap.setOnMarkerClickListener(this); isMarkerClicked = false; } } @Override public void onMapClick(LatLng point) { if(mGoogleMap != null){ mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(point)); isMarkerClicked = false; } } @Override public void onMapLongClick(LatLng point) { if(mGoogleMap != null) { mGoogleMap.addMarker(new MarkerOptions().position(point).title(point.toString())); double latitudeNew = point.latitude; double longitude = point.longitude; mLatLongArray.add(new double[]{latitudeNew, longitude}); isMarkerClicked = false; } } } XML for Map view will contain this component <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map_create_fence" class="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" />
{ "language": "en", "url": "https://stackoverflow.com/questions/36981171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get list of values from grandchildren records I'm trying to access the grandchildren records in a list to avoid duplicate records. In this example, a tag can only be used once across articles for a given author. I will use the resulting list of grandchildren records in my clean function to return validation errors. class Article(models.Model): tag = models.ManyToManyField(Tag) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Tag(models.Model): class Author(models.Model): Right now I can do this: print(author.articles.first().tag.first()) Travel I'd like to be able to use something like author.articles.tags.all() to return the list and check the submitted form against it to raise a ValidationError message to the user. How can this be done efficiently with the basic Many-to-Many setup without creating an intermediate table for the tag relationships? This is solely in the Admin interface, in case that matters at all. A: i come from the link you posted on upwork, the way i understand your question, what you want to achieve seems to be impossible , what i think can work , is to fetch articles related to the author, with their corresponding tags, after that they are retrieved you do filtering and remove duplicates. otherwise the tag has nothing to connect it with the author,, A: The Django ORM is pretty cool when you get used to it, but regular SQL is pretty cool too # created_at, updated_at, name and tag_val are variables I # added due to my slight ocd lol class Author(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Tag(models.Model): tag_val = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Article(models.Model): author = models.ForeignKey(Author,related_name='articles', on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, related_name='articles') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I can write my query like this, assuming the variable 'author' has been assigned an Author object instance, and get a list of dictionaries [{'tags':1},{'tags':2}] where the value is the auto generated primary key id of the Tag object instance author.articles.values('tags').distinct() A: I'm so jealous that's a great answer @since9teen94 Be aware, I will not base my answer in the easiest solution but how we model reality (or how we should do it). We put tags after things exists right? In that order I will make your life horrible with something like this: from django.db import models class Author(models.Model): name = models.CharField(max_length=30, null=False) class Article(models.Model): name = models.CharField(max_length=30, null=False) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Tag(models.Model): name = models.CharField(max_length=30, null=False, unique=True) articles = models.ManyToManyField(Article) but believe me you don't want to follow this approach it will make your work harder. You can search for Articles based on Tags directly Tag.objects.filter(name='Scify').first().articles.all() # name is unique The real issue with this is that the reverse lookup is really complex (I mean.. get ready for debug) Article.objects.filter( id__in=list( Tag.objects.filter(name='Scify').first().articles.values_list('id', flat=True) ) ) I am sure this does not solve your problem and I don't like complex code for no reason but if you're open to suggestions I don't mind to think different and add some options Edit: About the author and clean repeated tags.. well you don't have to deal with that and if you want to find all Tag your author has you could loop the tags for tag in Tag.objects.all(): if tag.articles.filter(author__name='StackoverflowContributor'): print(tag.name) # > Scify I am just saying that there are options not that this is the best for you but don't be afraid of the terminal, it's really cool
{ "language": "en", "url": "https://stackoverflow.com/questions/69397042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple filter in single function using angularjs I try to filter two values like this | filter:{voucher_type: selectedName } | filter:{voucher_type: both } Here both is "B" and selectedName "P or R". Below code work only one filter only. I want to combine this two filter values together and show the result like voucher_type B + P (Or) R. <html> <head> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/> <title>search</title> </head> <body> <div class="row"> <div class="container"> <div class="col-sm-9"> <div ng-app="myApp"> <script type="text/ng-template" id="search"> <a> <span bind-html-unsafe="match.label | typeaheadHighlight:query"></span> <i> {{match.model.sub_name}} -({{match.model.group_name}}) </i> </a> </script> <form class="form-search" ng-controller="autocompleteController"> Selected Ledger: {{selectedLedgers}} <br> <br> <!-- typeahead="c as c.ledger_id + '-' + c.ledger_name + ' <i>(' +c.group_name + ')</i>'--> <input type="text" ng-model="both"></p> <div>select voucher :<select ng-model="selectedName" ng-options="x for x in names"> </select> </diV> <input type="text" ng-model="selectedLedgers" placeholder="Search Ledger" typeahead="c as c.ledger_id + '-'+ c.ledger_name for c in producers | filter:$viewValue| limitTo:20 | filter:{voucher_type: selectedName1 } | filter:{voucher_type: both }" typeahead-min-length='2' typeahead-on-select='onSelectPart($item, $model, $label)' typeahead-template-url="search" class="form-control" style="width:350px;"> <i class="icon-search nav-search-icon"></i> </form> </div> </div> </div> </div> <script type="text/javascript" src="js/angular.min.js"></script> <script src="js/ui-bootstrap-tpls-0.9.0.js"></script> <script type="text/javascript"> var app = angular.module('myApp', ['ui.bootstrap']); app.controller('autocompleteController', function($scope, $http) { $http.get("getLedgers.php").success(function(data){ $scope.producers = data; }); $scope.names = ["P", "R"]; $scope.filters = { x: false, company: '', search: '' }; $scope.both ='B'; }); </script> </body> </html> Find my demo project here https://jsfiddle.net/basilbkodakk/sk549x4m/2/ .there have 3 company x,y,z .list box show x and y . z is common for x,y .that filter method in angularjs
{ "language": "en", "url": "https://stackoverflow.com/questions/39242011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Should I still respond to html if view is rendered with javascript? I have a Rails application integrated with react, my views are rendered with react, including the html (JSX). I noticed that I had a few format.html responses from back when my views were regular erb views, now that they are not, should I still respond to html just in case (even though I don't see how a user can use my app if they javascript have disabled)? Example : def destroy @comment.destroy respond_to do |format| format.json { head :no_content } format.html { redirect_to @question, notice: 'Comment was deleted.' } end end Can I get rid of the html responses? A: Whether to keep it or not is a personal choice. I sometimes do, but fewer LOC makes for cleaner code. To remove it you have several options. You can leave the respond_to as is and just remove the html eg: def destroy @comment.destroy respond_to do |format| format.json { head :no_content } end end but you can also remove the respond_to from each action (even fewer LOC) with something like this: # put this LOC at the top of your controller, outside of any action respond_with :json # then each action is much simpler... you just assume it's always json def destroy @comment.destroy head :no_content end
{ "language": "en", "url": "https://stackoverflow.com/questions/39629595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: how to deal with several .pyd dependencies with the same name? I have in my python workspace two Modules which need sip.pyd Module1.pyd needs sip.pyd (which implements v 8.0-8.1) Module2.pyd needs sip.pyd (another file, that implements v6.0) So I can't just choose the newer one, it doesn't work: I have to keep them both! (RuntimeError: the sip module implements API v6.0 but the fbx module requires API v8.1) How can I import a module in .pyd extension (a python dll, not editable), and specify which sip.pyd to source? As for a workaround, I manage to do that: * *One sip.pyd is in my root site-packages location. *If I have to import the module that need the other sip.pyd, I remove root path form sys.path, and I append the precise folder path where the other sip.pyd are. *I can import my Module and restore previous sys.path. A: VirtualEnv is done to handle those case. virtualenv is a tool to create isolated Python environments. Using virtualenv, you will be able to create 2 environements, one with the sip.pyd in version 8.x another in version 6.0 A: Assuming you don't have a piece of code needing both files at once. I'd recommend the following: * *install both files in 2 separate directories (call them e.g. sip-6.0 and sip-8.0), that you'll place in site-packages/ *write a sip_helper.py file with code looking like sip_helper.py contents: import sys import re from os.path import join, dirname def install_sip(version='6.0'): assert version in ('6.0', '8.0'), "unsupported version" keep = [] if 'sip' in sys.modules: del sys.modules['sip'] for path in sys.path: if not re.match('.*sip\d\.\d', path): keep.append(path) sys.path[:] = keep # remove other paths sys.path.append(join(dirname(__file__), 'sip-%s' % version)) * *put sip_helper.py in site_packages (the parent directory of the sip-6.0 and sip-8.0 directories) *call sip_helper.install_sip at the startup of your programs A: I don't know if that works (if a module's name has to match its contents), but can't you just rename them to sip6.pyd resp. sip8.pyd and then do if need6: import sip6 as sip else: import sip8 as sip ?
{ "language": "en", "url": "https://stackoverflow.com/questions/8298978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Draw polygon with hole inside I need to draw a rectangle polygon with a rectangle hole inside. I found this piece of code but I couldn't manage to understand how I can modify to meet my requirement. figure() p = [0 0; 0 1; 1 1; 1 0]; %ccw pp = [0 0; 1 0; 1 1; 0 1]; %cw ph = p + [1.2 0]; # add hole ph(end+1,:) = nan; ph = [ph; (pp-[0.5 0.5])*0.5+[1.7 0.5]]; po = polygon2patch (ph); patch (po(:,1), po(:,2), 'b', 'facecolor', 'c'); axis image A: The polygon2patch function certainly seems useful, but maybe for only drawing two rectangles, you could also use just two patch commands, and simply set the inner rectangle, i.e. the hole, to white foreground color, like so: outer = [0 0; 2 0; 2 1; 0 1]; inner = [0.4 0.2; 1.6 0.2; 1.6 0.8; 0.4 0.8]; patch(outer(:, 1), outer(:, 2), 'c'); patch(inner(:, 1), inner(:, 2), 'w'); axis equal; This will produce such an output: Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/58443322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grouping and Aggregating on multiple time series Im new to python and pandas and have some basic question about how to write a short function which takes a pd.Dataframe and returns relative values grouped by month. Example data: import pandas as pd from datetime import datetime import numpy as np date_rng = pd.date_range(start='2019-01-01', end='2019-03-31', freq='D') df = pd.DataFrame(date_rng, columns=['date']) df['value_in_question'] = np.random.randint(0,100,size=(len(date_rng))) df.set_index('date',inplace=True) df.head() value_in_question date 2019-01-01 40 2019-01-02 86 2019-01-03 46 2019-01-04 75 2019-01-05 35 def absolute_to_relative(df): """ set_index before using """ return df.div(df.sum(), axis=1).mul(100) relative_df = absolute_to_relative(df) relative_df.head() value_in_question date 2019-01-01 0.895055 2019-01-02 1.924368 2019-01-03 1.029313 2019-01-04 1.678228 2019-01-05 0.783173 Rather than taking the column sum and devide each row by that, I would like to have the sum groupby each month. The final df should have the same shape and form but the row values relate to sum of the month. old: value_in_question date "2019-01-01" value/colum_sum * 100 new: value_in_question date "2019-01-01" value/month_sum * 100 So I tried the following, which returns NA for value_in_question: def absolute_to_relative_agg(df, agg): """ set_index before using """ return df.div(df.groupby([pd.Grouper(freq=agg)]).sum(), axis=1) relative_df = absolute_to_relative(df, 'M') value_in_question date 2019-01-01 NaN 2019-01-02 NaN 2019-01-03 NaN 2019-01-04 NaN 2019-01-05 NaN A: Use GroupBy.transform instead aggregation for Series/DateFrame with same DatatimeIndex like original, so possible division: def absolute_to_relative_agg(df, agg): """ set_index before using """ return df.div(df.groupby([pd.Grouper(freq=agg)]).transform('sum')) relative_df = absolute_to_relative_agg(df, 'M') Another way for call function is DataFrame.pipe: relative_df = df.pipe(absolute_to_relative_agg, 'M') print (relative_df) value_in_question date 2019-01-01 0.032901 2019-01-02 0.045862 2019-01-03 0.048853 2019-01-04 0.008475 2019-01-05 0.041376 ... 2019-03-27 0.062049 2019-03-28 0.002165 2019-03-29 0.048341 2019-03-30 0.007937 2019-03-31 0.015152 [90 rows x 1 columns] A: For the sums, you can groupby the index month: In [31]: month_sum = df.groupby(df.index.strftime('%Y%m')).sum() ...: month_sum ...: Out[31]: value_in_question 201901 1386 201902 1440 201903 1358 You can then use .map to align the month with the correct rows of your DataFrame: In [32]: map_sum = df.index.strftime('%Y%m').map(month_sum['value_in_question']) ...: map_sum ...: Out[32]: Int64Index([1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358], dtype='int64') Then you just need to do the division: In [33]: df['value_in_question'].div(map_sum) Out[33]: date 2019-01-01 0.012987 2019-01-02 0.018759 2019-01-03 0.000000 2019-01-04 0.056277 2019-01-05 0.019481 ... 2019-03-27 0.031664 2019-03-28 0.007364 2019-03-29 0.050074 2019-03-30 0.033873 2019-03-31 0.005155 Name: value_in_question, Length: 90, dtype: float64 A: Use Grouper with freq='M'. The code is: relative_df = df.groupby(pd.Grouper(freq='M'))\ .value_in_question.apply(lambda x: x.div(x.sum()).mul(100)) It returns a Series with index the same like in original DataFrame and values equal to relative value_in_question for the current month.
{ "language": "en", "url": "https://stackoverflow.com/questions/59118129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can anyone solve the error in Spark databricks My SQL request: SELECT Incident Number FROM fireIncidents where Incident Date='04/04/2016' Error in SQL statement: ParseException: mismatched input 'Date' expecting {, ';'}(line 1, pos 57) A: You have a space in Incident Date column. If you want spark to know the column has space, use ` symbol in start and end of col. Same as Incident Number col. SELECT `Incident Number` FROM fireIncidents where `Incident Date`='04/04/2016' If your Incident Date col is a date, you can cast it to spark format, use select `Incident Date`, to_date(`Incident Date`, 'dd/MM/yyyy') FROM fireIncidents""").show() which yields +-------------+----------------------------------+ |Incident Date|to_date(Incident Date, dd/MM/yyyy)| +-------------+----------------------------------+ | 04/04/2016| 2016-04-04| | 04/04/2016| 2016-04-04| | 04/04/2016| 2016-04-04| +-------------+----------------------------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/69052422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use window lag function to partition the data with multiple sensor types I'm, trying to use the postgres LAG function to calculate a difference in absolute time between two sampling dates for each sensor in the system. The best I have come up with is to use WINDOW LAG function to calculate a difference from earlier line. However there are two problems with this. The first value is always null. I'd guess I can solve this using a CASE function. Second is that it does not take each sensor value explicitly. SELECT seq_id, stream_id, sensor, "timestamp", oper_value "timestamp" - LAG("timestamp",1) OVER (ORDER BY "timestamp") delta FROM public.mt_events where "type" = 'operational_value_event' limit 100; The data is logged when threshold breached (including hysteresis) and therefore some values are changed more often than other. There are no fixed intervals in when the data is logged. The end goal to to get a value that have atleast a certain amount of time difference. Example data: id stream_id sensor oper_value timestamp 44 100000000 GT1 17 2018-05-16 13:36:21.899821+00 45 100000000 GT2 44 2018-05-16 14:36:21.000000+00 88 100000000 GT1 26 2018-05-18 12:33:22.000000+00 94 100000000 GT1 99 2018-05-18 12:33:23.002000+00 For example if a selection of data with at least time difference of 5 minutes I would like to get the following values: id stream_id sensor oper_value timestamp 44 100000000 GT1 17 2018-05-16 13:36:21.899821+00 45 100000000 GT2 44 2018-05-16 14:36:21.000000+00 88 100000000 GT1 26 2018-05-18 12:33:22.000000+00 The last GT1 is filtered out since the difference was less than 5 minutes. Is there any way of doing this effectively using a SQL statement or do I need to write a stored procedure? Cheers, Mario A: You can use the three-argument form of lag() with partition by: ("timestamp" - LAG("timestamp", 1, "timestamp") OVER (PARTITION BY sensor ORDER BY "timestamp") ) as delta For your ultimate problem, the NULL value for the first row doesn't matter. You can solve the problem using a subquery: select * from (select seq_id, stream_id, sensor, "timestamp", oper_value , lag("timestamp") over (partition by sensor order by timestamp) as prev_timestamp from public.mt_events where "type" = 'operational_value_event' ) t where delta is null or prev_timestamp < timestamp - interval '5 minute';
{ "language": "en", "url": "https://stackoverflow.com/questions/51174903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: add typings for missing method (from a npm package) I'm using the package @types/cropperjs unfortunately it is behind the current cropper.js versions and lacks the method scale. So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix) I tried to merge the definitions from node_modules with my own declaration. declare class cropperjs { /** * Scale the image. * * @param scaleX The scaling factor to apply on the abscissa of the image. * When equal to 1 it does nothing. Default is 1 * @param scaleY The scaling factor to apply on the ordinate of the image. * If not present, its default value is scaleX. */ scale(scaleX: number, scaleY?: number): void; } export = cropperjs; export as namespace Cropper; the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here) Here's how I import cropper in an angular component. import * as Cropper from 'cropperjs'; Here's my tsconfig.json (parts of it) "typeRoots": [ "node_modules/@types", "node_modules/@angular", "src/typings" ], "types": [ "jasmine", "node", "karma", "webpack", "cropperjs" ] I tried it with my custom typings folder an with the tripple slash reference notation. But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module P.S. I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git). A: As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here. If the @types/cropperjs would have been written using interfaces, you could have extended that interface using your own declaration. Here is an ugly hack you can do for now: import * as Cropper from 'cropperjs'; interface MyCropper extends Cropper { scale(scaleX: number, scaleY?: number): void; } function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper { return new Cropper(dom, options) as MyCropper; } casting is always ugly, but at least you hide it in one place, I think it's reasonable... A: Just wanted to add another possible "solution". I say "solution" because it's in my opinion quite ugly but then again it's a workaround. After seeing and reading (see Aviad Hadad's answer) that class merging is not possible and read about typescripts node module resolution Basically if you import an non-relative path like import * as Cropper from 'cropperjs typescript will look for the appropriate files in a folder named node_modules and it starts in the directory in which the file with the import statement resides. It then traverses up (example taken from the typescript documentation) * */root/src/node_modules/moduleB.ts */root/node_modules/moduleB.ts */node_modules/moduleB.ts (I assume that's the global node_modules directory) Since typescript will also look for d.ts files I copied the whole index.d.ts from the @types/cropperjs package, renamed it to cropperjs.d.ts and put it in a folder named /root/src/node_modules. (and added the missing method) if you trace the resolution with tsc --traceResolution you'll see that typescript will take the d.ts file from the custom node_modules directory. The advantage with this solution is that you don't have to touch your code. As soon as @types/cropperjs has updated the missing method you can just delete your custom node_modules directory and everything will still work. Disadvantage is you have to copy and paste code around.
{ "language": "en", "url": "https://stackoverflow.com/questions/44408293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to remove unused blocks of code from a source code file? Let’s suppose I have a bunch of source code files (C or Delphi, i.e., *.c or *.pas). I want to purge them of blocks of text which are not used in the compilation. Those blocks are: * *Comments. They can be removed with regexp. (But, for example, Delphi uses the preprocessor directives which look like comments (“{ is it a comment or a directive? }”), so the regexp would not be trivial.) *But the most tricking part is the blocks of code which are excluded from the compilation with #ifdef. These blocks have to be removed too. So, the question is: “Is there a way to do it with some program or script?” Let’s suppose there is a program that can be given a source code file and a list of defined symbols to distinguish unused blocks of code, and it would spit out the cleansed file I want to get.
{ "language": "en", "url": "https://stackoverflow.com/questions/61867535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Quasar Vue: Set static width content on Grid Style I'm very new in dynamic web programming but I get a little problem with Quasar Grid Gutter. I have string on array with different word and length, I want to show them in Button with grid style. So I use Grid Gutter to build this. But I want the size of card is always static (etc width: 200), so add style="width: 100px". But if width too small and text length too long, the height is getting weird. If add height:50px the width is not work. Here is a codepen sample. I try the Offset too but I can set the padding between Button.
{ "language": "en", "url": "https://stackoverflow.com/questions/63663933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Blackberry SQLite optimal performance I've overcome many hurdles while trying to work with SQLite on Blackberry. Now I've reached the point where everything seems to work fine and I'm looking for ways to speed up my queries. Sometimes my app retrieves a lot of data from a web service call, this data is parsed and stored into my database. A lot of DELETE, INSERT and UPDATE going on. The database calls seem to be taking a lot of time. I would like to know some best practices when dealing with SQLite. Preferably from people who have experience with it on the Blackberry platform specifically. Any tricks to speed up DELETEs or INSERTs etc.... Links to good tutorials would be great. Or some snippets of useful code even better. Thanks in advance. EDIT: Here is some sample code from Blackberry using transactions. import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; import net.rim.device.api.database.*; import net.rim.device.api.io.*; public class UsingTransactions extends UiApplication { public static void main(String[] args) { UsingTransactions theApp = new UsingTransactions(); theApp.enterEventDispatcher(); } public UsingTransactions() { } } class UsingTransactionsScreen extends MainScreen { Database d; public UsingTransactionsScreen() { LabelField title = new LabelField("SQLite Using Transactions Sample", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH); setTitle(title); add(new RichTextField( "Updating data in one transaction in MyTestDatabase.db.")); try { URI myURI = URI.create("file:///SDCard/Databases/SQLite_Guide/" + "MyTestDatabase.db"); d = DatabaseFactory.open(myURI); d.beginTransaction(); Statement st = d.createStatement("UPDATE People SET Age=7 " + "WHERE Name='Sophie'"); st.prepare(); st.execute(); st.close(); st = d.createStatement("UPDATE People SET Age=4 " + "WHERE Name='Karen'"); st.prepare(); st.execute(); st.close(); d.commitTransaction(); d.close(); } catch ( Exception e ) { System.out.println( e.getMessage() ); e.printStackTrace(); } } } Is there a reason why they're closing the statement every time?? Isn't it better just to close it once at the end (in a Finally block perhaps??). A: The standard technique is to use a prepared insert statement, inside a loop inside a transaction. That will give you almost optimal efficiency in most instances. It will speed things up by at least an order of magnitude. A: I personally don't know many blackberry-specific practices, but these seem to be helpful (sorry I couldn't find code snippets): "Top 8 SQL Best Practices" "Best Practice: Optimizing SQLite Database Performance" Hope these help! A: You should do one thing is that, create different methods for database handling code. and simply call these methods from your main code and open and close database also in each and every block. It will reduce redundancy and will be better for your future. This will also helps you in your App performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/10013520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Contact form not sending email and no notification working on contact form for my website. All tree form fields are validating correctly somehow the email is not send but looks page is loading again. Can anyone check my code and tell me where could be a problem here. Would like temail to be sent and notification to the user shown. Contact form: <form role="form" id="contactForm"> <div class="row"> <div class="form-group"> <input type="text" class="form-control" name="name" id="name" placeholder="Wpisz swoje imię, nazwisko" required="required"> </div> <div class="form-group"> <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" required> </div> <div class="form-group"> <textarea id="message" name="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea> </div> <button type="submit" id="form-submit" class="btn-block">Wyślij wiadomość</button> <div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div> </div> </form> Java sripts within same html file as form: <script> $(document).ready(function () { var owl = $("#owl-hero"); owl.owlCarousel({ navigation: false, // Show next and prev buttons slideSpeed: 1, paginationSpeed: 400, singleItem: true, transitionStyle: "fade" })}); </script> <script> $("#contactForm").validator().on("submit", function (event) { if (event.isDefaultPrevented()) { // handle the invalid form... } else { // everything looks good! event.preventDefault(); submitForm(); } }); function submitForm(){ // Initiate Variables With Form Content var name = $("#name").val(); var email = $("#email").val(); var message = $("#message").val(); $.ajax({ type: "POST", url: "php/form-process.php", data: "name=" + name + "&email=" + email + "&message=" + message, success : function(text){ if (text == "success"){ formSuccess(); } } })}; } function formSuccess(){ $( "#msgSubmit" ).removeClass( "hidden" ); } </script> PHP file (process.php) : <?php $name = $_POST["name"]; $email = $_POST["email"]; $message = $_POST["message"]; $EmailTo = "[email protected]"; $Subject = "New Message Received"; // send email $success = mail($EmailTo, $Subject, $message, $email); // redirect to success page if ($success){ echo "success"; }else{ echo "invalid"; } ?> for further dicussion: my top code: <!DOCTYPE html> <html lang="pl"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>my site</title> <link rel="shortcut icon" href="img/ico.png"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="jakiś wyraz"> <meta name="keywords" content=""> <meta name="author" content="strona"> <!-- Bootstrap Css --> <link href="bootstrap-assets/css/bootstrap.min.css" rel="stylesheet"> <!-- Style --> <link href="plugins/owl-carousel/owl.carousel.css" rel="stylesheet"> <link href="plugins/owl-carousel/owl.theme.css" rel="stylesheet"> <link href="plugins/owl-carousel/owl.transitions.css" rel="stylesheet"> <link href="plugins/Lightbox/dist/css/lightbox.css" rel="stylesheet"> <link href="plugins/Icons/et-line-font/style.css" rel="stylesheet"> <link href="plugins/animate.css/animate.css" rel="stylesheet"> <link href="css/main.css" rel="stylesheet"> <!-- Icons Font --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script> $(document).ready(function () { var owl = $("#owl-hero"); owl.owlCarousel({ navigation: false, // Show next and prev buttons slideSpeed: 1, paginationSpeed: 400, singleItem: true, transitionStyle: "fade" })}); </script> <script> $("#contactForm").validator().on("submit", function (event) { if (event.isDefaultPrevented()) { // handle the invalid form... } else { // everything looks good! event.preventDefault(); submitForm(); } }); function submitForm(){ // Initiate Variables With Form Content var name = $("#name").val(); var email = $("#email").val(); var message = $("#message").val(); $.ajax({ type: "POST", url: "php/form-process.php", data: "name=" + name + "&email=" + email + "&message=" + message, success : function(text){ if (text == "success"){ formSuccess(); } } }); } function formSuccess(){ $( "#msgSubmit" ).removeClass( "hidden" ); } </script> </head> i notice couple errors in console please help me also to fix it.: error type: SCRIPT5009: '$' is undefined on this line: $("#contactForm").validator().on("submit", function (event) { error type: SCRIPT5009: '$' is undefined at the end on own.carousel script here: }); A: You haven't loaded the jQuery library (or at least prior to attempting to use it based on your <head> tag from above), add: <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script> before useing the $ function. After jQuery has resolved, remove the syntax error cased by the extra } in your submitForm function -right in between the ) and the ;.
{ "language": "en", "url": "https://stackoverflow.com/questions/35527463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested 'for' loop in Racket shows error 'not a procedure' I have the following code lines to do bubble sort in Racket. I find the syntax correct but it is still showing error: (define List (list 1 3 5 7 9 2 4 6 8 0)) (define Left 0) (define Right 0) (for ([I (range (- (length List) 1))]) (for ([J (range (+ I 1) (length List))]) (set! Left (list-ref List I)) (set! Right (list-ref List J)) (when (> Left Right) [(set! List (list-set List I Right)) (set! List (list-set List J Left ))] ) ) ) The error is: application: not a procedure; expected a procedure that can be applied to arguments given: #<void> arguments...: #<void> context...: /home/jdoodle.rkt:6:2: for-loop /home/jdoodle.rkt:5:0: for-loop top-level: [running body] eval-one-top12 begin-loop loop Can't guess it out why. I tested it on https://www.jdoodle.com/execute-racket-online but it didn't work. A: I found the answer, sorted it out. I must add the expression begin for multiple statements after when. Not the double parentheses. (for ([I (range (- (length List) 1))]) (for ([J (range (+ I 1) (length List))]) (set! Left (list-ref List I)) (set! Right (list-ref List J)) (when (> Left Right) (begin (set! List (list-set List I Right)) (set! List (list-set List J Left )) )))) Or just a series of forms after when: (for ([I (range (- (length List) 1))]) (for ([J (range (+ I 1) (length List))]) (set! Left (list-ref List I)) (set! Right (list-ref List J)) (when (> Left Right) (set! List (list-set List I Right)) (set! List (list-set List J Left )) )))
{ "language": "en", "url": "https://stackoverflow.com/questions/60123482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Phoenix - client requested channel transport error While running my Phoenix app, I suddenly noticed an error being logged: The client's requested channel transport version "2.0.0" does not match server's version requirements of "~> 1.0" It appears after starting the server with mix phoenix.server: [info] Running MyApp.Endpoint with Cowboy using http://localhost:4000 21 Nov 13:47:19 - info: compiled 4 files into app.js, copied robots.txt in 2.3 sec [error] The client's requested channel transport version "2.0.0" does not match server's version requirements of "~> 1.0" and then continues to log the error message every 10 seconds or so, regardless of whether or not I'm making any requests to the server. Despite this, the app seems to run fine, but it'd be great to resolve this. Can anyone shed any light on why this would've suddenly started happening, and what I can do to fix it? Here's some config info from mix.exs: def application do [mod: {MyApp, []}, applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext, :phoenix_ecto, :postgrex, :comeonin]] end defp deps do [{:phoenix, "~> 1.2.1"}, {:phoenix_pubsub, "~> 1.0"}, {:phoenix_ecto, "~> 3.0"}, {:postgrex, ">= 0.0.0"}, {:phoenix_html, "~> 2.6"}, {:phoenix_live_reload, "~> 1.0", only: :dev}, {:gettext, "~> 0.11"}, {:cowboy, "~> 1.0"}, {:cors_plug, "~> 1.1"}, {:comeonin, "~> 3.0"}, {:guardian, "~> 0.14"}, {:guardian_db, "~> 0.8.0"}] end
{ "language": "en", "url": "https://stackoverflow.com/questions/47420724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert short array to BitSet with 2 bit precision in Java? I have a short array {0,2,3,1,…} which I would like to convert to a BitSet. Expected bits in bitset: 00 10 11 01 … Every two bit in the bitset should represent a short. (2-bit precision) This should work fine for short values (0,1,2,3). I know that I can use ByteBuffer and BitSet to access the bits of the numbers but those are formatted into 2 bytes (16 bit). I assume I need to bitshift the values to access the correct bits but I don't know how. int nBit = 0; BitSet result = new BitSet(); for (int i = 0; i < numbers.length; i++) { ByteBuffer buffer = ByteBuffer.allocate(2); buffer.putShort(number); BitSet bits = BitSet.valueOf(buffer.array()); result.set(nBit++, bits.get(?)); result.set(nBit++, bits.get(?)); } It there maybe an easier way? A: My current pragmatic solution which may be okay since only 4 values need to be handled: public static BitSet transformToBitSet(short[] numbers) { BitSet data = new BitSet(); int nBit = 0; for (int i = 0; i < numbers.length; i++) { short number = numbers[i]; switch (number) { case 0: data.set(nBit++, false); data.set(nBit++, false); break; case 1: data.set(nBit++, true); data.set(nBit++, false); break; case 2: data.set(nBit++, false); data.set(nBit++, true); break; case 3: data.set(nBit++, true); data.set(nBit++, true); break; default: throw new RuntimeException("Invalid number encountered. Can't map values >4"); } } return data; } A: Here is one way to do it. * *set the desired bitLength (used for padding on the left with zero bits); *initialize the BitSet index to 0. *The iterate over the values. *convert each to a bit string. *pad on the left to achieve the desired bit length *then set the bits based on the numeric value of the bit BitSet b = new BitSet(); short[] vals = { 0, 2, 3, 1 }; int bitLength = 2; int idx = 0; for (short v : vals) { String bits = Integer.toBinaryString(v); bits = "0".repeat(bitLength - bits.length())+bits; for (char c : bits.toCharArray()) { b.set(idx++, c - '0' == 1); } } System.out.println(b) prints 2,4,5,7
{ "language": "en", "url": "https://stackoverflow.com/questions/70658220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Direct X 11 Texturing FX file error X3004 undiclared identifier "input" I am trying to texture a cube but when i try to run the progam the fx file thows error X3004 undiclared identifier "input" but input is declared near the top so i don't understand whats going wrong. I have tried for 4 day's plz help. This code includes diffuce lighting as well as texturing. i believe that output.tex=input.tex is the problem but im not sure. Texture2D txDiffuse : register(t0); SamplerState samLinear : register(s0); float4 textureColour = txDiffuse.Sample(samLinear, input.Tex); struct VS_INPUT { float4 Pos : POSITION; float2 Tex : TEXCOORD0; }; struct PS_INPUT { float4 Pos : SV_POSITION; float2 Tex : TEXCOORD0; }; //-------------------------------------------------------------------------------------- // Constant Buffer Variables //-------------------------------------------------------------------------------------- cbuffer ConstantBuffer : register( b0 ) { matrix World; matrix View; matrix Projection; float4 DiffuseMtrl; float4 DiffuseLight; float3 LightVecW; } //-------------------------------------------------------------------------------------- struct VS_OUTPUT { float4 Pos : SV_POSITION; float4 Color : COLOR0; float2 Tex : TEXCOORD0; }; //-------------------------------------------------------------------------------------- // Vertex Shader //-------------------------------------------------------------------------------------- //guroud shading with diffuse lighting VS_OUTPUT VS(float4 Pos : POSITION, float3 NormalL : NORMAL) { VS_OUTPUT output = (VS_OUTPUT)0; output.Pos = mul(Pos, World); output.Pos = mul(output.Pos, View); output.Pos = mul(output.Pos, Projection); // Convert from local space to world space // W component of vector is 0 as vectors cannot be translated float3 normalW = mul(float4(NormalL, 0.0f), World).xyz; normalW = normalize(normalW); // Compute Colour using Diffuse lighting only float diffuseAmount = max(dot(LightVecW, normalW), 0.0f); output.Color.rgb = diffuseAmount * (DiffuseMtrl * DiffuseLight).rgb; output.Color.a = DiffuseMtrl.a; return output; output.Tex = input.Tex; } //-------------------------------------------------------------------------------------- // Pixel Shader //-------------------------------------------------------------------------------------- float4 PS( VS_OUTPUT input ) : SV_Target { return input.Color; } error Framework.fx(12,53-57): error X3004: undeclared identifier 'input' A: You're trying to sample a texture (on line 4) outside of any function. Where do you expect this code to run, in the vertex shader (VS) or the pixel shader (PS)? Remove line 4 and change your pixel shader to: return txDiffuse.Sample(samLinear, input.Tex); You seem to have some structures that aren't used at all (VSINPUT, PSINPUT). The last line of the vertex shader won't compile either because you're using "input.Tex" and the vertex shader has no variable called "input". If you're not going to use them, change the first line of the VS to: VS_OUTPUT VS(float4 Pos : POSITION, float3 NormalL : NORMAL, float2 Tex : TEXCOORD0) and the end of the shader to be: output.Color.a = DiffuseMtrl.a; output.Tex = Tex; return output;
{ "language": "en", "url": "https://stackoverflow.com/questions/34600044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Intelij uses 100% of CPU -> vmware is extremely slow I'm getting an usage 100% when the Intelij is running. After 20 min I cannot do anything on VMWARE and then I am forced to supsend or restart VM. I tried to remove rm /var/crash/* but it did not help. May you please advice me how to resolve the slowness problems?
{ "language": "en", "url": "https://stackoverflow.com/questions/73958272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deduping a StringBuilder List of Items in C# I have a situation where I need to dedupe a list of columns in a SQL select statement that is being generated with a StringBuilder. I need to return a StringBuilder object as well. The solution I came up with works but it looks like a dang nightmare. Can someone suggest a cleaner way to achieve this? //The SQL statement is being passed to my code as a StringBuilder //This is just scaffolding to fake that input. StringBuilder items = new StringBuilder(); items.Append("SELECT "); items.Append("Apple,"); items.Append("Carrot,"); items.Append("Pear,"); items.Append("Orange,"); items.Append("Apple"); items.Append(" From fruit_table"); //End scaffolding //My code start: //Chop off the non-important parts items.Replace("SELECT ", ""); items.Replace(" From fruit_table", ""); //Convert string to list, seperating on commas List<string> itemList = items.ToString().ToUpper().Split(',').ToList<string>(); //Found a handy "distinct" method in LINQ library itemList = itemList.Distinct().ToList(); //Wipe out the original stringbuilder. For clarity and consistency with some other code, I'd like to reuse the same stringBuilder that was passed to me. items.Clear(); //Rebuild my stringbuilder, now deduped items.Append("SELECT "); itemList.ForEach(x => items.Append(x + ",")); //Remove that comma after last fruit item items.Remove((items.Length - 1), 1); items.Append(" FROM fruit_table"); //Not really going to output to console, but you //get the idea. Console.WriteLine(items.ToString()); Console.ReadLine(); Thank you in advance for any assistance! A: If you are stuck with starting with the StringBuilder then I think you've pretty much worked out what you need to do. I would make it a little cleaner like this though: var prefix = "SELECT "; var suffix = " From fruit_table"; var result = String.Format("{0}{2}{1}", prefix, suffix, String.Join(",", items .ToString() .Replace(prefix, "") .Replace(suffix, "") .Split(',') .Select(x => x.Trim()) .Distinct())); items.Clear(); items.Append(result); Before: SELECT Apple,Carrot,Pear,Orange,Apple From fruit_table After: SELECT Apple,Carrot,Pear,Orange From fruit_table If you know that there are no spaces between the names of the columns, then this is slightly cleaner: var result = String.Format("{0}{2}{1}", prefix, suffix, String.Join(",", items .ToString() .Split(' ')[1] .Split(',') .Distinct())); A: Here's another way to do it without having to hard-code the prefix and suffix elements: // Encapsulate the behavior in an extension method we can run // directly on a StringBuilder object public static StringBuilder DeduplicateColumns(this StringBuilder input) { // Assume that we can split into large "chunks" on spaces var sections = input.ToString().Split(' '); var resultSections = new List<string>(); foreach (var section in sections) { var items = section.Split(','); // If there aren't any commas, spit this chunk back out // Otherwise, split on the commas and get distinct items if (items.Count() == 1) resultSections.Add(section); else resultSections.Add(string.Join(",", items.Distinct())); } return new StringBuilder(string.Join(" ", resultSections)); } Test code: var demoStringBuilder = new StringBuilder ("SELECT Apple,Carrot,Pear,Orange,Apple From fruit_table"); var cleanedBuilder = demoStringBuilder.DeduplicateColumns(); // Output: SELECT Apple,Carrot,Pear,Orange From fruit_table Here's a fiddle: link
{ "language": "en", "url": "https://stackoverflow.com/questions/28553734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL to google charts PHP <?php $con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!"); mysql_select_db("data", $con); $sth = mysql_query("SELECT * FROM data"); $data = array ( 'cols' => array( array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'), array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'), array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number') ), 'rows' => array() ); while ($res = mysql_fetch_assoc($sth)) // array nesting is complex owing to to google charts api array_push($data['rows'], array('c' => array( array('v' => $res['date']), array('v' => $res['temp1']), array('v' => $res['temp2']) ))); } ?> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var bar_chart_data = new google.visualization.DataTable(<?php echo json_encode($data); ?>); var options = { title: 'Weather data' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(bar_chart_data, options); } </script> </head> <body> <div id="chart_div" style="width: 900px; height: 500px;"></div> </body> </html> I am having problem finishing this, echo count($bar_chart_rows_arr) AND echo count($task_submissions_arr) is showing corresponding good results (number of rows in table). The chart frame is showing but there are no table/chart data. Any suggestions ? output html: 6060 <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var bar_chart_data = new google.visualization.DataTable( { cols: [{"id":"date","label":"Date ","type":"datetime"},{"id":"temp1","label":"Temp 1","type":"number"},{"id":"temp2","label":"Temp 2","type":"number"}], rows: [{"c":[{"date":{"id":"1","temp1":"10.75","temp2":"4","date":"2013-10-05 20:41:00"}},{"temp1":{"id":"1","temp1":"10.75","temp2":"4","date":"2013-10-05 20:41:00"}},{"temp2":{"id":"1","temp1":"10.75","temp2":"4","date":"2013-10-05 20:41:00"}}]},{"c":[{"date":{"id":"2","temp1":"9.125","temp2":"4","date":"2013-10-05 22:18:17"}},{"temp1":{"id":"2","temp1":"9.125","temp2":"4","date":"2013-10-05 22:18:17"}},{"temp2":{"id":"2","temp1":"9.125","temp2":"4","date":"2013-10-05 22:18:17"}}]},{"c":[{"date":{"id":"3","temp1":"8.187","temp2":"4","date":"2013-10-05 23:51:20"}},{"temp1":{"id":"3","temp1":"8.187","temp2":"4","date":"2013-10-05 23:51:20"}},{"temp2":{"id":"3","temp1":"8.187","temp2":"4","date":"2013-10-05 23:51:20"}}]},{"c":[{"date":{"id":"4","temp1":"17.187","temp2":"4","date":"2013-10-07 11:39:21"}},{"temp1":{"id":"4","temp1":"17.187","temp2":"4","date":"2013-10-07 11:39:21"}},{"temp2":{"id":"4","temp1":"17.187","temp2":"4","date":"2013-10-07 11:39:21"}}]},{"c":[{"date":{"id":"5","temp1":"17.062","temp2":"4","date":"2013-10-07 12:00:05"}},{"temp1":{"id":"5","temp1":"17.062","temp2":"4","date":"2013-10-07 12:00:05"}},{"temp2":{"id":"5","temp1":"17.062","temp2":"4","date":"2013-10-07 12:00:05"}}]},{"c":[{"date":{"id":"6","temp1":"17.187","temp2":"4","date":"2013-10-07 14:30:04"}},{"temp1":{"id":"6","temp1":"17.187","temp2":"4","date":"2013-10-07 14:30:04"}},{"temp2":{"id":"6","temp1":"17.187","temp2":"4","date":"2013-10-07 14:30:04"}}]},{"c":[{"date":{"id":"7","temp1":"17.25","temp2":"4","date":"2013-10-07 15:00:04"}},{"temp1":{"id":"7","temp1":"17.25","temp2":"4","date":"2013-10-07 15:00:04"}},{"temp2":{"id":"7","temp1":"17.25","temp2":"4","date":"2013-10-07 15:00:04"}}]},{"c":[{"date":{"id":"8","temp1":"17.562","temp2":"4","date":"2013-10-07 15:30:04"}},{"temp1":{"id":"8","temp1":"17.562","temp2":"4","date":"2013-10-07 15:30:04"}},{"temp2":{"id":"8","temp1":"17.562","temp2":"4","date":"2013-10-07 15:30:04"}}]},{"c":[{"date":{"id":"9","temp1":"17.875","temp2":"4","date":"2013-10-07 16:00:04"}},{"temp1":{"id":"9","temp1":"17.875","temp2":"4","date":"2013-10-07 16:00:04"}},{"temp2":{"id":"9","temp1":"17.875","temp2":"4","date":"2013-10-07 16:00:04"}}]},{"c":[{"date":{"id":"10","temp1":"17.875","temp2":"4","date":"2013-10-07 16:30:04"}},{"temp1":{"id":"10","temp1":"17.875","temp2":"4","date":"2013-10-07 16:30:04"}},{"temp2":{"id":"10","temp1":"17.875","temp2":"4","date":"2013-10-07 16:30:04"}}]},{"c":[{"date":{"id":"11","temp1":"17.375","temp2":"4","date":"2013-10-07 17:00:04"}},{"temp1":{"id":"11","temp1":"17.375","temp2":"4","date":"2013-10-07 17:00:04"}},{"temp2":{"id":"11","temp1":"17.375","temp2":"4","date":"2013-10-07 17:00:04"}}]},{"c":[{"date":{"id":"12","temp1":"17.062","temp2":"4","date":"2013-10-07 17:30:04"}},{"temp1":{"id":"12","temp1":"17.062","temp2":"4","date":"2013-10-07 17:30:04"}},{"temp2":{"id":"12","temp1":"17.062","temp2":"4","date":"2013-10-07 17:30:04"}}]},{"c":[{"date":{"id":"13","temp1":"17.062","temp2":"4","date":"2013-10-07 18:00:04"}},{"temp1":{"id":"13","temp1":"17.062","temp2":"4","date":"2013-10-07 18:00:04"}},{"temp2":{"id":"13","temp1":"17.062","temp2":"4","date":"2013-10-07 18:00:04"}}]},{"c":[{"date":{"id":"14","temp1":"16.187","temp2":"4","date":"2013-10-07 18:30:04"}},{"temp1":{"id":"14","temp1":"16.187","temp2":"4","date":"2013-10-07 18:30:04"}},{"temp2":{"id":"14","temp1":"16.187","temp2":"4","date":"2013-10-07 18:30:04"}}]},{"c":[{"date":{"id":"15","temp1":"15.875","temp2":"4","date":"2013-10-07 19:00:03"}},{"temp1":{"id":"15","temp1":"15.875","temp2":"4","date":"2013-10-07 19:00:03"}},{"temp2":{"id":"15","temp1":"15.875","temp2":"4","date":"2013-10-07 19:00:03"}}]},{"c":[{"date":{"id":"16","temp1":"15.625","temp2":"4","date":"2013-10-07 19:30:03"}},{"temp1":{"id":"16","temp1":"15.625","temp2":"4","date":"2013-10-07 19:30:03"}},{"temp2":{"id":"16","temp1":"15.625","temp2":"4","date":"2013-10-07 19:30:03"}}]},{"c":[{"date":{"id":"17","temp1":"15.437","temp2":"4","date":"2013-10-07 20:00:05"}},{"temp1":{"id":"17","temp1":"15.437","temp2":"4","date":"2013-10-07 20:00:05"}},{"temp2":{"id":"17","temp1":"15.437","temp2":"4","date":"2013-10-07 20:00:05"}}]},{"c":[{"date":{"id":"18","temp1":"15.375","temp2":"4","date":"2013-10-07 20:30:03"}},{"temp1":{"id":"18","temp1":"15.375","temp2":"4","date":"2013-10-07 20:30:03"}},{"temp2":{"id":"18","temp1":"15.375","temp2":"4","date":"2013-10-07 20:30:03"}}]},{"c":[{"date":{"id":"19","temp1":"15.312","temp2":"4","date":"2013-10-07 21:00:04"}},{"temp1":{"id":"19","temp1":"15.312","temp2":"4","date":"2013-10-07 21:00:04"}},{"temp2":{"id":"19","temp1":"15.312","temp2":"4","date":"2013-10-07 21:00:04"}}]},{"c":[{"date":{"id":"20","temp1":"15.312","temp2":"4","date":"2013-10-07 21:30:04"}},{"temp1":{"id":"20","temp1":"15.312","temp2":"4","date":"2013-10-07 21:30:04"}},{"temp2":{"id":"20","temp1":"15.312","temp2":"4","date":"2013-10-07 21:30:04"}}]},{"c":[{"date":{"id":"21","temp1":"15.312","temp2":"4","date":"2013-10-07 22:00:04"}},{"temp1":{"id":"21","temp1":"15.312","temp2":"4","date":"2013-10-07 22:00:04"}},{"temp2":{"id":"21","temp1":"15.312","temp2":"4","date":"2013-10-07 22:00:04"}}]},{"c":[{"date":{"id":"22","temp1":"15.25","temp2":"15.25","date":"2013-10-07 22:20:00"}},{"temp1":{"id":"22","temp1":"15.25","temp2":"15.25","date":"2013-10-07 22:20:00"}},{"temp2":{"id":"22","temp1":"15.25","temp2":"15.25","date":"2013-10-07 22:20:00"}}]},{"c":[{"date":{"id":"23","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:21:40"}},{"temp1":{"id":"23","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:21:40"}},{"temp2":{"id":"23","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:21:40"}}]},{"c":[{"date":{"id":"24","temp1":"15.25","temp2":"15.187","date":"2013-10-07 22:22:25"}},{"temp1":{"id":"24","temp1":"15.25","temp2":"15.187","date":"2013-10-07 22:22:25"}},{"temp2":{"id":"24","temp1":"15.25","temp2":"15.187","date":"2013-10-07 22:22:25"}}]},{"c":[{"date":{"id":"25","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:30:06"}},{"temp1":{"id":"25","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:30:06"}},{"temp2":{"id":"25","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:30:06"}}]},{"c":[{"date":{"id":"26","temp1":"15.312","temp2":"15.312","date":"2013-10-07 22:53:33"}},{"temp1":{"id":"26","temp1":"15.312","temp2":"15.312","date":"2013-10-07 22:53:33"}},{"temp2":{"id":"26","temp1":"15.312","temp2":"15.312","date":"2013-10-07 22:53:33"}}]},{"c":[{"date":{"id":"27","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:53:45"}},{"temp1":{"id":"27","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:53:45"}},{"temp2":{"id":"27","temp1":"15.312","temp2":"15.25","date":"2013-10-07 22:53:45"}}]},{"c":[{"date":{"id":"28","temp1":"15.375","temp2":"15.312","date":"2013-10-07 23:00:05"}},{"temp1":{"id":"28","temp1":"15.375","temp2":"15.312","date":"2013-10-07 23:00:05"}},{"temp2":{"id":"28","temp1":"15.375","temp2":"15.312","date":"2013-10-07 23:00:05"}}]},{"c":[{"date":{"id":"29","temp1":"14.937","temp2":"15.25","date":"2013-10-07 23:01:04"}},{"temp1":{"id":"29","temp1":"14.937","temp2":"15.25","date":"2013-10-07 23:01:04"}},{"temp2":{"id":"29","temp1":"14.937","temp2":"15.25","date":"2013-10-07 23:01:04"}}]},{"c":[{"date":{"id":"30","temp1":"14.937","temp2":"15.25","date":"2013-10-07 23:01:11"}},{"temp1":{"id":"30","temp1":"14.937","temp2":"15.25","date":"2013-10-07 23:01:11"}},{"temp2":{"id":"30","temp1":"14.937","temp2":"15.25","date":"2013-10-07 23:01:11"}}]},{"c":[{"date":{"id":"31","temp1":"14.875","temp2":"15.312","date":"2013-10-07 23:01:16"}},{"temp1":{"id":"31","temp1":"14.875","temp2":"15.312","date":"2013-10-07 23:01:16"}},{"temp2":{"id":"31","temp1":"14.875","temp2":"15.312","date":"2013-10-07 23:01:16"}}]},{"c":[{"date":{"id":"32","temp1":"14.812","temp2":"15.312","date":"2013-10-07 23:01:21"}},{"temp1":{"id":"32","temp1":"14.812","temp2":"15.312","date":"2013-10-07 23:01:21"}},{"temp2":{"id":"32","temp1":"14.812","temp2":"15.312","date":"2013-10-07 23:01:21"}}]},{"c":[{"date":{"id":"33","temp1":"14.75","temp2":"15.25","date":"2013-10-07 23:01:38"}},{"temp1":{"id":"33","temp1":"14.75","temp2":"15.25","date":"2013-10-07 23:01:38"}},{"temp2":{"id":"33","temp1":"14.75","temp2":"15.25","date":"2013-10-07 23:01:38"}}]},{"c":[{"date":{"id":"34","temp1":"14.75","temp2":"15.25","date":"2013-10-07 23:03:29"}},{"temp1":{"id":"34","temp1":"14.75","temp2":"15.25","date":"2013-10-07 23:03:29"}},{"temp2":{"id":"34","temp1":"14.75","temp2":"15.25","date":"2013-10-07 23:03:29"}}]},{"c":[{"date":{"id":"35","temp1":"14.375","temp2":"15.25","date":"2013-10-07 23:03:37"}},{"temp1":{"id":"35","temp1":"14.375","temp2":"15.25","date":"2013-10-07 23:03:37"}},{"temp2":{"id":"35","temp1":"14.375","temp2":"15.25","date":"2013-10-07 23:03:37"}}]},{"c":[{"date":{"id":"36","temp1":"14.375","temp2":"15.312","date":"2013-10-07 23:04:15"}},{"temp1":{"id":"36","temp1":"14.375","temp2":"15.312","date":"2013-10-07 23:04:15"}},{"temp2":{"id":"36","temp1":"14.375","temp2":"15.312","date":"2013-10-07 23:04:15"}}]},{"c":[{"date":{"id":"37","temp1":"14.25","temp2":"15.25","date":"2013-10-07 23:09:53"}},{"temp1":{"id":"37","temp1":"14.25","temp2":"15.25","date":"2013-10-07 23:09:53"}},{"temp2":{"id":"37","temp1":"14.25","temp2":"15.25","date":"2013-10-07 23:09:53"}}]},{"c":[{"date":{"id":"38","temp1":"14.187","temp2":"15.187","date":"2013-10-07 23:19:44"}},{"temp1":{"id":"38","temp1":"14.187","temp2":"15.187","date":"2013-10-07 23:19:44"}},{"temp2":{"id":"38","temp1":"14.187","temp2":"15.187","date":"2013-10-07 23:19:44"}}]},{"c":[{"date":{"id":"39","temp1":"14.125","temp2":"15.125","date":"2013-10-07 23:30:05"}},{"temp1":{"id":"39","temp1":"14.125","temp2":"15.125","date":"2013-10-07 23:30:05"}},{"temp2":{"id":"39","temp1":"14.125","temp2":"15.125","date":"2013-10-07 23:30:05"}}]},{"c":[{"date":{"id":"40","temp1":"14.125","temp2":"15","date":"2013-10-08 00:00:06"}},{"temp1":{"id":"40","temp1":"14.125","temp2":"15","date":"2013-10-08 00:00:06"}},{"temp2":{"id":"40","temp1":"14.125","temp2":"15","date":"2013-10-08 00:00:06"}}]},{"c":[{"date":{"id":"41","temp1":"13.875","temp2":"14.937","date":"2013-10-08 00:30:05"}},{"temp1":{"id":"41","temp1":"13.875","temp2":"14.937","date":"2013-10-08 00:30:05"}},{"temp2":{"id":"41","temp1":"13.875","temp2":"14.937","date":"2013-10-08 00:30:05"}}]},{"c":[{"date":{"id":"42","temp1":"13.75","temp2":"14.937","date":"2013-10-08 01:00:05"}},{"temp1":{"id":"42","temp1":"13.75","temp2":"14.937","date":"2013-10-08 01:00:05"}},{"temp2":{"id":"42","temp1":"13.75","temp2":"14.937","date":"2013-10-08 01:00:05"}}]},{"c":[{"date":{"id":"43","temp1":"13.812","temp2":"14.75","date":"2013-10-08 01:30:06"}},{"temp1":{"id":"43","temp1":"13.812","temp2":"14.75","date":"2013-10-08 01:30:06"}},{"temp2":{"id":"43","temp1":"13.812","temp2":"14.75","date":"2013-10-08 01:30:06"}}]},{"c":[{"date":{"id":"44","temp1":"13.937","temp2":"14.625","date":"2013-10-08 02:00:06"}},{"temp1":{"id":"44","temp1":"13.937","temp2":"14.625","date":"2013-10-08 02:00:06"}},{"temp2":{"id":"44","temp1":"13.937","temp2":"14.625","date":"2013-10-08 02:00:06"}}]},{"c":[{"date":{"id":"45","temp1":"14","temp2":"14.625","date":"2013-10-08 02:30:05"}},{"temp1":{"id":"45","temp1":"14","temp2":"14.625","date":"2013-10-08 02:30:05"}},{"temp2":{"id":"45","temp1":"14","temp2":"14.625","date":"2013-10-08 02:30:05"}}]},{"c":[{"date":{"id":"46","temp1":"14.062","temp2":"14.812","date":"2013-10-08 03:00:06"}},{"temp1":{"id":"46","temp1":"14.062","temp2":"14.812","date":"2013-10-08 03:00:06"}},{"temp2":{"id":"46","temp1":"14.062","temp2":"14.812","date":"2013-10-08 03:00:06"}}]},{"c":[{"date":{"id":"47","temp1":"14.062","temp2":"14.937","date":"2013-10-08 03:30:05"}},{"temp1":{"id":"47","temp1":"14.062","temp2":"14.937","date":"2013-10-08 03:30:05"}},{"temp2":{"id":"47","temp1":"14.062","temp2":"14.937","date":"2013-10-08 03:30:05"}}]},{"c":[{"date":{"id":"48","temp1":"13.937","temp2":"14.875","date":"2013-10-08 04:00:06"}},{"temp1":{"id":"48","temp1":"13.937","temp2":"14.875","date":"2013-10-08 04:00:06"}},{"temp2":{"id":"48","temp1":"13.937","temp2":"14.875","date":"2013-10-08 04:00:06"}}]},{"c":[{"date":{"id":"49","temp1":"14","temp2":"14.812","date":"2013-10-08 04:30:05"}},{"temp1":{"id":"49","temp1":"14","temp2":"14.812","date":"2013-10-08 04:30:05"}},{"temp2":{"id":"49","temp1":"14","temp2":"14.812","date":"2013-10-08 04:30:05"}}]},{"c":[{"date":{"id":"50","temp1":"13.625","temp2":"14.75","date":"2013-10-08 05:00:06"}},{"temp1":{"id":"50","temp1":"13.625","temp2":"14.75","date":"2013-10-08 05:00:06"}},{"temp2":{"id":"50","temp1":"13.625","temp2":"14.75","date":"2013-10-08 05:00:06"}}]},{"c":[{"date":{"id":"51","temp1":"13.375","temp2":"14.687","date":"2013-10-08 03:30:06"}},{"temp1":{"id":"51","temp1":"13.375","temp2":"14.687","date":"2013-10-08 03:30:06"}},{"temp2":{"id":"51","temp1":"13.375","temp2":"14.687","date":"2013-10-08 03:30:06"}}]},{"c":[{"date":{"id":"52","temp1":"13.562","temp2":"14.562","date":"2013-10-08 04:00:06"}},{"temp1":{"id":"52","temp1":"13.562","temp2":"14.562","date":"2013-10-08 04:00:06"}},{"temp2":{"id":"52","temp1":"13.562","temp2":"14.562","date":"2013-10-08 04:00:06"}}]},{"c":[{"date":{"id":"53","temp1":"13.687","temp2":"14.312","date":"2013-10-08 04:30:05"}},{"temp1":{"id":"53","temp1":"13.687","temp2":"14.312","date":"2013-10-08 04:30:05"}},{"temp2":{"id":"53","temp1":"13.687","temp2":"14.312","date":"2013-10-08 04:30:05"}}]},{"c":[{"date":{"id":"54","temp1":"14","temp2":"14.375","date":"2013-10-08 05:00:05"}},{"temp1":{"id":"54","temp1":"14","temp2":"14.375","date":"2013-10-08 05:00:05"}},{"temp2":{"id":"54","temp1":"14","temp2":"14.375","date":"2013-10-08 05:00:05"}}]},{"c":[{"date":{"id":"55","temp1":"13.875","temp2":"14.5","date":"2013-10-08 05:30:05"}},{"temp1":{"id":"55","temp1":"13.875","temp2":"14.5","date":"2013-10-08 05:30:05"}},{"temp2":{"id":"55","temp1":"13.875","temp2":"14.5","date":"2013-10-08 05:30:05"}}]},{"c":[{"date":{"id":"56","temp1":"13.75","temp2":"14.5","date":"2013-10-08 06:00:06"}},{"temp1":{"id":"56","temp1":"13.75","temp2":"14.5","date":"2013-10-08 06:00:06"}},{"temp2":{"id":"56","temp1":"13.75","temp2":"14.5","date":"2013-10-08 06:00:06"}}]},{"c":[{"date":{"id":"57","temp1":"13.812","temp2":"14.5","date":"2013-10-08 06:30:05"}},{"temp1":{"id":"57","temp1":"13.812","temp2":"14.5","date":"2013-10-08 06:30:05"}},{"temp2":{"id":"57","temp1":"13.812","temp2":"14.5","date":"2013-10-08 06:30:05"}}]},{"c":[{"date":{"id":"58","temp1":"14.125","temp2":"14.562","date":"2013-10-08 07:00:05"}},{"temp1":{"id":"58","temp1":"14.125","temp2":"14.562","date":"2013-10-08 07:00:05"}},{"temp2":{"id":"58","temp1":"14.125","temp2":"14.562","date":"2013-10-08 07:00:05"}}]},{"c":[{"date":{"id":"59","temp1":"14.937","temp2":"14.625","date":"2013-10-08 07:30:05"}},{"temp1":{"id":"59","temp1":"14.937","temp2":"14.625","date":"2013-10-08 07:30:05"}},{"temp2":{"id":"59","temp1":"14.937","temp2":"14.625","date":"2013-10-08 07:30:05"}}]},{"c":[{"date":{"id":"60","temp1":"15.812","temp2":"15.937","date":"2013-10-08 14:34:40"}},{"temp1":{"id":"60","temp1":"15.812","temp2":"15.937","date":"2013-10-08 14:34:40"}},{"temp2":{"id":"60","temp1":"15.812","temp2":"15.937","date":"2013-10-08 14:34:40"}}]}] }); var options = { title: 'Weather data' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(bar_chart_data, options); } </script> </head> <body> <div id="chart_div" style="width: 900px; height: 500px;"></div> </body> </html> A: Your PHP code is producing JSON in an incorrect format for the Google Visualization API. Try this instead: <?php $con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!"); mysql_select_db("data", $con); $sth = mysql_query("SELECT * FROM data"); $data = array ( 'cols' => array( array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'), array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'), array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number') ), 'rows' => array() ); while ($res = mysql_fetch_assoc($sth)) // array nesting is complex owing to to google charts api array_push($data['rows'], array('c' => array( array('v' => $res['date']), array('v' => $res['temp1']), array('v' => $res['temp2']) ))); } ?> and then in your javascript: var bar_chart_data = new google.visualization.DataTable(<?php echo json_encode($data); ?>); A: From the code you've originally posted - change $task_submissions_arr[][] = $res; to $task_submissions_arr[] = $res; A: Thanks for all your help in the design, I had several mistakes but the crucial mistake was that I used the wrong format for date, datetime from MySQL database, when I changed it from date / datetime to string the code was complete! $table['cols']=array( array('label' => 'Date', type=>'string'), array('label' => 'Temp 1', type=>'number'), array('label' =>'Temp 2', type=>'number'), ); Jason result: new google.visualization.DataTable({"cols":[{"label":"Date","type":"string"},{"label":"Temp 1","type":"number"},{"label":"Temp 2","type":"number"}],"rows":[{"c":[{"v":"2013-10-05 20:41:00"},{"v":10.75},{"v":4}]}
{ "language": "en", "url": "https://stackoverflow.com/questions/19232898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I access the value of a slot in a Svelte 3 component? I've been playing around with Svelte 3. I'm trying to create a basic Link component that's used like this: <Link to="http://google.com">Google</Link> My component renders a normal HTML <a> tag with a favicon in front of the link text: <script> export let to const imageURL = getFaviconFor(to) </script> <a href={to}> <img src={imageURL} alt={`${title} Icon`} /> <slot /> </a> The title variable I'm showing in the alt attribute for my <img> tag needs to be the text value of the unnamed slot. This is a really basic example, but is there any way to get the value of a slot like this? A: In the mean time I found another (even better and not so hacky) way: <script> export let to let slotObj; const imageURL = getFaviconFor(to) </script> <a href={to}> <img src={imageURL} alt={slotObj? slotObj.textContent + ' Icon' : 'Icon'} /> <span bind:this={slotObj}><slot/></span> </a> A: This hack will work. Add a hidden span or div to bind the slot text: <span contenteditable="true" bind:textContent={text} class="hide"> <slot/> </span> And update your code like this: <script> export let to let text; const imageURL = getFaviconFor(to) </script> <a href={to}> <img src={imageURL} alt={text + ' Icon'} /> {text} </a>
{ "language": "en", "url": "https://stackoverflow.com/questions/56104899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do I specify a type bound for Float and Double on a generic type in Scala? I am writing some simple Vector and Matrix classes. They look like this: // Vector with Floats case class Vector3f(x: Float, y: Float, z: Float) { def +(v: Vector3f) = Vector3f(x + v.x, y + v.y, z + v.z) } // Vector with Doubles case class Vector3d(x: Double, y: Double, z: Double) { def +(v: Vector3d) = Vector3d(x + v.x, y + v.y, z + v.z) } If I go on with further methods and classes like Point3f/d, Vector4f/d, Matrix3f/d, Matrix4f/d ... this is going to be a lot of work. Uff... So I thought generics could possible help here and remove redundancy from my code base. I thought of something like this: // first I define a generic Vector class case class Vector3[@specialized(Float, Double) T](x: T, y: T, z: T) { def +(v: Vector3[T]) = new Vector3[T](x + v.x, y + v.y, z + v.z) } // than I use some type aliases to hide the generic nature type Vector3f = Vector3[Float] type Vector3d = Vector3[Double] The idea is that the scala compiler generates specialized classes for Vector3[Float] and Vector3[Double] similar as a C++ template would do. Unfortunately I have to put some type bound on the type parameter [T] of class Vector3 such that the operator + is defined on T. My question: How can I write Vector3[Float] that it has the same performance characteristics as Vector3f? Context: I would like to use the Vector3f / Vector3d classes in collision detection code ... so performance does matter for me. A: Use a context bound of Fractional: case class Vector3[@specialized(Float, Double) T : Fractional](x: T, y: T, z: T) { ... then within the body of the class, get an instance of the arithmetic operators: val fractOps = implicitly[Fractional[T]] lastly import its members into the scope of the class: import fractOps._ Thereafter you can write ordinary infix operations on values of type T used within the class. Sadly, you will have to use fractOps.div(a, b) instead of a / b for division.
{ "language": "en", "url": "https://stackoverflow.com/questions/3462983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: calculating how many lines of code in ipython notebook just for curiosity sake - is there a way to find how many lines of code you've written in your ipython notebook? I have multiple lines per box, so I can't just count the number of boxes I have...
{ "language": "en", "url": "https://stackoverflow.com/questions/22234271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSLT to sum product of two attributes I have the following XML source structure: <turnovers> <turnover repid="1" amount="500" rate="0.1"/> <turnover repid="5" amount="600" rate="0.5"/> <turnover repid="4" amount="400" rate="0.2"/> <turnover repid="1" amount="700" rate="0.05"/> <turnover repid="2" amount="100" rate="0.15"/> <turnover repid="1" amount="900" rate="0.25"/> <turnover repid="2" amount="1000" rate="0.18"/> <turnover repid="5" amount="200" rate="0.55"/> <turnover repid="9" amount="700" rate="0.40"/> </turnovers> I need an XSL:value-of select statement that will return the sum of the product of the rate attribute and the amount attribute for a given rep ID. So for rep 5 I need ((600 x 0.5) + (200 x 0.55)). A: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:template match="/turnovers"> <val> <!-- call the sum function (with the relevant nodes) --> <xsl:call-template name="sum"> <xsl:with-param name="nodes" select="turnover[@repid='5']" /> </xsl:call-template> </val> </xsl:template> <xsl:template name="sum"> <xsl:param name="nodes" /> <xsl:param name="sum" select="0" /> <xsl:variable name="curr" select="$nodes[1]" /> <!-- if we have a node, calculate & recurse --> <xsl:if test="$curr"> <xsl:variable name="runningsum" select=" $sum + $curr/@amount * $curr/@rate " /> <xsl:call-template name="sum"> <xsl:with-param name="nodes" select="$nodes[position() &gt; 1]" /> <xsl:with-param name="sum" select="$runningsum" /> </xsl:call-template> </xsl:if> <!-- if we don't have a node (last recursive step), return sum --> <xsl:if test="not($curr)"> <xsl:value-of select="$sum" /> </xsl:if> </xsl:template> </xsl:stylesheet> Gives: <val>410</val> The two <xsl:if>s can be replaced by a single <xsl:choose>. This would mean one less check during the recursion, but it also means two additional lines of code. A: In plain XSLT 1.0 you need a recursive template for this, for example: <xsl:template match="turnovers"> <xsl:variable name="selectedId" select="5" /> <xsl:call-template name="sum_turnover"> <xsl:with-param name="turnovers" select="turnover[@repid=$selectedId]" /> </xsl:call-template> </xsl:template> <xsl:template name="sum_turnover"> <xsl:param name="total" select="0" /> <xsl:param name="turnovers" /> <xsl:variable name="head" select="$turnovers[1]" /> <xsl:variable name="tail" select="$turnovers[position()>1]" /> <xsl:variable name="calc" select="$head/@amount * $head/@rate" /> <xsl:choose> <xsl:when test="not($tail)"> <xsl:value-of select="$total + $calc" /> </xsl:when> <xsl:otherwise> <xsl:call-template name="sum_turnover"> <xsl:with-param name="total" select="$total + $calc" /> <xsl:with-param name="turnovers" select="$tail" /> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> A: This should do the trick, you'll need to do some further work to select the distinct repid's <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <xsl:variable name="totals"> <product> <xsl:for-each select="turnovers/turnover"> <repid repid="{@repid}"> <value><xsl:value-of select="@amount * @rate"/></value> </repid> </xsl:for-each> </product> </xsl:variable> <totals> <total repid="5" value="{sum($totals/product/repid[@repid='5']/value)}"/> </totals> </xsl:template> </xsl:stylesheet> A: In XSLT 1.0 the use of FXSL makes such problems easy to solve: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:f="http://fxsl.sf.net/" xmlns:ext="http://exslt.org/common" exclude-result-prefixes="xsl f ext" > <xsl:import href="zipWith.xsl"/> <xsl:output method="text"/> <xsl:variable name="vMultFun" select="document('')/*/f:mult-func[1]"/> <xsl:template match="/"> <xsl:call-template name="profitForId"/> </xsl:template> <xsl:template name="profitForId"> <xsl:param name="pId" select="1"/> <xsl:variable name="vrtfProducts"> <xsl:call-template name="zipWith"> <xsl:with-param name="pFun" select="$vMultFun"/> <xsl:with-param name="pList1" select="/*/*[@repid = $pId]/@amount"/> <xsl:with-param name="pList2" select="/*/*[@repid = $pId]/@rate"/> </xsl:call-template> </xsl:variable> <xsl:value-of select="sum(ext:node-set($vrtfProducts)/*)"/> </xsl:template> <f:mult-func/> <xsl:template match="f:mult-func" mode="f:FXSL"> <xsl:param name="pArg1"/> <xsl:param name="pArg2"/> <xsl:value-of select="$pArg1 * $pArg2"/> </xsl:template> </xsl:stylesheet> When this transformation is applied on the originally posted source XML document, the correct result is produced: 310 In XSLT 2.0 the same solution using FXSL 2.0 can be expressed by an XPath one-liner: sum(f:zipWith(f:multiply(), /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.), /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.) ) ) The whole transformation: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:f="http://fxsl.sf.net/" exclude-result-prefixes="f xs" > <xsl:import href="../f/func-zipWithDVC.xsl"/> <xsl:import href="../f/func-Operators.xsl"/> <!-- To be applied on testFunc-zipWith4.xml --> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:value-of select= "sum(f:zipWith(f:multiply(), /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.), /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.) ) ) "/> </xsl:template> </xsl:stylesheet> Again, this transformation produces the correct answer: 310 Note the following: * *The f:zipWith() function takes as arguments a function fun() (of two arguments) and two lists of items having the same length. It produces a new list of the same length, whose items are the result of the pair-wise application of fun() on the corresponding k-th items of the two lists. *f:zipWith() as in the expression takes the function f:multiply() and two sequences of corresponding "ammount" and "rate" attributes. The sesult is a sequence, each item of which is the product of the corresponding "ammount" and "rate". *Finally, the sum of this sequence is produced. *There is no need to write an explicit recursion and it is also guaranteed that the behind-the scenes recursion used within f:zipWith() is never going to crash (for all practical cases) with "stack overflow" A: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0"> <xsl:variable name="repid" select="5" /> <xsl:template match="/"> <xsl:value-of select= "sum(for $x in /turnovers/turnover[@repid=$repid] return $x/@amount * $x/@rate)"/> </xsl:template> </xsl:stylesheet> You can do this if you just need the value and not xml. A: The easiest way to do it in XSLT is probably to use programming language bindings, so that you can define your own XPath functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/1333558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Code API default signature gsuite email in admin I am not sure how to input the code and location input the code for gsuite. So it is set up as default for each employee
{ "language": "en", "url": "https://stackoverflow.com/questions/51574059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passing data to dynamically created ascx user control I want to display user control which produces different set of data depending on values which are being passed to it. No. of UserControls are decided at run-time * *Now it dint Hit in Page_Load of ascx.cs Default.aspx <%@ Register Src="~/UserControl/SquareEUA.ascx" TagName="Square" TagPrefix="EUA" %> <body> <div id="divControls" runat="server"></div> </body> Default.aspx.cs protected void Page_Load(object sender, EventArgs e) { string[] Property; foreach (string sPropID in Property) { SquareEUA userControl = (SquareEUA)Page.LoadControl("~/UserControl/SquareEUA.ascx"); userControl.ID = "MyControl_" + sPropID.Trim(); userControl.sCustID = CustomerID; userControl.sCustPropID = sPropID.Trim(); userControl.Visible = true; divControls.Controls.Add(userControl); userControl.Dispose(); } } SquareEUA.ascx <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SquareEUA.ascx.cs" Inherits="UserControl.SquareEUA" %> <div> // Some HTML Markup </div> SquareEUA.ascx.cs public partial class SquareEUA : System.Web.UI.UserControl { public string sCustID { get; set; } public string sCustPropID { get; set; } protected void Page_Load(object sender, EventArgs e) { // Some Code // Didnt Hit Breakpoint Here; } } A: you need to cast your usercontrol as the actual class SquareEUA to access that class's properties SquareEUA userControl = (SquareEUA)(Page.LoadControl("~/UserControl/SquareEUA.ascx")); that should do the trick (you should add some error handling, null check, etc.) edit: seems I missed a parenthesis around (Page...
{ "language": "en", "url": "https://stackoverflow.com/questions/26119091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linux: Join two lines with an equal value in the SAME file I have a file that looks like this: 1 51 Brahui A C A A T 1 51 Brahui A C A G T 3 51 Brahui A C A G C 3 51 Brahui A C G A T 5 51 Brahui A C G A T 5 51 Brahui A C G G C 7 51 Brahui A C G A T 7 51 Brahui A C G G T 9 51 Brahui A C G G T 9 51 Brahui A C G G T And I want to generate an output file whereby if the first column/field are of equal value then I want to merge the two lines together with a "/" character as a delimiter. For example: 1 51 Brahui A/A C/C A/A A/G T/T 3 51 Brahui A/A C/C A/G G/A C/T Is there a way that I can do that? P.S.The columns starting from $4 are actually 2,834 long (i.e. $4-$2841) so I don't think it will be practical to physically enter $4, $5, $6, etc.. Is there a way to do this? A: pearl.229>awk '{a=$1; b=$4; c=$5; d=$6; e=$7; f=$8; getline; if(a==$1) print a,$2,$3,b"/"$4,c"/"$5,d"/"$6,e"/"$7,f"/"$8}' file3 1 51 Brahui A/A C/C A/A A/G T/T 3 51 Brahui A/A C/C A/G G/A C/T 5 51 Brahui A/A C/C G/G A/G T/C 7 51 Brahui A/A C/C G/G A/G T/T 9 51 Brahui A/A C/C G/G G/G T/T pearl.230> A: I like using fmt. It makes the code prettier. [ghoti@pc ~]$ cat doit #!/usr/bin/awk -f BEGIN { fmt="%s %s %s %s/%s %s/%s %s/%s %s/%s %s/%s\n"; } one == $1 { split(last,a); printf(fmt, $1,$2,$3, a[4],$4, a[5],$5, a[6],$6, a[7],$7, a[8],$8); } { last = $0; one = $1; } [ghoti@pc ~]$ ./doit input.txt 1 51 Brahui A/A C/C A/A A/G T/T 3 51 Brahui A/A C/C A/G G/A C/T 5 51 Brahui A/A C/C G/G A/G T/C 7 51 Brahui A/A C/C G/G A/G T/T 9 51 Brahui A/A C/C G/G G/G T/T [ghoti@pc ~]$
{ "language": "en", "url": "https://stackoverflow.com/questions/9992215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Explain Traverse[List] implementation in scalaz-seven I'm trying to understand the traverseImpl implementation in scalaz-seven: def traverseImpl[F[_], A, B](l: List[A])(f: A => F[B])(implicit F: Applicative[F]) = { DList.fromList(l).foldr(F.point(List[B]())) { (a, fbs) => F.map2(f(a), fbs)(_ :: _) } } Can someone explain how the List interacts with the Applicative? Ultimately, I'd like to be able to implement other instances for Traverse. A: An applicative lets you apply a function in a context to a value in a context. So for instance, you can apply some((i: Int) => i + 1) to some(3) and get some(4). Let's forget that for now. I'll come back to that later. List has two representations, it's either Nil or head :: tail. You may be used to fold over it using foldLeft but there is another way to fold over it: def foldr[A, B](l: List[A], acc0: B, f: (A, B) => B): B = l match { case Nil => acc0 case x :: xs => f(x, foldr(xs, acc0, f)) } Given List(1, 2) we fold over the list applying the function starting from the right side - even though we really deconstruct the list from the left side! f(1, f(2, Nil)) This can be used to compute the length of a list. Given List(1, 2): foldr(List(1, 2), 0, (i: Int, acc: Int) => 1 + acc) // returns 2 This can also be used to create another list: foldr[Int, List[Int]](List(1, 2), List[Int](), _ :: _) //List[Int] = List(1, 2) So given an empty list and the :: function we were able to create another list. What if our elements are in some context? If our context is an applicative then we can still apply our elements and :: in that context. Continuing with List(1, 2) and Option as our applicative. We start with some(List[Int]())) we want to apply the :: function in the Option context. This is what the F.map2 does. It takes two values in their Option context, put the provided function of two arguments into the Option context and apply them together. So outside the context we have (2, Nil) => 2 :: Nil In context we have: (Some(2), Some(Nil)) => Some(2 :: Nil) Going back to the original question: // do a foldr DList.fromList(l).foldr(F.point(List[B]())) { // starting with an empty list in its applicative context F.point(List[B]()) (a, fbs) => F.map2(f(a), fbs)(_ :: _) // Apply the `::` function to the two values in the context } I am not sure why the difference DList is used. What I see is that it uses trampolines so hopefully that makes this implementation work without blowing the stack, but I have not tried so I don't know. The interesting part about implementing the right fold like this is that I think it gives you an approach to implement traverse for algebric data types using catamorphisms. For instance given: trait Tree[+A] object Leaf extends Tree[Nothing] case class Node[A](a: A, left: Tree[A], right: Tree[A]) extends Tree[A] Fold would be defined like this (which is really following the same approach as for List): def fold[A, B](tree: Tree[A], valueForLeaf: B, functionForNode: (A, B, B) => B): B = { tree match { case Leaf => valueForLeaf case Node(a, left, right) => functionForNode(a, fold(left, valueForLeaf, functionForNode), fold(right, valueForLeaf, functionForNode) ) } } And traverse would use that fold with F.point(Leaf) and apply it to Node.apply. Though there is no F.map3 so it may be a bit cumbersome. A: This not something so easy to grasp. I recommend reading the article linked at the beginning of my blog post on the subject. I also did a presentation on the subject during the last Functional Programming meeting in Sydney and you can find the slides here. If I can try to explain in a few words, traverse is going to traverse each element of the list one by one, eventually re-constructing the list (_ :: _) but accumulating/executing some kind of "effects" as given by the F Applicative. If F is State it keeps track of some state. If F is the applicative corresponding to a Monoid it aggregates some kind of measure for each element of the list. The main interaction of the list and the applicative is with the map2 application where it receives a F[B] element and attach it to the other F[List[B]] elements by definition of F as an Applicative and the use of the List constructor :: as the specific function to apply. From there you see that implementing other instances of Traverse is only about applying the data constructors of the data structure you want to traverse. If you have a look at the linked powerpoint presentation, you'll see some slides with a binary tree traversal. A: List#foldRight blows the stack for large lists. Try this in a REPL: List.range(0, 10000).foldRight(())((a, b) => ()) Typically, you can reverse the list, use foldLeft, then reverse the result to avoid this problem. But with traverse we really have to process the elements in the correct order, to make sure that the effect is treated correctly. DList is a convenient way to do this, by virtue of trampolining. In the end, these tests must pass: https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/TraverseTest.scala#L13 https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/std/ListTest.scala#L11 https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Traverse.scala#L76
{ "language": "en", "url": "https://stackoverflow.com/questions/9713910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Issue with deploying Azure project using Powershell 2 I used the Azure training kit command New-Deployment -serviceName <YOUR_SERVICE_NAME_LOWER_CASE> -subscriptionId <YOUR_SUBSCRIPTION_ID> -certificate (get-item cert:\CurrentUser\MY\<YOUR_CERTIFICATE_THUMBPRINT>) -slot staging –package <PACKAGE_LOCATION> -configuration <CONFIGURATION_LOCATION> -label "v2.0" –storageServiceName <YOUR_STORAGE_SERVICE_NAME_LOWER_CASE> to deploy my Azure app. It was able to upload package to the blob but when Create a new deployment it shows error as: New-Deployment : Cannot access a closed Stream. At line:1 char:15 + New-Deployment <<<< -serviceName mytodo -subscriptionId xxxxxxxxx 8ad-360cdbdc361f -certificate (get-item cert:\CurrentUser\MY\xxxxxxxx 6DD27E3DFF5F7FE24A3FBF) -slot staging -package MyTodo.cspkg -configuration Serv iceConfiguration.cscfg -label "v1.0" -storageServiceName xxxxx + CategoryInfo : CloseError: (:) [New-Deployment], ObjectDisposed Exception + FullyQualifiedErrorId : Microsoft.WindowsAzure.Samples.ManagementTools.P owerShell.Services.HostedServices.NewDeploymentCommand A: Do you have a local proxy (e.g. Fiddler) running? If so, you'll need to disable it. Also, check the certificate is installed properly and in the right place: follow, to the letter, the instructions here: http://msdn.microsoft.com/en-us/gg271300 in particular noting there are no line breaks or spaces in the path for (get-Item cert:\CurrentUser\MY\XXXXX).
{ "language": "en", "url": "https://stackoverflow.com/questions/8642175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can not create virtual environment for a django project I'm trying to create a Django project from scratch. I executed django-admin startproject autoshine in my zsh terminal. Then I opened pycharm and run pipenv install in its local terminal to create a virtual environment for this project. But I got this error: raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/home/mohsen/.local/share/virtualenvs/autoshine-YDp111VE/bin/python' I realized that in the above directory, it can create a virtual environment but unfortunately it doesn't have any bin file. I don't know how to solve this problem. Thank you for your answers in advance. A: You can try the default way of creating a venv. For more information look here python3 -m venv tutorial-env and activate it with source/tutorial-env/bin/activate
{ "language": "en", "url": "https://stackoverflow.com/questions/73843229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you get Ember Data to recognize that the server is returning IDs for hasMany relationships? My server returns JSON responses that look like this: { 'book': { 'id': 252, 'name': 'The Hobbit', 'tag_ids': [1, 2, 3, 5, 6, 7] } } I'm using Ember Data's DS.RESTSerializer, which I've extended to include a keyForRelationship function that recognizes that keys ending in "_ids" are really hasMany relationships. Thus, the above code should match up just fine with my model code, which looks like this: App.Book = DS.Model.extend({ name: DS.attr('string'), tags: DS.hasMany('tag') }); The problem is that whenever I create a new book and the server returns its JSON response, Ember Data's store gets it wrong. It fails to convert the IDs into actual tag instances. Instead, the tags property on the model is literally set to an array of IDs. Any ideas? A: You should consider using DS.ActiveModelAdapter instead of DS.RESTAdapter. See also https://stackoverflow.com/a/19209194/1345947
{ "language": "en", "url": "https://stackoverflow.com/questions/19216031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use Django templatetags on Google App Engine? My Django site has many templatetags directories, can I use Django templatetags on Google App Engine? A: Yes.
{ "language": "en", "url": "https://stackoverflow.com/questions/2710832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: check which names have the same field in a database i have this table: id name lastname id_op time 0 Richard Touch 5 8.00 1 Mattew Cast 6 9.00 2 Carl Cappai 7 10.00 3 Mario Bros 8 10.00 4 Luigi Same 9 8.00 I want to print in page ex: "Richard and Luigi have the sames time: 8.00" "Carl and Mario have the same time: 10.00" i tryed with this choice: $link=connect_db(); $query_count="SELECT * FROM table"; $result_count=mysql_query($query_count,$link); while($var = mysql_fetch_assoc($result_count)){ foreach ($var as $key => $value){ $i=0; $var[$i]; $row_count[$i][$key] = $value; //echo $content[$index][$key]; echo $key.' '.$value.', '; } $i++; } for($i=0;$i<count($row_count);$i++) { for($j=$i+1;$j<count($row_count);$j++) { if($row_count[$i]['time']==$row_count[$j]['time']) { echo ' '.$row_count[$i]['name'].' and '.$row_count_lun[$j]['name'].'have the same time:'.$row_count_lun[$i]['time'].''; } } } Final Result = Carl Carl Richard Richard.. -__- A: How about this: select group_concat(name) as names, time from table t group by time having count(*) > 1; This will give you output such as: Names Time Richard,Luigi 8:00 . . . Which can then format on the application side.
{ "language": "en", "url": "https://stackoverflow.com/questions/21646708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }