text
stringlengths
15
59.8k
meta
dict
Q: Can anyone help me with this shadow upload script? I have the shadow uploader also and works great for the 5 form fields (added 2 from original code) in the exmple but want 11, as soon as i add an extra field I get an error: Request object error 'ASP 0104 : 80004005' Operation not Allowed /a20couk/includes/ShadowUploader.asp, line 56 Here is my extra code the shadowuploader include remains the same: <!-- #include file="../../includes/ShadowUploader.asp" --> <% Dim objUpload If Request("action")="1" Then Set objUpload=New ShadowUpload If objUpload.GetError<>"" Then Response.Write("sorry, could not upload: "&objUpload.GetError) Else Response.Write("found "&objUpload.FileCount&" files...<br />") For x=0 To objUpload.FileCount-1 Response.Write("file name: "&objUpload.File(x).FileName&"<br />") Response.Write("file type: "&objUpload.File(x).ContentType&"<br />") Response.Write("file size: "&objUpload.File(x).Size&"<br />") Response.Write("image width: "&objUpload.File(x).ImageWidth&"<br />") Response.Write("image height: "&objUpload.File(x).ImageHeight&"<br />") If (objUpload.File(x).ImageWidth>200) Or (objUpload.File(x).ImageHeight>200) Then Response.Write("image to big, not saving!") Else Call objUpload.File(x).SaveToDisk(Server.MapPath("../../tempuloads/"), "") Response.Write("file saved successfully!") End If Response.Write("<hr />") Next Response.Write("thank you, "&objUpload("name")) End If End If %> <form action="<%=Request.ServerVariables( "Script_Name" )%>?action=1" enctype="multipart/form-data" method="POST"> File1: <input type="file" name="file1" /><br /> File2: <input type="file" name="file2" /><br /> File3: <input type="file" name="file3" /><br /> File4: <input type="file" name="file4" /><br /> File5: <input type="file" name="file5" /><br /> File6: <input type="file" name="file6" /><br /> File7: <input type="file" name="file7" /><br /> File8: <input type="file" name="file8" /><br /> File9: <input type="file" name="file9" /><br /> File10: <input type="file" name="file10" /><br /> File11: <input type="file" name="file11" /><br /> Name: <input type="text" name="name" /><br /> <button type="submit">Upload</button> </form> Been tearing hair out as changed alot of settings one by one nothing worked, will lose all my hair if not resolved quickly!! The shadow include file: <% 'constants: Const MAX_UPLOAD_SIZE=1500000 'bytes Const MSG_NO_DATA="nothing to upload!" Const MSG_EXCEEDED_MAX_SIZE="you exceeded the maximum upload size!" Const SU_DEBUG_MODE=False Class ShadowUpload Private m_Request Private m_Files Private m_Error Public Property Get GetError GetError = m_Error End Property Public Property Get FileCount FileCount = m_Files.Count End Property Public Function File(index) Dim keys keys = m_Files.Keys Set File = m_Files(keys(index)) End Function Public Default Property Get Item(strName) If m_Request.Exists(strName) Then Item = m_Request(strName) Else Item = "" End If End Property Private Sub Class_Initialize Dim iBytesCount, strBinData 'first of all, get amount of uploaded bytes: iBytesCount = Request.TotalBytes WriteDebug("initializing upload, bytes: " & iBytesCount & "<br />") 'abort if nothing there: If iBytesCount=0 Then m_Error = MSG_NO_DATA Exit Sub End If 'abort if exceeded maximum upload size: If iBytesCount>MAX_UPLOAD_SIZE Then m_Error = MSG_EXCEEDED_MAX_SIZE Exit Sub End If 'read the binary data: strBinData = Request.BinaryRead(iBytesCount) 'create private collections: Set m_Request = Server.CreateObject("Scripting.Dictionary") Set m_Files = Server.CreateObject("Scripting.Dictionary") 'populate the collection: Call BuildUpload(strBinData) End Sub Private Sub Class_Terminate Dim fileName If IsObject(m_Request) Then m_Request.RemoveAll Set m_Request = Nothing End If If IsObject(m_Files) Then For Each fileName In m_Files.Keys Set m_Files(fileName)=Nothing Next m_Files.RemoveAll Set m_Files = Nothing End If End Sub Private Sub BuildUpload(ByVal strBinData) Dim strBinQuote, strBinCRLF, iValuePos Dim iPosBegin, iPosEnd, strBoundaryData Dim strBoundaryEnd, iCurPosition, iBoundaryEndPos Dim strElementName, strFileName, objFileData Dim strFileType, strFileData, strElementValue strBinQuote = AsciiToBinary(chr(34)) strBinCRLF = AsciiToBinary(chr(13)) 'find the boundaries iPosBegin = 1 iPosEnd = InstrB(iPosBegin, strBinData, strBinCRLF) strBoundaryData = MidB(strBinData, iPosBegin, iPosEnd-iPosBegin) iCurPosition = InstrB(1, strBinData, strBoundaryData) strBoundaryEnd = strBoundaryData & AsciiToBinary("--") iBoundaryEndPos = InstrB(strBinData, strBoundaryEnd) 'read binary data into private collection: Do until (iCurPosition>=iBoundaryEndPos) Or (iCurPosition=0) 'skip non relevant data... iPosBegin = InstrB(iCurPosition, strBinData, AsciiToBinary("Content-Disposition")) iPosBegin = InstrB(iPosBegin, strBinData, AsciiToBinary("name=")) iValuePos = iPosBegin 'read the name of the form element, e.g. "file1", "text1" iPosBegin = iPosBegin+6 iPosEnd = InstrB(iPosBegin, strBinData, strBinQuote) strElementName = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin)) 'maybe file? iPosBegin = InstrB(iCurPosition, strBinData, AsciiToBinary("filename=")) iPosEnd = InstrB(iPosEnd, strBinData, strBoundaryData) If (iPosBegin>0) And (iPosBegin<iPosEnd) Then 'skip non relevant data.. iPosBegin = iPosBegin+10 'read file name: iPosEnd = InstrB(iPosBegin, strBinData, strBinQuote) strFileName = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin)) 'verify that we got name: If Len(strFileName)>0 Then 'create file data: Set objFileData = New FileData objFileData.FileName = strFileName 'read file type: iPosBegin = InstrB(iPosEnd, strBinData, AsciiToBinary("Content-Type:")) iPosBegin = iPosBegin+14 iPosEnd = InstrB(iPosBegin, strBinData, strBinCRLF) strFileType = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin)) objFileData.ContentType = strFileType 'read file contents: iPosBegin = iPosEnd+4 iPosEnd = InstrB(iPosBegin, strBinData, strBoundaryData)-2 strFileData = MidB(strBinData, iPosBegin, iPosEnd-iPosBegin) 'check that not empty: If LenB(strFileData)>0 Then objFileData.Contents = strFileData 'append to files collection if not empty: Set m_Files(strFileName) = objFileData Else Set objFileData = Nothing End If End If strElementValue = strFileName Else 'ordinary form value, just read: iPosBegin = InstrB(iValuePos, strBinData, strBinCRLF) iPosBegin = iPosBegin+4 iPosEnd = InstrB(iPosBegin, strBinData, strBoundaryData)-2 strElementValue = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin)) End If 'append to request collection m_Request(strElementName) = strElementValue 'skip to next element: iCurPosition = InstrB(iCurPosition+LenB(strBoundaryData), strBinData, strBoundaryData) Loop End Sub Private Function WriteDebug(msg) If SU_DEBUG_MODE Then Response.Write(msg) Response.Flush End If End Function Private Function AsciiToBinary(strAscii) Dim i, char, result result = "" For i=1 to Len(strAscii) char = Mid(strAscii, i, 1) result = result & chrB(AscB(char)) Next AsciiToBinary = result End Function Private Function BinaryToAscii(strBinary) Dim i, result result = "" For i=1 to LenB(strBinary) result = result & chr(AscB(MidB(strBinary, i, 1))) Next BinaryToAscii = result End Function End Class Class FileData Private m_fileName Private m_contentType Private m_BinaryContents Private m_AsciiContents Private m_imageWidth Private m_imageHeight Private m_checkImage Public Property Get FileName FileName = m_fileName End Property Public Property Get ContentType ContentType = m_contentType End Property Public Property Get ImageWidth If m_checkImage=False Then Call CheckImageDimensions ImageWidth = m_imageWidth End Property Public Property Get ImageHeight If m_checkImage=False Then Call CheckImageDimensions ImageHeight = m_imageHeight End Property Public Property Let FileName(strName) Dim arrTemp arrTemp = Split(strName, "\") m_fileName = arrTemp(UBound(arrTemp)) End Property Public Property Let CheckImage(blnCheck) m_checkImage = blnCheck End Property Public Property Let ContentType(strType) m_contentType = strType End Property Public Property Let Contents(strData) m_BinaryContents = strData m_AsciiContents = RSBinaryToString(m_BinaryContents) End Property Public Property Get Size Size = LenB(m_BinaryContents) End Property Private Sub CheckImageDimensions Dim width, height, colors Dim strType '''If gfxSpex(BinaryToAscii(m_BinaryContents), width, height, colors, strType) = true then If gfxSpex(m_AsciiContents, width, height, colors, strType) = true then m_imageWidth = width m_imageHeight = height End If m_checkImage = True End Sub Private Sub Class_Initialize m_imageWidth = -1 m_imageHeight = -1 m_checkImage = False End Sub Public Sub SaveToDisk(strFolderPath, ByRef strNewFileName) Dim strPath, objFSO, objFile Dim i, time1, time2 Dim objStream, strExtension strPath = strFolderPath&"\" If Len(strNewFileName)=0 Then strPath = strPath & m_fileName Else strExtension = GetExtension(strNewFileName) If Len(strExtension)=0 Then strNewFileName = strNewFileName & "." & GetExtension(m_fileName) End If strPath = strPath & strNewFileName End If WriteDebug("save file started...<br />") time1 = CDbl(Timer) Set objFSO = Server.CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.CreateTextFile(strPath) objFile.Write(m_AsciiContents) '''For i=1 to LenB(m_BinaryContents) ''' objFile.Write chr(AscB(MidB(m_BinaryContents, i, 1))) '''Next time2 = CDbl(Timer) WriteDebug("saving file took " & (time2-time1) & " seconds.<br />") objFile.Close Set objFile=Nothing Set objFSO=Nothing End Sub Private Function GetExtension(strPath) Dim arrTemp arrTemp = Split(strPath, ".") GetExtension = "" If UBound(arrTemp)>0 Then GetExtension = arrTemp(UBound(arrTemp)) End If End Function Private Function RSBinaryToString(xBinary) 'Antonin Foller, http://www.motobit.com 'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string) 'to a string (BSTR) using ADO recordset Dim Binary 'MultiByte data must be converted To VT_UI1 | VT_ARRAY first. If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary Dim RS, LBinary Const adLongVarChar = 201 Set RS = CreateObject("ADODB.Recordset") LBinary = LenB(Binary) If LBinary>0 Then RS.Fields.Append "mBinary", adLongVarChar, LBinary RS.Open RS.AddNew RS("mBinary").AppendChunk Binary RS.Update RSBinaryToString = RS("mBinary") Else RSBinaryToString = "" End If End Function Function MultiByteToBinary(MultiByte) '© 2000 Antonin Foller, http://www.motobit.com ' MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY) ' Using recordset Dim RS, LMultiByte, Binary Const adLongVarBinary = 205 Set RS = CreateObject("ADODB.Recordset") LMultiByte = LenB(MultiByte) If LMultiByte>0 Then RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte RS.Open RS.AddNew RS("mBinary").AppendChunk MultiByte & ChrB(0) RS.Update Binary = RS("mBinary").GetChunk(LMultiByte) End If MultiByteToBinary = Binary End Function Private Function WriteDebug(msg) If SU_DEBUG_MODE Then Response.Write(msg) Response.Flush End If End Function Private Function BinaryToAscii(strBinary) Dim i, result result = "" For i=1 to LenB(strBinary) result = result & chr(AscB(MidB(strBinary, i, 1))) Next BinaryToAscii = result End Function '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::: ::: '::: This routine will attempt to identify any filespec passed ::: '::: as a graphic file (regardless of the extension). This will ::: '::: work with BMP, GIF, JPG and PNG files. ::: '::: ::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::: Based on ideas presented by David Crowell ::: '::: (credit where due) ::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::: blah blah blah blah blah blah blah blah blah blah blah blah ::: '::: blah blah blah blah blah blah blah blah blah blah blah blah ::: '::: blah blah Copyright *c* MM, Mike Shaffer blah blah ::: '::: bh blah ALL RIGHTS RESERVED WORLDWIDE blah blah ::: '::: blah blah Permission is granted to use this code blah blah ::: '::: blah blah in your projects, as long as this blah blah ::: '::: blah blah copyright notice is included blah blah ::: '::: blah blah blah blah blah blah blah blah blah blah blah blah ::: '::: blah blah blah blah blah blah blah blah blah blah blah blah ::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::: ::: '::: This function gets a specified number of bytes from any ::: '::: file, starting at the offset (base 1) ::: '::: ::: '::: Passed: ::: '::: flnm => Filespec of file to read ::: '::: offset => Offset at which to start reading ::: '::: bytes => How many bytes to read ::: '::: ::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Private Function GetBytes(flnm, offset, bytes) Dim startPos If offset=0 Then startPos = 1 Else startPos = offset End If if bytes = -1 then ' Get All! GetBytes = flnm else GetBytes = Mid(flnm, startPos, bytes) end if ' Dim objFSO ' Dim objFTemp ' Dim objTextStream ' Dim lngSize ' ' Set objFSO = CreateObject("Scripting.FileSystemObject") ' ' ' First, we get the filesize ' Set objFTemp = objFSO.GetFile(flnm) ' lngSize = objFTemp.Size ' set objFTemp = nothing ' ' fsoForReading = 1 ' Set objTextStream = objFSO.OpenTextFile(flnm, fsoForReading) ' ' if offset > 0 then ' strBuff = objTextStream.Read(offset - 1) ' end if ' ' if bytes = -1 then ' Get All! ' GetBytes = objTextStream.Read(lngSize) 'ReadAll ' else ' GetBytes = objTextStream.Read(bytes) ' end if ' ' objTextStream.Close ' set objTextStream = nothing ' set objFSO = nothing End Function '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::: ::: '::: Functions to convert two bytes to a numeric value (long) ::: '::: (both little-endian and big-endian) ::: '::: ::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Private Function lngConvert(strTemp) lngConvert = clng(asc(left(strTemp, 1)) + ((asc(right(strTemp, 1)) * 256))) end function Private Function lngConvert2(strTemp) lngConvert2 = clng(asc(right(strTemp, 1)) + ((asc(left(strTemp, 1)) * 256))) end function '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: '::: ::: '::: This function does most of the real work. It will attempt ::: '::: to read any file, regardless of the extension, and will ::: '::: identify if it is a graphical image. ::: '::: ::: '::: Passed: ::: '::: flnm => Filespec of file to read ::: '::: width => width of image ::: '::: height => height of image ::: '::: depth => color depth (in number of colors) ::: '::: strImageType=> type of image (e.g. GIF, BMP, etc.) ::: '::: ::: '::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: function gfxSpex(flnm, width, height, depth, strImageType) dim strPNG dim strGIF dim strBMP dim strType dim strBuff dim lngSize dim flgFound dim strTarget dim lngPos dim ExitLoop dim lngMarkerSize strType = "" strImageType = "(unknown)" gfxSpex = False strPNG = chr(137) & chr(80) & chr(78) strGIF = "GIF" strBMP = chr(66) & chr(77) strType = GetBytes(flnm, 0, 3) if strType = strGIF then ' is GIF strImageType = "GIF" Width = lngConvert(GetBytes(flnm, 7, 2)) Height = lngConvert(GetBytes(flnm, 9, 2)) Depth = 2 ^ ((asc(GetBytes(flnm, 11, 1)) and 7) + 1) gfxSpex = True elseif left(strType, 2) = strBMP then ' is BMP strImageType = "BMP" Width = lngConvert(GetBytes(flnm, 19, 2)) Height = lngConvert(GetBytes(flnm, 23, 2)) Depth = 2 ^ (asc(GetBytes(flnm, 29, 1))) gfxSpex = True elseif strType = strPNG then ' Is PNG strImageType = "PNG" Width = lngConvert2(GetBytes(flnm, 19, 2)) Height = lngConvert2(GetBytes(flnm, 23, 2)) Depth = getBytes(flnm, 25, 2) select case asc(right(Depth,1)) case 0 Depth = 2 ^ (asc(left(Depth, 1))) gfxSpex = True case 2 Depth = 2 ^ (asc(left(Depth, 1)) * 3) gfxSpex = True case 3 Depth = 2 ^ (asc(left(Depth, 1))) '8 gfxSpex = True case 4 Depth = 2 ^ (asc(left(Depth, 1)) * 2) gfxSpex = True case 6 Depth = 2 ^ (asc(left(Depth, 1)) * 4) gfxSpex = True case else Depth = -1 end select else strBuff = GetBytes(flnm, 0, -1) ' Get all bytes from file lngSize = len(strBuff) flgFound = 0 strTarget = chr(255) & chr(216) & chr(255) flgFound = instr(strBuff, strTarget) if flgFound = 0 then exit function end if strImageType = "JPG" lngPos = flgFound + 2 ExitLoop = false do while ExitLoop = False and lngPos < lngSize do while asc(mid(strBuff, lngPos, 1)) = 255 and lngPos < lngSize lngPos = lngPos + 1 loop if asc(mid(strBuff, lngPos, 1)) < 192 or asc(mid(strBuff, lngPos, 1)) > 195 then lngMarkerSize = lngConvert2(mid(strBuff, lngPos + 1, 2)) lngPos = lngPos + lngMarkerSize + 1 else ExitLoop = True end if loop if ExitLoop = False then Width = -1 Height = -1 Depth = -1 else Height = lngConvert2(mid(strBuff, lngPos + 4, 2)) Width = lngConvert2(mid(strBuff, lngPos + 6, 2)) Depth = 2 ^ (asc(mid(strBuff, lngPos + 8, 1)) * 8) gfxSpex = True end if end if End Function End Class %> thanks A: it is not allowed to use request.binaryread after you have used the request.form collection. but your If Request("action")="1" Then uses the request.form collection because you are not using request.querystring("action"). after that you instantiate the uploader and this uses in line 56 request.BinaryRead A: As explained in this answer, the default limit for POST request size is 200KB - typical to Microsoft, the error message in case the limit is exceeded is far from helpful. To fix this error and allow bigger files and/or more files, you need to change the setting in IIS. For IIS 7.5 (default for Windows 7) first choose the site then double click "ASP" under IIS: Now write a number bigger than 200000 as value of "Maximum Requesting Entity Body Limit" under "Limit Properties" section: (15728640 is 15 MB which is reasonable limit) Click "Apply" in the right sidebar and you're done. Happy programming!
{ "language": "en", "url": "https://stackoverflow.com/questions/24054669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery beginner - accordion menu, but jittery buttons I built an accordion FAQ menu as part of a personal exercise here There's a slight jitter/shake when clicking the buttons that I can't seem to solve for. I've searched Google, but to no avail for something that works. Any ideas? Also, is there a more efficient way to write the code? Here's what I have: (function () { $('dd').hide(); $('dt').click(function(){ $(this) .next() .slideDown(100) .siblings('dd') .slideUp(100); }); $('dd').click(function(){ $(this).hide(); }); })(); A: I am not quite sure, but could it be that you're seeing the sub-pixel renderer adjusting the inter-colour border in response to elements on the page moving around? Unfortunately, if this is the case, there's little you can do about it from a web application. At best, you can pick a colour scheme with less button border contrast, which would make the wobble less obvious. A: Have you tried to change the jquery custom theme that you are currently using? A: Doing animations with jQuery is actually quite expensive in terms of performance. I would suggest not using animations that is likely your problem. Also, you could also use jquery ui as they have solved the accordion problem already. No sense in re-inventing the wheel A: Try toggling some transition effects to get your desired result. Use CSS3 where possible; or stick with jQuery if you'd rather. $(this).animate({ 'paddingBottom': 5, }, 300, 'linear')
{ "language": "en", "url": "https://stackoverflow.com/questions/19967646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Vue 3 rellax.js usage i have installed rellax.js in vue3 project. import App from './App.vue' import VueRellax from 'vue-rellax' createApp(App).use(VueRellax).mount(#app) but when i add rellax class on any components template tags its not working <section class="rellax section portfolio-section pd-34" id="portfolio"> <PortfolioComponent /> </section> not working when i add class rellax in component class even doesnot show in inspect A: It looks like vue-rellax was never rewritten for Vue 3. You're likely better off to use the rellax library and import it into your components or as a window variable. App.vue: <script setup> import { onMounted } from 'vue'; import Rellax from 'rellax' onMounted(() => { let rellax = new Rellax('.rellax'); }) </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/74408890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading Core Data as Objects I have 1 entity in my database "Message" with the values MessageID, messageText and i want to read every row of Core Data, make an object of my class "Message" and put the new object into an array. It's the first time I'm using Core Data and I don't quite get it yet, how I manage to do that. A: Create a fetch request for the entity you wish to retrieve. Don't give it a predicate, set whatever sort descriptor you want. Execute the fetch request in a managed object context and it will return an array of all the objects of that entity. This is purposely just a descriptive answer, you can find the specifics of how to do this from the Core Data introductory documentation; you are new in Core Data and this is a good way to learn it. Also - don't think of Core Data in terms of rows of data that you turn into objects. It's an Object-Relationship graph. It stores the objects of entities and their relationships between them. You don't turn the "rows" into objects, you get the objects back directly. A: The response of @Abizern with code : NSManagedObjectContext *moc = // your managed object context; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Message" inManagedObjectContext:moc]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDescription]; // You can also add a predicate or sort descriptor to your request NSError *error; NSArray *array = [moc executeFetchRequest:request error:&error]; if (array == nil) { // Deal with error... }
{ "language": "en", "url": "https://stackoverflow.com/questions/20214686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Update statement in stored procedure with varbinary parameter I have the following table: CREATE TABLE NZQA_Unit( NZQAUnitID int IDENTITY(1,1) PRIMARY KEY NOT NULL, NZQAUnitNumber int NOT NULL, Title nvarchar(255) NOT NULL, Level smallint NOT NULL, Credits smallint NOT NULL, Classification nvarchar(255) NULL, AvailableGrade int NULL DEFAULT 1, Purpose nvarchar(max) NULL, Validity int NOT NULL DEFAULT 1, -- by default the unit will be 'Current' Document VARBINARY(MAX) NULL, -- for being able to upload a PDF or Word document DocumentExtension varchar(5) NULL, -- for storing the file extension CONSTRAINT AK_NZQA_Unit_Title UNIQUE(Title), CONSTRAINT AK_NZQA_Unit_Number UNIQUE(NZQAUnitNumber), CONSTRAINT FK_NZQA_Unit_Validity FOREIGN KEY (Validity) REFERENCES NZQA_Unit_Validity (ValidityID), CONSTRAINT FK_NZQA_Unit_AvailableGrade FOREIGN KEY (AvailableGrade) REFERENCES NZQA_Unit_Assessment_Grade (AssessmentGradeID), CONSTRAINT CK_NZQA_Unit_Title CHECK ((len(ltrim(rtrim(Title)))>(2))), CONSTRAINT CK_NZQA_Unit_ID_Range CHECK (NZQAUnitNumber >= 1000 AND NZQAUnitNumber <= 99999), --Inclusive CONSTRAINT CK_NZQA_Unit_Level CHECK (Level >= 1 AND Level <= 10), -- Level must be between 1 and 10 https://www.nzqa.govt.nz/studying-in-new-zealand/understand-nz-quals/ CONSTRAINT CK_NZQA_Unit_Credits CHECK (Credits >= 1 AND Credits <= 999), -- 999 has been set arbitrarily but it's high enough to fit an Engineering Degree CONSTRAINT CK_NZQA_Unit_DocumentSize CHECK (DATALENGTH(Document) <= 524288), -- Maximum size 500 KB https://stackoverflow.com/questions/34741079/can-i-set-2-mb-for-maximum-size-of-varbinary https://www.gbmb.org/mb-to-bytes CONSTRAINT CK_NZQA_Unit_DocumentExtension CHECK (DocumentExtension IN ('.pdf', '.doc', '.docx')) -- this check is not case sensitive, i.e. '.DOCX' won't trigger an error ); GO And I'm writing the following stored procedure: DROP PROCEDURE IF EXISTS Modify_NZQA_Unit GO CREATE PROCEDURE Modify_NZQA_Unit @NZQAUnitID int, @NZQAUnitNumber int, @Title nvarchar(255), @Level smallint, @Credits smallint, @Classification nvarchar(255) NULL, @AvailableGrade int, @Purpose nvarchar(max), @Validity int, @Document VARBINARY(MAX), @DocumentExtension varchar(5), @overwriteFile bit -- 1 to overwrite, 0 to no overwrite AS BEGIN IF (@NZQAUnitID IS NULL) BEGIN THROW 51006, 'You must input the NZQA identifier (NZQAUnitID)', 1; END SET @Title = Replace(@Title, '''', '''''') -- singles quotes must be escaped SET @Classification = Replace(@Classification, '''', '''''') SET @Purpose = Replace(@Purpose, '''', '''''') SET @DocumentExtension = Replace(@DocumentExtension, '''', '''''') DECLARE @updateStatement AS NVARCHAR(1000); SET @updateStatement = 'UPDATE NZQA_Unit SET NZQAUnitNumber = '+CONVERT(VARCHAR, @NZQAUnitNumber)+', Title = '''+@Title+''', Level = '+CONVERT(VARCHAR, @Level)+', Credits = '+CONVERT(VARCHAR, @Credits)+', Classification = '''+@Classification+''', AvailableGrade = '+CONVERT(VARCHAR, @AvailableGrade)+', Purpose = '''+@Purpose+''', Validity = '+CONVERT(VARCHAR, @Validity) IF (@overwriteFile IS NULL) BEGIN THROW 51007, 'Variable @overwriteFile cannot be null', 1; END ELSE BEGIN IF (@overwriteFile = 1) BEGIN IF (@Document IS NULL) BEGIN THROW 51008, 'If the variable @overwriteFile is set to 1, a file (@Document) must be provided', 1; END IF (@DocumentExtension IS NULL) BEGIN THROW 51009, 'If the variable @overwriteFile is set to 1, the document extension (@DocumentExtension) must be provided', 1; END SET @updateStatement = @updateStatement + ', Document = '+'HERE WILL COME THE VARBINARY'+', DocumentExtension = '''+@DocumentExtension + ''' ' --DOESN'T WORK: EXEC('UPDATE NZQA_Unit SET NZQAUnitNumber = '+@NZQAUnitNumber+', Title = '''+@Title+''', Level = '+@Level+', Credits = '+@Credits+', Classification = '''+@Classification+''', AvailableGrade = '+@AvailableGrade+', Purpose = '''+@Purpose+''', Validity = '+@Validity + ', Document = ' + @document + ', DocumentExtension = '''+@DocumentExtension + ''' ' +' WHERE NZQAUnitID = '+@NZQAUnitID) UPDATE NZQA_Unit SET NZQAUnitNumber = @NZQAUnitNumber, Title = @Title, Level = @Level, Credits = @Credits, Classification = @Classification, AvailableGrade = @AvailableGrade, Purpose = @Purpose, Validity = @Validity, Document = @document, DocumentExtension = @DocumentExtension WHERE NZQAUnitID = @NZQAUnitID END ELSE BEGIN UPDATE NZQA_Unit SET NZQAUnitNumber = @NZQAUnitNumber, Title = @Title, Level = @Level, Credits = @Credits, Classification = @Classification, AvailableGrade = @AvailableGrade, Purpose = @Purpose, Validity = @Validity WHERE NZQAUnitID = @NZQAUnitID END END SET @updateStatement = @updateStatement +' WHERE NZQAUnitID = '+CONVERT(VARCHAR, @NZQAUnitID) PRINT @updateStatement END GO How could I insert the varbinary data (@Document) into the @updateStatement variable? That way I could simply do a EXEC(@updateStatement)? Code to execute the procedure below: DECLARE @current AS INT = 1 DECLARE @expiring AS INT = 2 DECLARE @expired AS INT = 3 DECLARE @achieved AS INT = 1 DECLARE @datos AS VARBINARY(30) = CONVERT(varbinary(30), N'this IS a test') INSERT NZQA_Unit (NZQAUnitNumber, [Title], [Level], [Credits], [Classification], [AvailableGrade], [Purpose], Validity) VALUES (6401, N'Provide first aid', 2, 1, N'Health Studies > First Aid', @achieved, N'People credited with this unit standard are able to provide first aid.', @current) EXEC Modify_NZQA_Unit 1, 6424, N'Provide first aid', 2, 1, N'Health Studies > First Aid', @achieved, N'People credited with this unit standard are able to provide first aid.', @current, @datos, '.pdf', 1
{ "language": "en", "url": "https://stackoverflow.com/questions/66205026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Heroku Automated Generated Name How to change heroku automated created name (ex: glacial-dawn-22102 ) its not related to my project name! When I input the command git push heroku main then it creates the name of the file. Is there any opton to modify this? git push heroku main
{ "language": "en", "url": "https://stackoverflow.com/questions/72174175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recording video with webcam using VideoCapture I want to record a video with python (using my webcam) and I came across VideoCapture which was easy to install on windows. I know there is OpenCV out there, but that was too much for me. So far I can create every 0.04 seconds a .jpg with this code: from VideoCapture import Device import time cam = Device(devnum=0) #uses the first webcame which is found x = 0 while True: cam.saveSnapshot(str(x)+'.jpg', timestamp=3, boldfont=1) ######################### x += 1 time.sleep(0.04) 0.04 seconds * 25 = 1. So what I am planning to do is an animated gif, that has 25 frames/sec. If somebody of you knows how to produce a real video file like .mp4, I really would prefer the .mp4 rather than .gif. However if thats not possible, the next thing I need to do is, to concatenate all .jpg files (0.jpg, 1.jpg, 2.jpg ...) but as you can imagine with increasing recording time I get A LOT of files. So I was wondering if it would be possible to write the .jpg files (the frames) to one .gif file consecutively. If thats not possible in python, how would you concatenate the jpg files to get an animated gif in the end? A: OpenCV will make it more easy. You will find more problem in your method. To use opencv you have to install 1 more package known as numpy (numerical python). It's easy to install. If you want to install it automatically: Install * *Install pip manually *After that go to your cmd>python folder>Lib>site-packages and type pip install numpy *but for using pip you have to be in internet access. *After installation of numpy just type pip intall opencv. Now you can import all the packages. If numpy somehow fails, maunually downlaod numpy 1.8.0 and install it.
{ "language": "en", "url": "https://stackoverflow.com/questions/22440350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is lastApplied and matchIndex in raft protocol for volatile state in server? I am using the following pdf as reference. It says that lastApplied is the highest log entry applied to state machine, but how is that any different than the commitIndex? Also is the matchIndex on leader just the commitIndex on followers? If not what is the difference? A: Your observation is reasonable: most of the time, nextIndex equals matchIndex + 1, but it is not always the case. For example, when a leader is initiated, matchIndex is initiated to the 0, while nextIndex is initiated to the last log index + 1. The difference here is because these two fields are used for different purposes: matchIndex is an accurate value indicating the index up to which all the log entries in leader and follower match. However, nextIndex is only an optimistic "guess" indicating which index the leader should try for the next AppendEntries operation, it can be a good guess (i.e. it equals matchIndex + 1) in which case the AppendEntries operation will succeed, but it can also be a bad guess (e.g. in the case when a leader was just initiated) in which case the AppendEntries will fail so that the leader will decrement nextIndex and retry. As for lastApplied, it's simply another accurate value indicating the index up to which all the log entries in a follower have been applied to the underlying state machine. It's similar to matchIndex in that they both are both accurate values instead of heuristic "guess", but they really mean different things and serve for different purposes. A: ... lastApplied is the highest log entry applied to state machine, but how is that any different than the commitIndex? These are different in a practical system because the component that commits the data in the log is typically separate from the component that applies it to replicated state machine or database. The commitIndex is typically just nanoseconds or maybe a few milliseconds more up-to-date than lastApplied. Is the matchIndex on leader just the commitIndex on followers? If not what is the difference? They are different. There is a period of time when the data is on a server and not yet committed, such as during the replication itself. The leader keeps track of the latest un-committed data on each of its peers and only need to send log[matchIndex[peer], ...] to each peer instead of the whole log. This is especially useful if the peer is significantly behind the leader; because the leader can update the peer with a series of small AppendEntries calls, incrementally bringing the peer up to date. A: * *commit is not mean already applied, there is time different between them. but eventually applied will catch up commit index. *matchIndex[i] which is saved in leader is equal to follower_i's commitIndex, and they are try to catch up to nextIndex
{ "language": "en", "url": "https://stackoverflow.com/questions/46376293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: gradlew.bat invalid directory in android studio How do I address the following error? ERROR: JAVA_HOME is set to an invalid directory: C:\Program Files\Java\jdk1.7.0_67\bin; Please set the JAVA_HOME variable in your environment to match the location of your Java installation. I've been researching this for hours today but I haven't been able to find a solution that works for me. My JAVA_HOME is set to C:\Program Files\Java\jdk1.7.0_67; I tried setting it to JAVA_HOME C:\Progra~2\Java\jdk1.7.67; per the advise of a different thread but gradle is still throwing the same error in android studio. Does anyone have an idea about what might be going wrong right now? A: You need to remove the bin from the end of your JAVA_HOME variable. If Android Studio still gives the same error, close and restart it. If you still get the same error, restart your machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/25374303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Programmatically layout buttons I am new to Android Development, having much experience in desktop and Web Application coding, and am just getting to grips with how the view layouts work. I have been using Linear Layouts and weights previously to solve my design issues, but due (I believe) to this design not being, uniformly tabular I am struggling. I want Tag5 next to Tag0 and under Tag1, and then Tag 6 and 7 next to it. My code to do this so far is Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int width = size.x; int height = size.y; String tag; for (int i = 0; i <= 7; i++) { int indColumn = width / 7; int indColumnHeight = height / 9; tag = "#tag" + i; View tagView = layoutInflater.inflate(R.layout.layout_child, null, false); Button tagTextView = (Button) tagView.findViewById(R.id.tagTextView); if (i == 0 || i == 3 || i == 6 || i == 7) { tagTextView.setWidth(Math.round(indColumn * 2)); } else { tagTextView.setWidth(Math.round(indColumn)); } if (i == 0) { tagTextView.setHeight(Math.round(indColumnHeight * 2)); } else { tagTextView.setHeight(Math.round(indColumnHeight)); } tagTextView.setText(tag); tagLayout.addView(tagView); I have tried adding if(i==5) { RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.RIGHT_OF, 0); lp.addRule(RelativeLayout.BELOW, 1); tagTextView.setLayoutParams(lp); } before the tagTextView.set Text but it is making no difference The xml looks like this for an individual button <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"> <Button android:id="@+id/tagTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#a000" android:textColor="#fff"/> </RelativeLayout> A: I took what EasyJoin Dev said, and tweaked it a little, I created a Relative layout using the layout_toEndOf and layout_below options, and then in the activities create method I overrode the width and height programmatically to get my percentage based sizing.
{ "language": "en", "url": "https://stackoverflow.com/questions/50084779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kieran Healy's emacs starter kit in linux (fedora19): "/bin/bash: osascript: command not found" message I am user of Kieran Healy's Emacs Starter Kit. I have run it on the Fedora distro of Linux for around a year or so. Things have always run smoothly, but now that I have upgraded from Fedora17 to Fedora19, when I try to commit in Magit, I get the following message: /bin/bash: osascript: command not found I understand I get this message because Kieran customizes the ESSK for the Mac OS. So I thought I just needed to tweak this feature. To do that, I need to find where in the emacs dot files is the call to an osascript, but when I use Grep to find the string 'osascript', I get no match. Hence my question: does anyone know where in the emacs dot files there is a call to an osascript for the commit command in git to run? Thank you very much! A: This is based on a current version of the starter kit: http://kieranhealy.org/resources/emacs-starter-kit.html MP:~ HOME$ grep -inIEr --color=ALWAYS -C1 "osascript" .../emacs-starter-kit-master .../emacs-starter-kit-master/kjhealy.org-189- (defun raise-emacs-on-aqua() .../emacs-starter-kit-master/kjhealy.org:190: (shell-command "osascript -e 'tell application \"Emacs\" to activate' &")) .../emacs-starter-kit-master/kjhealy.org-191- (add-hook 'server-switch-hook 'raise-emacs-on-aqua) MP:~ HOME$
{ "language": "en", "url": "https://stackoverflow.com/questions/19429188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete action doesn't work for entities without dependencies in entity framework Here is my Delete action code and when I try to delete an entity which doesn't contain any dependencies. It always return index without delete. I just want to set it only for the entities with dependencies and others should allow deleted and add to the log. // GET: Company/5/Delete [Route("{companyPk:int}/Delete")] public async Task<ActionResult> Delete(int? companyPk) { //Validate parameters if (companyPk == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Company identifier is missing."); } //Get the model from db Company company = await _work.Companies.GetAsync(companyPk); if (company == null) { return HttpNotFound(); } //Convert model to dto CompanyDto companyDto = _mapper.Map<CompanyDto>(company); return View(companyDto); } // POST: Company/5/Delete [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Route("{companyPk:int}/Delete")] public async Task<ActionResult> DeleteConfirmed(int companyPk) { //Get the model from db Company company = await _work.Companies.GetAsync(companyPk); var Related = _work.Companies.Where(i => i.CompanyPk == companyPk) .Include(i => i.Departments) .Include(i => i.Locations); //.FirstOrDefault(); if (Related != null) { ViewBag.Message = String.Format("Company Pk has dependencies for Department and Location. Can't Delete"); return RedirectToAction("Index"); } //Prepare log model var logCompany = _mapper.Map<LogCompany>(company); logCompany.RecordId = 0; Utilities.Instance.SetLogEntityProperties(logCompany, "D"); //Save model to db _work.LogCompanies.Add(logCompany); _work.Companies.Remove(company); await _work.CompleteAsync(); return RedirectToAction("Index"); } A: Have you tried to add this line after the delete one? _work.SaveChanges(); As far as i know, without it, you just delete locally, and savechanges edit into the DB as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/58317035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to initialise QTextEdit find options I am trying to set the options in the following call: bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags()) But the signature of option is complicated for a Python programmer. I tried the following: option = 0 option = option | QTextDocument.FindBackward # continue to check other checkboxes and build up the option this way Unfortunately, the error is that 'int' is unexpected. I understand that since the option=0, then the following OR operation probably didn't yield an int type as well. But how to get a the proper starting null/unset/zero value? A: If you would have default value let this parameter unfilled: doc = QTextDocument() doc.find("aaa") If you would like to use flag, do not read value from documentation, but use QTextDocument.FindBackward QTextDocument.FindCaseSensitively QTextDocument.FindWholeWords If you would like to have or use | operator: QTextDocument.FindWholeWords | QTextDocument.FindBackward If you have default value in function signature, you not need to provide this argument. A: The error is caused by a minor bug that occasionally appears in PyQt. If you update to the latest version, the error will probably go away. However, if you can't update, or if you want to bullet-proof your code against this problem, a work-around is to initialise the variable like this: >>> option = QTextDocument.FindFlag(0) >>> option = option | QTextDocument.FindBackward This will now guarantee that option has the expected type. The correct flag to use can be found by explicitly checking the type of one of the enum values: >>> print(type(QTextDocument.FindBackward)) <class 'PyQt5.QtGui.QTextDocument.FindFlag'> Or you can just look up the relevant enum in the docs: QTextDocument.
{ "language": "en", "url": "https://stackoverflow.com/questions/57209842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: changing React.js form values from a chrome extension I'm not developing in React.js, but I'm working on a chrome extension that needs to programatically fill form values for different kinds of sites. The site uses React.js, and I'm filling the value in the usual way with: element = document.querySelector("input[name=firstName]"); element.value = "something"; When the user clicks the submit button, he gets this error for that form element, even if the element has a value: "This information is required." It doesn't help if fire "change" event for that element. evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); element.dispatchEvent(evt); There is some method in the React.js framework I need to call to programatically change the value? Help from React.js experienced users is appreciated! A: I found a solution. Call element.select(); before changing the value.
{ "language": "en", "url": "https://stackoverflow.com/questions/39202120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Merge specific keys in a multidimensional array into one-dimensional array I have a complex data that structure I want to simplify. This array depth may change since it's dynamic data coming from external resource. I want to merge all arrays that has key price into one dimensional array. I want to turn this: array( 'first_name' => 'John', 'last_name' => 'Due', 'product' => array( 'title' => 'Product #1', 'price' => '90', 'product' => array( 'title' => 'Product #2', 'price' => '90', 'product' => array( 'title' => 'Product #3', 'price' => '90', ), ), ), 'misc' => array( 'country' => 'United States', array( 'product' => array( 'title' => 'Product #4', 'price' => '90', ), ) ), array( 'title' => 'Product #5', 'price' => '90', ) ); Into this: array( array( 'title' => 'Product #1', 'price' => '90', ), array( 'title' => 'Product #2', 'price' => '90', ), array( 'title' => 'Product #3', 'price' => '90', ), array( 'title' => 'Product #4', 'price' => '90', ), array( 'title' => 'Product #5', 'price' => '90', ), ); I thought a simple way to do it would be using array_walk_recursive, but found I cannot access the parent array. array_walk_recursive( $array, function( $value, $key ) { if ( 'price' === $key ) { // cannot access the parent array } } ); A: $array = array( 'first_name' => 'John', 'last_name' => 'Duei', 'product' => array( 'title' => 'Product #1', 'price' => '90', 'product' => array( 'title' => 'Product #2', 'price' => '90', 'product' => array( 'title' => 'Product #3', 'price' => '90', ), ), ), 'misc' => array( 'country' => 'United States', array( 'product' => array( 'title' => 'Product #4', 'price' => '90', ), ) ), array( 'title' => 'Product #5', 'price' => '90', ) ); function array_walk_recursive_full($array, $callback) { if (!is_array($array)) return; foreach ($array as $key => $value) { $callback($value, $key); array_walk_recursive_full($value, $callback); } } $result = []; array_walk_recursive_full( $array, function ($value, $key) use (&$result) { if (isset($value['price'])) { $result[] = [ 'title' => $value['title'], 'price' => $value['price'], ]; } } ); print_r($result); working code example here
{ "language": "en", "url": "https://stackoverflow.com/questions/63830100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirect a php script after sending header I have an html page with a form and a submit button. Once I click submit all the form data, thanks to fpdf, gets turned into pdf. This pdf is sent without problems to my email. Building this little page everything always worked without problems and I was able to redirect my user to a thank you page without problems with this code: header("Location: /thank-you.php",303); exit(); As soon as I've implemented the pdf file save the final redirection stopped working. I've implemented the pdf save easily with fpdf: $pdf->Output("filename.pdf", "D"); And reading on stackoverflow and all the internet I've understood that you can't send two headers. I thought about solving the problem with javascript so I put after the pdf generation echo "<script language=javascript> window.location = 'thanks.html' </script>"; but no luck. The php page simply "stops" when the browser downloads the pdf file. Any chance to solve this? EDIT: All the suggestion I got (thanks to everybody) get me to the same point: use thank you page to handle the pdf save. Sounds great to me. I've tried preparing a thankyou.php page with a simple $pdf->Output(); in it. It didn't work... So I thought to use an include to my create.php (where happens all the magic: pdf creation, email sending, insert into db etc) with: <?php include("create.php"); $pdf->Output(); ?> Still no luck. What's wrong with my thinking? A: You should approach this the other way around. Send the user to the thanks page, and on that thanks page do $pdf->Output(). That should do what you want. A: Webpages/HTTP is a request-response system. The browser sends one request, to which there's exactly one response. You simply cannot respond with a PDF and a redirect, or a PDF and some Javascript. The typical thing to do is to display the Thank You page first, then inside this page redirect to the file download using Javascript. That way the page stays up and the file downloads. A: You can make thank-you.php send the PDF file. After submitting the form, send the user to the thank-you page then the thank you page will send the user the PDF file. In that way, the thank you page is visible and the page will still be visible after downloading the PDF file.
{ "language": "en", "url": "https://stackoverflow.com/questions/12145625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: vim: NERDTree how to: create/rename/move file/directory I checked the documentation of NERDTree, but didn't find the way to create new file/directory or rename/move it (once I'm browsing directory tree). In the netrw plugin it would be easy, but this one is not used any more as NERDTree just replaced it. And I don't want to look back. Anyone ready to point me to the right direction? A: It's a little bit hidden behind a menu (see :help NERDTreeMenu), but as an upside it is extensible. It is launched (for the current file node) with the m key by default. The script comes with two default menu plugins: exec_menuitem.vim and fs_menu.vim. fs_menu.vim adds some basic filesystem operations to the menu for creating/deleting/moving/copying files and dirs. exec_menuitem.vim provides a menu item to execute executable files.
{ "language": "en", "url": "https://stackoverflow.com/questions/19765721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Cannot open website link in J2ME I am working on a simple J2ME application and i have a StringItem linked to a terms and conditions page online. I have the StringItem setup and it appears underlined (giving the feeling that it is linked); but when i click on it, it does not perform any action. Find below my code: public class mobiMidlet extends MIDlet implements CommandListener { private Display display; private TextField userName,password; public Form form; private Command login, register, forgot, terms, cancel; private Image img_error, img_login, img_register, img_forgot, img_terms; private String termsurl = "http://example.com/terms.php"; private StringItem termsItem; public mobiMidlet() { form = new Form("Welcome to My App"); termsItem = new StringItem("", "Terms and Conditions", Item.HYPERLINK); termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1)); ItemCommandListener listener = new ItemCommandListener() { public void commandAction(Command cmd, Item item) { if(cmd==terms) { try { platformRequest(termsurl); } catch (Exception e) { e.printStackTrace(); } } } }; termsItem.setItemCommandListener(listener); userName = new TextField("LoginID:", "", 30, TextField.ANY); password = new TextField("Password:", "", 30, TextField.PASSWORD); cancel = new Command("Cancel", Command.CANCEL, 2); login = new Command("Login", Command.OK, 2); try{ img_login = Image.createImage("/logo.jpg"); img_register = Image.createImage("/error2.png"); img_forgot = Image.createImage("/logo.jpg"); img_register = Image.createImage("/error2.png"); }catch(Exception e){ System.out.println(e.getMessage()); } } public void startApp() { display = Display.getDisplay(this); form.append(termsItem); form.append(userName); form.append(password); form.addCommand(cancel); form.addCommand(login); form.setCommandListener(this); display.setCurrent(form); } public void commandAction(Command c, Displayable d) { String label = c.getLabel(); if(label.equals("Cancel")) { destroyApp(true); } else if(label.equals("Login")) { validateUser(userName.getString(), password.getString()); } } } How can I fix this so that when I click on the terms and conditions link, it opens the page on a browser? A: You have not initialized variable terms, so it remains null. Therefore condition cmd==terms is always false and you never enter the if statement. Separate line termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1)); to two: terms = new Command("terms", Command.ITEM, 1); termsItem.setDefaultCommand(terms); Now you have a chance. BTW why not to debug you program? Run it in emulator, put break point into commandAction and see what happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/10498664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Any way to run an internal python script from a webpage? I finally made a project that I wanted to make since a long time : I'm using an Arduino Uno to replace my PC power button (with a simple relay) and that Arduino Board is connected to a Raspi 3 for network connection purposes My wish is to do a webpage (or a API-Like request) that at a touch of a button (preferably in a password-protected page) It'll power the PC on I know how to code in Python, and my script to control the Arduino is already done but I can't find a way to run, only server-side, a Python Script from a button in a webpage I found that CherryPy framework but I don't think it'll suit my needs Can someone give me any ideas about that please? A: As already mentioned by @ForceBru, you need a python webserver. If this can be useful to you, this is a possible unsecure implementation using flask: from flask import Flask from flask import request app = Flask(__name__) @app.route('/turnOn') def hello_world(): k = request.args.get('key') if k == "superSecretKey": # Do something .. return 'Ok' else: return 'Nope' If you put this in an app.py name file and, after having installed flask (pip install flask), you run flask run you should be able to see Ok if visiting the url http://localhost:5000/turnOn?key=superSecretKey . You could write a brief html gui with a button and a key field in a form but I leaves that to you (you need to have fun too!). To avoid potential security issues you could use a POST method and https. Look at the flask documentation for more infos.
{ "language": "en", "url": "https://stackoverflow.com/questions/65369383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using MultiValuedMap with Jackson Hello I am trying to create an object from the following json : { "property1": "value1", "property2": [ {"key1":"value1"}, {"key1":"value2"}, {"key2":"value1"} ] } The reason am using MultiValuedMap is because the keys in property 2 can be duplicates (as for the values). The problem is that jackson throws an error when I try something like this : @AllArgsConstructor @NoArgsConstructor @Data @Builder @EqualsAndHashCode @JsonInclude(JsonInclude.Include.NON_NULL) public class MyClass { private String property1; private List<MultiValuedMap<String, String>> property2; } As for the controller it's like this : @PostMapping(value = "update") MyClass saveMyClass(@RequestBody @Valid MyClass myClass); but when trying to send the json to my api it gives the following error : org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.apache.commons.collections4.MultiValuedMap]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.apache.commons.collections4.MultiValuedMap (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information A: Why not just use a List<Map.Entry<String,String>> ? This works right out of the box and if you really want to use a MuliValuedMap you can convert the List into one with the following sniped: var map = new ArrayListValuedHashMap<String, String>(); result.property2.stream() .collect(Collectors.groupingBy(Map.Entry::getKey)) .entrySet() .forEach(entry -> map.putAll(entry.getKey(), entry.getValue().stream().map(Map.Entry::getValue).toList()));
{ "language": "en", "url": "https://stackoverflow.com/questions/71508956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Closest point from List for every point of other List I have a population of so called "Dots" that search for food. Every Dot has a sight_ value, which indicates the range in which it can see food. The position of each Dot is saved as a pair<uint16_t,uint16_t>. The positions of all foodsources are in a vector<pair<uint16_t,uint16_t>>. Now I want to calculate the closest foodsource for every Dot, which this Dot can see. And I don't want to calculate the distance of every combination. My idea was to create a copy of the food-vector, sort one copy by x and the other by y. Then find the interval [x-sight, x+sight] respectively [y-sight, y+sight] in the vectors and then create the intersection of both. I've read over set_intersection, but it requires both ranges to be sorted with the same rule. Any Ideas how I could do this? Could also be that my Idea is just the wrong approach. Thanks IceFreez3r Edit: I did some runtime approximations: Sort Food: n log n Find Interval for one Coordinate and one Dot: 2 log n (lower and upper bound) If we assume equal distribution of food sources, we can calculate the bound that is estimated to be closer to the middle first and then calculate the second bound in the rest interval. This would reduce the runtime to: log n + log(n/2) (Just realized this s probably not *that* powerful:log(n/2) =~ log(n) - 1) Build intersection: #x * #y =~ (n * sight/testgroundsize)^2 Compute exact Distance for every Food in Intersection: n * (sight/testgroundsize)^2 Sum: 2 n log n + 2 * #Dots * (log n + log(n/2) + (n * sight/testgroundsize)^2 + n * (sight/testgroundsize)^2) Sum with just limiting one coordinate: n log n + #Dots * (log n + log(n/2) + n * sight/testgroundsize) I did some tests and just calculated the above formulas on the run: int dots = dots_.size(); int sum = 2 * n * log(n) + 2 * dots * (log(n) + log(n/2) + pow(n * (sum_sight / dots) / testground_size_,2) + n * pow((sum_sight / dots) / testground_size_, 2)); int sum2 = n * log(n) + dots * (log(n) + log(n/2) + n * (sum_sight / dots) / testground_size_); cout << n*dots << endl << sum << endl << sum2 << endl; It turned out the Intersection idea is just bad. While the idea of just limiting one coordinate is at least better than brute-force. I didn't think about the grid-idea yet @Daniel Jour A: You're stepping into a whole field of interesting approaches to this problem. Terms to Google are binary space partitioning, quadtrees, ... and of course nearest neighbour search. A relatively simple but effective approach when the dots are far more spread than what their "visible range" is: * *Select a value "grid size". *Create a map from grid coordinates to a list/set of entities *For each food source: put them in the map at their grid coordinates *For each dot: put them in the map at their grid coordinates and also in the neighbour grid "cells". The size of the neighbourhood depends on the grid size and the dot's sight value *For each entry in the map which contains at least one dot: Either do this algorithm recursively with a smaller grid size or use the brute force approach: check each dot in that grid cell against each food source in that grid cell. This is a linear algorithm, compared with the quadratic brute force approach. Calculation of grid coordinates: grid_x = int(x / grid_size) ... same for other coordinate. Neighbourhood: steps = ceil(sight_value / grid_size) .. the neighbourhood is a square with side length 2×steps + 1 centred at the dot's grid coordinates A: I believe your approach is incorrect. This can be mathematically verified. What you can do instead is calculate the magnitude of the vector joining the dot with the food source by means of Pythagoras theorem, and ensure that this magnitude is less than the observation limit. This deals exclusively with determining relative distance, as defined by the Cartesian co-ordinate system, and the standard unit of measurement. In relation to efficiency concerns, the first order of business is to determine if the approach to be taken is in computational terms in actuality less efficient, as measured by time, even though the logical component responsible for certain calculations are, in virtue of this alternative implementation, less time consuming. Of coarse, the ideal is one in which the time taken is decreased, and not merely numerically contained by means of refactoring. Now, if it is the case that the position of a dot can be specified as any two numbers one may choose, this of course implies a frame of reference called the basis, and also one local to the dot in question. With respect to both, one can quantify position, and other such characteristics and properties. As a consequence of this observation, it would seem that you need n*2 data structures, where n is the amount of dots in the environment, that contain the sorted values relative to each dot, and quite frankly it is unclear whether or not this approach would even work or is optimal. You state the design and programmatic constraint that the solution shall not compute the distances from each dot to each food source. But to achieve this, one must implement other such procedures, in order that we derive the correct results. These comments are made in relation to my discussion on efficiency. Therefore, you may be better of simply calculating the distance in each case. This is somewhat elegant.
{ "language": "en", "url": "https://stackoverflow.com/questions/59432185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can you append strings to variables in PHP? Why does the following code output 0? It works with numbers instead of strings just fine. I have similar code in JavaScript that also works. Does PHP not like += with strings? <?php $selectBox = '<select name="number">'; for ($i=1; $i<=100; $i++) { $selectBox += '<option value="' . $i . '">' . $i . '</option>'; } $selectBox += '</select>'; echo $selectBox; ?> A: In PHP use .= to append strings, and not +=. Why does this output 0? [...] Does PHP not like += with strings? += is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0. More about operators in PHP: * *Reference - What does this symbol mean in PHP? *PHP Manual – Operators A: PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation. <?php $selectBox = '<select name="number">'; for ($i=1;$i<=100;$i++) { $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with . $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced . } $selectBox += '</select>'; // <-- (Wrong) Replace + with . $selectBox .= '</select>'; // <-- (Correct) Here + is replaced . echo $selectBox; ?> A: This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator: for ($i=1;$i<=100;$i++) { $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; } $selectBox .= '</select>';
{ "language": "en", "url": "https://stackoverflow.com/questions/9050685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "83" }
Q: Pandas Dataframe sum row based on column header I have the following dataframe and want to create two columns, one will show the amount MTD and the other will show the cumulative YTD based on a date parameter for each Account Name. This is easily achievable in Excel using a =SUMIFS formula and want to know the Python equivalent. +---------------+------------+------------+------------+------------+ | Account Names | 31/01/2022 | 28/02/2022 | 31/03/2022 | 30/04/2022 | +---------------+------------+------------+------------+------------+ | Cash At Bank | 100 | 150 | 100 | 150 | | Debtors | 50 | 50 | 50 | 100 | | Inventory | 250 | 250 | 350 | 100 | | PAYG Withheld | 50 | 50 | 10 | 150 | +---------------+------------+------------+------------+------------+ Ideally, I'd want this to be as efficient as possible i.e. doesn't require loops. I went the route of trying to do this using np.select as I've read this is one of the fastest methods, but had no luck. I get the following error: ValueError: shape mismatch: objects cannot be broadcast to a single shape EndDate = '31/03/2022' Budget_Assets["MTD_Amount"] = np.select(condlist=[Budget_Assets.columns == EndDate],choicelist=[Budget_Assets[EndDate]],default=0) For example, the value in the MTD_Amount column for Cash At Bank should be 100 and the YTD_Column will be 350 (sum of numbers from '31/01/2022' to '31/03/2022') A: You can try sum(axis=1) by slicing the datetime like columns to calculate YTD and just use loc to get MTD EndDate = '31/03/2022' date_cols = df.filter(regex='\d{2}/\d{2}/\d{4}') date_cols.columns = pd.to_datetime(date_cols.columns, dayfirst=True) df['YTD_Column'] = date_cols.loc[:, :pd.to_datetime(EndDate, dayfirst=True)].sum(axis=1) df['MTD_Column'] = df[EndDate] Account Names 31/01/2022 28/02/2022 31/03/2022 30/04/2022 YTD_Column MTD_Column 0 Cash At Bank 100 150 100 150 350 100 1 Debtors 50 50 50 100 150 50 2 Inventory 250 250 350 100 850 350 3 PAYG Withheld 50 50 10 150 110 10
{ "language": "en", "url": "https://stackoverflow.com/questions/72329919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Firefox Password Field is not empty I'm new here on stackoverflow. I'm writing a Form to add a Album to a gallery, but now I discovered a problem in Firefox which I've never had. The password field is already set. I never filled out the form. Does somebody knows, why Firefox fills text in? A: If it is a saved password, you will be able to find it in the security and password settings (see link for more information). If you've saved a password on a different portion of the site (say you have a form on www.site.com/login.html and www.site.com/admin.html for example), it could be pulling it from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/34298010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you use "first class" concept on Python methods/attributes? Can the "first-class" concept be applied to Python methods/attributes like it can functions? >>>a=sum >>>a([1,2,3]) 6 I would like to do something like: >>>case='lower' >>>'UPPERCASE'.case() To produce the string object 'uppercase'. Otherwise, would I just have to use eval? A: You can do it this way: case = str.lower # Take the lower() method of the str class. case('UPPERCASE') # pass your string as the first argument, which is self. In this case, Python being explicit about self being the first argument to methods makes this a lot clearer to understand.
{ "language": "en", "url": "https://stackoverflow.com/questions/38317314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Reduce 3G data consumption using Google Map API for Android I am developing an android application that requires to display the current location of a user and to load KMZ file (with poly lines) on Google Map (use of google map api). My application opens the google map, loads the KMZ file and diplays current position fast, when having wi-fi and 3G enabled to mobile.The problem I face is that having 3G the data consumption is too big. I checked that after 5 clicks/zoom in-out on a single map the data consumption on mobile become 100MB.. Are there any ways to reduce the 3G data consumption? Should I use another map source? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/25607168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remap the copy-paste keyboard shortcuts in MATLAB on Ubuntu? The default keys are alt-w for copying and ctrl-y for pasting. Is there any way to remap this to ctrl-c for copying and ctrl-v for pasting? A: Yes. Go to Preferences -> Keyboard. There you will find "Command Window keybindings" and "Editor/Debugger" keybindings. These are most likely set to "Emacs" style for you -- you should change them to "Windows" style to copy and paste with Ctrl-C and Ctrl-V, respectively. Source: http://blogs.mathworks.com/community/2007/05/11/setting-up-keybindings-for-the-command-window-and-editor/ A: In Matlab version R2020a, you can change the keyboard shortcuts by following these steps: * *Go to Home > Preferences > Keyboard > Shortcuts *Change the Active Settings to Windows Default Set *Apply the changes by clicking on Apply and then Ok It will look like this screenshot. Now you can use ctrl-C / ctrl-V to copy / paste as usual.
{ "language": "en", "url": "https://stackoverflow.com/questions/35730436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Google breakpad crashes when run under a debugger We have a problem where initializing the Google Breakpad exception handler errors out when the program is run under lldb, but not when run normally from the shell. The system is MacOS 13 (Ventura) and the IDE is Visual Studio Code. The code below fails on a call to init(): namespace crashhandler { static std::unique_ptr<google_breakpad::ExceptionHandler> pExceptionHandler; namespace { bool DumpCallback(const char* dump_dir, const char* minidump_id, void*, bool success) { if (success) printf("Application crashed. Breakpad Crash Handler created a dump at location %s/%s.dmp\n", dump_dir, minidump_id); else printf("Application crashed. Breakpad Crash Handler failed to create a dump"); fflush(stdout); return success; } } // namespace void init(const std::string& reportPath) // <-- crash happens when calling this function { if (pExceptionHandler) return; pExceptionHandler.reset( new google_breakpad::ExceptionHandler(reportPath, nullptr, DumpCallback, nullptr, true, nullptr)); } } // namespace crashhandler The debug console shows: ================================================================= ==5060==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x00016fdfee00 at pc 0x000100ac9030 bp 0x00016ff11540 sp 0x00016ff10d08 READ of size 4608 at 0x00016fdfee00 thread T2 #0 0x100ac902c in wrap_write+0x15c (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c) #1 0x100109f08 in google_breakpad::UntypedMDRVA::Copy(unsigned int, void const*, unsigned long)+0x54 (my_server:arm64+0x100109f08) #2 0x10010ce14 in google_breakpad::MinidumpGenerator::WriteStackFromStartAddress(unsigned long long, MDMemoryDescriptor*)+0xf8 (my_server:arm64+0x10010ce14) #3 0x10010d244 in google_breakpad::MinidumpGenerator::WriteThreadStream(unsigned int, MDRawThread*)+0x100 (my_server:arm64+0x10010d244) #4 0x10010c04c in google_breakpad::MinidumpGenerator::WriteThreadListStream(MDRawDirectory*)+0xfc (my_server:arm64+0x10010c04c) #5 0x10010bd20 in google_breakpad::MinidumpGenerator::Write(char const*)+0xc8 (my_server:arm64+0x10010bd20) #6 0x10010adc0 in google_breakpad::ExceptionHandler::WriteMinidumpWithException(int, int, int, __darwin_ucontext64*, unsigned int, bool, bool)+0x160 (my_server:arm64+0x10010adc0) #7 0x10010af1c in google_breakpad::ExceptionHandler::WaitForMessage(void*)+0x104 (my_server:arm64+0x10010af1c) #8 0x1a330a068 in _pthread_start+0x90 (libsystem_pthread.dylib:arm64e+0x7068) #9 0x1a3304e28 in thread_start+0x4 (libsystem_pthread.dylib:arm64e+0x1e28) Address 0x00016fdfee00 is located in stack of thread T0 at offset 0 in frame #0 0x1000034cc in main main.cpp:36 This frame has 10 object(s): [32, 56) 'reportPath' (line 39) <== Memory access at offset 0 partially underflows this variable [96, 120) 'ref.tmp' (line 40) <== Memory access at offset 0 partially underflows this variable [160, 208) 'parser' (line 43) <== Memory access at offset 0 partially underflows this variable [240, 264) 'configPath' (line 45) <== Memory access at offset 0 partially underflows this variable [304, 320) 'ref.tmp12' (line 46) <== Memory access at offset 0 partially underflows this variable [336, 360) 'agg.tmp' <== Memory access at offset 0 partially underflows this variable [400, 416) 'ref.tmp30' (line 57) <== Memory access at offset 0 partially underflows this variable [432, 456) 'agg.tmp42' <== Memory access at offset 0 partially underflows this variable [496, 520) 'agg.tmp80' <== Memory access at offset 0 partially underflows this variable [560, 568) 'ref.tmp86' (line 74) <== Memory access at offset 0 partially underflows this variable HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork (longjmp and C++ exceptions *are* supported) SUMMARY: AddressSanitizer: stack-buffer-underflow (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c) in wrap_write+0x15c Shadow bytes around the buggy address: 0x00702dfdfd70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x00702dfdfd80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x00702dfdfd90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x00702dfdfda0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x00702dfdfdb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 =>0x00702dfdfdc0:[f1]f1 f1 f1 00 00 00 f2 f2 f2 f2 f2 f8 f8 f8 f2 0x00702dfdfdd0: f2 f2 f2 f2 f8 f8 f8 f8 f8 f8 f2 f2 f2 f2 f8 f8 0x00702dfdfde0: f8 f2 f2 f2 f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2 0x00702dfdfdf0: f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2 f2 f2 00 00 0x00702dfdfe00: 00 f2 f2 f2 f2 f2 f8 f3 f3 f3 f3 f3 00 00 00 00 0x00702dfdfe10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb Thread T2 created by T0 here: #0 0x100ae8c5c in wrap_pthread_create+0x54 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x38c5c) #1 0x10010a360 in google_breakpad::ExceptionHandler::Setup(bool)+0xd0 (my_server:arm64+0x10010a360) #2 0x10010a1c4 in google_breakpad::ExceptionHandler::ExceptionHandler(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool (*)(void*), bool (*)(char const*, char const*, void*, bool), void*, bool, char const*)+0x110 (my_server:arm64+0x10010a1c4) #3 0x1001132b4 in crashhandler::init(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)+0x58 (my_server:arm64+0x1001132b4) #4 0x10000367c in main main.cpp:41 #5 0x1a2fdfe4c (<unknown module>) ==5060==ABORTING To reiterate, if I run the program outside of the debugger, it proceeds normally. What can cause this? A: Breakpad is inserting a right into the process's "task exception port" - which is where you listen for crashes and the like either from within the process or externally - i.e. when you are a debugger. But in Mach the exception ports only have a single owner. So when you run under the debugger, Breakpad and the debugger fight for control of the exception port. For example, if you got your port right set up before the debugger attached, you will end up with a bad port right after the attach, because lldb now owns the port. Debugging programs that use task exception port handlers is not well supported, because (a) it would be tricky to get that right and (b) there aren't enough programs that need to do this to motivate the effort (at least on the debugger side). Most people turn off their exception handling for their debug builds since their exception catcher and the debugger are pretty much doing the same job, and it's more convenient to trap in the debugger than the internal exception handler. And the core part of the exception handler is usually simple enough that you can do printf debugging if you really need to debug that part.
{ "language": "en", "url": "https://stackoverflow.com/questions/74645275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony 2 - Form collection for one entity without parent entity I have problem with form collection. I want to show one form with all values from one entity and I want to be able to add or remove some record(line) from this entity on one page. I have the following solutions, which is ok. CurrencyController class CurrencyController extends Controller { /** * @Template() */ public function testAction() { $em = $this->getDoctrine()->getManager(); $currencies = $em->getRepository('MyWebBundle:Currency')->findAll(); $arr = array('currencies' => $currencies); $form = $this->createFormBuilder($arr) ->add('currencies', 'collection', array( 'type' => new CurrencyType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, )) ->add('submit', 'button', array('label' => 'Odeslat')) ->getForm(); return array( 'form' => $form->createView(), ); } } CurrencyType class CurrencyType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('abbreviation', 'text') ->add('rate', 'number') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'My\WebBundle\Entity\Currency' )); } /** * @return string */ public function getName() { return 'currency'; } } Twig {% extends '::base.html.twig' %} {% block body -%} <h1>Test</h1> {{ form(form) }} {% endblock %} If I use form class for CurrenciesType, then Symfony throws exception Notice: Object of class My\WebBundle\Entity\Currency could not be converted to int in ....\web\vendor\symfony\symfony\src\Symfony\Component\ Form\Extension\Core\ChoiceList\ChoiceList.php line 462 Code for this is below. CurrencyController class CurrencyController extends Controller { /** * @Template() */ public function testAction() { $em = $this->getDoctrine()->getManager(); $currencies = $em->getRepository('MyWebBundle:Currency')->findAll(); $arr = array('currencies' => $currencies); $form = $this->createForm(new CurrenciesType(), $arr); return array( 'form' => $form->createView(), ); } } CurrenciesType class CurrenciesType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('currencies', 'collection', array( 'type' => new CurrencyType(), 'allow_add' => true, 'allow_delete' => true, 'by_reference' => false, )) ->add('submit', 'button', array('label' => 'Send')) ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => null )); } /** * @return string */ public function getName() { return 'my_webbundle_currencies'; } } CurrencyType and Twig are same as above. I found solution these solution #1 solution #2, but my symfony still throws exception as above and I don't see different in my solution and these solutions. Please help with this problem. Thank you all :)
{ "language": "en", "url": "https://stackoverflow.com/questions/27150736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set the color of margins in a QGridLayout? How to set the color of margins in a QGridLayout? I want to show the different columns and rows separately by placing lines between various rows and columns. In other words, how to display items in grid-layout such that they are in a table. A: QGridLayout doesn't draw anything, it just calculates the layout. So the QGridLayout itself cannot draw gridlines for you. The easiest way is to put a QFrame to each of your QGridLayout's cell and move your content to these QFrames. In WinXP, setting QFrame's frameShape to Box and frameShadow to Plain, you get simple boxes. You could also create a new widget that draws the gridlines according to the layout that the QGridLayout calculates. By using QGridLayout::itemAtPosition you can get a QLayoutItem for each cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/3233133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL table with a lot of text So I have this database (Size 3.1Gb total), but this is due to one specific table I've got, containing A LOT of console output text, from some test runs. The table itself is 2.7Gb, and I was wondering if there could be another solution for this table, so the database would get a lot smaller? It's getting a bit anoying to backup the database or even make a copy of the database to a playground, because it's so big this table. The Table is this one Would it be better to delete this table and make all the LogTextData <- LongText, be stored in a PDF, instead of the database? (Then I can't backup this data tho...) Do anyone have an idea on how to make this table smaller, or another solution? I'm open for suggestions, to make this table smaller. The way this console log data gets imported to the database is by Python scipts, so I have fully access to other python solutions, if there is any. A: You could try enabling either the Storage-Engine Independent Column Compression or InnoDB page compression. Both provides ways to have a smaller on-disk database which is especially useful for the large text fields. Since there's only one table with one particular field that's taking up space, trying out individual column compression seems like the easiest first step. A: According to me you should just store the path of log files instead of the complete logs in the database. By using those paths you can access the files anytime you want. It will decrease the size of database too. Your new table would look like this, LogID, BuildID, JenkinsJobName,LogTextData.
{ "language": "en", "url": "https://stackoverflow.com/questions/68994225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set dashed axes on a box plot I would like to figure out if it is possible using pyplot setting a dashed box (I mean the axes of plot contours) of the plot. I know that could sound strange and horrible. but I would like to try using it. A: The axes "box" consists of 4 "spines", which are accessible via ax.spines. You may set a linestyle to those as shown below. import matplotlib.pyplot as plt fig, axes = plt.subplots(2,2) linestyles = ["--","-.",":", (0,(5,2,1,4))] for ax, ls in zip(axes.flat, linestyles): for spine in ax.spines.values(): spine.set_linestyle(ls) spine.set_linewidth(2) ax.set_title("linestyle: {}".format(ls)) plt.tight_layout() plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/52794309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Having issues with fetching an environment variable In the root of my React project, I have this .env file containing the following. DS_API_URL=[http://url.com](http:url.com/) In another file of the project, an axios call utilizes this to return some stuff. const url = 'http://url.com/graph/tech-stack-by-role' will return what I need. const url = `${DS_API_URL}/graph/tech-stack-by-role`; returns an error. How do I fetch the link from the env file and assign it to a var? A: To use environment variable in react you need to prefix the variable name with process.env.REACT_APP_. Documentation So in your .env file you have: REACT_APP_DS_API_URL=[http://url.com](http:url.com/) Then to use: const url = `${process.env.REACT_APP_DS_API_URL}/graph/tech-stack-by-role` Update to answer question: update your start script to use the .env file you want. in this case it is .env.localhost. You will also need to npm install or yarn install env-cmd: "start": "env-cmd -f ./.env.localhost react-scripts start",
{ "language": "en", "url": "https://stackoverflow.com/questions/74132164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Capture 2nd entry from database I'm quite new to the programming world and have become stuck with querying a database in C#. I am trying to return a date and an Int32 from the second entry in a database using the code below: OleDbCommand com101 = new OleDbCommand("SELECT TOP 2 [Flight_Date], [No_Launches] FROM Flights WHERE [Claimed_By_ID] = ? ORDER BY [Flight_Date] DESC LIMIT 1,1", Program.DB_CONNECTION); com101.Parameters.Add(new OleDbParameter("", 451)); OleDbDataReader dr101 = com101.ExecuteReader(); when I run the code I get an error saying there is a problem with the Syntax error in ORDER BY clause. Can anyone spot what I am missing? Cheers A: This is your query: SELECT TOP 2 [Flight_Date], [No_Launches] FROM Flights WHERE [Claimed_By_ID] = ? ORDER BY [Flight_Date] DESC LIMIT 1,1; You need to decide which database you are using. Some support TOP; some support LIMIT. Based on your error and the use of the square braces, I would guess that you are using SQL Server/Sybase and should remove the LIMIT clause: SELECT TOP 2 [Flight_Date], [No_Launches] FROM Flights WHERE [Claimed_By_ID] = ? ORDER BY [Flight_Date] DESC; If this is true, you should change the tag on the question from "mysql" to "sql-server". EDIT: To get the second entry, I think you can use a subquery: SELECT TOP 1 * FROM (SELECT TOP 2 [Flight_Date], [No_Launches] FROM Flights WHERE [Claimed_By_ID] = ? ORDER BY [Flight_Date] DESC ) as t ORDER BY Flight_Date ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/22337552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating an if/elif statement with regex error in python So recently I started learning python through an online education platform and currently I hit a wall. So the problem is: Create an if statement that takes an age value. This if statement should print the word “child” if age is 12 or less, “teenager” if age is between 13 and 19 inclusive, and “adult” if age is greater than 19. and my code is: age = 16 if age < 13: print("child") elif (age >= 13) and (age < 20): print("teenager") else: print("adult") So according to the website, the part I did for child and adult is correct but the teenager part of it is wrong and is showing this regex message: Searched your code for a specific pattern: ^elif (13\s*<=\s*age|12\s*<\s*age)?\s*(or|\|)?\s*(age)?(\s*<\s*20|\s*<=\s*19):$\s*print\(('|")teenager('|")\) So I basically tried learning regex to understand what I did wrong and what I could understand from it is basically but I'm sure that I'm reading it wrong: elif (13 <= age 12 < age) or (age < 20 <= 19): print("teenager") So what am I missing? Any help would be very much appreciated thanks! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/68371648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java.util.NoSuchElementException: No line found* I keep getting this error java.util.NoSuchElementException No line found when I use this method public boolean hasMoreCommands() { if (input.hasNextLine()) { return true; } else { //input.close(); return false; } } public void advance() { String str; if(hasMoreCommands() == true){ do { str = input.nextLine().trim(); // Strip out any comments if (str.contains("//")) { str = (str.substring(0, str.indexOf("//"))).trim(); } } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands()); command = str; } } I have main code here: public class Ptest { public Ptest(String fileName) { String line = null; String nName = fileName.replace(".vm", ".asm"); Parser p = new Parser(); try{ File neF = new File(nName); if(!neF.exists()){ neF.createNewFile(); } File tempFile = new File("temp.txt"); if(!tempFile.exists()){ tempFile.createNewFile(); } FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(nName); BufferedWriter bw = new BufferedWriter(fw); FileWriter writR = new FileWriter(tempFile); BufferedWriter buffR = new BufferedWriter(writR); while((line = br.readLine()) != null) { buffR.write(line+ "\n"); //System.out.println(line); } buffR.flush(); buffR.close(); p.insertTitle(tempFile); String ctype = p.commandType(); int len = ctype.length(); int spaces = 13 - len; String sp = " "; String asp = " "; String a1 = null; int a2; int alen; boolean t = false; while(p.hasMoreCommands()){ for(int i= 0; i < spaces; i++){ sp += " "; } t = p.hasMoreCommands(); a1 = p.arg1(); alen = (10 - a1.length()); for(int i= 0; i < alen; i++){ asp += " "; } //a2 = p.arg2(); if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") { a2 = p.arg2(); bw.write(ctype + sp + a1 + asp + a2); } else { bw.write(ctype + sp + a1); } p.advance(); ctype = p.commandType(); len = ctype.length(); spaces = 13 - len; } bw.flush(); bw.close(); } catch(FileNotFoundException ex){ System.out.println("File not found!"); } catch(IOException ex){ System.out.println("Error reading file '" + fileName + "'"); } } } I went through debugger and it literally goes the entire file then gives me an error when its finished. A: Like @hfontanez I think your problem is in this code: if(hasMoreCommands() == true){ do { str = input.nextLine().trim(); // Strip out any comments if (str.contains("//")) { str = (str.substring(0, str.indexOf("//"))).trim(); } } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands()); command = str; } However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands()); I'm assuming that "advance" ought to return the next non-comment / blank line. If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while. I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank. A: My guess is that your problem is here: if(hasMoreCommands() == true){ do { str = input.nextLine().trim(); // Strip out any comments if (str.contains("//")) { str = (str.substring(0, str.indexOf("//"))).trim(); } } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands()); command = str; } The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get. The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop. The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine(). You have to check is there is a next line to be got before calling this method. Surround this line with an if(input.hasNextLine()) and I think you should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/26708184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Axios + Typescript: how to pass a param of type "ResponseType"? Axios defines ResponseType as export type ResponseType = | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' I'm trying to pass a configuration to axios.post const config = { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': HOST_HEADER, }, responseType: 'json' } const data_to_post = { .... omitted ... } return axios.post(HOST, data_to_post, config) Problem: typescript linter warn me saying the type string cannot be assigned to type ResponseType. Also tried: Of course I cannot use the syntax responseType: ResponseType.json How can I fix this? A: The problem is that Typescript will infer config to be of type { headers: { 'X-Requested-With': string; 'Content-Type': string; 'Host-Header': string; }; responseType: string; } Typescript does not know that you are trying to create a config object for Axios. You can explicitly type the entire object as AxiosRequestConfig, or you could explicitly type responseType: 'json' to be of type ResponseType. const config: AxiosRequestConfig = { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'Host-Header': 'dsa', }, responseType: 'json' }; A: Fixed using explicit casting responseType: <ResponseType> 'json'
{ "language": "en", "url": "https://stackoverflow.com/questions/56987042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get source branch name in commit-msg hook of merge commit In the commit-msg hook for a merge commit, how can I get the branch name of the immediate source branch for the merge? I can get the target branch with something like git rev-parse --abbrev-ref HEAD But HEAD and HEAD^ both refer to the target branch. Is there a way to programmatically determine the source? I'm using a bash script for the hook. The default merge commit message contains this text: Merge branch 'source-branch' into target-branch So the commit-msg hook could grab the name right out of the message, but there's no guarantee that the user hasn't edited it. If there's a more foolproof method, I would prefer it. Edit: ah, unfortunately I also didn't realize that commit-msg doesn't actually even run on merge commits! So I'll have to find a different way to do what I want anyway. A: This will give you the commit being merged: git rev-parse MERGE_HEAD I do not think that there is a way to find the branch name other than guessing with a command like: git for-each-ref | grep ^$(git rev-parse MERGE_HEAD) (which finds all branches pointing to the commit you are merging) Note that the commit being merged does not have to be a branch, one can also merge a commit directly like git merge deadbeef. In the case of octopus merge, there is more than one commit being merged at the same time, and MERGE_HEAD is not present. If you are to extract it from the merge message, then using .git/MERGE_MSG is safer than .git/COMMIT_EDITMSG, since it is less likely to be hand-edited. The message is generated by git merge, hence has access to the branch name from git merge's arguments, but this does not seem to be stored on disk. A: but there's no guarantee that the user hasn't edited it imvho you should use the merge commit summary line, after the user has had a chance to edit it. I've edited subject lines for good reason. All branch names are repo-local. Sometimes you're pulling from a coworker, sometimes you realize you typo'd during branch creation, or you're publishing from a wip that turned out well, there's lots more ways to get there. If you're worried about inbound commits not meeting your standards for one of your own repositories, vet the inbound commits in its pre-receive. No dvcs can be sure without doing that anyway. #!/bin/sh rc=0 existing=$(git for-each-ref --format='%(object)' refs/heads refs/tags); validmergesubject='Merge (branch|tag) '\''[^ ]*'\'' (of|into) .*' while read old new ref; do while read commit Subject; do if [[ ! $Subject =~ $validmergesubject ]]; then echo Merge $commit in $ref history has invalid summary line \"$Subject\" rc=1; fi; done >&2 <<EOD $(git log --merges --pretty='%H %s' $new --not $existing) EOD done exit $rc
{ "language": "en", "url": "https://stackoverflow.com/questions/29936978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get a range of elements from an array in Redisjson? I have a simple array as such : [1,2,3,4,5] and I wish to get a range for example from index 2 to index 4. I can get the last element of the array by : json.get key .[-1] However I cannot find anyway to return a specific results without trimming the array. Is there anyway I can get a range of elements from a Redis json array? A: The answer is : await Client.json.get("key" , {path : '$.[1:3]'}) which gets index 1 to 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/71897854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to hide url in the popup window opened using window.open I am using below code to open a popup window in my page: window.open("myPopupWindow.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no, addressbar=no, top=200, left=300"); Although the url is disabled but even then it can be seen and copied. I have already set addressbar to no. How can I hide url in popup window? A: Are you just trying to mask the address, to make it look nicer or hide the fact that you're linking to to another website, or is it that you don't want people to know they can access that page without using your popup? If it's the former, then what you could do is make the page you open in window.open an iframe, and point the iframe to your actual page. They user could still access the target page, but only via your nicer looking url. The other option is to use something like a colorbox with an iframe instead of window.open, which will mask the address. Have a look at the Outside Webpage (iframe) example on this page. Of course whichever option you choose, someone smart can still track down the target url via the source code and go there directly. A: window.open('http://mysite/proxy.html') and in proxy.html : <html> <body> <iframe src="/realPage.html"></iframe> </body> </html> A: Simple solution open new tab after that add url to location.href. window.open('','_blank').location.href = "url"
{ "language": "en", "url": "https://stackoverflow.com/questions/22982105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QFileDialog::getOpenFileName doesn't set the initial directory on Mac OS 10.8 Mountain Lion I can not change the current directory with QFileDialog with Qt 4.8. The same code works fine on Windows and Mac OS 10.6 Snow Leopard. It also works fine if I don't use the native Mac OS X dialog. This works: fn=QFileDialog::getOpenFileName(this,"Select File","/Users/myuser/Desktop",QString(),0,QFileDialog::DontUseNativeDialog); This doesn't work: fn=QFileDialog::getOpenFileName(this,"Select File","/Users/myuser/Desktop"); It looks like if most of the time it opens the last path of the last call to getOpenFileName. A: Got the same issue with Qt5.2.0 on Mavericks... I found a work around: append a dummy file name to the directory you want to select. However, be sure not to do this on Windows because the user will see it. QString dir = "/Users/myuser/Desktop"; #if defined(__APPLE__) dir += "/MyFile.txt"; #endif fn = QFileDialog::getOpenFileName(this, "Select File", dir); Also, for those like me that instantiate a file dialog because they need more options you can also do: QFileDialog fileDialog(this, "Select File"); #if defined(__APPLE__) fileDialog.selectFile(dir + "/MyFile.txt"); #else fileDialog.setDirectory(dir); #endif ... A: This is a bug in Qt that is reportedly fixed in Qt 5.0.1 and Qt 4.8.4 (though it seems that it still reproducible in 4.8.4 by people (myself included)). This bug has been reported in JIRA as QTBUG-20771, QTBUG-28161 and finally QTBUG-35779 (which appears to have finally fully resolved the issue in Qt 5.2.1). Here is a link to the patch in Gerrit.
{ "language": "en", "url": "https://stackoverflow.com/questions/16194475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Navigator.getUserMedia and Navigator.webkitGetUserMedia undefined after updating to Chrome 74 After updating from Chrome 73 to 74 navigator.getUserMedia and navigator.webkitGetUserMedia return undefined. Here https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia I see that getUserMedia is actually deprecated in favor of navigator.mediaDevices.getUserMedia(), but in my case navigator.mediaDevices too is undefined so I cannot use it. Anyone knows if it's a bug in the latest release of Chrome or if I need to use something else? A: I tried a small setting on chrome and it turned out to work for me. I enabled: chrome://flags/#unsafely-treat-insecure-origin-as-secure and provided my HTTP server link along with the port. It worked for me. You could refer to the following: 1. https://stackoverflow.com/a/61472984/12906501 2. https://medium.com/@Carmichaelize/enabling-the-microphone-camera-in-chrome-for-local-unsecure-origins-9c90c3149339 Hope it helps!! Thanks. A: Since version 74 of Chrome navigator.getUserMedia, navigator.webkitGetUserMedia and navigator.mediaDevices can be used only in secure context (https), otherwise they are undefined. I've understood what the problem was while writing the question, as usual... A: In my case HTTP was the cause of undefined for navigator.mediaDevices with HTTPS works as expected
{ "language": "en", "url": "https://stackoverflow.com/questions/56005165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: ng-file-upload issue on IE9 - after uploading one file receiving error var prevFiles = ((ngModel && ngModel.$modelValue) || attr.$$ngfPrevFiles || []).slice(0); I am getting an error that the result of this statement does not have a slice method. A: Without knowing too much about the module I have a theory: The first evaluation (ngModel && ngModel.$modelValue), when true, returns a Boolean which does not have a slice method. A: There was an issue filed in Github about this https://github.com/danialfarid/ng-file-upload/issues/1139 Reportedly fixed in release 10.0.3.
{ "language": "en", "url": "https://stackoverflow.com/questions/33740352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can the code being allowed to continue from one question to another question even though the input answer had wrong for 3 attempts? import time import random #declare variables and constant guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"] nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"] guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False guess_no = 0 score = 0 #set the maximum number of questions for looping and random pick an element from the list before deleting it for i in range(7): randomelement = random.choice(guessingelement) guessingelement.remove(randomelement) time.sleep(2) #tips of the element if randomelement == "Hydrogen" and not out_of_guesses: print("Tip 1: It is the most flammable of all the known substances.") print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.") print("Tip 3: It reacts with oxygen to form water.") #test the number of tries so that it doesn't exceed 3 times if answer is wrong while guess != randomelement and not(out_of_guesses): if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 else: out_of_guesses = True #add score, praise when answer is correct and encourage when answer is wrong for 3 times if out_of_guesses: print("Out of Guesses, NICE EFFORT!") else: print(random.choice(nicephrases), ", YOU GET IT!") score = score + 1 #tips of the element if randomelement == "Magnesium" and not out_of_guesses: print("Tip 1: It has the atomic number of 12.") print("Tip 2: It's oxide can be extracted into free metal through electrolysis.") print("Tip 3: It is a type of metal.") Same as first questions' code.. and so on.... In the progress of changing:` #tips of the element if randomelement == "Hydrogen": print("Tip 1: It is the most flammable of all the known substances.") print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.") print("Tip 3: It reacts with oxygen to form water.") #test the number of tries so that it doesn't exceed 3 times if answer is wrong while guess != randomelement: if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 else: print(random.choice(wronganswers)) #add score, praise when answer is correct and encourage when answer is wrong for 3 times else: print(random.choice(nicephrases), ", YOU GET IT!") score = score + 1 However, after 3 times of attempts, it keeps printing the elements from the wronganswers list non-stop, and can't proceed to the next question. The output I expected is that it will show an element from the list when the input answer is wrong and proceed to the next question. A: I hope this helps. I wrote this code for myself in a new way. I have used recursion to keep the guess happening and simple used a while loop that will break when max attempts go beyond 3. import random elements = ["hydrogen", "magnesium", "cobalt", "mercury", "aluminium", "uranium", "antimony"] nice_phrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"] # I went ahead and created a dictionary of lists for storing the Hints hints = { 'hydrogen': [ "Tip 1: It is the most flammable of all the known substances.", "Tip 2: It reacts with oxides and chlorides of many metals, " "like copper, lead, mercury, to produce free metals.", "Tip 3: It reacts with oxygen to form water." ], 'magnesium': [ "Tip 1: It has the atomic number of 12.", "Tip 2: It's oxide can be extracted into free metal through electrolysis.", "Tip 3: It is a type of metal." ], } score = 0 def guess_again(): global score random_element = random.choice(elements) max_attempts = 3 # this will remove the element from occurring again for x in elements: if x == random_element: elements.remove(x) while max_attempts > 0: user_guess = input("Take a Guess").lower() if user_guess == random_element: print(f"{random.choice(nice_phrases)}, you got it!") score += 1 # If the answer is right calling the function again will continue the game guess_again() else: max_attempts -= 1 print("That was a wrong guess. Here is a Hint") if random_element in hints: print(hints[random_element]) else: print("Sorry no hints available at the moment") if max_attempts == 0: print("Sorry your out of guesses") print(f"{random.choice} was the element") guess_again() If the Answer is right it will select the next element and the game continues until all the elements in the list are finished. I have coded it to give 3 attempts for each elements. If you want the maximum 3 attempts for the entire duration of the game just declare max_attempts outside the function and give it global scope like done for score
{ "language": "en", "url": "https://stackoverflow.com/questions/74487482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: if_attribute on declarative authorization I have a many-to-many relationship like this: A user has_many organizations through affiliations and vice-versa. I'm using declarative organizations and I only want a user to edit a particular organization if he is affiliated and the affiliationtype attribute of affiliation is a particular value. So affiliations has 3 columns , user_id, organization_id and affiliationtype_id I can do: o = Organization.find(:first) o.affiliatons[0].user and get the user now I wish to do this: has_permission_on [:organizations], :to => :edit do if_attribute (...) end That if_attribute should see if the current user is the organization.affiliation[?].user and if the organization.affiliation[?].affiliationtype_id = "3" I hope this is syntax issue ... I really need to get this working. A: EDIT: You can restrict the type of affiliation with intersects_with(&block) : has_permission_on [:organizations], :to => :edit do if_attribute :affiliations => intersects_with { user.affiliations.with_type_3 } end Why not create a named_scope to find affiliations whose affiliationtype_id = 3? From declarative_authorization documentation: To reduce redundancy in has_permission_on blocks, a rule may depend on permissions on associated objects: authorization do role :branch_admin do has_permission_on :branches, :to => :manage do if_attribute :managers => contains {user} end has_permission_on :employees, :to => :manage do if_permitted_to :manage, :branch # instead of #if_attribute :branch => {:managers => contains {user}} end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/2439747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Print "hello world" every X seconds Lately I've been using loops with large numbers to print out Hello World: int counter = 0; while(true) { //loop for ~5 seconds for(int i = 0; i < 2147483647 ; i++) { //another loop because it's 2012 and PCs have gotten considerably faster :) for(int j = 0; j < 2147483647 ; j++){ ... } } System.out.println(counter + ". Hello World!"); counter++; } I understand that this is a very silly way to do it, but I've never used any timer libraries in Java yet. How would one modify the above to print every say 3 seconds? A: You can use Thread.sleep(3000) inside for loop. Note: This will require a try/catch block. A: public class HelloWorld extends TimerTask{ public void run() { System.out.println("Hello World"); } } public class PrintHelloWorld { public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new HelloWorld(), 0, 5000); while (true) { try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("InterruptedException Exception" + e.getMessage()); } } } } infinite loop is created ad scheduler task is configured. A: The easiest way would be to set the main thread to sleep for 3000 milliseconds (3 seconds): for(int i = 0; i< 10; i++) { try { //sending the actual Thread of execution to sleep X milliseconds Thread.sleep(3000); } catch(InterruptedException ie) {} System.out.println("Hello world!"); } This will stop the thread at least X milliseconds. The thread could be sleeping more time, but that's up to the JVM. The only thing guaranteed is that the thread will sleep at least those milliseconds. Take a look at the Thread#sleep doc: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. A: Try doing this: Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { System.out.println("Hello World"); } }, 0, 5000); This code will run print to console Hello World every 5000 milliseconds (5 seconds). For more info, read https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html A: Use java.util.Timer and Timer#schedule(TimerTask,delay,period) method will help you. public class RemindTask extends TimerTask { public void run() { System.out.println(" Hello World!"); } public static void main(String[] args){ Timer timer = new Timer(); timer.schedule(new RemindTask(), 3000,3000); } } A: If you want to do a periodic task, use a ScheduledExecutorService. Specifically ScheduledExecutorService.scheduleAtFixedRate The code: Runnable helloRunnable = new Runnable() { public void run() { System.out.println("Hello world"); } }; ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS); A: You can also take a look at Timer and TimerTask classes which you can use to schedule your task to run every n seconds. You need a class that extends TimerTask and override the public void run() method, which will be executed everytime you pass an instance of that class to timer.schedule() method.. Here's an example, which prints Hello World every 5 seconds: - class SayHello extends TimerTask { public void run() { System.out.println("Hello World!"); } } // And From your main() method or any other method Timer timer = new Timer(); timer.schedule(new SayHello(), 0, 5000); A: This is the simple way to use thread in java: for(int i = 0; i< 10; i++) { try { //sending the actual Thread of execution to sleep X milliseconds Thread.sleep(3000); } catch(Exception e) { System.out.println("Exception : "+e.getMessage()); } System.out.println("Hello world!"); } A: I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below: TimerTask task = new TimerTask() { @Override public void run() { System.out.println("Hello World"); } }; Timer timer = new Timer(); timer.schedule(task, new Date(), 3000); A: What he said. You can handle the exceptions however you like, but Thread.sleep(miliseconds); is the best route to take. public static void main(String[] args) throws InterruptedException { A: Here's another simple way using Runnable interface in Thread Constructor public class Demo { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 5; i++){ try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread T1 : "+i); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 5; i++) { try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread T2 : "+i); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 5; i++){ try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread T3 : "+i); } } }); t1.start(); t2.start(); t3.start(); } } A: Add Thread.sleep try { Thread.sleep(3000); } catch(InterruptedException ie) {} A: For small applications it is fine to use Timer and TimerTask as Rohit mentioned but in web applications I would use Quartz Scheduler to schedule jobs and to perform such periodic jobs. See tutorials for Quartz scheduling. A: public class TimeDelay{ public static void main(String args[]) { try { while (true) { System.out.println(new String("Hello world")); Thread.sleep(3 * 1000); // every 3 seconds } } catch (InterruptedException e) { e.printStackTrace(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/12908412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "148" }
Q: how to create a single webapplication as a sub domain for many companies i am working on a project that you can subscribe with your company name and you can use all features of site specificly to your company. for example company abcd can get its own url from our website like www.test.com/abcd/productlist.aspx company efgh can also login with its own url and see its product list. www.test.com/efgh/productlist.aspx can any one help me how can i implement this with my site with best approaches I am thinking on the approach that will use Global.ascx file to distinguish companies, i will write code to extract company name from url in global.ascx for every valid request and in all the pages i will put this.form.action = request.rawurl. is there any other approaches? if anybody implemented this type of feature, please let me know your approaches. Thanks A: If you're working with ASP.NET 3.5 SP1 then you should investigate the new routing engine that has been introduced from the MVC project. It will make for a clean solution. A: We are using the DLL from http://urlrewriting.net and rules similar to the following: <urlrewritingnet xmlns="http://www.urlrewriting.net/schemas/config/2006/07"> <rewrites> <add name="Customer" virtualUrl="^~/([^/]+)/([^/]+).aspx" destinationUrl="~/$2.aspx?customer=$1"/> <add name="CustomerStart" virtualUrl="^~/([^/]+)/$" destinationUrl="~/Default.aspx?customer=$1"/> <add name="CustomerStartAddSlash" virtualUrl="^http\://([^/]+)/([a-zA-Z0-9_-]+)$" destinationUrl="http://www.example.com/$2/" redirect="Domain" redirectMode="Permanent" /> </rewrites> </urlrewritingnet> Those rules do the following mappings. These are rewrites, so the user always sees the left-hand URL in his browser: Rule 1: http://www.example.com/customerA/something.aspx => http://www.example.com/something.aspx?customer=customerA Rule 2: http://www.example.com/customerA/ => http://www.example.com/Default.aspx?customer=customerA The third rule is a redirect rather than a rewrite, i.e., it ensures that the trailing slash is added in the user's browser (makes sure that relative paths work correctly): Rule 3: http://www.example.com/customerA => http://www.example.com/customerA/ A: Take a look at these questions. Your approach has a name. It's called Multitenancy. A: I did not found any solution that fully suites my requirement , I have written my own logic for this , which uses Global.ascx's BeginRequest, Login page, Base page and common classes created for Response.Redirect. I am no longer directly using Asp.Net's Response.Redirect, Paths and Session variables, instead I have created wrappers over them to add companyName from url to the Paths. Let me know if you need more information on my code Other answers are welcome. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/2084393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to send a Whatsapp message to a specific user using third party apps in iPhone? Let my app be A and the app user is called A1 I have a completely different person with his mobile mobile number - N1 Now I want achieve the following in my app A - When the user A1 clicks on a button, Whatsapp is opened(if present) with a compose message to the number N1, whether or not he is in his contact list. I am pretty sure that this is possible on Android as I my self have done it but in iOS, I am not able to find any solution. What ever solutions are out there don't achieve what I want as they open Whatsapp in general, and show me all the users out there. Please, do not redirect to the Whatsapp.com support URL as it is pretty useless.
{ "language": "en", "url": "https://stackoverflow.com/questions/25810824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ember : sortBy or Ember.computed.sort I saw an example of Ember sortBy somewhere which goes like: model.sortBy("time").reverse().sortBy("place") It was working, but am not sure if this is a good way to do that. Would the below a better fit for this. If yes, why. sortOptions: ['time:desc','place'] Ember.computed.sort('model',sortOptions) A: model.sortBy("time").reverse().sortBy("place") Will sort the array model one time. Ember.computed.sort('model',sortOptions) Will recompute its value every time model or its properties change. So what you should use depends on what you need. I don't think there's a significant difference in performance of the sort itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/37650565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP extension conflict with Ioncube extension The problem is with the IonCube obfuscation library being used to encode/obfuscate their PHP application. This IonCube library which is a zend extension, is interfering with PHP extension. When IonCube is enabled, for all encoded/obfuscated PHP pages monitored, PHP extensions’ “myextensionfunc” method is being skipped because of which I am having problem in my extension code and some transaction related values are missing. “myextensionfunc i.e. (zend_execute)” function is used by my PHP extension to identify the some transaction related values and to monitor php app methods. Problem here is that - Is there any workaround(apart from disabling ioncube) so that ioncube doesn't interfere with my php extension? Please provide some thoughts on this, thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/52215962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can't get href from beautifulsoup from 'a class' I'm trying to extract the href from this web site, but I can't find the way to do that, I tried using this: busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF') auto_cont = BeautifulSoup(busqueda.content) auto_cont.find_all('a',{'class':'item__info-title'}, href = True) But there is a '< span>' content and I can't overcome that. A: find_all has been explained. However, your selector is going to produce duplicates as it will pull the same urls from title and price. Instead, I would use a child combinator and a different class for parent and add a child a tag to get the unique list. I prefer select over find_all. select applies css selectors in order to match on elements. All these a tags have an href so no need to add a test. from bs4 import BeautifulSoup as bs import requests r = requests.get('https://autos.mercadolibre.com.ar/volkswagen/vento/_DisplayType_LF') soup = bs(r.content, 'lxml') links = [item['href'] for item in soup.select('.list-view-item-title > a')] Child combinator: The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the children of elements matched by the first. Ref: * *https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html?highlight=select_one#css-selectors A: Since you are using Beautiful Soup, it is important to understand that the find_all method will return a list of tags that match your requirements. Your issue is that you want the href attribute of those tags. To do that, you can use the notation tag['attr'] on each tag. To do that we will iterate through the returned tags. from bs4 import BeautifulSoup import requests busqueda = requests.get('https://autos.mercadolibre.com.ar/vento/_DisplayType_LF') auto_cont = BeautifulSoup(busqueda.content) print([tag['href'] for tag in auto_cont.find_all('a',{'class':'item__info-title'}, href = True)]) A: Try this: >>> import requests >>> s = requests.Session() >>> resp = s.get("https://autos.mercadolibre.com.ar/vento/_DisplayType_LF") >>> from lxml import html >>> doc = html.fromstring(resp.text) >>> doc.xpath("//a[@class='item__info-title']") [<Element a at 0x11c005688>, <Element a at 0x11c0059a8>, <Element a at 0x11c007e58>, <Element a at 0x11c007ea8>, <Element a at 0x11c007ef8>, <Element a at 0x11c007c78>, <Element a at 0x11c007db8>, <Element a at 0x11c007e08>, <Element a at 0x11c007d68>, <Element a at 0x11c007cc8>, <Element a at 0x11c007d18>, <Element a at 0x11c007bd8>, <Element a at 0x11c007c28>, <Element a at 0x11c007228>, <Element a at 0x11c003318>, <Element a at 0x11c003408>, <Element a at 0x11c0034f8>, <Element a at 0x11c003688>, <Element a at 0x11c0035e8>, <Element a at 0x11c003228>, <Element a at 0x11c003598>, <Element a at 0x11c003458>, <Element a at 0x11c003278>, <Element a at 0x11c003548>, <Element a at 0x11c0034a8>, <Element a at 0x11c003368>, <Element a at 0x11c0033b8>, <Element a at 0x11c0032c8>, <Element a at 0x11c0031d8>, <Element a at 0x11c003188>, <Element a at 0x11c003098>, <Element a at 0x11c003138>, <Element a at 0x11c0030e8>, <Element a at 0x11c003048>, <Element a at 0x11c0036d8>, <Element a at 0x11c003728>, <Element a at 0x11c003778>, <Element a at 0x11c0037c8>, <Element a at 0x11c003818>, <Element a at 0x11c003868>, <Element a at 0x11c0038b8>, <Element a at 0x11c003908>, <Element a at 0x11c003958>, <Element a at 0x11c0039a8>, <Element a at 0x11c0039f8>, <Element a at 0x11c003a48>, <Element a at 0x11c003a98>, <Element a at 0x11c003ae8>, <Element a at 0x11c003b38>, <Element a at 0x11c003b88>, <Element a at 0x11c003bd8>, <Element a at 0x11c003c28>, <Element a at 0x11c003c78>, <Element a at 0x11c003cc8>, <Element a at 0x11c003d18>, <Element a at 0x11c003d68>, <Element a at 0x11c003db8>, <Element a at 0x11c003e08>, <Element a at 0x11c003e58>, <Element a at 0x11c003ea8>, <Element a at 0x11c003ef8>, <Element a at 0x11c003f48>, <Element a at 0x11c003f98>, <Element a at 0x11c006048>, <Element a at 0x11c006098>, <Element a at 0x11c0060e8>, <Element a at 0x11c006138>, <Element a at 0x11c006188>, <Element a at 0x11c0061d8>, <Element a at 0x11c006228>, <Element a at 0x11c006278>, <Element a at 0x11c0062c8>, <Element a at 0x11c006318>, <Element a at 0x11c006368>, <Element a at 0x11c0063b8>, <Element a at 0x11c006408>, <Element a at 0x11c006458>, <Element a at 0x11c0064a8>, <Element a at 0x11c0064f8>, <Element a at 0x11c006548>, <Element a at 0x11c006598>, <Element a at 0x11c0065e8>, <Element a at 0x11c006638>, <Element a at 0x11c006688>, <Element a at 0x11c0066d8>, <Element a at 0x11c006728>, <Element a at 0x11c006778>, <Element a at 0x11c0067c8>, <Element a at 0x11c006818>, <Element a at 0x11c006868>, <Element a at 0x11c0068b8>, <Element a at 0x11c006908>, <Element a at 0x11c006958>, <Element a at 0x11c0069a8>, <Element a at 0x11c0069f8>, <Element a at 0x11c006a48>, <Element a at 0x11c006a98>, <Element a at 0x11c006ae8>, <Element a at 0x11c006b38>, <Element a at 0x11c006b88>] >>> doc.xpath("//a[@class='item__info-title']/@href") ['https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-793135798-volkswagen-vento-20t-sportline-2007-4p-dh-aa-san-blas-auto-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788603493-volkswagen-vento-25-advance-plus-manual-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-774423219-vento-comfortline-0km-2019-volkswagen-linea-nueva-vw-2018-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-795714156-volksvagen-vento-advance-plus-25-anticipo-290000-y-ctas-_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792330462-volkswagen-vento-25-luxury-wood-tiptronic-2009-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-763941297-vento-highline-0km-automatico-auto-nuevos-volkswagen-vw-2019-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-791000164-volkswagen-vento-20-advance-115cv-2015-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-788125558-volkswagen-vento-14-tsi-highline-150cv-at-2017-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-777140113-volkswagen-vento-gli-dsg-nav-my-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-795016462-volkswagen-vento-25-luxury-tiptronic-2011-imolaautos--_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-792487602-volkswagen-25-luxury-170cv-tiptronic-2015-rpm-moviles-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-789645020-volkswagen-vento-20-advance-115cv-summer-package-371-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185003-vw-0km-volkswagen-vento-14-comfortline-highline-financiado-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-774502893-volkswagen-vento-14-comfortline-150cv-at-dsg-0km-2019-vw-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795734858-volkswagen-vento-25-luxury-tiptronic-2009-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-795501655-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792476554-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-790622152-volkswagen-vento-14-tsi-comfortline-dsg-como-nuevo-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-741867064-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-770677950-volkswagen-vento-20-sportline-tsi-200cv-dgs-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-756888148-volkswagen-vento-14-highline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792470321-volkswagen-vento-highline-14-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-780443475-volkswagen-vento-20-sportline-tsi-200cv-bi-xenon-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-775185107-vw-0km-volkswagen-vento-14-comfortline-highline-financio-ya-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-763006237-volkswagen-nuevo-vento-comfortline-14-tsi-150cv-autotag-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-792344363-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-789195021-volkswagen-vento-comfortline-motor-14-at-tiptronic-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-787103884-volkswagen-vento-comfortline-14-150-cv-dsg-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-795438039-volkswagen-vento-14-highline-150cv-at-financio-leasing-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-785080712-vento-25-advance-manual-permutofinancio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-739533930-volkswagen-vento-20-tsi-i-2017-i-permuto-i-financio-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-787212749-volkswagen-vento-14-comfortline-150cv-at-_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-785738851-volkswagen-vento-advance-summer-package-20-unico-dueno--_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-788508924-volkswagen-vento-25-advance-tiptronic-2007-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-790696083-volkswagen-vento-14-highline-150cv-at-0km-tiptronic-nuevo-1-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-788446116-volkswagen-vento-20-sportline-tsi-200-2013-luxury-tdi-bora-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-752087027-volkswagen-nuevo-vento-14-highline-0-km-2019-autotag-cb-a7-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-781505508-nuevo-vento-entrega-inmediata-tomo-usado-moto-auto-18-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-742485511-volkswagen-vento-14-highline-150cv-0km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-769182377-vw-volkswagen-vento-gli-230-cv-preventa-2019-0-km-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790609996-volkswagen-vento-20-luxury-i-140cv-dsg-automatico-diesel-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-790664862-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-784454164-volkswagen-vento-25-luxury-170cv-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-769868579-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-d-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-787564006-volkswagen-vento-20t-sportline-automatico-dsg-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-788080154-volkswagen-vento-20-sportline-tsi-200cv-dgs-2013-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-771885864-volkswagen-vento-14-comfortline-150cv-aut-sf-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-795273990-vento-25-manual-unico-dueno-80000-km-motor-cadenero-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-769870550-0km-volkswagen-vento-14-highline-150cv-at-2019-tasa-159-f-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM', 'https://auto.mercadolibre.com.ar/MLA-790653682-volkswagen-vento-25-triptronic-170-cv-cuero-carhaus-_JM']
{ "language": "en", "url": "https://stackoverflow.com/questions/56828578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing erlang 19.3 with ubuntu 18.04 gives the following error: crypto: No usable OpenSSL found, ssh : No usable OpenSSL found My OS is ubuntu 18.04, erlang version is 19.3, openssl version is 1.1.1, and when I use . /configure --prefix=/opt/erlang , the error report: ********************************************************************* ********************** APPLICATIONS DISABLED ********************** ********************************************************************* crypto : No usable OpenSSL found jinterface : No Java compiler found ssh : No usable OpenSSL found ssl : No usable OpenSSL found ********************************************************************* ********************************************************************* ********************** APPLICATIONS INFORMATION ******************* ********************************************************************* wx : wxWidgets not found, wx will NOT be usable ********************************************************************* ********************************************************************* ********************** DOCUMENTATION INFORMATION ****************** ********************************************************************* documentation : xmllint is missing. Using fakefop to generate placeholder PDF files. ********************************************************************* I check the version of libssl-dev # dpkg -s libssl-dev Package: libssl-dev Status: install ok installed Priority: optional Section: libdevel Installed-Size: 7669 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Architecture: amd64 Multi-Arch: same Source: openssl Version: 1.1.1-1ubuntu2.1~18.04.14 Depends: libssl1.1 (= 1.1.1-1ubuntu2.1~18.04.14) Suggests: libssl-doc Conflicts: libssl1.0-dev Description: Secure Sockets Layer toolkit - development files This package is part of the OpenSSL project's implementation of the SSL and TLS cryptographic protocols for secure communication over the Internet. . It contains development libraries, header files, and manpages for libssl and libcrypto. Homepage: https://www.openssl.org/ Original-Maintainer: Debian OpenSSL Team <pkg-openssl-devel@lists.alioth.debian.org> I check the version of openssl: # openssl version OpenSSL 1.1.1 11 Sep 2018 What is the reason for the above error? How can I solve the above problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/71478497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automate data extraction from Elasticsearch Dev Tools? I have to do the following steps two or three times a day * *log in into Elasticsearch *Go to Dev Tools *Run a specific query by selecting it and pressing ctrl + enter Query that I have to run *Select the results that returns in the "buckets" and copy it. The yellow markdown in the image is what I have to select and copy *Then I go to https://www.convertcsv.com/json-to-csv.htm and paste the results so it converts to CSV. Where I have to paste the results. *I can then download the CSV and then import it into google sheets so I can view the results in a Looker Dashboard. Button to download the converted CSV. This take me some time everyday and I would like if there is any way that I could automate such routine. Maybe some ETL tool that can perform at least part of the process or may some more specific way to do it with python. Thanks in advance. I don't have much experience with what I want to do and I tried to search online similar issues, but couldn't really find anything useful. A: I don't know you tried, but there is a reporting tool on elasticsearch inside the "Stack Management > Reporting". On the other side, there are another tools which you can work from a server with crontab. Here are some of them : * *A little bit old but I think it can work for you. ES2CSV. YOu can check there are examples inside the docs folder. YOu can send queries via file and report to CSV. *Another option which is my preference too. You can use pandas library of python. YOu can write a script according to this article, and you can get a csv export CSV. The article I mentioned is really explained in a great way. *Another alternative a library written in Java. But the documentation is a little bit weak. *Another alternative for python library can be elasticsearch-tocsv. This one is a little bit recently updated when I compare it to first alternative. But the query samples are a little bit weak. But there is a detailed article. You can check it. *You can use elasticdump, which is written on NodeJS and a great tool to report data from elasticsearch. And there is a CSV export option. You can see examples on GitHub page. I will try to find more and I will update this answer time by time. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/74993417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Express JS not rendering jade template I'm going to keep this short, I'm just trying to render a jade template using express js. I'm using express 3.0.0rc5 and jade 0.27.6. Here's my jade templates, the layout: // test-layout.jade doctype 5 html head title My title block head body #content block content And the index: // test-index.jade extends test-layout block head script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js") block content h1 My page Here's some excerpts from app.js: var app = express(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.get('/test-jade', function(req, res) { res.render('test-index', {}, function(err, html) { }); }); app.get('/test', function(req, res) { res.send('this works'); }); Now whenever I try to go to http://myurl.com/test-jade the browser just hangs and timesout without showing any output in the console (even though I'm in dev mode). However when I go to http://myurl.com/test I see 'this works'. I feel like I'm missing something really simple here, I'm currently upgrading from 2.5 to 3.0. Thanks in advance if anyone has advice. A: Is it the blank call back? res.render('test-index', {}, function(err, html) { }); In my app I'm using res.render('test-index', {});
{ "language": "en", "url": "https://stackoverflow.com/questions/12849746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP number_format() and round() not producing valid upper-range results 3 CODE: in_array($number, round(range(65,74))) or round(in_array($number,range(65,74))) I'm doing a switch case whenever the user inputs 73.4 the result is null. But whenever I input 73 or 74 it executes. How to do it I'm a newbie in php here. A: You need to round the user input number and not the range. So, it will be , in_array(round($number), range(65,74)); DEMO.
{ "language": "en", "url": "https://stackoverflow.com/questions/21495876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autolayout is expecting a different height I'm struggling with autolayout in my iOS 7 project on Xcode 5. Let's say I want to show these buttons : Something - | 10 pts fixed space from top - Button 1 50 pts height on 4" display, reduce height if 3"5 - | 10 pts fixed space - Button 2 50 pts height on 4" display, reduce height if 3"5 I layout my buttons in Interface Builder (with a storyboard). Then I start adding constraints : * *The vertical spacing from "button 1" to "something" *The leading space to container for "button 1" *The fixed width for "button 1" Problem is Autolayout is complaining about my button's, saying "Expected: height=30". Why ? I want a 50 pts button, why is this a problem ? Of course, I can fix this by adding a height constraint, but I want the height to be reduced if the height of the screen is reduced. And, if I run it, even on a 4" display, the button's height is set to 30, as autolayout said it "should be".. And I didn't even set the second button's constraints yet, which will make it even worse. How can I achieve such a thing ? It seems really basic and I still don't understand what's going on. Note that I could manually set all the heights in code, but I really want to avoid that. A: What you can do for solving the vertical constraint issue is to give Equal constraints to your button1 and button2 and give a fixed vertical constraint to the something view and from your second button to the bottom of the superview. So this way you won`t need to give a fixed height to any of them and the distance between them and other elements (something and bottom of superview) will be standard. I hope this helps! A: Ok, I think I made it. Here is what I did : * *I set all my constraints in the storyboard, with the Retina 4" form-factor. *Constraints for the something view : fixed height & width, fixed top space and leading space. This view is absolutely fixed. *Constraints for button 1 : fixed vertical space to something view, fixed leading space, fixed width. 2 height constraints : 30 <= height <= 50. *Constraints for button 2 : fixed vertical space to button 1, fixed leading space, fixed width. Also 2 height constraints : 30 <= height <= 50. And fixed bottom space to bottom layout. All constraints have a maximum priority of 1000, except the last one (fixed bottom space to bottom layout), which is set at 900 ! That way, the buttons keep a height >=30 and move up, but get shrinked vertically because the other constraints are more important. Thanks a lot to @VasiliyDeych and @P.Sami for their advice. It helped a lot. A: You're going to need to show us how your constraints are set up. Constraints are a set of rules that the views must follow. If there is no rule saying the button must shrink with the parent view, it will not happen. Based on your example, if I understood it correctly, you would want a set of constraints like this (defined in VFL for ease): [yourParentView addVisualConstraints:@"V:|[something(100@75)]-(10@100)-[button1(<=50,>=30@100)]-(10@100)-[button2(button1@100)]-(>=300@50)-|" forViews:NSDictionaryOfVariableBindings(something,button1,button2)]; All constraints here are vertical (V:), the numbers in parentheses represent a number of points, followed by @ and the desired priority of maintaining that number of points. The | symbols represent the top and bottom edges of the superview. So ]-(>=300@50)-| is saying, I'd like to keep 300 or more pixels between button2 and the bottom of the superview, but I care about it with a priority of 50. button1(<=50,>=30@100) means I really care that this button is between 30 and 50 pixels in height, with a priority of 100. button2(button1) means I want button2 to be the same height as button1. I also really care about keeping that 10-point distance between my elements. And I somewhat care that something (which is flush to the superview's top edge, hence |[) is going to stay at 100 points tall. Does this not work for what you are intending to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/22097320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Firebase login with GCP service account I am trying to login to the Firebase Tools CLI with a GCP service account. I have the path to the service account credentials saved as GOOGLE_APPLICATION_CREDENTIALS. I have logged out of firebase with firebase logout and have tried to sign in with the service account with firebase login --no-localhost and firebase login --no-localhost --token $GOOGLE_APPLICATION_CREDENTIALS. However in bother cases a web browser opens asking me to log in with my user account. How can I log in to firebase with a service account? A: Taken from Michael Bleighs comment: "The Firebase CLI does support GOOGLE_APPLICATION_CREDENTIALS, but you don't need to "log in" with them. If the environment variable is pointing to a valid service account you should be able to just use CLI commands as if you are logged in. You do need to be logged out for GAC to work correctly. Run the command with --debug if you're getting errors while trying to do so." I can confirm I have this working. Note you might need to run firebase use <project-id> for it to work correctly. A: You can't sign in to your Firebase project with a service account. You will need to use the proper user account of a collaborator on the project to sign in with Firebase tools. Even when using the CI integration, the documentation says to: * *Start the signin process by running the following command: firebase login:ci *Visit the URL provided, then sign in using a Google account.
{ "language": "en", "url": "https://stackoverflow.com/questions/61229315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert Indirectly Into a Naming Table? Let's consider this diagram With this JPA snippet of the Track class. @Entity @Table(name = "track") public class Track { @Id @Type(type="pg-uuid") private UUID id; @Column(name = "genre") private String genre; /* Getters, setters, etc */ } And the database schema /** Liquibase */ <changeSet id="1" author="SoulBeaver"> <createTable tableName="genre"> <column name="name" type="VARCHAR(1024)"> <constraints primaryKey="true" nullable="false" /> </column> </createTable> <createTable tableName="track"> <column name="id" type="UUID"> <constraints primaryKey="true" nullable="false" /> </column> <column name="genre" type="VARCHAR(1024)" /> </createTable> <addForeignKeyConstraint baseTableName="track" baseColumnNames="genre" constraintName="genre_fk" referencedTableName="genre" referencedColumnNames="name" /> </changeSet> Now, when I try to persist a track, which has been given a track.setGenre("Rock"); I get a RuntimeError stating that the key does not exist in Genre. Is there any way I can avoid having to create the Genre class, persisting the Genre first, and finally persisting the Track? A: Basically the FKey Constraint works in such a way that if you try to insert a value in child table with FKey value not present in your parent table, it will fail. This is not specific to JPA. It is how relational DB is designed.
{ "language": "en", "url": "https://stackoverflow.com/questions/19789141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why not wrap content within ``? It seems common to use the following HTML structure to accommodate users who have enabled/disable javascript: <html> <style> div.body { display:none; } .body > ... { ... } </style> <script> document.onload( function() { javascript(CONTENT => div.body); }); </script> <noscript> <style> body > :not(noscript) { display:none; } </style> </noscript> <body> <div class="body"> </div> <noscript class="body"> CONTENT </noscript> </body> </html> The mechanism uses a <div>; whose display attribute, initially set to none, is subsequently set to block|grid|etc. and populated with CONTENT once the page is loaded; alongside a <noscript>; which is pre-populated with CONTENT. No one seems to suggest simply popping the CONTENT within <noscript> into the <body> when javascript is available as follows : <html> <style> .body { ... } .body > ... { ... } </style> <script> document.onload( function() { let noscript = document.querySelector("noscript"); noscript.outerHTML = noscript.innerHTML; }); </script> <noscript> <style> body > noscript { display:content; } </style> </noscript> <body> <noscript> CONTENT </noscript> </body> </html> Here the CONTENT within noscript is displayed by default and if there is javascript the tag is simply dropped; the specification states the content of noscript should be parsable and that the parsed result be readily assignable as noscript.outerHTML. The first method requires one to repeat ones CONTENT in both the noscript and wrapped into the javascript that populates the div; this isn't especially DRY. I can't see that populating a page through javascript calls is any faster then assigning ELEMENT.outerHTML; if this is not true let me know. The second method relies upona bit of CSS trickery. Finally both methods seem subject to flicker. The only reasons I can think of for not using the latter structure are : * *SEO; I can't see how though e.g. you only have to scan CONTENT once, it sn't repeated, it isn't bundled between javascript, better aria/a11y support. *Frontend framework e.g. they all rely on the first structure *historic reasons e.g. setting noscript.outerHTML breaks events or something ut they are broken under the spec anyhow, jQuery.unwrap being a "recent" development, browser woes.
{ "language": "en", "url": "https://stackoverflow.com/questions/65817298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django form isn't rendering at all I'm trying to make a non model form that just gets input text for a chat like interface. views.py def get_input(request): if request.method == 'POST': form = inputForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = inputForm() return render(request, 'index.html', {'form': form}) def shelley_test(request): form = inputForm() return render(request, 'shelley_test.html') form.py from django import forms class inputForm(forms.Form): input = forms.CharField(label='input field') shelley_test.html <form action="/get_input/" method="get"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> please please help. I'm new at django and stumped :( A: You're not sending the form to the context in your shelley_test method - see the difference in the render line compared with get_input. Note though you don't need shelley_test at all: just go straight to /get_input/ to see the empty form.
{ "language": "en", "url": "https://stackoverflow.com/questions/31686259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hash created from CSV row not behaving like a normal hash I'm getting some weird issues. I'm trying to allow importing of a CSV into my model. I'm getting an unknown attribute 'hashtag' for Job. error, but that's not the issue. My model definitely has a hashtag column. When I get the error, if I try doing job.to_hash I get {"hashtag"=>"apples", "number"=>"10", "job_type"=>"0"} and if I do job.to_hash.symbolize_keys (with or without a !) I get {:hashtag=>"apples", :number=>"10", :job_type=>"0"} However, here comes the issue. Both of these seem to be of the Hash class when I call .class on them. But if I try assigning it to a variable and calling ["hashtag"] or [:hashtag] on it, it returns nil. Example of what I mean: >> foo = job.to_hash.symbolize_keys => {:hashtag=>"apples", :number=>"10", :job_type=>"0"} >> bar = {hashtag: "apples", number: "10", job_type: "0"} => {:hashtag=>"apples", :number=>"10", :job_type=>"0"} >> foo == bar => false >> foo.class => Hash >> foo.class == bar.class => true Model: class Job < ApplicationRecord require 'csv' def self.import(file) file = CSV.read(file.path, headers:true) file.each { |job| Job.create(job.to_hash)} end end CSV: hashtag,number,job_type apples,10,0 bees,10,0 carrots,10,0 I really don't see what's going wrong... I'm literally copying and pasting the foo variable above into a new variable and it works, yet the original doesn't, despite, despite apparently being a hash as well. A: Apparently the :hashtag has two different encodings for me, seems like one is stored as US-ASCII, and one (the parsed) in UTF-8. Funny that I was able to reproduce this only by pasting this into my irb. To solve this, make sure they have the same encoding
{ "language": "en", "url": "https://stackoverflow.com/questions/50700567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compiling cross-referenced classes in Codelite I'm sure this topic has come up before, but I am not sure what even to google for: I am new to C++ and while learning I wrote first a Vector class, then a Matrix class (which uses the Vector class). While working on the Vector class the program compiled fine, but when adding the Matrix class (which includes and uses the Vector class) I'm starting to get compile errors. Specifically "undefined reference to functionname" - eventhough the function for sure exists and was working fine before when only the Vector class existed (it's a getter function for a component). Showing this code to someone who knows C++ but not Codelite they said my code is fine, but the compiling/build order seems weird and that it seems like the software tries to compile my classes like a main.cpp. Is that enough for anybody to give me any pointers to what to research/look up to get this working?
{ "language": "en", "url": "https://stackoverflow.com/questions/74408088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are rails development credentials gitignored by default? I'm generating credentials using the following command: rails credentials:edit --environment development I notice that rails puts this in the gitignore: +/config/credentials/development.key I dont understand why, based on the following reasons: * *The development credential file is encrypted by default, hence harmless to check in as long as the master key isnt checked in. *It's essential for a fresh environment setup (eg. on a new dev environment) *If the original file is lost, all the data in the dev environment will have to be reseeded. I'm inclined to check it in but figured, given Chesterton's fence and all, I'm likely missing something. A: I figured it out. I was confused between the development.key and the config/credentials/development.yml.enc. The latter is the encrypted credential file.
{ "language": "en", "url": "https://stackoverflow.com/questions/72634772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python/Bash - Tab completion not including files when arguments are provided I'm not sure whether this is a Python issue or a bash issue, but I'm having trouble with tab completion not working on files (only directories) when I'm providing arguments to my python script. Example of how I want it to work: python myscript.py -e data_dir/da[TAB] python myscript.py -e data_dir/data.tsv However, it works when I'm not providing an argument, or if I'm using an equals sign between the argument and the file path. Examples of scenarios where it works: python myscript.py data_dir/da[TAB] python myscript.py data_dir/data.tsv python myscript.py -e=data_dir/da[TAB] python myscript.py data_dir/data.tsv Is what I'm expecting unreasonable, considering the normal behavior of python and bash? I.e. is my tab completion working like it's supposed to? Alternatively, am I using python arguments incorrectly when I'm not including the equals sign with my arguments? I'm using bash version 4.3.11(1)-release and python version 2.7.6. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/34062349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue with stock Browser picking photos from Gallery I am working on a web page for uploading photos from a mobile device, using the <input type="file" accept="image/*"/> tag. This works beautifully on iphone and on chrome on the android, but where we are running into issues is with the stock android browser. The issue arises when you select a file from your gallery (it works fine when you use the camera to take a photo). And we have narrowed it down even further to seeing that the data MIME type isn't available when taken from the gallery on the stock browser (the photos below show the first 100 characters of the data URL being loaded. The goal was to force JPEG, but without the MIME type we cannot know for sure how to fix this. See code below for how the images are being rendered. How can an image be rendered without the type? Better yet, does anybody know why the type is not available on the stock android browser? EDIT Firstly, these are not the same image, they were taken near the same time, and that's not the issue, that's why the data is different (The MIME type doesn't appear on any images on the stock browser, so that's not the problem. Update I confirmed that the MIME type is the issue by inserting image/jpeg into the stock browser where it is on chrome. Unfortunately, we have no way of guaranteeing that it's going to be jpeg, so we again really can't do it that way _readInputFile: function (file, index) { var w = this, o = this.options; try { var fileReader = new FileReader(); fileReader.onerror = function (event) { alert(w._translate("There was a problem opening the selected file. For mobile devices, some files created by third-party applications (those that did not ship with the device) may not be standard and cannot be used.")) $('#loadingDots').remove(); return false; } fileReader.onload = function (event) { var data = event.target.result; //alert(data.substring(0,100)); //var mimeType = data.split(":")[1].split(";")[0]; alert("Load Image"); //I get to this point $('#' + w.disp.idPrefix + 'hiddenImages').append($('<img />', { src: data, id: "dummyImg" + index, load: function(){ var width = dummy.width(); var height = dummy.height(); $('#dummyImg' + index).remove(); alert("Render"); // I don't get here var resized = w._resizeAndRenderImage(data, null, null, biOSBugFixRequired, skewRatio, width, height); alert("Image Rendered"); // I don't get here } })); } fileReader.readAsDataURL(file); } catch (e) { } } Chrome Stock Browser A: Since the issue is probably browser-related, and you can't really fix the browser(you could report a bug to Google though), I'd suggest taking a different path. Have a look Here: In Node.js, given a URL, how do I check whether its a jpg/png/gif? See the comments of the accepted answer, which suggests a method to check the file type using the file stream. I'm pretty sure this would work on browser-implemented Javascript and not only in Node.js.
{ "language": "en", "url": "https://stackoverflow.com/questions/17702396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Passing params in Knockout component as a AMD Module My tagname component is like below and while the component is registered as a single AMD module, I want to get the all params. ko.components.register('tagname', { synchronous: true, require: params.url }); <tagname params="url: 'some/relative/url'"></tagname> How can I do that? A: The function that you provide for your view model (or as the createViewModel factory) will receive all of the params. For example: define(['knockout', 'text!./my-tagname.html'], function(ko, templateString) { function MyTagNameComponent(params) { // do something with params here } return { viewModel: MyTagNameComponent, template: templateString }; }); So, your component will receive its params as the first argument to MyTagNameComponent in this case. Here is a sample: http://jsfiddle.net/rniemeyer/g7zhjfz1/
{ "language": "en", "url": "https://stackoverflow.com/questions/32264853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can this element button be clicked using protractor? I'm trying to select this button using protractor: <button tabindex="-1" type="button" class="btn btn-default pull-left" ng-click="$arrowAction(-1, 0)"> <i class="glyphicon glyphicon-chevron-up"> </i> </button> the only unique element in this is ng-click="$arrowAction(-1, 0)" Nothing I have tried works: element(by.css("//button[@ng-click='$arrowAction(-1, 0)']")).click(); A: //button[@ng-click='$arrowAction(-1, 0)'] is not a valid CSS selector. It actually looks like this is an XPath expression and you meant to use by.xpath() locator. You can though use the partial attribute check instead: $("button[ng-click*=arrowAction]").click(); $ here is a shortcut to element(by.css(...)), *= means "contains". Or, do an exact match: $("button[ng-click='$arrowAction(-1, 0)']").click(); I still don't like the location technique used in this case, but, given what we have, it is probably the best we can do. Ideally, if you have control over the application code and templates, add a meaningful id, class or a custom data attribute to uniquely identify the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/38591172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML - Send email without open new windows in Outlook I send an email to a client that contains a button that must be pressed to send a user's cofee. Pressing the button opens a new Outlook window and then the user must click on SEND I would like the new window not to be opened but automatically the email must be sent without any confirmation. is it possible to do this? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/48972855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Success on emulator, Force stop on real device I deployed an application for Android which is successfully running on emulator. But, when I try to run on real device (My device is Acer A200, tablet), my application always forced stop. The requirement of the operating system is no problem. The error in logcat when I tried to run on real device is : 07-16 15:09:20.870: I/SqliteDatabaseCpp(780): sqlite returned: error code = 1, msg = no such table: kategori, db=/data/data/com.mroring.belajarperancis/databases/MY_DATABASE I think the application didn't install the database correctly. What should I do ? Thanks in advance :) A: table name "kategori" does not exist on your database, you should check the code if you created the table or not. if created, change the version number of the database, It will call the onUpgrade method and the database will create again.
{ "language": "en", "url": "https://stackoverflow.com/questions/24775644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filter a list of data using a select box in Blazor I have a table called SchoolsTable and there is a view that will show all the records that have been entered. Here is the my model: public partial class SchoolsTable { public int Id{ get; set; } public int Name{ get; set; } public int State{ get; set; } } What I want to do is have a dropdown in that view that will let me select a State and the data shown on the view will only be those that have the corresponding state. The razor component: <table style="width:50%; margin-left:710px; border:1px solid black" border="1" class="table-bordered"> <tr bgcolor="#ffffff" style="border:1px solid black"> <th style="border:1px solid black">Schools</th> @foreach (var item in school) { <th style="border:1px solid black">@item.Name</th> <th style="border:1px solid black">@item.State</th> } </tr> </table> @code{ private List<SchoolTable> schools=new List <SchoolTable>(); private SchoolTable school= new SchoolTable(); protected override async Task OnInitializedAsync() { GetSchoolTable(); } private List<SchoolTable> GetSchoolTable() { schools= SchoolService.GetSchoolTable(); return schools; } } the select gets all the states as duplicates: <label for="State">Choose a State:</label> <select name="State"> @foreach (var item in schools) { <option value="@item.State">@item.State</option> } </select> additionally, I have created a state table which has 2 records in them: public partial class StatesTable { public int Id{ get; set; } public int Description{ get; set; } } using this select, gets the states as singles and no duplicate states <label for="State">Choose a State:</label> <select name="State"> @foreach (var item in branch) { <option value="@item.Id">@item.Description</option> } </select> A: You need to do a couple of things. First you need to bind the selected value of your <select> element to a field. For that you need to use the @bind attribute: <label for="State">Choose a State:</label> <select id="State" @bind="selectedState"> <option value="">Choose a state</option> @foreach (var item in branch) { <option value="@item.Id">@item.Description</option> } </select> @code { private int? selectedState; } Also add an option with empty value in your select so that by default no state is selected: <option value="">Choose a state</option> Now you can create a property that returns the filtered schools based on the selected state: private List<SchoolTable> FilteredSchools => selectedState.HasValue ? schools.Where(s => s.State == selectedState.Value).ToList() : schools; Use this property to generate the <table> element content: <label for="State">Choose a State:</label> <select id="State" @bind="selectedState"> <option value="">Choose a state</option> @foreach (var item in branch) { <option value="@item.Id">@item.Description</option> } </select> <table style="width:50%; margin-left:710px; border:1px solid black" border="1" class="table-bordered"> <tr bgcolor="#ffffff" style="border:1px solid black"> <th style="border:1px solid black">Schools</th> @foreach (var item in FilteredSchools) { <th style="border:1px solid black">@item.Name</th> <th style="border:1px solid black">@item.State</th> } </tr> </table> @code{ private List<SchoolTable> schools = new List<SchoolTable>(); private int? selectedState; private List<SchoolTable> FilteredSchools => selectedState.HasValue ? schools.Where(s => s.State == selectedState.Value).ToList() : schools; protected override void OnInitialized() { schools = SchoolService.GetSchoolTable(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/73740524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FileNotFoundException when restarting the app I don't know why but I get an FileNotFoundException from my Init() function. What's happening is, when I launch the app for the first time, it's normal to get one (the file does not exist). Then I press a button which calls Save and so creates the file (if I add a Log just after outputStream.close(), I'm able to see it). I actually tried to open the created file with a FileInputStream and I didn't get the exception. But. When I close the app and open it again. I get the FileNotFoundException. Any idea why ? public class MyClass { public static Context mContext ; public static void Save(){ String test = "test" ; FileOutputStream outputStream; try { outputStream = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE); outputStream.write(test.getBytes()); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static void Init(Context c){ mContext = c ; FileInputStream inputStream; try { inputStream = c.openFileInput(FILENAME); String test = ""; char ch ; while((ch=(char) inputStream.read())!=-1) test+= ch ; inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } Edit : So, those calls are not in an activity but in a static class. Init is called from onCreate of my main activity. Save is called from onPause of another activity. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/24205177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS ng-cloak: empty page is displaying in IE9 when browser cache is cleared I just encountered a weird issue on angular's ng-cloak. When I cleared my IE9 browser's cache and close and open my browser again, when i accessed the page, it display empty page :( but when i tried to refresh the page it the page is now displaying.
{ "language": "en", "url": "https://stackoverflow.com/questions/22064030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery compare data/object differences on checked I'm trying to make a checkbox to hihglight the differences between data inside a div rather than table. So if row has differences "Single, Single, Married" this should be highlighted. http://jsfiddle.net/Ly61u493/1/ Logic: $('.check-diff').click(function() { if($(this).prop('checked')){ //highlight status except header alert("Bang highlight it..."); } else{ //unchecked should remove the highlight areas alert("Not highlighted"); } }); <label for="">Click to see differences</label> <input type="checkbox" class="check-diff"> <div class="compare-diff"> <div class="row header"> <div class="col-sm-3 title">Name</div> <div class="col-sm-3">John</div> <div class="col-sm-3">Henry</div> <div class="col-sm-3">Kim</div> </div> <div class="row"> <div class="col-sm-3 title">Status</div> <div class="col-sm-3 diff">Single</div> <div class="col-sm-3 diff">Married</div> <div class="col-sm-3 diff">Single</div> </div> <div class="row"> <div class="col-sm-3 title">Car</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> </div> </div> A: how about the following jquery code? $('.check-diff').click(function() { if($(this).prop('checked')){ checkDiff(); } else{ $(".row").each(function(){ $(this).css("background-color","#fff"); }); } }); function checkDiff(){ $(".row").each(function(){ var diff = false; var source = $(this).find(".diff").first().text(); $(this).find(".diff").each(function(){ var compare = $(this).text(); if(source != compare){ diff = true; } }); if(diff == true){ $(this).css("background-color","red"); } }); } hope i got you right and you get an idea, how to move on! :) A: You can use 2 each loops and a class name for the rows you want to check. Only row that has a class name checkDiff will be validated and cells that has a class name diff. JSnippet DEMO - validate difference in rows base on the cell text JS: $(function(){ $('.check-diff').click(function() { if($(this).prop('checked')){ $('.row.checkDiff').each(function(i,ele){ var values = $(ele).find('.diff'); var first = values.eq(0).text(); var diff = false; values.each(function(j,e){ if ($(e).text() !== first) diff = true; }); if (diff) $(ele).addClass('highlight'); }); } else{ $('.row.checkDiff').removeClass('highlight'); } }); }); HTML: <label for="">Click to see differences</label> <input type="checkbox" class="check-diff"> <div class="compare-diff"> <div class="row"> <div class="col-sm-3 title">Name</div> <div class="col-sm-3">John</div> <div class="col-sm-3">Henry</div> <div class="col-sm-3">Kim</div> </div> <div class="row checkDiff"> <div class="col-sm-3 title">Status</div> <div class="col-sm-3 diff">Single</div> <div class="col-sm-3 diff">Married</div> <div class="col-sm-3 diff">Single</div> </div> <div class="row checkDiff"> <div class="col-sm-3 title">Car</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> </div> <div class="row checkDiff"> <div class="col-sm-3 title">Kids</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">No</div> </div> <div class="row checkDiff"> <div class="col-sm-3 title">Home</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> <div class="col-sm-3 diff">Yes</div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/32583563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting unused props passed in components in React I currently refactoring some old code and I'm curious if there's any way to detect parameters which are passed into the component but never actually used inside it? Without looking at all the places where the component is called and checking manually. Eg. detecting that name and age are not used inside the Greet component so can be deleted. export default function Greet ({ greeting }) { return ( <h1>{greeting}</h1> ) } <Greet greeting="Hello Word" name="David" age="100"/> A: TypeScript will warn you if you try to pass unknown props. Eslint will warn you if you have unused variables, imports ... with rules like: * *no-unused-expressions *no-unused-vars *react/no-unused-prop-types *unused-imports
{ "language": "en", "url": "https://stackoverflow.com/questions/73052061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access Windows.Services.Store from Java application We have a Java application that we publish in the Windows Store. We would like to implement in-app purchases, for which we need to use the Windows.Services.Store API. How can we access the Windows.Services.Store API from Java?
{ "language": "en", "url": "https://stackoverflow.com/questions/73737061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML5 swipe.js css3 transitions; offscreen rendering and caching of page elements I am building a HTML5 magazine for tablets and desktops with use of swipe.js (http://swipejs.com). Everything seems to work fine, In one HTML page I have set next to each other fullscreen list elements. The whole magazine is build up in one static html file. I can slide through the pages by swiping on tablets, and by using buttons for the desktop version (consider the example on the swipe.js homepage, but then with fullscreen slides). The pages are placed next to each other, and have the dimensions of the screen. [ |0||1||2| .. |i-1||i||i+1| .. |n| ] The swipe.js transitions are done with help of css3, using the translate3d() css function. In this case, hardware rendering is used. On desktop (Chrome, Safari, FF), iPad1 and (even better on) iPad2 this has the desired effect I was looking for; smooth transitions. Perfect! However, on the iPad3, the pages seem to render 'slow' when entered (by transition) for the first time. Even without setting background images (just the color), the 'rendering' of the transitioned page is considered a little 'slow'; the page is build up by 'flickering' blocks. Assumption: My assumption is (after reading into the subject), that this is because the browser only renders the elements that are in-screen, and will cache the swiped pages only for a while, cleaning the cache afterwards to control memory management. My question: Is there a way to control the offscreen rendering and caching, so that I can force (pre) render page elements i-1, i+1 (and flush the cache for all other page elements), to speed up my transition rendering? Note: In several topics on StackOverflow, 'flickering' of css3 transitions is mentioned. I have implemented the suggested CSS tricks but will not solve my case. -webkit-backface-visibility: hidden; -webkit-transform:translate3d(0,0,0); A: In the end the solution was a hack of Swipejs in which I added a method 'hideOthers()', setting the style visibility to 'hidden', which unloads the pages from hardware memory: hideOthers: function(index) { var i = 0; var el; for( i in this.slides ) { el = this.slides[i]; if ( el.tagName == 'LI' ) { // Show pages i-1, i and i+1 if ( parseInt(i) == index || (parseInt(i) + 1) == index || (parseInt(i) - 1) == index ) { el.style.visibility = 'visible'; } else { el.style.visibility = 'hidden'; } } } } ..and added the trigger below as last line in the 'slide()' method // unload list elements from memory var self = this; setTimeout( function() { self.hideOthers(index); }, 100 ); Only the translate3d was needed to toggle the hardware acceleration on (as mentioned in my question above): -webkit-transform:translate3d(0,0,0); You can find the result (including iScroll for vertical scrolling) here. A: in regards to the webkit backface/translate3d props used to trigger hardware acceleration, I've read that in iOS 6+ these don't work quite the same as in previous versions, and (more importantly) that hardware acceleration needs to be applied not only on the element that is being animated, but also on any element that it is overlapping/overlaps it. reference (not much): http://indiegamr.com/ios6-html-hardware-acceleration-changes-and-how-to-fix-them/ To be fair this is fairly anecdotal, I was myself unable to fix my own flickering issue - due to tight deadlines - but this might be a point in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/12284820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: AngularJS Form data is not defined In AngularJS, I have a form, that when submitted, passes data off to a controller and sends it to an API. Form: <form ng-submit="newCompany()"> <div class="form-group" ng-controller="CompaniesController"> <label>ID</label><input type="text" name="id" id="id" ng-model="newCompany.id" tabindex="1" class="form-control"> <label>Name</label><input type="text" name="name" id="name" tabindex="2" ng-model="newCompany.name" class="form-control"> <label>Primary Contact</label><input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control"> <label>Address</label><input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control"> <label>Function</label><input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control"> <label>Telephone</label><input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control"> <label>Fax</label><input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control"> <label>URL</label></label><input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control"> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <input type="submit" name="add-submit" id="add-submit" tabindex="10" class="form-control btn btn-primary" value="Add Company"> <br> <div class="text-center"> <p ng-show="addCompany"><span class="label label-info">{{ addCompany }}</span></p> </div> </div> </div> </div> </form> And the controller... app.controller("CompaniesController", ['$scope', 'Companies', function($scope, Companies) { $scope.title = 'Companies'; $scope.title_sub = 'Add Company'; $scope.companyData = { id: $scope.newCompany.id, name: $scope.newCompany.name, primary_contact: $scope.newCompany.primary_contact, address: $scope.newCompany.address, function: $scope.newCompany.function, telephone: $scope.newCompany.phone, fax: $scope.newCompany.fax, url: $scope.newCompany.url }; $scope.newCompany = function() { var company = new Companies($scope.companyData); company.$save(); }; $scope.companies = Companies.query(); }]); However - I get an error that says "cannot read property 'id' of undefined" Does anybody know what is wrong here? I thought $scope.[NG-MODEL] gets the form data... A: * *You have a $scope.newCompany variable which is a function, not an object. *When you initialize $scope.companyData, you call id: $scope.newCompany.id, where $scope.newCompany is undefined. Try define it first with all its properties ($scope.newCompany = { id : "", ... }) *Call your submit function something else. *Do not create a function whose name itself a 'function'. (function: $scope.newCompany.function). This is reserved as a keyword. These steps may be close to the result you want to see, if not reply back.
{ "language": "en", "url": "https://stackoverflow.com/questions/33802005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to switch to another branch while recursively initing submodules I have a git repository with several submodules (see an example). Its structure looks like this: I--A--B <- main \ C <- branch-c * *Commit A adds a submodule-a *Commit B adds a submodule-b *Commit C adds a submodule-c on branch branch-c When I clone the above repo using git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned. When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint. When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error: fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c fatal: could not reset submodule index How do I check out (or switch to) branch branch-c while automatically initialising all submodules? A: Your example repository is lacking a branch-c, so it's not a complete MCVE, but it's a good start :) When I clone the above repo using git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned. Yes, this is the current behaviour of git clone --recurse-submodules. The submodules are cloned and initialized using an invocation of git submodule update --init --recursive during the checkout phase of git clone, and as such, only submodules recorded in the default branch (or the branch specified using git clone -b <branch>) are cloned and initialized. When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint. Yes, this is unfortunately still the default behaviour of Git. Submodules working trees are not checked out by default by git checkout <branch>. git submodule status (or just git submodule) will show uninitialized submodules with a - prefixed. When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error: fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c fatal: could not reset submodule index This is a good reflex but unfortunately it does not work in that specific case and leads to this bad UX. git checkout --recurse-submodules <branch> assumes that every submodule recorded in branch-c are already initialized. Since that's not the case here, it errors out because it can't find the .git directory of the submodule. The message could be clearer. What you have to do (the first time you switch to branch-c after cloning your repository) is to check out branch-c non-recursively, and then initialize the submodule: git checkout branch-c git submodule update --init --recursive Then, you will be able to correctly switch between your branches with --recurse-submodules: git checkout --recurse-submodules main git checkout --recurse-submodules branch-c # etc Note that you can set submodule.recurse in your config to avoid having to use --recurse-submodules all the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/72272371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Phone emulator in Visual Studio 2015 RC on Windows 10 preview build 10074 does not work I had some problem in running some Phone of the emulators in VS2015 RC so I tried to install also the "Pre-release Microsoft Emulator for Windows 10 Mobile" and then also the external SDK ... Now, even thought I uninstalled the external Windows 10 SDK and made a "repair" of VS2015 RC, no one of the phone emulators stars (it goes till the "OS is starting" phase and then remain in that state till, after many minutes, the emulator crashes and some time a popup says "The emulator is unable to get the sensor states from the device: Operation failed because connection is shut down", ... most of the times no error is reported). I also tried to delete in the Hyper-V manager both the created emulators virtual machines and the related Virtual Switches related to Windows Phone Emulator Internal: these are recreated at the next run of the emulator from VS, but nothing changed ... Any suggestion? How can I make at least some of the phone emulators work properly? Regards Enzo
{ "language": "en", "url": "https://stackoverflow.com/questions/30460642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check File Extension in android i made a small method to check whether defined folder has files with a specific extension or not. I m getting null point exception on run.pls help to find mistake.method is checking .mp4 files and returning true if found and message is displayed. Here is Code: import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView filecheck; filecheck = (TextView) findViewById(R.id.filecheck); filecheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (accept()) { Toast.makeText(MainActivity.this, "Files Found", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Files Not Found", Toast.LENGTH_SHORT).show(); } } }); } public boolean accept() { final File pathname = new File("/sdcard/test/"); String files[] = pathname.list(); System.out.println(files.length); for (String s : files) { if (s.contains(".mp4")) { System.out.println(s); return true; } return false; } return false; } } Here is exception: E/AndroidRuntime: FATAL EXCEPTION: main Process: jss.testmethods, PID: 23659 java.lang.NullPointerException at jss.testmethods.MainActivity.accept(MainActivity.java:38) at jss.testmethods.MainActivity$1.onClick(MainActivity.java:24) at android.view.View.performClick(View.java:4478) at android.view.View$PerformClick.run(View.java:18698) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) at dalvik.system.NativeStart.main(Native Method) A: i was expecting simple error, i missed to add permission for read storage. it is working now.
{ "language": "en", "url": "https://stackoverflow.com/questions/40492184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I define custom comparison (0 < mytype) in python? So I'm currently (ab)using python notation to create a domain specific language. As part of this I'm overriding comparison functions to return non-boolean values. So, for (mytype1 < mytype2) and (mytype < 0) I can easily do this by defining the __lt__() magic method. However, I cannot figure out how to do so for (0 < mytype) as presumably the magic method would need to be defined on the built-in int type. There doesn't seem to be a __rlt__() function as exists for numeric operations. How do I add support for this comparison where the lhs is of type int (in python3)? A: As per the documentation the reflected form of __lt__() is __gt__(). There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.
{ "language": "en", "url": "https://stackoverflow.com/questions/37514787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iOS SDK - using @2x, and icons.. where do they go? I have been developing my app for about a week and have loaded some images into it. I noticed that you can put an image into the app and it scales correctly. I have some larger images that have scaled down and look great. I guess this is discouraged because it takes some processing power or memory correct? Okay, so I want to scale my images to their actual size. Let's say I have a button that is 40x50 Should that be the @2x size, or should I double that, and set that to the @2x size? Second question is: I read apple guidelines about submissions to the app store, and it looks like you need to submit a plethora of icons. I know you can apply a retina icon, and a regular icon when setting up your project. What about the rest. do you just use their naming guidelines and dump them into your project somewhere? A: should that be the @2x size, or should I double that, and set that to the @2x size? Listen to your intuition. It's not called image@0.5x but image@2x... do you just use their naming guidelines and dump them into your project somewhere? After your graphics designer has sent you the necessary files, yes. But not just "somewhere". Rather into the root of your app bundle.
{ "language": "en", "url": "https://stackoverflow.com/questions/17627510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift iOS 13 : Click on push notification how to open textfield? User want to interact on click of push notification and send comment/reply/message. I have following code in AppDelegate: func configureNotification() { let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in } center.delegate = notificationDelegate let replyAction = UNTextInputNotificationAction(identifier: replyID, title: "Add reply", options: [], textInputButtonTitle: "Send", textInputPlaceholder: "Reply here") let deafultCategory = UNNotificationCategory(identifier: "CustomSamplePush", actions: [replyAction], intentIdentifiers: [], options: []) center.setNotificationCategories(Set([deafultCategory])) UIApplication.shared.registerForRemoteNotifications() } And Handle action like following: func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let identifier = response.actionIdentifier let request = response.notification.request if identifier == replyID{ let textResponse = response as! UNTextInputNotificationResponse let newContent = request.content.mutableCopy() as! UNMutableNotificationContent newContent.body = textResponse.userText addNotification(content: newContent, trigger: request.trigger, indentifier: request.identifier) } completionHandler() } func addNotification(content:UNNotificationContent,trigger:UNNotificationTrigger?, indentifier:String){ let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: { (errorObject) in if let error = errorObject{ print("Error \(error.localizedDescription) in notification \(indentifier)") } }) } FYI : This code perfectly run for iOS 11 device but not working in iOS 13
{ "language": "en", "url": "https://stackoverflow.com/questions/60829980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: unable to read lines of log file I have an AWS S3 bucket with a bunch of log files in them. I have a lambda function using node.js 8.10 runtime that reads each line of the log file. This is what I have: const readline = require('readline'); exports.handler = async (event) => { try { let bucket = event.Records[0].s3.bucket.name; let key = event.Records[0].s3.object.key; // documentation for this method: // https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property let readStream = S3.getObject({ Bucket: bucket, Key: key }).createReadStream(); // 1 const rl = readline.createInterface({ input: readStream }); rl.on('line', async (line) => { console.log(line); // process line as needed }); } catch (err) { console.log(err); return err; } }; In the snippet above I'm printing the line in the log file to the console just for testing, but I don't see any output. But if I refactor the code like this it works: const stream = require('stream'); const bufferStream = new stream.PassThrough(); const readline = require('readline'); exports.handler = async (event) => { try { // retrieving first record only just for // testing let bucket = event.Records[0].s3.bucket.name; let key = event.Records[0].s3.object.key; // data.Body is a Buffer let data = await S3.getObject({ Bucket: bucket, Key: key }).promise(); bufferStream.end(data.Body); // 2 const rl = readline.createInterface({ input: bufferStream }); rl.on('line', (line) => { console.log(line); // process line as needed }); } catch (err) { console.log(err); return err; } }; For the line marked 2, the getObject function returns a buffer and is converted to a stream. Is it possible to do this without using a buffer? My thinking is if the log file is very large it is inefficient to convert a buffer to a stream. I'm wondering if I can use a stream directly like the line marked 1. EDIT: I did some more testing and got it to work but without an async lambda function. Here it is: exports.handler = function (event, context, callback) { // for testing I'm looking at the first record let bucket = event.Records[0].s3.bucket.name; let key = event.Records[0].s3.object.key; const readStream = S3.getObject({ Bucket: bucket, Key: key }).createReadStream(); const rl = readline.createInterface({ input: readStream, crlfDelay: Infinity }); rl.on('line', (line) => { console.log(line); }); } Does anyone know why this refactored code works, but not with async lambda ?
{ "language": "en", "url": "https://stackoverflow.com/questions/55107692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AngularJS: Ng:init - how to assign ng:model? I have ng:repeat, created by json (methods), inside it creates a series of radio buttons that are characterized by iteration (method). Below, I need to create a variable that will be based on method selected radio button, for use in the future. I will prepare the template for clarity. <li ng:repeat="method in methods"> <label> <input type="radio" ng:model="$parent.deliveryMethod" ng:value="method" /> </label> </li> <table ng:init="myValue = deliveryMethod.price | format"> <tr> <td ng:bind="myValue"></td> </tr> </table> I hope the point is clear. The problem is, as I understand it, ng:init is triggered earlier than time to form methods. What I must to do? Thanks! A: You're syntax looks incorrect , You should be declaring ng- as listed below : ng-repeat ng-model ng-init ng-bind ect... docs here: https://docs.angularjs.org/api/ng/directive/ngRepeat upadte - to apply method to radio button try ng-change : ng-change="dosomething()"
{ "language": "en", "url": "https://stackoverflow.com/questions/36187635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What errors can WebSocket emit? Is there a list of all possible error events a js websocket client can emit? Are the errors spec'ed or are they implementation dependent? webSocket.on('error', (event) => ...) // What can event be? A: here is a list of Websocket errors codes that you might receive. websocket-close-codes Most likely you'll receive 1006 in case of an exception A: Browser-side error events are actually related to "close codes" used by the WebSocket protocol, as detailed in section 11.7 to the RFC. You can find the registered WebSocket closure codes here. In addition to server-side specified errors, some parsing errors and protocol errors are also emitted by the client (such as UTF-8 requirements)... which are often mapped to a closure code (UTF-8 is mapped to code 1003). AFAIK, these closure error codes are actually sent to the onclose callback, as part of the close event. (i.e., close_event.code). However, according to MDN when the closure isn't normal (code 1000), the onerror callback is also called. Personally I've never tested or coded anything with these error-codes, since they are unreliable and optional: When closing an established connection (e.g., when sending a Close frame, after the opening handshake has completed), an endpoint MAY indicate a reason for closure. Exposing these "error codes" is optional for a reason. Sending error codes from a server to a client / application could (potentially) expose security vulnerabilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/56075080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ORA-00060: Deadlock Trace file query found but can we get its parameter values As this ORA-00060 is quite famous and I too have analyzed it in past and have solved a few of them in past. In my case I have ensured there is no common update from multiple session, still the error was occurring, and for such solutions I have used to increase the initrans and frequent commit in the concurrent transactions have helped me to solve it. Now in another program again I saw the ORA-00060. Then I analyze the .trc file. There it is showing the merge query running from two session which is causing deadlock. This query has bind parameters. I wanted to know the values of this bind parameter. Because if by any bug if this binding parameter is same from the two session then it will be obvious that the two sessions are updating the same records, and eventually causing the deadlock. Where I am struggling is that I am not able to see any way to get the value of these bind parameter in the .trc file. The call stack trace in the .trc file does have some blocks but very difficult to figure out where and what is the value of this parameter when the deadlock graph was created. Does anyone know whether it is possible to get the bind parameter values from .trc file for the queries causing the deadlock? I have started putting the log in the code so that next time when it occurs I will get that from normal logs. Deadlock graph: ------------Blocker(s)----------- ------------Waiter(s)------------ Resource Name process session holds waits serial process session holds waits serial TX-0012000B-0004A991-00000000-00000000 193 203 X 7643 195 583 S 11914 TX-000F000E-000871FC-00000000-00000000 195 583 X 11914 193 203 S 7643 The query (table/column names I have changed) is: ----- Information for waiting sessions ----- Session 203: sid: 203 ser: 7643 audsid: 38682755 user: 151/SCHMEA1 ... pid: 193 O/S info: user: grid, term: UNKNOWN, ospid: 11010512 image: oracle@hostname client details: ... application name: JDBC Thin Client, hash value=2546894660 current SQL: MERGE INTO TABLE_A TA USING ZPD_TABL2 ZPD ON (TA.COY=ZPD.COY AND TA.COL2=ZPD.COL2 AND TA.TRXNO=ZPD.TRXNO AND (TA.COL3 = ' ' OR TA.COL3 IS NULL OR TA.COL3 = 'I') AND ZPD.THREADNO=:B1 ) WHEN MATCHED THEN UPDATE SET TA.COL3 = 'Y', TA.USRPRF=:B3 , TA.JOBNM=:B2 , TA.DATIME=LOCALTIMESTAMP Session 583: sid: 583 ser: 11914 audsid: 38682758 user: 151/VM1DTA ... pid: 195 O/S info: user: grid, term: UNKNOWN, ospid: 58064926 image: oracle@hostname client details: .. application name: JDBC Thin Client, hash value=2546894660 current SQL: MERGE INTO TABLE_A TA USING ZPD_TABL2 ZPD ON (TA.COY=ZPD.COY AND TA.COL2=ZPD.COL2 AND TA.TRXNO=ZPD.TRXNO AND (TA.COL3 = ' ' OR TA.COL3 IS NULL OR TA.COL3 = 'I') AND ZPD.THREADNO=:B1 ) WHEN MATCHED THEN UPDATE SET TA.COL3 = 'Y', TA.USRPRF=:B3 , TA.JOBNM=:B2 , TA.DATIME=LOCALTIMESTAMP ----- End of information for waiting sessions ----- So if I get the value of THREADNO =:B1 (this bind parameter) value from .trc file then I can confirm whether these two merge from two sessions are updating the same records or not. A: One possible suspect constalation in your use case would be if the threadno is not uniquely mapped to the join keys used in the MERGE. You may quickly check it with the query below - it should not return any row. If yes, you have a postential problem described later. select COY, COL2, TRXNO, min(THREADNO), max(THREADNO) from zpd_tabl2 zpd group by COY, COL2, TRXNO having count(distinct THREADNO) > 1; Bind Variables Used in Dealock Statements Well, the deadlock trace file contains some information Peeked Binds ============ Bind variable information position=1 datatype(code)=2 datatype(string)=NUMBER precision=0 scale=0 max length=22 value=1 But this will not help you as it is the peeked value used while the statement was parsed. Rows waited on More usefull information is the rowid of the rows caused the problem Rows waited on: Session 138: obj - rowid = 00012563 - AAASVjAARAAAACbAAB (dictionary objn - 75107, file - 17, block - 155, slot - 1) Session 12: obj - rowid = 00012563 - AAASVjAARAAAACbAAA (dictionary objn - 75107, file - 17, block - 155, slot - 0) The object_id (here 75107) should point to your TABLE_A and you can check the threadnos that try to modify the problematic rows with the following query. select a.rowid, a.COY, a.COL2, a.TRXNO , zpd.threadno from table_a a join zpd_tabl2 zpd ON ( a.coy = zpd.coy AND a.col2 = zpd.col2 AND a.trxno = zpd.trxno) where a.rowid in ( 'AAASVjAARAAAACbAAB','AAASVjAARAAAACbAAA'); If you see at least four rows, that you suffer the threadnoproblem stated in the beginning. Reproducible Example Note, I can't claim that this is exact your situation, but this is the simplest way how to get a deadlock you observed. create table table_a as select rownum coy, rownum col2, rownum trxno, ' ' col3, localtimestamp datime from dual connect by level <= 2; create table zpd_tabl2 as select rownum coy, rownum col2, rownum trxno, 1 threadno from dual union all select rownum coy, rownum col2, rownum trxno, 2 threadno from dual union all select 1+rownum coy, 1+rownum col2, 1+rownum trxno, 3 threadno from dual union all select 1+rownum coy, 1+rownum col2, 1+rownum trxno, 4 threadno from dual ; * *in Session 1 run the MERGE with pareter 1 . MERGE INTO table_a ta USING zpd_tabl2 zpd ON ( ta.coy = zpd.coy AND ta.col2 = zpd.col2 AND ta.trxno = zpd.trxno AND ( ta.col3 = ' ' OR ta.col3 IS NULL OR ta.col3 = 'I' ) AND zpd.threadno = :b1 ) WHEN MATCHED THEN UPDATE SET ta.col3 = 'Y', ta.datime = localtimestamp; 1 row merged * *in Session 2 run the MERGE with pareter 4 1 row merged * *in Session 1 run the MERGE with pareter 3 waiting * *in Session 2 run the MERGE with pareter 1 waiting * *in Session 1 ORA-00060: deadlock detected while waiting for resource
{ "language": "en", "url": "https://stackoverflow.com/questions/70678272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to rotate AVPlayerViewController when fullscreen The app I am working on has UIInterfaceOrientationPortrait set as UISupportedInterfaceOrientations. I create an AV player like so: let playerVC = AVPlayerViewController() // Some AVPlayer input playerVC.player = player presentableViewController?.present(playerVC, animated: true, completion: nil) The AVPlayerViewController works however when I enter fullscreen and try to rotate it remains fixed to portrait. I need the ability to rotate to landscape. I tried subclassing AVPlayerViewController like so: class AVPlayerViewControllerRotatable: AVPlayerViewController { override var supportedInterfaceOrientations: UIInterfaceOrientationMask { .all } } However this had no effect. What am I doing wrong here?
{ "language": "en", "url": "https://stackoverflow.com/questions/68543846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Rectangle of Image JPG and generate thumbnail in rectangle I try explain: I have a JPG image (img A). This A.jpg has contents -colors, it's a picture of persons- and a one more little white rectangle (color white; the head of person is a white rectangle). I need get the position of rectangle in A.jpg. Then, I have another B.jpg image, more little; and I'll generate thumbnail of B.jpg , with Rectangle dimensions (of white rectangle in A.jpg). Finally, I'll generate new image: C.jpg, will has A.jpg, and B.jpg in rectangle of A.jpg. any suggestions, any sample code ? I use vs 2008, .net 3.5, GDI+ only. A: For the A problem, you could count the number of white pixels in each column and each row. The columns/rows with the highest number of white pixels are where the borders of your rectangle are. (Assuming that the rectangle sides are parallel to the sides of the image) For B and C the hint is to start with Bitmap aImage; // Initialize with your images using (Graphics g = Graphics.FromImage(aImage)) { // Do stuff } And then you can find and overload of Graphics.DrawImage to scale and draw your images atop of each other. To count the number of pixels you can use the GetPixel method. // Sketchy code // Calculate each column in sum[x] [x,y] = b.Size; for(x ...) for(y ..) if (aImage.GetPixel(x, y) == Color.White) sum[x]++; A: Here is a snippet on draing an image over another image. (No credit i took it from here) Bitmap bmp = Bitmap.FromFile(initialFileName); // This draws another image as an overlay on top of bmp in memory. // There are additional forms of DrawImage; there are ways to fully specify the // source and destination rectangles. Here, we just draw the overlay at position (0,0). using (Graphics g = Graphics.FromImage(bmp)) { g.DrawImage(Bitmap.FromFile(overlayFileName), 0, 0); } bmp.Save(saveAsFileName, System.Drawing.Imaging.ImageFormat.Png); Now on how to locate a large white rectangle inside an image? This bit is a little trickier. There is a library which can do this for you
{ "language": "en", "url": "https://stackoverflow.com/questions/3525728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perform optimization with F# and Accord.net I'm using F# with Accord.NET, and I'm trying to perform an optimization using the Nelder-Mead algorithm. After a week of attempts, trying to follow the examples from website, I still can't perform the operation. I didn't find the way to write the expression for optimize the function. I wrote a custom function which accept 9 parameters: let FunSqEuclid (F:float) (X:float[]) (T:float) (iv:float[]) (atmVol:float) (alpha:float) (beta:float) (volVol:float) (rho:float) = let dum01 = VecAlphaSABR (F:float) (X:float[]) (T:float) (atmVol:float) (alpha:float) (beta:float) (volVol:float) (rho:float) let dum02 = Array.map2 (+) dum01 iv let dum03 = dum02.SquareEuclidean() dum03 What I need is to optimize this function varying only the "volVol" and "rho" parameters, but keeping constant all the others. Following examples (in C#), I tried with: let ObFunc = NonlinearObjectiveFunction(function: () => (FunSqEuclid (F:float) (X:float[]) (T:float) (iv:float[]) (atmVol:float) (alpha:float) (beta:float) (volVol:float) (rho:float))) using costraints to keep parameters constant, but I have error on keyword "function", both for NonlinearObjectiveFunction and NonlinearCostraint. I read on documentation that objective function can be written as a Linq Expression, but I never used it. There is an alternative way to insert objective function and costraints? Or, please, can you suggest where are similar examples in Linq Expression for F#? EDIT I found more informations from the examples of "Extreme Optimization" library. I have seen it has a similar approach to "Accord.net" about the optimization, and there are examples in F#, so, with appropriate adaptations, I understand how it works when parameters are simple values. The point is that I'm trying to translate some R code to F#. The R code performing the optimization is the following: objective <- function(x){sum( (iv - SABR.BSIV(t, f, K, exp(x[1]), .t1(x[2]), .t2(x[3]), exp(x[4])))^2) } x <- nlm(objective, c(0.2, 1.0, 0.0, 0.1)) where K and iv are arrays. So, I still didn't find a way to pass array arguments for the objective function in Accord.net. Please, can you suggest me some way? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/38248229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Socket.IO Client How to Connect? I was following the second example here: https://github.com/socketio/socket.io-client and trying to connect to a website that uses websockets, using socket.io-client.js in node. My code is as follows: var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket'); socket.on('connect', function() { console.log("Successfully connected!"); }); Unfortunately, nothing gets logged. I also tried: var socket = require('socket.io-client')('http://website.com/'); socket.on('connect', function() { console.log("Successfully connected!"); }); but nothing. Please tell me what I'm doing wrong. Thank you! A: Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client. Socket.io Client const io = require('socket.io-client'); const socket = io.connect('http://website.com'); socket.on('connect', () => { console.log('Successfully connected!'); }); Socket.io Server w/ Express const express = require('express'); const app = express(); const server = require('http').Server(app); const io = require('socket.io')(server); const port = process.env.PORT || 1337; server.listen(port, () => { console.log(`Listening on ${port}`); }); io.on('connection', (socket) => { // add handlers for socket events }); Edit Added Socket.io server code example.
{ "language": "en", "url": "https://stackoverflow.com/questions/41319028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Loading a new window from local files and accessing it's contents I am setting up a local webpage which shows videos in a HTML5 video tag. I just want to be able to do database search from a PHP request and show the results from which I can click on and show the video I want. The problem I have is that hte videos load WAY faster when loading from a "file:///" link than from the "http://" link. Server works flawlessly when in "HTTP" mode but nothing works in "file:///" mode which is normal as PHP codes only execute on the server side when requested to the server. I have spent my full day trying soo much stuff. I changed my server to accept CORS, I tried window.open, storing the reference in a variable, local or global but I lose this as soon as I get out of my javascript function. I tried window.open in a function which is called from another function but no matter what I do, the window reference gets lost as soon as I leave the functions, or once the functions have finished. Since my browser is used as my main browser, I do not want to disable the security arround CORS but since my webpage's link comes from "file:///" requesting to "HTTP" on the same computer, CORS blocks me and wants an HTTP request which I can't give. I have done all the searching for retrieving information from another webpage but I am always stuck with the "same domain" problem. I tried AJAX HTTPRequest, I just have no more solution for this simple problem which finished way more complicated than expected. The initial problem was just my videos not loading fast enough in HTTP mode (The speed difference is extreme, for 10 min videos, I can wait 5-10 seconds to skip through it while as in FILE:/// urls, It's almost instant, no waiting. longer videos of 1h, I can wait up to 20 and 30 seconds while as in file:/// mode, almost instant.) and I had to learn all that Allow cross domains stuff which ended up with no success either. I figure that maybe a few other heads may have better ideas than mine now. #In my httpd.conf file from Apache DocumentRoot "e:/mainwebfolder" Alias "/lp" "d:/whatever" ////////////////////////////////////// // index.php file that does not contain PHP contents // window.location.href: file://d:/whatever/index.php ////////////////////////////////////// <head> <script src="html/servcom.js" type="text/javascript"></script> </head> <video id="vplayer" width="1280" height="720" controls></video> <div id="search-form"> <input id="srch" name="srch" type="text"> &nbsp;<button class="bbut" onclick="ServInfo('search-results','http://127.0.0.1/lp/html/db.php','mode=s','search-form');">Search</button> </div> <div id='search-results'></div> <script> var dplay = document.getElementById("vplayer"); ShowVideo('MyVideo.mp4'); function ShowVideo (vidUrl) { dplay = document.getElementById("vplayer"); dplay.src = vidUrl; dplay.load; } </script> ////////////////////////////////////// // Now this is in my javascript file servcom.js ////////////////////////////////////// var win_ref = -1; function ServInfo(pop_field_id,web_page,params="",form_id="",exec_string = "") { var sparams = params; var swpage = web_page; var eobj = document.getElementById(pop_field_id); var moreparams = ""; // If we entered extra parameters including form fields, // add the the "&" before the form field list if (sparams != "") {moreparams = "&";} // Get form field values if a form id is specified if (form_id != "") { var efrm = document.getElementById(form_id); sparams += moreparams+GetDivFields(form_id); } // Add the question mark if there is any parameters to pass if (sparams != "") { sparams = "?"+sparams; // Add recieving objects reference sparams += "&srco="+pop_field_id; } // If HTML element to populate does not exist, exit if (typeof(eobj) == "!undefined" || eobj == null) {return;} win_ref = window.open(swpage+sparams,"_blank"); ////////////////////////////////////// // right here win_ref will never be available once the code from this function has been finished executing although the variable is global. The problem starts here. ////////////////////////////////////// // Execute a string if a user defined one if (exec_string != "") {eval(exec_string);} } // Build a parameter string with div fields of type text, hidden or password function GetDivFields(div_id) { var ediv = document.getElementById(div_id); var elem = ediv.children; var retval = ""; var ssep = ""; for (var i = 0; i < elem.length; i++) { if (elem[i].type == "text" || elem[i].type == "hidden" || elem[i].type == "password") { retval += ssep+elem[i].name+"="+pURL(elem[i].value); ssep = "&"; } if (elem[i].type == "checkbox") { if (elem[i].checked == true) { retval += ssep+elem[i].name+"="+elem[i].value; ssep = "&"; } } } return retval; } ////////////////////////////////////// // And this is a brief overview of my db.php page ////////////////////////////////////// <?php // Search Database code ?> <div id="output"></div> <script> document.getElementById('output').innerHTML = "<?php echo $search_results; ?>"; // I actually want to retrieve the info from this div element once it has been populated from the initial page that called window.open for this page. BUT again. window.opener becomes empty once my initial window.open script finishes. </script> Access my newly loaded page's "output" div innerHTML OR loading videos through local HTTP as fast as "FILE:///". A: Well, I fanally found a solution. Since this is for local and presentation use only, I could bypass some securities. Basically, doing what we would normally NOT do in a website but all this WITHOUT modifying your webserver config or touching any .htaccess file. Basically, no security restrictions, just a plain old hack that poses no security breaches for your browser or your server. To be noted: * *2 different websites exist (so 2 different folders at very different locations), 1 for developpement and serious releases, one for internal and/or presentation purposes. *Every file is local abd inside the presentation folder. *No PHP code can be ran from a "file:///" link. *Access to the mysql database is done through PHP and server is on Apach24 *Reading video locally from a "file:///" link are WAY faster than from an "http://" link *Searching needs to be done in MySQL database frm a "http://" link and results need to be displayed on a webpage opened from a "file:///" link. *No changes must be made in the Browser's configuration so disabling CORS is not a solution. *Bypassing cors with methods proposed by many site won't work because of security reasons or because CORS bypass does not accept "file:///" links PHP can write files on the server which is where I decided to bypass CORS. Since XML requests through AJAX can be done on the same origin domain an thus, purely in javascript. If a file exists which contains no PHP code AND resides on the same domaine i/e "file:///", the contents can the be read wothout any problems. So I simply do the following in my db.php file: $s_mode = ""; $s_text = ""; $sres = ""; if (isset($_REQUEST["srch"])) {$s_text=$_REQUEST["srch"];} if (isset($_REQUEST["mode"])) {$s_mode=$_REQUEST["mode"];} if ($s_mode == "s") { $sres = SearchDB($s_text); WriteFile("D:/whatever/my_path/dbres.html",$sres); } // Writes the contents of the search in a specified file function WriteFile($faddress,$fcontents) { $ifile = fopen($faddress,"w"); fwrite($ifile,$fcontents); fclose($ifile); } Now using a normal AJAX request, I do 2 things. I opted to use an iframe with a "display:none" style to not bother seeing another tab openup. * *Do the actual request which opens the "cross-doamin" link in the iframe WHICH executes my db.php code. I basically open "http://127.0.0.1/whatever/db.php?param1=data&parma2=data" inside my iframe. *Once my search is done and I have the results, my db.php will save an html file with the results as it's contents in my "file:///" direct location's path so: "D:/whatever/my_path/dbres.html". I added a new function in my servcom.js. So my new file's contents looks like this: // Show page info in another page element or window with parameters (for local use only) function ServInfoLocal(dest_frame,web_page,params="",form_id="") { var sparams = params; var swpage = web_page; var iweb = document.getElementById(dest_frame); var moreparams = ""; // If we entered extra parameters including form fields, // add the the "&" before the form field list if (sparams != "") {moreparams = "&";} // Get form field values if a form id is specified if (form_id != "") { var efrm = document.getElementById(form_id); sparams += moreparams+GetDivFields(form_id); } // If destination frame does not exist, exit if (typeof(iweb) == "!undefined" || iweb == null) {return;} // Add the question mark if there is any parameters to pass if (sparams != "") {sparams = "?"+sparams;} // Show results in iframe iweb.src = swpage+sparams; } // AJAX simple HTTP GET request function ServInfo(pop_field_id,web_page,params="",form_id="",append_data_to_output = "",exec_string = "",dont_show_results = "") { var sparams = params; var swpage = web_page; var eobj = document.getElementById(pop_field_id); var moreparams = ""; // If we entered extra parameters including form fields, // add the the "&" before the form field list if (sparams != "") {moreparams = "&";} // Get form field values if a form id is specified if (form_id != "") { var efrm = document.getElementById(form_id); sparams += moreparams+GetDivFields(form_id); } // If HTML element to populate does not exist, exit if (typeof(eobj) == "!undefined" || eobj == null) {return;} if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // IE6- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Do not show any results if requested if (dont_show_results == "") { if (append_data_to_output == "y") { document.getElementById(pop_field_id).innerHTML += this.responseText; } if (append_data_to_output == "") { document.getElementById(pop_field_id).innerHTML = this.responseText; } } // Execute a string if a user defined one if (exec_string != "") { eval(exec_string); } } }; // Add the question mark if there is any parameters to pass if (sparams != "") {swpage += "?";} xmlhttp.open("GET",swpage+sparams,true); xmlhttp.send(); } // Build a parameter string with div fields of type text, hidden or password function GetDivFields(div_id) { var ediv = document.getElementById(div_id); var elem = ediv.children; var retval = ""; var ssep = ""; for (var i = 0; i < elem.length; i++) { if (elem[i].type == "text" || elem[i].type == "hidden" || elem[i].type == "password") { retval += ssep+elem[i].name+"="+pURL(elem[i].value); ssep = "&"; } if (elem[i].type == "checkbox") { if (elem[i].checked == true) { retval += ssep+elem[i].name+"="+elem[i].value; ssep = "&"; } } } return retval; } Now, my dbres.html file will contain just the div elements and all the information I need to show up in my "file:///" page from which the search request came from. So I simply have this inside my page: <div id="search-form" style="color:white;font-weight:bold;"> <input id="srch" name="srch" type="text"> &nbsp;<button class="bbut" onclick="ServInfoLocal('iweb','http://127.0.0.1/whatever/html/db.php','mode=s','search-form');">Search</button> <button class="bbut" onclick="ServInfo('search-results','dbres.html');">Click here</button> </div> <div id="search-results">Results here</div> <iframe id="iweb" style="display:none;" src=""></iframe> For now I have 2 buttons, one for the search and one to show the results from my newly created file. Now, I can show my local videos which will load in my video container with "file:///" source directly without passing through http. I'll make my results display automatic which I will be able to do myself from here on. So, if someone on planet earth wants to be able to do cross-domain searches in a MySQL database from a local file ran directly from the Windows explorer, there's not too many solutions, actually, I found none so here is at least one for who would ever need this solution. For the curious ones out there, my next step will be to loop my folder until my dbres file is present using another js function. Once my file has been fetched, call another php file which wil destroy the created file and I'll be ready for another database request from my webpage situated in a "file:///" location.
{ "language": "en", "url": "https://stackoverflow.com/questions/55351033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In GreenDao, build a join query with OR instead of AND I generated an SQLite DB with GreenDao v2.1.0. Here is its diagram (a tiny piece of it) A CONTACT can have many phone numbers. I want to make a search query : list all contacts whose GIVEN_NAME or FAMILY_NAME or PHONE.NUMBER contains a specific word. For example, with these entries, if I use the word "bob" the contact Sponge Bob will be returned. If I use the word "222", the contact Patrick Star will be returned. Since, two tables are involved in the query, I resorted to the JOIN solution with this piece of code : QueryBuilder<Contact> qb = getContactDao(context).queryBuilder(); qb.whereOr(ContactDao.Properties.Given_name.like("%" + word + "%"), ContactDao.Properties.Family_name.like("%" + word + "%")); qb.join(Phone.class, PhoneDao.Properties.Contact_id) .where(PhoneDao.Properties.Number.like("%" + word + "%")); List<Contact> contacts = qb.list(); This generates the following SQL : SELECT T."_id", T."GIVEN_NAME", T."FAMILY_NAME" FROM "CONTACT" T JOIN PHONE J1 ON T."_id"=J1."CONTACT_ID" WHERE (T."GIVEN_NAME" LIKE ? OR T."FAMILY_NAME" LIKE ?) AND J1."NUMBER" LIKE ? COLLATE LOCALIZED ASC The 5th line points out the problem : the "AND" connector. I am desperately trying to replace it with an "OR". Am I missing something ? Shall I leave the JOIN solution ? Thanks :) A: I have the same problem. It seems that greendao is currently not able to do that. I am resorting to using queryRaw() instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/35043891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Evenly Distribute Players between 2 teams in Excel I have a group of players, 915 in total, each with different engagement scores that I am trying to break out into two evenly distributed groups based on their engagement scores. I tried using Solver in excel to set contstraints, indices etc, but unfortunately Solver can only handle 200 variables, and I have 915. Another approach I researched is to give the first group with the best player also the worst player, give the second group the second best player and the second worst player, and so on. Problem is I am not an excel wiz and need some help writing out this formula in excel so both columns A and B show "1's" for the agents that should be selected for both groups in the group A and group B columns in the below screenshot (the screenshot is a small sample of the entire data set, FYI), Screenshot Here A: As you mentioned combination of best and worst player. Your data is already sorted on descending index. Say, the data is in A,B and C Columns. Just put A in D2 and B in D3. Select D2 and D3 and once you get + cursor on the bottom right of the selection, double click. Filter A for group A and B for group B.
{ "language": "en", "url": "https://stackoverflow.com/questions/62000127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create a nested list from a list of ages? I am downloading tables of data in csv format from an online model. The data includes a column for age. My program works fine when all the data in the column has the one age, but now I am downloading data for a large range of ages so that I might have 400 rows of data at age 1 Billion Years, and then 350 at 1.1 Billion Years, etc. There are around 30,000 rows and 40 columns in my csv file. I thought I would create nested lists controlled by the age, and then loop through each sub-list. I pick my data up as follows log_age = data_upload[:,2] mass = data_upload[:,5] log_L = data_upload[:,6] log_Teff = data_upload[:,7] log_g = data_upload[:,8] mbolmag = data_upload[:,24] Umag = data_upload[:,25] Bmag = data_upload[:,26] How would I go about creating nested lists from these individual lists? To generalise the problem if I have a list as follows: age = [1,1,1,1,1,1,1,1,1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.2,1.2,1.2...] how do I get it into the following format: [[1,1,1,1,1,1,1,1,1],[1.1,1.1,1.1,1.1,1.1,1.1,1.1],[1.2,1.2,1.2...]] I would need to do this for all the lists using the structure of the age list. I am thinking a list comprehension might be the way to go? I have come across them but don't really know how to use them. There is a command called np.unique which will list the unique numbers in my original list so I can start by: unique_age = np.unique(age) nested_age = [[] for _ in range(len(unique_age))] I could then repeat this for all the nested lists that I want to create, but then I have to go through each list and convert them to a nested list. Could someone show me how to this? Thanks A: I'd like to generate the result like this: from collections import Counter age = [1,1,1,1,1,1,1,1,1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.2,1.2,1.2] c = Counter(age) result = [[k]*v for k,v in c.items()] print(result) # Result would be: # [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1], [1.2, 1.2, 1.2]] Line 3 means: * *Group the list according to the content of list, *the item of Counter result looks like a dict, the key is age, while the value is frequency of each age. Line 4 means: * *Iterate the item of Counter result, get the keys(k) and values(v) *Create list of same value by [k]*v
{ "language": "en", "url": "https://stackoverflow.com/questions/58891086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to have vertical scrolling in Webviews that are inside a Scrollview? I have a Webview that is embedded inside a scrollview. The Webview itself has areas that are vertical scrollable. Now if I try to scroll inside the webview, the scrollview intercepts the touchevent and scrolls the whole webview instead that only the small scrollable div is moved. How can I make the scrollview work only if the webview does not want to scroll? A: @Janusz, I have had the same problem. My solution is based on the extended scroll view behaviour in couple with the correct layout. I have wrote the answer to the same question here. Let me know in case you have implementation problems or questions and, please inform whether it helps :) A: In my case, I have a webview within a scrollview container, and the scrollview and webview are full screen. I was able to fix this by overriding the onTouch event in my webView touchListener. scrollView = (ScrollView)findViewById(R.id.scrollview); webView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { scrollView.requestDisallowInterceptTouchEvent(true); return false; } } A: Use TouchyWebView.java public class TouchyWebView extends WebView { public TouchyWebView(Context context) { super(context); } public TouchyWebView(Context context, AttributeSet attrs) { super(context, attrs); } public TouchyWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent event){ requestDisallowInterceptTouchEvent(true); return super.onTouchEvent(event); } } In layout file: <yourclasapath.TouchyWebView android:id="@+id/description_web" android:layout_width="match_parent" android:layout_height="wrap_content" /> A: Our solution uses a Javascript callback through the Javascript Interface. Every time a part of the UI that is scrollable inside the WebView is touched a listener is called through java script and this listener calls requestDisallowInterceptTouchEvent on the WebViews parent. This is not optimal but the nicest solution found at the moment. If the user scrolls very fast the layer in the WebView won't scroll but at a normal scroll rate it works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/11138788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Laravel's rollback transaction support polymorphic relations? I've got these polymorphic relations: staff: id - integer name - string orders: id - integer price - integer photos: id - integer path - string imageable_id - integer imageable_type - string And in a controller: public function example() { \DB::beginTransaction(); try { $staff = Staff::findOrFail(1); $row = $staff->photos()->create([ 'path' => 1 ]); $row->path = 2; $row->save(); abort(445); } catch( \Exception $e ) { \DB::rollback() } } As expected, the current row must be deleted from photos table, but it's still there with path = 2 Do I think in a right away? or It's a misundertanding? A: If it's not rolling back the transaction, there is one possibility that your table has MyISAM as the engine, since MyISAM tables do not support rollbacks. So double-check that the table's engine is correctly set to InnoDB.
{ "language": "en", "url": "https://stackoverflow.com/questions/38562296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PHP values that come before negative and after numbers That probably doesn't make a ton of sense. I want to know if there are any values that you could put in an array and sort it and it would come before all negative entries or after all positive entries. $keys = array('m1' => 1, -500 => 1, 0 => 1, 1000 => 1, 'm' => 1, 5000 => 1, ); foreach($keys as $k => $v){ echo $k . '<br />'; } Returns -500 m 0 m1 1000 5000 A: <? $keys = array('m1' => 1, -500 => 1, 0 => 1, 1000 => 1, 'm2' => 1, 5000 => 1, ); ksort($keys, SORT_STRING); foreach($keys as $k => $v){ echo $k . '<br />'; } ?> Will return: -500 0 1000 5000 m1 m2 Make sure to keep all the string keys lowercase if you want them in the right order too. This will put the strings after all integers. Heres an example of the method: http://codepad.org/IBc3wnso The only way I can think of to simply get your non int keys first, is to prefix them with --: <? $keys = array('--m2' => 1, -500 => 1, 0 => 1, 1000 => 1, '--m1' => 1, 5000 => 1, ); ksort($keys, SORT_STRING); foreach($keys as $k => $v){ echo $k . "\n"; } ?> Will return: --m1 --m2 -500 0 1000 5000 Example: http://codepad.org/rwbrj3rJ It's a bit of a hack though. There's probably a better way to accomplish that. A: If you want single chars as array keys, try chr(0) and chr(255). Wait a minute: if you keep changing the question it's difficult to reply. You have -500 as a key: this is not a single char. Then, use -PHP_INT_MAX for lower value and PHP_INT_MAX for upper value.
{ "language": "en", "url": "https://stackoverflow.com/questions/15092541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Check if login already added in User Defined Database Role I am working on a script to add a Login to a user-defined role, where it will take RoleName and Login as input parameters. Checking if already exist before adding, but the following check is returning NULL. USE [MYDatabase]; DECLARE @AddUser NVARCHAR(100) = 'test' DECLARE @RoleName NVARCHAR(100) = 'MYDatabase_ReadOnly' -- User Defined DB ROle IF EXISTS (Select name from sys.database_principals where name = @RoleName) BEGIN SELECT IS_SRVROLEMEMBER (@RoleName, @AddUser) --Output: NULL END I can see both test and MYDatabase_ReadOnly available in sys.database_principals. What I am missing here? (I am doing it in SQL Server 2014) A: --Syntax: IS_SRVROLEMEMBER ( 'role' [ , 'login' ] ) --Return value as NULL indicates role or login is not valid, or you do not have permission to view the role membership --Return value as 0 indicates login is not a member of role. --Return value as 1 indicates login is a member of role. --I think you are using rong value for role paramenter.(Use role value from below) --sysadmin,bcreator,bulkadmin,diskadmin,public,processadmin USE [MYDatabase]; DECLARE @database_principals_name NVARCHAR(100) = 'db_owner' DECLARE @RoleName NVARCHAR(100) = 'sysadmin' -- User Defined DB ROle IF EXISTS (Select name from sys.database_principals where name = @database_principals_name) BEGIN select IS_SRVROLEMEMBER ('sysadmin') --Output: NULL END A: It has to be IS_ROLEMEMBER(@RoleName, @AddUser) as it is checking for the database role instead of IS_SRVROLEMEMBER (@RoleName, @AddUser).
{ "language": "en", "url": "https://stackoverflow.com/questions/39763596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: align dotted circle and botted Line equally in dart Need to align the dotted circle and dotted line like the image shown below. Tried aligning in a row but it somehow merged with a row and it's not displaying exactly like the image. The first line is aligned well but not below the other ones. Here is the code for displaying the widgets dotted line and circle. import 'package:dotted_border/dotted_border.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:get/get.dart'; import 'package:get/get_core/src/get_main.dart'; import 'package:get/get_utils/src/extensions/internacionalization.dart'; import 'package:matab/ui/general_widgets/custom_gradient_button.dart'; import 'package:matab/ui/pages/all_orders/one_order.dart'; import 'package:matab/ui/pages/styles.dart'; import 'package:dotted_line/dotted_line.dart'; import '../../../models/order.dart'; import '../home/home.dart'; class TrackOrder extends StatefulWidget { const TrackOrder({Key? key, required this.order}) : super(key: key); final Order order; @override State<TrackOrder> createState() => _TrackOrderState(); } class _TrackOrderState extends State<TrackOrder> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Center(child: Text('Track Order')), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox(height: 50), Text( widget.order.orderID, style: TextStyle( color: darkGreyColor, fontSize: 18, fontWeight: FontWeight.bold), ), SizedBox(height: 50), Text('Sat, 12 Mar 2022', style: TextStyle( color: darkGreyColor, fontSize: 18, fontWeight: FontWeight.bold)), SizedBox( height: 15, ), Text('Estimated Time: 07 Days', style: TextStyle( color: mainColorShades[9], fontSize: 23, fontWeight: FontWeight.bold)), SizedBox(height: 30), Align( alignment: Alignment.topLeft, child: Container( margin: EdgeInsets.fromLTRB(240, 0, 0, 0), child: SizedBox( height: 30, child: DottedLine( dashColor: Colors.black, direction: Axis.vertical, lineLength: 25, lineThickness: 3, dashLength: 5, dashGapLength: 5, )), ), ), Container( // margin: EdgeInsets.fromLTRB(240, 05, 0, 0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ OrderStatusBar(title: "Received", status: true), // Container( // // margin: EdgeInsets.fromLTRB(60, 05, 0, 0), // ) ], ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( width: 10, ), OrderStatusBar(title: "Shipped", status: false), ], ), Container( // margin: EdgeInsets.fromLTRB(65, 05, 0, 0), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( // width: 50, height: 50, ), OrderStatusBar(title: "Delivering", status: false), ], ), Container( // margin: EdgeInsets.fromLTRB(65, 05, 0, 0), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ OrderStatusBar(title: "Delivered", status: false), ], ), SizedBox( height: 40, ), Center( child: Text(widget.order.deliveryAddress.address, style: TextStyle( color: darkGreyColor, fontSize: 18, fontWeight: FontWeight.bold)), ), Padding( padding: const EdgeInsets.all( 18.0, ), child: CustomGradientButton( buttonText: "Done".tr, buttonFunction: () => {Get.offAll(Home())}), ), Padding( padding: const EdgeInsets.only(top: 18.0), child: GestureDetector( child: Text( 'Back to Home'.tr, style: TextStyle( color: mainColor, fontSize: 23, fontWeight: FontWeight.bold), ), onTap: () => Get.offAll(Home()), ), ) ], ), ); } } class OrderStatusBar extends StatefulWidget { const OrderStatusBar({Key? key, required this.title, required this.status}) : super(key: key); final String title; final bool status; @override State<OrderStatusBar> createState() => _OrderStatusBarState(); } class _OrderStatusBarState extends State<OrderStatusBar> { @override Widget build(BuildContext context) { return Row( children: [ Text( widget.title, style: TextStyle(fontSize: 20), ), SizedBox( width: 30, ), widget.status ? dottedCircleWithCheckMark() : dottedCircle(), ], ); } } dottedCircle() { return DottedBorder( borderType: BorderType.Circle, dashPattern: const [5, 5], child: Container( height: 50, width: 50, decoration: const BoxDecoration(shape: BoxShape.circle), )); } dottedCircleWithCheckMark() { return DottedBorder( color: Colors.red, borderType: BorderType.Circle, dashPattern: const [5, 5], child: Container( height: 50, width: 50, decoration: const BoxDecoration(shape: BoxShape.circle), child: Icon( Icons.check, color: Colors.red, size: 40, ), )); } A: The following would do the trick: class TrackOrder extends StatefulWidget { const TrackOrder({Key? key}) : super(key: key); @override State<TrackOrder> createState() => _TrackOrderState(); } class _TrackOrderState extends State<TrackOrder> { static const darkGreyColor = Colors.grey; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Center(child: Text('Track Order')), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const SizedBox(height: 50), const Text( 'orderID', style: TextStyle( color: darkGreyColor, fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 50), const Text('Sat, 12 Mar 2022', style: TextStyle( color: darkGreyColor, fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox( height: 15, ), const Text('Estimated Time: 07 Days', style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold)), const SizedBox(height: 30), SizedBox( width: 200, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const OrderStatusBar(title: "Received", status: true), dottedLine(), const OrderStatusBar(title: "Shipped", status: false), dottedLine(), const OrderStatusBar(title: "Delivering", status: false), dottedLine(), const OrderStatusBar(title: "Delivered", status: false), ], ), ), const SizedBox( height: 40, ), const Center( child: Text('deliveryAddress.address', style: TextStyle( color: Colors.grey, fontSize: 18, fontWeight: FontWeight.bold)), ), Padding( padding: const EdgeInsets.all( 18.0, ), child: ElevatedButton(child: const Text("Done"), onPressed: () => {}), ), Padding( padding: const EdgeInsets.only(top: 18.0), child: GestureDetector( child: const Text( 'Back to Home', style: TextStyle( // color: mainColor, fontSize: 23, fontWeight: FontWeight.bold), ), onTap: () => {}, ), ) ], ), ); } } class OrderStatusBar extends StatefulWidget { const OrderStatusBar({Key? key, required this.title, required this.status}) : super(key: key); final String title; final bool status; @override State<OrderStatusBar> createState() => _OrderStatusBarState(); } class _OrderStatusBarState extends State<OrderStatusBar> { @override Widget build(BuildContext context) { return Row( children: [ widget.status ? dottedCircleWithCheckMark() : dottedCircle(), const SizedBox(width: 30), Text( widget.title, style: TextStyle( fontSize: 20, fontWeight: widget.status ? FontWeight.bold : null, ), ), ], ); } } const size = 25.0; const strokeWidth = 1.0; const checkedColor = Color.fromRGBO(232, 113, 65, 1); Widget dottedLine() { return const Padding( padding: EdgeInsets.only(left: 27 / 2), child: SizedBox( height: size, child: DottedLine( dashColor: Colors.black, direction: Axis.vertical, lineLength: size, lineThickness: strokeWidth, dashLength: 5, dashGapLength: 5, ), ), ); } dottedCircle() { return DottedBorder( borderType: BorderType.Circle, dashPattern: const [5, 5], child: Container( height: size, width: size, decoration: const BoxDecoration(shape: BoxShape.circle), )); } dottedCircleWithCheckMark() { return Container( height: size + strokeWidth * 2, width: size + strokeWidth * 2, decoration: const BoxDecoration( shape: BoxShape.circle, color: checkedColor, ), child: const Icon( Icons.check, color: Colors.white, size: size / 4 * 3, ), ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/73543455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }