text:
Q: Random row selection in multiple excel sheets I have an output excel file from another macro which has multiple sheets (named 100,101,102... etc.) Sheet numbers will vary depending on prior macro's output.
Also there is a sheet named sheet1 which has info about how many random rows should be selected from 100,101,102... etc.
I tried to merge/combine what i could find from similar macros but i guess the loop part is way over my head.
I will run the macro from another "main" excel. which will open related output xls.
Then it will lookup for random rows amount from sheet1 and then select that number of random rows in related sheet and move to next sheet. (I'm getting the correct amount from lookup (used index match))
But for randomized part i was not able to make it work for multiple sheets.
It does not matter if it selects and colors the rows or copies and pastes them to another sheet/wb. Both is ok, but I need to automate this process since i have so much data waiting.
The macro i have managed so far is below, since I'm a newbie there may be unrelated or unnecessary things.
Is it possible?
Sub RANDOM()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim Sh As Worksheet
Dim Durat As Long
StartTime = Now()
Dim mvn As Workbook
Dim FPath As String
Dim newWB As Workbook
Dim SheetN As Integer
Dim I As Long

FPath = ThisWorkbook.Path
Set mvn = Workbooks.Open(FileName:=ActiveWorkbook.Path & "\" &
Sheets("Data").Range("C2").Value & " " & Sheets("Data").Range("C3").Value
& " Muavinbol" & ".xls")

SheetN = mvn.Worksheets.Count
Set SampleS = mvn.Sheets("Sheet1")

For Each Sh In mvn.Worksheets
    Sh.Activate
    If Sh.Name <> "Sheet1" Then
        Dim lookupvalue As Integer
        Dim ranrows As Integer
        Dim randrows As Integer
     lookupvalue = Cells(1, 1).Value
     ranrows = Application.WorksheetFunction.Index(mvn.Sheets("Sheet1")_
.Range("S1:S304"), Application.WorksheetFunction.Match(lookupvalue,
mvn.Sheets("Sheet1").Range("$D$1:$D$304"), 0))

'MsgBox lookupvalue & " " & ranrows
    End If

Next Sh

Durat = Round((Now() - StartTime) * 24 * 60 * 60, 0)

'MsgBox Durat & " seconds."

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

A: Here is an example (i have integrated some code, adapted from other places, and added the references in to the code itself) I would welcome feedback from other users and can refine.
Sheet1 has the number of rows to return and the sheet names (i have used a short list)

The other sheets have some random data e.g. Sheet2

The code reads the sheet names into one array and the number of rows to randomly choose from each sheet into another array.
It then loops the sheets, generates the number of required random rows by selecting between the first and the start row in the sheet (this currently doesn't have error handling in case specified number of random rows exceeds available number ,but then could set numRows to lastRow. Union is used to collect these for the given sheet and they are copied to the next available row in the target sheet of another workbook. Union can't be used across worksheets sadly so a workaround has to be found, i chose this copy for each worksheet.
I have made some assumptions about where to copy from and to but have a play. I have also left some of your code in and currently set mnv = ThisWorkbook and the workbook to copy to is called otherWorkbook. Yours may be differently named and targeted but this was aimed at showing you a process for generating numbers and copying them in a loop.
Have used a function by Rory to test if the worksheet exists.
Example result:

Option Explicit

Public Sub RANDOM()

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Dim Sh As Worksheet
    Dim Durat As Long

    Dim mvn As Workbook
    Dim FPath As String
    Dim newWB As Workbook
    'Dim SheetN As Long
    Dim i As Long
    Dim otherWorkbook As Workbook
    Dim targetSheet As Worksheet
    Dim startTime As Date
    Dim mnv As Workbook
    Dim SampleS As Worksheet

    startTime = Now()

    FPath = ThisWorkbook.Path

    'Set mvn = Workbooks.Open(Filename:=ActiveWorkbook.Path & "\" & Sheets("Data").Range("C2").Value & " " & Sheets("Data").Range("C3").Value & " Muavinbol" & ".xls")

    Set mnv = ThisWorkbook

    Set otherWorkbook = Workbooks.Open("C:\Users\HarrisQ\Desktop\My Test Folder\Test.xlsx")

    Set targetSheet = otherWorkbook.Sheets("TargetSheet")
    Set SampleS = mnv.Worksheets("Sheet1")

    Dim worksheetNames()
    Dim numRandRows()

    worksheetNames = SampleS.Range("$D$1:$D$3").Value
    numRandRows = SampleS.Range("$S$1:$S$3").Value

    Dim copyRange As Range

    Dim currSheetIndex As Long
    Dim currSheet As Worksheet

    Dim selectedRows As Range

    For currSheetIndex = LBound(worksheetNames, 1) To UBound(worksheetNames, 1)

        If WorksheetExists(CStr(worksheetNames(currSheetIndex, 1))) Then

            Set currSheet = mnv.Worksheets(worksheetNames(currSheetIndex, 1))

            With currSheet

                Dim firstRow As Long
                Dim lastRow As Long
                Dim numRows As Long

                firstRow = GetFirstLastRow(currSheet, 1)(0) 'I am using Column A (1) to specify column to use to find first and last row.
                lastRow = GetFirstLastRow(currSheet, 1)(1)
                numRows = numRandRows(currSheetIndex, 1)

                Set selectedRows = RandRows(currSheet, firstRow, lastRow, numRows) 'Union cannot span different worksheets so copy paste at this point

                Dim nextTargetRow As Long

                If IsEmpty(targetSheet.Range("A1")) Then
                    nextTargetRow = 1
                Else
                    nextTargetRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row + 1
                End If

                selectedRows.Copy targetSheet.Cells(nextTargetRow, 1)

                Set selectedRows = Nothing
            End With

        End If

    Next currSheetIndex

    Durat = Round((Now() - startTime) * 24 * 60 * 60, 0)

    'MsgBox Durat & " seconds."

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End Sub
Private Function RandRows(ByRef currSheet As Worksheet, ByVal firstRow As Long, ByVal lastRow As Long, ByVal numRows As Long) As Range
    'http://www.ozgrid.com/VBA/RandomNumbers.htm
    Dim iArr As Variant
    Dim selectedRows As Range

    Dim i As Long

    Dim r As Long

    Dim temp As Long

    Application.Volatile

    ReDim iArr(firstRow To lastRow)

    For i = firstRow To lastRow

        iArr(i) = i

    Next i

    For i = lastRow To firstRow + 1 Step -1

        r = Int(Rnd() * (i - firstRow + 1)) + firstRow

        temp = iArr(r)

        iArr(r) = iArr(i)

        iArr(i) = temp

    Next i

    Dim currRow As Range

    For i = firstRow To firstRow + numRows - 1

        Set currRow = currSheet.Cells.Rows(iArr(i))

        If Not selectedRows Is Nothing Then
            Set selectedRows = Application.Union(selectedRows, currRow)
        Else
            Set selectedRows = currRow
        End If

    Next i

    If Not selectedRows Is Nothing Then
        Set RandRows = selectedRows
    Else
        MsgBox "No rows were selected for copying"
    End If

End Function

Private Function GetFirstLastRow(ByRef currSheet As Worksheet, ByVal colNum As Long) As Variant
    'colNum determine which column you will use to find last row
    Dim startRow As Long
    Dim endRow As Long

    endRow = currSheet.Cells(currSheet.Rows.Count, colNum).End(xlUp).Row

    startRow = FirstUsedCell(currSheet, colNum)

    GetFirstLastRow = Array(startRow, endRow)

End Function

Private Function FirstUsedCell(ByRef currSheet As Worksheet, ByVal colNum As Long) As Long
    'Finds the first non-blank cell in a worksheet.
    'https://www.excelcampus.com/library/find-the-first-used-cell-vba-macro/
    Dim rFound As Range

    On Error Resume Next
    Set rFound = currSheet.Cells.Find(What:="*", _
                                      After:=currSheet.Cells(currSheet.Rows.Count, colNum), _
                                      LookAt:=xlPart, _
                                      LookIn:=xlFormulas, _
                                      SearchOrder:=xlByRows, _
                                      SearchDirection:=xlNext, _
                                      MatchCase:=False)

    On Error GoTo 0

    If rFound Is Nothing Then
        MsgBox currSheet & ":All cells are blank."
        End
    Else
        FirstUsedCell = rFound.Row
    End If

End Function

Function WorksheetExists(sName As String) As Boolean
'@Rory https://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

A: Since QHarr's code needed to have all worksheet names should  exist in the workbook did not work for me in the end. But with merging it some other project's function i made it work.
Opens an output xlsx file in same folder,
Index&Match to find the random rows amount
loop through all sheets with random function
then paste all randomized rows into Sheet named RASSAL
It may be unefficient since I really dont have much info on codes, but guess i managed to modify it into my needs.
Open to suggestions anyway and thanks to @QHarr very much for His/Her replies.
Sub RASSALFNL()

'Application.ScreenUpdating = False
'Application.DisplayAlerts = False

Dim Durat As Long
startTime = Now()

Dim Sht As Worksheet
Dim mvn As Workbook
Dim FPath As String
Dim newWB As Workbook
Dim SheetN As Long
Dim i As Long
Dim lookupvalue As Long
Dim indexrange As Range
Dim matchrange As Range
Dim ranrows As Long
Dim firstRow As Long
Dim lastRow As Long
Dim numRows As Long
Dim sayf As String
Dim nextTargetRow As Long
Dim Rassal As Worksheet
Dim rngToCopy As Range
Dim sampleCount As Long
Dim ar() As Long
Dim total As Long
Dim rowhc As Long

FPath = ThisWorkbook.Path
Set mvn = Workbooks.Open(FileName:=ActiveWorkbook.Path & "\" &
Sheets("Data").Range("C2").Value & " " & Sheets("Data").Range("C3").Value
& " Muavinbol" & ".xlsx")
SheetN = mvn.Worksheets.count
Set SampleS = mvn.Sheets("Sheet1")
Set Rassal = Worksheets.Add
Rassal.Name = "RASSAL"

Set indexrange = SampleS.Range("$S$8:$S$304")
Set matchrange = SampleS.Range("$D$8:$D$304")

mvn.Activate
For Each Sht In mvn.Worksheets
Sht.Activate
    If Sht.Name = "Sheet1" Or Sht.Name = "Sayfa1" Or Sht.Name = "RASSAL"
Then
    'do nothing
    Else
        lookupvalue = Sht.Cells(1, 1).Value
        ranrows = Application.WorksheetFunction.Index(indexrange,
Application.WorksheetFunction.Match(lookupvalue, matchrange, 0))
        With Sht
             firstRow = GetFirstLastRow(Sht, 1)(0)
             lastRow = GetFirstLastRow(Sht, 1)(1)
             numRows = ranrows
             sayf = Sht.Name
             'MsgBox sayf & " " & firstRow & " " & lastRow & " " &
ranrows
          If numRows = 0 Then
          'do nothing
          Else
             ar = UniqueRandom(numRows, firstRow, lastRow)
             Set rngToCopy = .Rows(ar(0))
             For i = 1 To UBound(ar)
             Set rngToCopy = Union(rngToCopy, .Rows(ar(i)))
             Next

                    If IsEmpty(mvn.Sheets("RASSAL").Range("A1")) Then
                    nextTargetRow = 1
                    Else
                    nextTargetRow =
mvn.Sheets("RASSAL").Cells(mvn.Sheets("RASSAL").Rows.count,
"A").End(xlUp).Row + 1
                    End If
                    rngToCopy.Copy Rassal.Cells(nextTargetRow, 1)
                    Set rngToCopy = Nothing
          End If
        End With
    End If
Next Sht

rowhc = Rassal.Cells(Rows.count, 1).End(xlUp).Row

Durat = Round((Now() - startTime) * 24 * 60 * 60, 0)
MsgBox rowhc & " " & "random selections made in" & " " & Durat & "
seconds."

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

Private Function GetFirstLastRow(ByRef Sht As Worksheet, ByVal colNum As
Long) As Variant
'colNum determine which column you will use to find last row
Dim firstRow As Long
Dim lastRow As Long

lastRow = Sht.Cells(Sht.Rows.count, colNum).End(xlUp).Row
firstRow = FirstUsedCell(Sht, colNum)

GetFirstLastRow = Array(firstRow, lastRow)

End Function

Private Function FirstUsedCell(ByRef Sht As Worksheet, ByVal colNum As
Long) As Long
Dim rFound As Range
On Error Resume Next
Set rFound = Sht.Cells.Find(What:="*", _
                                  After:=Sht.Cells(Sht.Rows.count,
colNum), _
                                  LookAt:=xlPart, _
                                  LookIn:=xlFormulas, _
                                  SearchOrder:=xlByRows, _
                                  SearchDirection:=xlNext, _
                                  MatchCase:=False)

On Error GoTo 0

If rFound Is Nothing Then
    'do Nothing MsgBox Sh & ":All cells are blank."
    End
Else
    FirstUsedCell = rFound.Row
End If

End Function

Function UniqueRandom(ByVal numRows As Long, ByVal a As Long, ByVal b As
Long) As Long()
Dim i As Long, j As Long, x As Long

ReDim arr(b - a) As Long

Randomize
For i = 0 To b - a:    arr(i) = a + i:     Next
If b - a < count Then UniqueRandom = arr:    Exit Function

For i = 0 To b - a    'Now we shuffle the array
j = Int(Rnd * (b - a))
x = arr(i):   arr(i) = arr(j):   arr(j) = x    ' swap
Next

' After shuffling the array, we can simply take the first portion

If numRows = 0 Then
ReDim Preserve arr(0)
Else
ReDim Preserve arr(0 To numRows - 1)
 On Error Resume Next
End If
'sorting, probably not necessary
For i = 0 To count - 1
For j = i To count - 1
  If arr(j) < arr(i) Then x = arr(i):   arr(i) = arr(j):   arr(j) = x   '
swap
Next
Next

UniqueRandom = arr
End Function


text:
Q: Whitelist allow for specific requests Nginx I have a server and there is a Nginx in front. There are many requests which some of them contains special word example:
/posts/men/clouths

I have a whitelist ip file also. I want to write a rule in Nginx that if requests contains "men", only allow the request if requester's ip is in whitelist file.
If requests does not contains "men" allow the request anyway.

A: Done
http {
    ## load whitelist
      map $remote_addr $deny {
        default 0;
        include /path/to/whitelist.txt;
}

server{
    ## check
    set $is_white_list 0;
    if ($request_uri ~ ".*men.*"){
      set $is_white_list 1;
    }
    if ($deny) {
      set $is_white_list 1$is_white_list;
    }
    if ($is_white_list = 1) {
      return 403;
    }
    ##// epg check
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern Check for a specific string Required I want to validate every string in text file. The contents in each row are separated by tab.
Data Format:
EmployeeNumber {tab} EmployeeName {tab} Age {tab} IsCurrentlyEmployed

Sample text:

E001 {tab} Jim Watson {tab} 35 {tab} Yes

E002 {tab} Mark Smith {tab} 50 {tab} No

So I am guessing the check should be
(AlphaNumeric String){tab}(Normal String){tab}(Number){tab}(Yes/No)

Thank you

A: You can use a regex like this that matches the pattern you have provided:
\w+\t[a-zA-Z\s]+\t\d{1,3}\t(Yes|No)

matches:
E001    Jim Watson  35  Yes //where blanks are tabs.

Walkthrough of the steps:
\w  -> Matches any word character (equal to [a-zA-Z0-9_])
+   -> Matches between one and unlimited times, as many times as possible
\t  -> Matches a tab character
[a-zA-Z\s]+  ->  Matches entire alphabet, upper/lower case and spaces between one and unlimited times
\t  -> Matches a tab character
\d{1,3}  ->  Matches any digit between 1-3 times (age 1-100+)
\t  -> Matches a tab character
(Yes|No)  -> Matches string "Yes" or "No" (it will break if string is "yes" or "no").

A: If it needs to be in that exact format you provided, you could use
E\d+\t[A-Za-z] [A-Za-z]\t\d+\t(?:Yes|No)

That regex would match the following
E015 {Tab} John Doe {Tab} 32 {Tab} Yes
E451 {Tab} Jane Doe {Tab} 25 {Tab} No

but not the following
015 {Tab} John Doe {Tab} 32 {Tab} Yes # the E at the beginning is missing
E451 {Tab} Jane {Tab} 32 {Tab} No # only the first name is given
E {Tab} Johnson Doe {Tab} 48 {Tab} Yes # no employee number provided

If you are looking for a less-strict regex, use the one provided in demogorgon.net's answer


text:
Q: refresh Page at set interval I have tried a number of different methods for auto refreshing a page at a specified interval.
1. added <meta http-equiv="refresh" content="30"> to page html. It got rejected.
2. Tried content editor web part with a link to a script i found:
    <script>
var reloadTimer = null;
var sURL = unescape(window.location.pathname);
function setReloadTime(secs)
{if (arguments.length == 1)
   { if (reloadTimer) clearTimeout(reloadTimer);
       reloadTimer = setTimeout("setReloadTime()", Math.ceil(parseFloat(secs)*1000));
   }
else   { reloadTimer = null;
     window.location=window.location;
     window.location.replace( sURL );
   }
}
setReloadTime(30);

</script>

But nothing seems to work. I have a media web part running a .wmv, but it doesn't reset.
Ultimately I am trying to have it refresh so that i can upload a replacement .wmv and have it auto refresh on the page so that we don;t have to clear the cache, etc.
After further testing it seems i need to clear the cache since the presentation doesn't reset until the browser is restarted.


text:
Q: How to get all users who wrote to the bot in telegram? I am using library for c # Telegram.Bot. Can I somehow get the ChatID of all users who have ever written to the bot?

A: This is not possible with standard API methods.
You must save user in database when you receive messages.


text:
Q: In Docker Hub Is it possible to build an automated build for an Arm Image In Docker Hub website Is it possible to build an automated build for an Arm Image ?
I have modified my existing DockerFile to use an Arm base image, but it fails on the next line when it tries to run the apk command with exec format error. So it looks like Docker Hub is trying to build as Intel despite base image being built for Arm.
Is it possible to build Arm image with Docker Hub website or not ?
If not can anyone provide succint instructions on how to build Arm Image from my Dockerfile either by

*

*Using my (Intel PC) from the docker command line

*Using my (Intel Mac) from the docker command line

*Using QNAP TS131P Container station, (since this is natively Arm maybe this is simpler)

A: Turned out to be relatively easy using the QNAP, alot simpler than it seemed from the posts I had read, I think my confusion was these posts were about building Arm version on an Intel machine, which i didnt need to do. And all the Arm specific instructions were for Raspberry Pi which had its own problems.

*

*Created new empty repository in DockerHub

*Uploaded my DockerFile to my webserver

*ssh qnapserver

*docker build DockerFileUrl

*docker login DockerHubUsername DockerHubPassword

*docker images (to get imageId of built image)

*docker tag imageId DockerHubNameSpace/DockerHubRepository:latest

*docker push DockerHubNameSpace/DockerHubRepository:latest

The push worked, and I was then able to use ContainerStation to get the image from Docker Hub and run in a container.


text:
Q: Counting words, and ordering strings that have that N word I have and entry like this:
(bc9, de, viana=do=castelo)
(bc9, tomar o, aeroporto=de=pedras=rubras)
(arábia=saudita, em o, afeganistão)

And I want to count how many times and which appears the most, like this:
bc9: 2 times.

(bc9, de, viana=do=castelo)
(bc9, tomar o, aeroporto=de=pedras=rubras)

afeganistão: 1 times.

(arábia=saudita, em o, afeganistão)

The words between the commas aren't supposed to be counted, either.
Here is the code, it output some connectors, that I'll remove, but after that, i thought of iterating the input and grouping the sentences that contains the words in order in their appear
from Tkinter import Tk
from tkFileDialog import askopenfilename
import operator

Tk().withdraw()
filename = askopenfilename()
file = open(filename, "r+")
wordcount = {}
saida=open('saida.txt','w')
string = 'portugal] <civ> <*> prop m s @p<   ['
for line in file:
 line = line.replace("(", "")
 line = line.replace(")", "")
 line = line.replace(",", "")
 line = line.replace("=", " ")
 line = line.replace(string, "")
 saida.write(line)
saida.close()
file.close()
file=open("saida.txt","r")
for word in file.read().split():
 if word not in wordcount:
    wordcount[word] = 1
 else:
    wordcount[word] += 1
file.close
sorted_x = sorted(wordcount.items(), key=operator.itemgetter(1), reverse=True)
saida2=open('saida2.txt','w')
for key, value in sorted_x:
 saida2.write(key+':')
 saida2.write('\t')
 saida2.write(str(value) + '\n')
 print key, value

A: from collections import Counter

zipped_entries = zip(*entries)
Counter(zipped_entries[0] + zipped_entries[2])

Assumes you have a fixed number of entries (3). Should be enough code to get you started.


text:
Q: Integration with respect to a measure I am trying to get an explanation in words, or math, of what the $d\mu$ means in an integration statement. Such as:
$$\int f \ d\mu$$
How does the measure change our old "calculus" notion of integration? What is going on here that is different?

A: I actually struggled with this concept in grad school since I was studying applied math and was sort of thrust into higher level theory without building it up rigorously like I assume would be done in a pure math program.
If we are integrating over a space $X$, I sometimes prefer the notation $\int_X f(x)\mu(dx)$. I like to think of it as splitting the space we are integrating over into infinitesimal pieces, but we have to take the measure of those infinitesimal pieces as they may not all be identical under $\mu$. I'm used to working with probability measures, and at least in that case, you can often think of it similar to the way Lebesgue and Riemann integration are developed.
Create a disjoint partition $X=\cup_{k=1}^N A_k$, and define the sum which will approximate the integral using appropriately chosen sample points $x_k\in A_k$.
$$\int_X f(x)\mu(dx) \approx \sum_{k=1}^N f(x_k) \mu(A_k).$$
Ideally, taking the limit as $N\rightarrow\infty$ (carefully refining the partition and choosing appropriate sample points as $N$ increases) will make the sum converge to the integral. What we are doing here is effectively approximating the function $f$ with a simple function which is constant on a finite collection of measurable sets.

A: Think of it physically: each measure assigns different weights to given sets: consider for example the particular case $d\mu=df(x)=f'(x)dx$ for a well behaved $f(x)$. Here you can really see the difference between the "ordinary" measure $dx$, which does not care about the location of the set, and $f'(x)dx$, which indeed does! In formulas:
\begin{equation}
\int_{[0,1]}dx =1= \int_{[1,2]}dx
\end{equation}
But in general
\begin{equation}
\int_{[0,1]}df(x) = f(1)-f(0) \neq f(2)-f(1) = \int_{[1,2]}df(x)
\end{equation}
This is just an example, but the idea applies with general measures $\mu$; it is in this sense that this perspective conveys the concept - in my view - of a weighted measure. It allows far more general and powerful structures than the old Riemann integration idea with shrinking rectangles.
One can then go further and (try to) relate different measures, for example via the Radon-Nikodym theory. There's a new world out there. :-)


text:
Q: Switch to the main scene when back from background Using cocos2d i am trying to switch back to the main scene where ever the user is back from background . the main scene is called Home
I have tried that without success :
-(void) applicationWillEnterForeground:(UIApplication*)application
{

    if( [navController_ visibleViewController] == director_ )
          //[director_ startAnimation]; //this one i took out
        [[CCDirector sharedDirector] replaceScene:[Home node]];

}

what happen is that i can see that the Home scene was loaded- BY LOGS, but the view i can see is still another scene and not the Home
Whats the correct way to switch/replace/push back the main scene each time we back from background ?

A: Put the startAnimation back in and everything should be fine. Without startAnimation, cocos2d is still in the suspended state and won't do anything.


text:
Q: Test View Controllers separately I am using Quick/Nimble for testing in my application. This is the first time I am doing tests. I have three VC in my app embedded in a navigationController like this:
StoryBoard1(NAV -> VC1 -> VC2)->StoryBoard2(VC3).

I want to test each viewController separately meaning, when the test for VC3 for example is launched I don't want to launch VC1, I need the test to go directly to VC3 and test it, keep in mind that VC3 is in a separated storyBoard and they all share one NAV in the first storyBoard. I tried doing it like this.
import XCTest
import Quick
import Nimble

@testable import MYApp

class VC3Tests: QuickSpec {

    override func spec() {
        var vc3: VC3!
        var navigationController: UINavigationController!

        beforeEach {

            let storyBoard2 = UIStoryboard(name: "StoryBoard2", bundle: Bundle.main)
            let storyBoard1 = UIStoryboard(name: "StoryBoard1", bundle: Bundle.main)
            navigationController = storyBoard1.instantiateInitialViewController() as! UINavigationController
            vc3 = storyBoard2.instantiateViewController(withIdentifier: NSStringFromClass(VC3.self)) as! VC3
            navigationController.pushViewController(vc3, animated: false)
            expect(navigationController.visibleViewController).toEventually(beAnInstanceOf(VC3.self),timeout: 3,pollInterval: 1)

         _ = navigationController?.view
         _ = vc3.view

        }
    }
}

But it doesn't push to VC3 and when launched it just stays on VC1. Am I doing something wrong?


text:
Q: Solve for unknown interest rate in accumulated amount Hi I am looking for a way to iterate some value with an unknown.
There are 18 cashflows (cf_1 to cf_18) and their corresponding accumulate periods (t1 to t18), stored in 2 lists. I wish to equate the sum of the accumulated amounts (in terms of the unknown interest rate i) to 500000, and solve for this i.
The formula is: 500000 = accumulated value = cf1 * (1+i)^t1 +...+ cf_18 * (1+i)^t18. I could think of using sympy solver:
solve(cf1 * (1+i)**t1 +...+ cf_18 * (1+i)**t18 - 500000, i)

to solve for i. But apparently for loop can not take this unknown i. So what else can I do beside type out the whole 18 expressions?
This is the data and what I have tried:
from sympy.solvers import solve
from sympy import Symbol

i = Symbol('i')

cashflow = [13000,
12500,
12000,
11500,
11000,
10500,
10000,
9500,
9000,
8500,
8000,
7500,
7000,
6500,
6000,
5500,
5000,
4500,]

years_accum = [22.75,
22.5,
20.5,
20,
19.25,
19,
18.75,
12,
10.25,
10,
9.75,
9,
8.5,
8,
7.5,
5,
3.5,
3.25,]

for cf in cashflow:
    for yr in years_accum:
        S_t = sum(cf* (1+i)^yr)
        print(S_t)
solve(S_t - 500000, i)

Any help appreciated!

A: Your double loop is incorrect since for each cash flow it adds all the years. I would have done
>>> eq = sum([cf*(1+i)**yr for cf,yr in zip(cashflow, years_accum)]) - 500000

But to see this in a loop it could be
>>> S_t = 0
>>> for cf, yr in zip(cashflow, years_accum):
...    S_t = S_t + cf*(1+i)**yr

>>> eq = S_t - 500000

Now to solve...solve would be good if we expect a simple answer (from a relatively simple equation). Since this is highly non-linear nsolve (for numerical-solutions) is a better choice:
>>> nsolve(eq, 0)  # assume i is close to 0
0.0747836528616713


text:
Q: CSS Subnav not staying active I'm trying to get clever with some z-index stuff. (parent list item overlapping a child ul) But I think it's interfering with my subnav staying active once the mouse comes off the parent list item. I have a fiddle that demonstrates what is going on. Any ideas?
http://jsfiddle.net/dv8withn8/8QCZk/
(The placeholder footer is there to demonstrate that everything after the nav should probably have a z-index less than -1 like the content area.)
Markup:
<!DOCTYPE html>

    <title>Header Test</title>
    <link rel="stylesheet" href="style.css" type="text/css">

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

                <hgroup id="branding" class="group">

Name!

Memorable slogan!

                </hgroup>

Item 1

Item 2

Item 3

Item 4

Item 5

                            Hi, John3

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Hello, World!

I'm a footer, lol!

Styles:
* {
    box-sizing:border-box;
}

html {
    font-size:100%;
}

body {
    margin:0 auto;
    font:1em/1 Helvetica,Arial,sans-serif;
    width:100%;
}

#global-header {
    width:100%;
}

.wrapper {
    margin:0 auto;
    max-width:960px;
}

.nav ul {
    list-style:none;
}

.nav ul > li {
    display:block;
    float:left;
}

.nav li a {
    display:block;
}

[role=toolbar] {
    display:block;
    margin:0 auto;
    width:100%;
    background:url(grey_diagnol.png) repeat;
    overflow:hidden;
}

[role=toolbar] ul {
    display:block;
    margin:0 auto;
    font-size:.625em;
    float:right;
}

[role=toolbar] li {
    margin:.5em 0;
}

[role=toolbar] li:not(:last-child) {
    border-right:1px solid #436394;
}

[role=toolbar] ul li > a {
    color:#436394;
    text-decoration:none;
    padding:.25em .72em;
}

[role=toolbar] a:hover {
    color:#a1c336;
}

#page-top {
    border-top:2px solid #32568F;
    background-color:#172842;
    color:#fff;
    width:100%;
    overflow:visible;

}

#branding {
    display:inline;
    float:left;
    line-height:2em;
    vertical-align:middle;
    padding-top:.9em;
}

#branding h1.logo {
    display:inline-block;
    margin:0;
    padding:0;
    float:left;
    text-indent:100%;
    overflow:hidden;
    background:url(logo.png) no-repeat left top;
    width:124px;
    height:27px;
    vertical-align:bottom;
    margin-right:.4em;
}

#branding h2 {
    display:inline-block;
    font-size:.625em;
    font-style:oblique;
    font-weight:400;
    float:left;
    margin:0;
    padding:0;
}

[role=navigation] ul {
    display:block;
    margin:0;
    padding:0;
    float:right;
}

[role=navigation] li {
    display:block;
    position:relative;
    margin-bottom:-5px;
    font-family:'MuseoSlab500',Georgia,'Times New Roman',serif;
    font-weight:700;
    font-size:1.2em;
    text-transform:lowercase;
}

[role=navigation] li:hover {
    background:#b4df5b;
    background:-moz-linear-gradient(top,#a1c336 0%,#88a13d 100%);
    background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#a1c336),color-stop(100%,#88a13d));
    background:-webkit-linear-gradient(top,#a1c336 0%,#88a13d 100%);
    background:-o-linear-gradient(top,#a1c336 0%,#88a13d 100%);
    background:-ms-linear-gradient(top,#a1c336 0%,#88a13d 100%);
    background:linear-gradient(to bottom,#a1c336 0%,#88a13d 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#a1c336',endColorstr='#88a13d',GradientType=0);
    box-shadow:0 1px 4px #000;
    text-shadow:1px 1px 1px #3D4427;
    color:#fff;
}

[role=navigation] a {
    color:#fff;
    text-decoration:none;
    padding:1em;
}

[role=navigation] .user-name {
    position: relative;
    text-transform:uppercase;
    font:.64em Helvetica,Arial,sans-serif;
    color:#a2bf39;
    text-shadow:none;
    /* max-width: 5em;
    overflow: hidden;
    text-overflow: clip;
    display: inline-block; */
}

[role=navigation] li:hover .user-name {
    color:#172842;
}

a.message-count {
    display: block;
    position: absolute;
    top: -2px;
    right: -2px;
    box-shadow: 0px 1px 4px black;
    border: 2px solid #fff;
    border-radius: 50px;
    padding: .25em .5em;
    background-color: #d52424;
    font: .75em Helvetica, Arial, sans-serif;
    font-weight: bold;
    color: #fff;
    cursor: pointer;
}
a.message-count:hover {
    background-color: red;
    box-shadow: 0px 1px 4px white;
}

[role=navigation] li ul.sub-nav {
    display:none;
    position:absolute;
    top:2.5em;
    left:-.75em;
    z-index:-1;
    box-shadow:0 1px 8px rgba(23,40,66,.5);
    border-right:1px solid #172842;
    border-bottom:1px solid #172842;
    border-left:1px solid #172842;
    padding-top:.5em;
    background-color:#ededf4;
}

[role=navigation] li:hover ul.sub-nav {
    display:block;
}

.sub-nav li {
    float:none;
    display:list-item;
    font-size:14px;
    font-size:.82rem;
    font-family:Helvetica,Arial,sans-serif;
    font-weight:400;
    min-width:150px;
    margin:0;
    text-shadow:none;
}

.sub-nav li:hover {
    background:#a1c336;
    text-shadow:none;
    box-shadow:none;
}

.sub-nav li a {
    padding:.5em .75em;
    color:#172842;
}

.sub-nav li a:hover {
    color:#fff;
}

#content {
    width: 100%;
    background-color: red;
    height: 100%;
    z-index: -2;
    position: relative;
}

#footer {
    width: 100%;
    background-color: blue;
    height: 100%;
}

/* group */
.group:after {
    content:".";
    display:block;
    clear:both;
    visibility:hidden;
    line-height:0;
    height:0;
    overflow:hidden;
    font-size:0;
}

.group {
    display:inline-block;
}

html[xmlns] .group {
    display:block;
}

* html .group {
    height:1%;
}


text:
Q: Add extra page in pdf when table doesn't fit in that page using Shield UI Export Pdf I am using ShieldUI for exporting HTML table to pdf. On using , my table content exceeds the page size height and rest of the contents are hidden from the page rather than displaying it in second page.
I want to move the rows that doesn't fit in that page to the next page.
Below is my code snippet:
<script>

jQuery(function ($) {
    $("#exportBt").click(function () {
        var dataSource = new shield.DataSource.create({
            data: "#admin-table",
            schema: {
                type: "table",
                fields: {
                    sno: {type: Number},
                    Name: {type: String},
                    Age: {type: Number},
                    Gender: {type: String},
                    Contact_Number: {type: Number},
                    Boarding_Point: {type: String},
                    Drop_Point:{type: String},
                    Seat_Number:{type: String}
                }
            }
        });

        dataSource.read().then(function (data) {
            var pdf = new shield.exp.PDFDocument({
                author: "PrepBootstrap",
                created: new Date()
            });

            pdf.addPage("a4", "potrait");
            pdf.table(
                    10,
                    10,
                    data,
                    [   {field: "sno", title: "#", width: 20},
                        {field: "Name", title: "Name", width: 100},
                        {field: "Age", title: "Age", width: 20},
                        {field: "Gender", title: "gender", width: 45},
                        {field: "Contact_Number", title: "Contact No", width: 82},
                        {field: "Boarding_Point", title: "Boarding Point", width: 100},
                        {field: "Drop_Point", title: "Drop Point", width: 100},
                        {field: "Seat_Number", title: "Seat No", width: 100}
                    ],
                    {
                        margins: {
                            top: 10,
                            left: 10
                        }
                    }
            );

            pdf.saveAs({
                fileName: "PrepBootstrapPDF"
            });
        });
    });
});
</script>

A: From what I can see in the code, I am not sure that this functionality is supported by the exporting mechanism.
What you can try instead is to toggle on paging when the grid is being shown on the page and then when exporting - disable the paging. This should show all records.

A: I try this code block. If you add the bottom margin, document will pass the second page.
    <script>

jQuery(function ($) {
    $("#exportBt").click(function () {
        var dataSource = new shield.DataSource.create({
            data: "#admin-table",
            schema: {
                type: "table",
                fields: {
                    sno: {type: Number},
                    Name: {type: String},
                    Age: {type: Number},
                    Gender: {type: String},
                    Contact_Number: {type: Number},
                    Boarding_Point: {type: String},
                    Drop_Point:{type: String},
                    Seat_Number:{type: String}
                }
            }
        });

        dataSource.read().then(function (data) {
            var pdf = new shield.exp.PDFDocument({
                author: "PrepBootstrap",
                created: new Date()
            });

            pdf.addPage("a4", "potrait");
            pdf.table(
                    10,
                    10,
                    data,
                    [   {field: "sno", title: "#", width: 20},
                        {field: "Name", title: "Name", width: 100},
                        {field: "Age", title: "Age", width: 20},
                        {field: "Gender", title: "gender", width: 45},
                        {field: "Contact_Number", title: "Contact No", width: 82},
                        {field: "Boarding_Point", title: "Boarding Point", width: 100},
                        {field: "Drop_Point", title: "Drop Point", width: 100},
                        {field: "Seat_Number", title: "Seat No", width: 100}
                    ],
                    {
                        margins: {
                            top: 10,
                            left: 10,
                            bottom: 10
                        }
                    }
            );

            pdf.saveAs({
                fileName: "PrepBootstrapPDF"
            });
        });
    });
});
</script>


text:
Q: setCoordinate updating after annotation added on my mapView Im adding a bunch of annotations, and sotirng them in an array so i can pull in their new locations and update the map accordingly WITHOUT removing all the annotations first and adding them which causes a flicker. Unfortunately, after their coordinates are initially set and added any setCoordinate call no longer works. Any ideas?
- (void)updateMap:(NSData *)responseData {
    //parse out the JSON data
    NSError* error;
    vehicleData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    //find which Dictionary is for our bus.
    for (NSDictionary* route in vehicleData) {
        //find our bus in our vehicles dictionary. Key is by routeID.
        BusPositionDot *busLocationDot;
        if ([vehicles objectForKey:[route objectForKey:@"RouteID"]] == nil) {
            busLocationDot = [[BusPositionDot alloc] init];
            [vehicles setObject:busLocationDot forKey:[route objectForKey:@"RouteID"]];
            [mapView addAnnotation:[vehicles objectForKey:[route objectForKey:@"RouteID"]]];

        }
        else {
            busLocationDot = [vehicles objectForKey:@"RouteID"];
        }

        float latitude = [[route objectForKey:@"Latitude"] floatValue];
        float longitude = [[route objectForKey:@"Longitude"] floatValue];
        float groundSpeed = [[route objectForKey:@"GroundSpeed"] floatValue];
        float direction = [[route objectForKey:@"Heading"] floatValue];

        float roundedDirection=45 * round(direction/45);

        if(groundSpeed<=3)
            //get view for annotation
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot.png"];
        else if((roundedDirection==0)||(roundedDirection==360))
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot0.png"];
        else if(roundedDirection==45)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot45.png"];
        else if(roundedDirection==90)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot90.png"];
        else if(roundedDirection==135)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot135.png"];
        else if(roundedDirection==180)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot180.png"];
        else if(roundedDirection==225)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot225.png"];
        else if(roundedDirection==270)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot270.png"];
        else if(roundedDirection==315)
            [mapView viewForAnnotation:busLocationDot].image=[UIImage imageNamed:@"buspositiondot315.png"];

        CLLocationCoordinate2D currentBusLocation = CLLocationCoordinate2DMake(latitude, longitude);
        NSLog(@"setting coord %f & %f",currentBusLocation.latitude,currentBusLocation.longitude);

        [UIView animateWithDuration:0.5 animations:^{
            [busLocationDot setCoordinate:currentBusLocation];

        }];
    }
}

A: In reference to this part:
if ([vehicles objectForKey:[route objectForKey:@"RouteID"]] == nil) {
    ...
    [mapView addAnnotation:
        [vehicles objectForKey:[route objectForKey:@"RouteID"]]];
}
else {
    busLocationDot = [vehicles objectForKey:@"RouteID"];
}

when you call addAnnotation, you pass:
[vehicles objectForKey:[route objectForKey:@"RouteID"]]

but if it already exists, you use:
[vehicles objectForKey:@"RouteID"]

This means when updating an annotation, a different (most likely wrong) reference is being used.
Either [vehicles objectForKey:@"RouteID"] is not actually a BusPositionDot or it's not the same instance that was originally added with that "route id".
Therefore, the setCoordinate wouldn't work.
Using the same reference when updating the annotation should fix it.

There are a couple of other unrelated, potential issues:

*

*The code is doing a direct comparison using a float variable (eg. if(roundedDirection==45)).  This is not recommended even if it "seems to work" -- there's the potential for floating-point precision errors.  Either check if roundedDirection is within a very small range of the target value or, in your case, just declare roundedDirection as an int since it looks like the expression
45 * round(direction/45) will only return values with no fractions.

*The code is setting the image of the annotation view directly.  This is ok but make sure the viewForAnnnotation delegate method also has the same exact logic to set the image based on direction otherwise what may happen is the annotation view's image will get reset to some default when panning or zooming.  You may need to add a direction property to BusPositionDot.


text:
Q: How to mock and test a UserDefaults computed property that store String? I am trying to mock UserDefaults to be able to test its behaviour.
What is the best way to do it without corrupting the real computed property that save the user token key?
class UserDefaultsService {

  private struct Keys {
    static let token = "partageTokenKey"
  }

  //MARK: - Save or retrieve the user token
  static var token: String? {
    get {
      return UserDefaults.standard.string(
        forKey: Keys.token)
    }
    set {
      UserDefaults.standard.set(
        newValue, forKey: Keys.token)
    }
  }
}

A: You can subclass UserDefaults :
(source)
class MockUserDefaults : UserDefaults {

  convenience init() {
    self.init(suiteName: "Mock User Defaults")!
  }

  override init?(suiteName suitename: String?) {
    UserDefaults().removePersistentDomain(forName: suitename!)
    super.init(suiteName: suitename)
  }

}

And in UserDefaultsService instead of directly accessing UserDefaults.standard you can create property based on the target that you are running. In production/staging you can have UserDefaults.standard and for testing you can have MockUserDefaults
You should add PREPROCESSOR Flag before using them
#if TESTING
    let userDefaults: UserDefaults = UserDefaults.standard
    #else
    let userDefaults: UserDefaults = MockUserDefaults(suiteName: "testing") ?? UserDefaults.standard
#endif

A: One way of doing it is to wrap your UserDefaults in a protocol and expose what you need.
Then you create a an actual class which conforms to that protocol and which uses UserDefaults
You can then instantiate your UserDefaultsService with that class.
When you need to test, you can create a mock conforming to the same protocol and use that instead. That way you won't "pollute" your UserDefaults.
The above might seem like a bit of a mouthful so lets break it down.
Note that in the above I removed the "static" part as well, it didn't seem necessary, and it made it easier without it, hope that is OK
1. Create a Protocol
This should be all you are interested in exposing
protocol SettingsContainer {
    var token: String? { get set }
}

2. Create an Actual Class
This class will be used with UserDefaults but it is "hidden" behind the protocol.
class UserDefaultsContainer {
    private struct Keys {
        static let token = "partageTokenKey"
    }
}

extension UserDefaultsContainer: SettingsContainer {
    var token: String? {
        get {
            return UserDefaults.standard.string(forKey: Keys.token)
        }
        set {
            UserDefaults.standard.set(newValue, forKey: Keys.token)
        }
    }
}

3. Instantiate UserDefaultsService With That Class
Now we create an instance of your UserDefaultsService which has an object conforming to the SettingsContainer protocol.
The beauty is that you can change the provided class later on...for instance when testing.
The UserDefaultsService does not know - or care - whatever the SettingsContainer actually does with the value, as long as it can give and take a token, then the UserDefaultsService is happy.
Here's how that looks, note that we are passing a default parameter, so we don't even have to pass a SettingsContainer unless we have to.
class UserDefaultsService {
    private var settingsContainer: SettingsContainer

    init(settingsContainer: SettingsContainer = UserDefaultsContainer()) {
        self.settingsContainer = settingsContainer
    }

    var token: String? {
        get {
            return settingsContainer.token
        }
        set {
            settingsContainer.token = newValue
        }
    }
}

You can now use a new UserDefaultsService like so:
let userDefaultsService = UserDefaultsService()
print("token: \(userDefaultsService.token)")

4 Testing
"Finally" you say :)
To test the above, you can create a MockSettingsContainer conforming to the SettingsContainer
class MockSettingsContainer: SettingsContainer {
    var token: String?
}

and pass that to a new UserDefaultsService instance in your test target.
let mockSettingsContainer = MockSettingsContainer()
let userDefaultsService = UserDefaultsService(settingsContainer: mockSettingsContainer)

And can now test that your UserDefaultsService can actually save and retrieve data without polluting UserDefaults.
Final Notes
The above might seem like a lot of work, but the important thing to understand is:

*

*wrap 3rd party components (like UserDefaults) behind a protocol so you are free to change them later on if so needed (for instance when testing).

*Have dependencies in your classes that uses these protocols instead of "real" classes, that way you - again - are free to change the classes. As long as they conform to the protocol, all is well :)

Hope that helps.

A: A very good solution is to not bother creating a mock or extracting a protocol. Instead init a UserDefaults object in your tests like this:
let userDefaults = UserDefaults(suiteName: #file)
userDefaults.removePersistentDomain(forName: #file)

Now you can go ahead and use the UserDefaults keys you already have defined in an extension and even inject this into any functions as needed! Cool. This will prevent your actual UserDefaults from being touched.
Brief article here

A: Instead of mocking UserDefaults, you should check the value you persist in UserDefaults, should get retrieved from the same user defaults by accessing using same key. the test case should look like this.
func testWhenTokenIsSavedInUserDefaults_ReturnSameTokenAndVerify {
  let persistenceService = UserDefaultsService()
  persistenceService.token = "ABC-123"

  let defaults = UserDefaults.standard
  let expectedValue = defaults.value(forKey: "partageTokenKey")

  XCTAssertEquals(persistenceService.token, expectedValue)
}


text:
Q: Sakuli Test sometimes gives 503 (Service temporarily unavailable) error Test result is in OK status but this error appears on the screen .Can someone help what needs to be cheked?
Error : Error in testcase Form-test

Cannot find Element within 3000ms by query:
Locator: By(css selector, span)
identifier: Jetzt anfordern
relations:
Wait timed out after 3119ms
TimeoutError: Cannot find Element within 3000ms by query:
Locator: By(css selector, span)
identifier: Jetzt anfordern
relations:
Wait timed out after 3119ms
at /headless/sakuli/sakuli-v2.3.0/node_modules/selenium-webdriver/lib/webdriver.js:841:17

A: "Service temp. unavailable" is usually thrown by a server, and means there is an issue with the server serving the request. Also see 503.
So in my opinion, this has nothing to do with Sakuli. With this server error, sakuli doesn´t find your identifier "Jetzt anfordern" as it clearly is not there. Test should be red and you should be informed about this server issue.
Unless I did not understood your question.. In this case, please describe in more detail what is happening.


text:
Q: CD/DVD drive won't operate after installing Linux I'm not sure if this problem is related to installing Linux, but I have a Dell desktop from many years ago (I can look up the model number if it's important) on which I installed Bodhi Linux a few years ago before preparing to sell/give the system away. I recently got an extra monitor and was rechecking the system to see if it was still working. I had to replace the system battery, but then it seemed happy.
However, I wanted to see if I could install Windows XP off the disc that came with the system and I can't even get the drive to open without a paperclip. When I look in the CMOS setup utility at the boot sequence, it lists the optical drive as "not installed". Was there possibly a partition on the hard drive with optical drivers that got deleted when Linux was installed? I know when I tell the boot menu to boot to the utility partition, it boots to the same default Linux installation instead.
Is there any way to get this drive working again? I suspect if I plugged in an Ethernet cable I would be able to connect to the internet with Linux. The system also has a 3.5" drive, BTW.

A: This is a hardware fault. There are 2 implied indicators in your post -

*

*Its not showing in BIOS - BIOS is separate to and loaded before Linux. If the drive is not found here, the computer does not recognise its existence, and this has nothing to do with hard drive partitions.

*(This may be irrelevant on CD drives without a button on the front, but most old desktop PCs have one). Pushing the eject button should work regardless of the state of the OS.
It might be that the power cable has become dislodged/partially dislodged. I might be inclined to open the PC and reseat the power cable.


text:
Q: Como puedo bloquear un usuario al 3 intento ¿Como puedo bloquear un usuario al 3 intento?
Estoy haciendo un login de usuario y contraseña. Me piden que si un usuario hizo 3 intentos fallidos para loguearse se le bloquee la cuenta, según la función en JavaScript tendría que bloquear al usuario después de 3 intentos fallidos, pero el bucle solo se queda en "Te restan 2 intentos" y aunque me vuelva a equivocar solo se queda en "Te restan 2 intentos".

A: Tu error es porque tienes una variable que siempre declaras en 3 cuando se llama la función iniciarsesion.
Lo que tienes que cambiar es el código a esta manera:
var saldoPrincipal = 2500.00;
var conteo = 3;

function iniciarsesion(){
user = .... //Tu código
pass = ... //Tu código

//conteo = 3 -- Tienes que eliminar esto de la función y colocarlo arriba como está en el ejemplo

De esa manera irá bajando hasta llegar a 0.
Espero te sirva la respuesta.


text:
Q: JPQL issue resolving nodes of a collection to compare in query I have a book entity which has a OneToMany relationship set up to Document entity.  In other words, in Hibernate, my book entity returns a list of Documents as the property docs.
I want to return a list of documents for a user which have not been assigned to a book, yet.  Here is my jpql query, and I've finagled it every way I can, and I can't get it to work:
select d from Document d WHERE d.user = :user
AND NOT EXISTS( SELECT b.docs from Book b WHERE b.docs = d )

Where Book is an entity, User is an entity passed in, b.docs is a list of Documents, and Document(d) is an entity.
What am I doing wrong?  With this particular version of the query, I'm receiving the error:

org.hibernate.TypeMismatchException: left and right hand sides of a binary logic
  operator were incompatibile
  [java.util.Collection(com.fallenjusticestudios.bardwalk.model.Book.docs) : com.fallenjusticestudios.bardwalk.model.Document]

Book:
@Entity
@Table(name="book")
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column
    @NotEmpty
    @NotNull
    private String title;

    @Column
    @NotEmpty
    @NotNull
    private String description;

    @ManyToOne(cascade=CascadeType.MERGE, targetEntity=User.class)
    @JoinColumn(name="user")
    private User user;

    @OneToMany(cascade=CascadeType.MERGE, fetch=FetchType.LAZY, targetEntity=Document.class)
    @JoinColumn(name="document_id",referencedColumnName="id")
    private List<Document> docs;

    // Will need to add Contest to the fields later on.
    //
    //

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public User getUser() {
        return user;
    }

    public List<Document> getDocs() {
        return docs;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setDocs(List<Document> docs) {
        this.docs = docs;
    }

}

UPDATE:
Another try:
Query:
select d from Document d WHERE d.user = :user
AND NOT EXISTS( SELECT Document from Book.docs b WHERE b.id = dn.id )

org.hibernate.hql.ast.QuerySyntaxException: Book.docs is not mapped [select d from com.fallenjusticestudios.bardwalk.model.Document d WHERE d.user = :user AND NOT EXISTS( SELECT Document from Book.docs b WHERE b.id = dn.id)]

UPDATE2:
I figured this out.  I was going about the query all wrong.  Solution query was:
select d from Document d WHERE d.user = :user
AND NOT d IN( SELECT d from Book b, IN(b.docs) bd WHERE bd.id = d.id )

A: I figured this out. I was going about the query all wrong. Solution query was:
select d from Document d WHERE d.user = :user
AND NOT d IN( SELECT d from Book b, IN(b.docs) bd WHERE bd.id = d.id )


text:
Q: gRPC generated code misses service implementation Following the tutorial I successfully generated the code I expected with protocol buffers:
protoc service.proto --proto_path="../proto/" --cpp_out="../cxx/gen/" --plugin=protoc-gen-grpc=`which grpc_cpp_plugin`

The models are generated as usable classes without error, but the service implementation differs from the one described in the above tutorial. The proto file looks like this:
syntax = "proto3";
option cc_enable_arenas = true;
option cc_generic_services = true;

package my_package;

message Service_slot{...}

message Slot_status{...}

message Slot_request{...}

message Service_slot{...}

service My_service{
  rpc add_slot(Service_slot) returns (Slot_status) {}
  rpc update_slot(Service_slot) returns (Slot_status) {}
  rpc request_action(Slot_request) returns (Slot_status) {}
}

What I could identify as a service looks like this(in service.pb.h):
class My_service: public ::google::protobuf::Service {
 protected:
  // This class should be treated as an abstract interface.
  inline My_service() {};
 public:
  virtual ~My_service();

  typedef My_service_Stub Stub;

  static const ::google::protobuf::ServiceDescriptor* descriptor();

  virtual void add_slot(::google::protobuf::RpcController* controller,
                       const ::my_package::Service_slot* request,
                       ::my_package::Slot_status* response,
                       ::google::protobuf::Closure* done);
  //... (others left out for clairty)
 private:
  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(My_service);
};

but it's nothing like what' described in the tutorial. Not even sure how to provide those arguments.
I've done this in Java, and there the server I implemented was based on a classname ending with grpc, but I found nothing like this here.

*

*What have I found, and how can I understand it? I believe this must be a base service implementation, and the actual server I need to implement is not here.

*Maybe I generated the proto files wrong? What can I do to correct it?

A: I was missing the --grpc_out="../cxx/gen" argument.
With the command
protoc service.proto --proto_path="../proto/" --cpp_out="../cxx/gen/" --grpc_out="../cxx/gen --plugin=protoc-gen-grpc=`which grpc_cpp_plugin`

The service code now generates into the service.grpc.pb.cc file.


text:
Q: How to get a single solution by simultaneously solving three equations with three variables? I'm trying to solve the following three equations having three variables.
ClearAll;
Clear[R2, R3, R4, r2, r3, r4, L2, L3, L4, L5];
L2 = 1.0; L3 = 2.0; L4 = 3.0; L5 = 30.0;
Do[Do[Do[Print[
FindRoot[
 2 (1 + R4 L4) ( (1 + R4 L4)^0.5  (1 - 1/R2) + ((1 + R4 L4)/(
        1 + R2 L2))^0.5 (1/R2 - 1/R3) + ((1 + R4 L4)/(
        1 + R3 L3))^0.5 (1/R3 - 1/R4) + 1/R4  ) - L5 == 0
&& 2 (1 +
  R4 L4) ( (1 + R4 L4)^1.5  (1 - 1/R2) + ((1 + R4 L4)/(
    1 + R2 L2))^1.5 (1/R2 - 1/R3) + ((1 + R4 L4)/(
    1 + R3 L3))^1.5 (1/R3 - 1/R4) + 1/R4  ) - 3 L5 == 0
&& 2 (1 +
  R4 L4) ( (1 + R4 L4)^2.5  (1 - 1/R2) + ((1 + R4 L4)/(
    1 + R2 L2))^2.5 (1/R2 - 1/R3) + ((1 + R4 L4)/(
    1 + R3 L3))^2.5 (1/R3 - 1/R4) + 1/R4  ) - 5 L5 == 0
, {{R2, 1.0}, {R3, 1.0}, {R4, 1.0}}]], {r2, 0.879, 1.0, 0.1}], {r3,
  0.9, 1.0, 0.1}], {r4, 0.9, 1.0, 0.1}]

The output:
    FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal but could not find a sufficient decrease in the merit function. You may need more than MachinePrecision digits of working precision to meet these tolerances. >>

{R2->0.898056,R3->3.10929,R4->1.13828}

FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal but could not find a sufficient decrease in the merit function. You may need more than MachinePrecision digits of working precision to meet these tolerances. >>

{R2->0.898056,R3->3.10929,R4->1.13828}

FindRoot::lstol: The line search decreased the step size to within tolerance specified by AccuracyGoal and PrecisionGoal but could not find a sufficient decrease in the merit function. You may need more than MachinePrecision digits of working precision to meet these tolerances. >>

General::stop: Further output of FindRoot::lstol will be suppressed during this calculation. >>

{R2->0.898056,R3->3.10929,R4->1.13828}

{R2->0.898056,R3->3.10929,R4->1.13828}

{R2->0.898056,R3->3.10929,R4->1.13828}

{R2->0.898056,R3->3.10929,R4->1.13828}

{R2->0.898056,R3->3.10929,R4->1.13828}

{R2->0.898056,R3->3.10929,R4->1.13828}

As one can observe, there are multiple values of {R2, R3, R4} corresponding to the different values of r2,r3, and r4. Is it possible to get a single set of values for {R2, R3, R4}? If yes, then what is the best way to achieve it?
The journal paper that I'm following had a solution of {R2, R3, R4} = {0.9066, 2.1798, 1.2204}.
Thank you so much in advance. I'll appreciate your help.
It would be also helpful if you can provide a link to an answer to a similar kind of problem.

A: Clear["Global`*"]

$Version

(* "12.3.1 for Mac OS X x86 (64-bit) (June 19, 2021)" *)

Use exact values when possible:
L2 = 1; L3 = 2; L4 = 3; L5 = 30;

eqns = {2 (1 +
          R4 L4) ((1 + R4 L4)^0.5 (1 -
             1/R2) + ((1 + R4 L4)/(1 + R2 L2))^0.5 (1/R2 -
             1/R3) + ((1 + R4 L4)/(1 + R3 L3))^0.5 (1/R3 - 1/R4) +
          1/R4) - L5 == 0,
     2 (1 +
          R4 L4) ((1 + R4 L4)^1.5 (1 -
             1/R2) + ((1 + R4 L4)/(1 + R2 L2))^1.5 (1/R2 -
             1/R3) + ((1 + R4 L4)/(1 + R3 L3))^1.5 (1/R3 - 1/R4) +
          1/R4) - 3 L5 == 0,
     2 (1 +
          R4 L4) ((1 + R4 L4)^2.5 (1 -
             1/R2) + ((1 + R4 L4)/(1 + R2 L2))^2.5 (1/R2 -
             1/R3) + ((1 + R4 L4)/(1 + R3 L3))^2.5 (1/R3 - 1/R4) +
          1/R4) - 5 L5 == 0} // Rationalize // Simplify;

sol = Sort /@ NSolve[eqns, {R2, R3, R4}, PositiveReals]

(* {{R2 -> 0.85298, R3 -> 8.49764, R4 -> 2.27966}, {R2 -> 0.893403,
  R3 -> 2.66003, R4 -> 2.70195}, {R2 -> 0.893874, R3 -> 0.448215,
  R4 -> 2.69833}} *)

Verifying,
(#[[1]] - #[[-1]] & /@ eqns) /. sol // Chop

(* {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}} *)


text:
Q: ODP.NET : Error while executing create- select- alter- select or create - select - drop - create - select I am using ODP.NET for a project. It requires writing queries and executing it from a web interface.
Problem Statement:- When I create a table and then do some insertion and then selecting the data. Till now every thing works fine.Now I alter the table structure by adding one or more columns and firing the select query. It shows exception- Index out of the bounds if I had altered table by adding some columns while shows variable not found in select list if i drop some column while altering the table. While in actual I am simply using select * from table.
I thought it may be related to some statement caching by dot net. So I used connection.PurgeStatementCache. But it has also not worked. Please guide me through this problem.


text:
Q: Maven: How to verify that the BOM is valid? If I have a BOM (Bill of Materials) for Maven that is stored in its own separate repository, how can I verify that the file is valid? For instance, the dependencies listed should correspond to valid dependencies in Artifactory (or any binaries server) and the versions should be valid versions. The BOM shouldn't be asking for a version that doesn't exist.
I thought about just creating a blank Maven project and attaching the BOM as that project's POM file, since when you run Maven install, it should fetch dependencies from the specified server and in doing so, check that those dependencies exist. However, running that command doesn't do anything - it just says Build Succeeded, even when I type in invalid versions (ie. v100000000000).


text:
Q: Button for a webview android i was wondering is it possible to add a button below a webview such that on clicking it, it should flip and give another webpage and so on, maybe a back button to return to the previous webpage, Can we make such changes in the layout> if so how? Coz whenever I wrote TabHost program for webview, upon selecting the tab,it would fill the entire page hiding the tabs,
I want to create a combination of ViewFlipper, WebView and Button

A: Make a layout with a flipper.
In your code, try

WebView myWebView1 = ...;
WebView myWebView2 = ...;
Flipper myFlipper = (Flipper)(findViewById(R.id_myflipper);
myFlipper.addView(myWevView1);
myFlipper.addView(myWebView2)
when you press your button, change the current view in the flipper by
myFlipper.setDisplayedChild(flipperID);

Where flipperID is the index of the view you want to show.


text:
Q: Automatic creation of parameters with the SqlDataSource Control I've recently converted an existing web application from 3.5 to framework 4.0 and noticed a page stopped working - with an "incorrect number of parameters" error.
Page is fairly simple and has a SQLDataSource Control with 3 explicit update parameters:

However there is a textbox on page which is read only, but is set to Bind to another field in datasource - which means auto creation of parameters now expects 4 update parameters.
I have set Bind to Eval to overcome this problem, but I'm worried that this bad practice wasn't picked up in production version running on 3.5.
My question is:  Automatic creation of parameters isn't something that was introduced in framework 4.0 - so is it just a case of stricter enforcement of rules causing this to be picked up now?
Worried in case there are other instances of this within web app...


text:
Q: Precision level of numeric luminosity sensor on GPIO Raspberry Pi I just got shipped a Luminosity sensor today.
I want to write in nodejs a function that get live data from it(using the "onoff" package).
I manage to do it, here is the code,

"use strict";

var Gpio = require('onoff').Gpio,
    pr = new Gpio(4, 'in'),
    readInterval = setInterval(getPrValue, 25);

function getPrValue(){
    console.log("Value of photo resistance : "+pr.readSync());
}

process.on('SIGINT', function(){
    clearInterval(readInterval);
    pr.unexport();
});

(For info I plugged the "VCC" pin directly in 3.3V GPIO pin, i plugged the GND in one of the GND GPIO pin, and the other pin to plug is called "DO" and I plugged it on the GPIO pin 4 !
But the problem is that I get only 0 and 1 from it. I thought I would get a value between 0.00000 and 1 you know ?
So my question is ; is there any way to get a precise value of the ambient luminosity or the little things I got just send 1 and 0 ?
Hope someone can help me. Have a nice day

A: It is not possible to get a better data than 0 or 1. Since the DO only send to state


text:
Q: RuntimeException when running rebuildData.php I upgraded my MW from 1.31 to 1.33 and SMW from 2.5.6 to 3.1 by following the official tutorials. Everything works fine until Step 6 when I run rebuildData.php to rebuild the data and it throws an exception after about 10000 updates. Here is the exception message:
... updating 10281     [S: User:Reddgamer]
[d55bfb09d717f88aa3e7da6e] [no req]   RuntimeException from line 58 of /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/SQLStore/Lookup/SingleEntityQueryLookup.php: Expected a ValueDescription instance!
Backtrace:
#0 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/includes/query/SMW_QueryProcessor.php(338): SMW\SQLStore\Lookup\SingleEntityQueryLookup->getQueryResult(SMWQuery)
#1 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/ParserFunctions/AskParserFunction.php(364): SMWQueryProcessor::getResultFromQuery(SMWQuery, array, integer, integer)
#2 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/ParserFunctions/AskParserFunction.php(197): SMW\ParserFunctions\AskParserFunction->doFetchResultsFromFunctionParameters(array, array)
#3 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/ParserFunctions/ShowParserFunction.php(45): SMW\ParserFunctions\AskParserFunction->parse(array)
#4 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/ParserFunctionFactory.php(428): SMW\ParserFunctions\ShowParserFunction->parse(array)
#5 /home/example/public_html/dev.example.com/wiki/includes/parser/Parser.php(3528): SMW\ParserFunctionFactory->SMW\{closure}(Parser, string, string)
#6 /home/example/public_html/dev.example.com/wiki/includes/parser/Parser.php(3235): Parser->callParserFunction(PPFrame_DOM, string, array)
#7 /home/example/public_html/dev.example.com/wiki/includes/parser/Preprocessor_DOM.php(1285): Parser->braceSubstitution(array, PPFrame_DOM)
#8 /home/example/public_html/dev.example.com/wiki/includes/parser/Parser.php(3152): PPFrame_DOM->expand(DOMElement)
#9 /home/example/public_html/dev.example.com/wiki/includes/parser/Preprocessor_DOM.php(1285): Parser->braceSubstitution(array, PPFrame_DOM)
#10 /home/example/public_html/dev.example.com/wiki/includes/parser/Parser.php(3049): PPFrame_DOM->expand(DOMElement, integer)
#11 /home/example/public_html/dev.example.com/wiki/includes/parser/Parser.php(1359): Parser->replaceVariables(string)
#12 /home/example/public_html/dev.example.com/wiki/includes/parser/Parser.php(491): Parser->internalParse(string)
#13 /home/example/public_html/dev.example.com/wiki/includes/content/WikitextContent.php(369): Parser->parse(string, Title, ParserOptions, boolean, boolean, integer)
#14 /home/example/public_html/dev.example.com/wiki/includes/content/AbstractContent.php(555): WikitextContent->fillParserOutput(Title, integer, ParserOptions, boolean, ParserOutput)
#15 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/includes/ContentParser.php(186): AbstractContent->getParserOutput(Title, integer, ParserOptions, boolean)
#16 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/includes/ContentParser.php(145): SMW\ContentParser->fetchFromContent()
#17 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/MediaWiki/Jobs/UpdateJob.php(197): SMW\ContentParser->parse()
#18 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/MediaWiki/Jobs/UpdateJob.php(137): SMW\MediaWiki\Jobs\UpdateJob->parse_content()
#19 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/MediaWiki/Jobs/UpdateJob.php(94): SMW\MediaWiki\Jobs\UpdateJob->doUpdate()
#20 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/SQLStore/Rebuilder/Rebuilder.php(237): SMW\MediaWiki\Jobs\UpdateJob->run()
#21 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/Maintenance/DataRebuilder.php(423): SMW\SQLStore\Rebuilder\Rebuilder->rebuild(integer)
#22 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/Maintenance/DataRebuilder.php(349): SMW\Maintenance\DataRebuilder->do_update(integer)
#23 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/src/Maintenance/DataRebuilder.php(200): SMW\Maintenance\DataRebuilder->rebuild_all()
#24 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/maintenance/rebuildData.php(202): SMW\Maintenance\DataRebuilder->rebuild()
#25 /home/example/public_html/dev.example.com/wiki/maintenance/doMaintenance.php(96): SMW\Maintenance\RebuildData->execute()
#26 /home/example/public_html/dev.example.com/wiki/extensions/SemanticMediaWiki/maintenance/rebuildData.php(261): require_once(string)
#27 {main

Does someone know why this is happening and how I could get it sorted out?

A: I created the bug report for you: smw issue 4349


text:
Q: Custom query - get_the_terms not work I want to to show my customer works in a slide
This is my query to show these works.
I want to obtain the term of the taxonomy "idm_real_tax" for each custom type record.
$query = new WP_Query($criterias);
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        $posts[] = array(
            "id" => $query->post->ID,
            "permalink" => get_permalink($query->post->ID),
            "title" => $query->post->post_title,
            "excerpt" => $query->post->post_excerpt,
            "thumbnail" => get_the_post_thumbnail($query->post->ID , "carrousel-realisation"),
            "pager_thumbnail" => get_the_post_thumbnail($query->post->ID , "thumbnail", array( 'class' => 'img-thumbnail img-responsive' )),
            // "term_single" => get_the_terms( $query->$post->id, "idm_real_tax" ),
        );
    }

The problem is this line, that I commented :
"term_single" => get_the_terms( $query->$post->id, "idm_real_tax" ),

A: I'm not sure exactly how you want 'term_single' formatted, but you can amend the below as required if it's not quite what you are looking for.
I'd also suggest not using the name $posts for your array, as I believe that WP has a global of the same name, so it could cause funkyness that is undesirable.
Finally, as you were in The Loop you can use simple functions to get all of the info that you require (ID, name, etc.) - check out the Codex.
$query = new WP_Query($criterias);
if($query->have_posts()) : while ($query->have_posts()) : $query->the_post();

        /** Get all terms (as objects) from the 'idm_real_tax' taxonomy that are associated with this Post */
        $terms = get_the_terms(get_the_ID(), 'idm_real_tax');

        /** Check that '$terms' is not empty */
        if($terms && !is_wp_error($terms)) :    // It's not...

            $term_names = array();  // Pre-stage to avoid errors

            /** Loop through each term object and add just the name to the '$term_names' array */
            foreach($terms as $term) :
                $term_names[] = $term->name;
            endif

            /** Join all of the term names together to make a comman seperated string of term names */
            $term_names_string = (!empty($term_names)) ? join(", ", $term_names) : '';

        endif;

        $my_posts[] = array(
            'id'                => get_the_ID(),
            'permalink'         => get_permalink(),
            'title'             => get_the_title(),
            'excerpt'           => get_the_excerpt(),
            'thumbnail'         => get_the_post_thumbnail(get_the_ID(), 'carrousel-realisation'),
            'pager_thumbnail'   => get_the_post_thumbnail(get_the_ID(), 'thumbnail', array('class' => 'img-thumbnail img-responsive')),
            'term_single'       => $term_names
        );

    endwhile;
endif;


text:
Q: xorriso created ISO boots in VirtualBox but not physical laptop I have created a modified Ubuntu 22.04 ISO image from recent desktop ISO images.  It boots and installs correctly as an ISO in a new VirtualBox VM (if I don't enable UEFI); however, my relatively new laptop will not boot from a USB stick formatted with my modified ISO, although it recognizes and installs from the original Ubuntu 22.04 ISO image.  I imagine I am misusing xorriso, but do not understand it well enough to discover my error.  What am I doing wrong?
xorriso reports the following details for the original Ubuntu 22.04 desktop ISO:
$  xorriso -indev jammy-desktop-amd64.iso -report_el_torito as_mkisofs
xorriso 1.5.4 : RockRidge filesystem manipulator, libburnia project.

xorriso : NOTE : Loading ISO image tree from LBA 0
xorriso : UPDATE :     963 nodes read in 1 seconds
libisofs: NOTE : Found hidden El-Torito image for EFI.
libisofs: NOTE : EFI image start and size: 2007921 * 2048 , 8496 * 512
xorriso : NOTE : Detected El-Torito boot information which currently is set to be discarded
Drive current: -indev 'jammy-desktop-amd64.iso'
Media current: stdio file, overwriteable
Media status : is written , is appendable
Boot record  : El Torito , MBR protective-msdos-label grub2-mbr cyl-align-off GPT
Media summary: 1 session, 2010211 data blocks, 3926m data, 1117g free
Volume id    : 'Ubuntu 22.04.1 LTS amd64'
-V 'Ubuntu 22.04.1 LTS amd64'
--modification-date='2022080117275700'
--grub2-mbr --interval:local_fs:0s-15s:zero_mbrpt,zero_gpt:'jammy-desktop-amd64.iso'
--protective-msdos-label
-partition_cyl_align off
-partition_offset 16
--mbr-force-bootable
-append_partition 2 28732ac11ff8d211ba4b00a0c93ec93b --interval:local_fs:8031684d-8040179d::'jammy-desktop-amd64.iso'
-appended_part_as_gpt
-iso_mbr_part_type a2a0d0ebe5b9334487c068b6b72699c7
-c '/boot.catalog'
-b '/boot/grub/i386-pc/eltorito.img'
-no-emul-boot
-boot-load-size 4
-boot-info-table
--grub2-boot-info
-eltorito-alt-boot
-e '--interval:appended_partition_2_start_2007921s_size_8496d:all::'
-no-emul-boot
-boot-load-size 8496

And, I create the new ISO using most of the same arguments:
$ xorriso -as mkisofs -o my-modified-ubuntu-22.04.iso \
    -V 'Modified Ubuntu 22.04 amd64' \
    --grub2-mbr --interval:local_fs:0s-15s:zero_mbrpt,zero_gpt:'jammy-desktop-amd64.iso' \
    --protective-msdos-label \
    -partition_cyl_align off \
    -partition_offset 16 \
    --mbr-force-bootable \
    -append_partition 2 28732ac11ff8d211ba4b00a0c93ec93b \
    --interval:local_fs:7129428d-7137923d::'jammy-desktop-amd64.iso' \
    -appended_part_as_gpt -iso_mbr_part_type a2a0d0ebe5b9334487c068b6b72699c7 \
    -c '/boot.catalog' \
    -b '/boot/grub/i386-pc/eltorito.img' \
    -no-emul-boot \
    -boot-load-size 4 \
    -boot-info-table \
    --grub2-boot-info \
    -eltorito-alt-boot \
    -e '--interval:appended_partition_2_start_1782357s_size_8496d:all::' \
    -no-emul-boot \
    -boot-load-size 8496 \
    <SRC_DIR>

My <SRC_DIR> is an overlay that uses the original ISO as its base, but I modify the following files in its root:

*

*/casper/filesystem.squashfs

*/casper/filesystem.manifest

*/casper/filesystem.size

*/md5sum.txt

*/preseed/ubuntu.seed
All other files and ISO contents are identical to the original.
I'm confident the ISO is almost good, because it works well in VirtualBox, exhibiting the desired modifications, but I cannot coerce my laptop to see it and boot from it, even though it will boot from the original Ubuntu 22.04 desktop ISO.  :(
I am working on the same laptop with Ubuntu 22.04 desktop, installed from the original upstream ISO.
And, I created the USB key using:
$ dd bs=4M \
    if=/home/me/my-modified-ubuntu-22.04.iso \
    of=/dev/sda \
    status=progress \
    oflag=sync

$ xorriso --version
xorriso 1.5.4 : RockRidge filesystem manipulator, libburnia project.

xorriso 1.5.4
ISO 9660 Rock Ridge filesystem manipulator and CD/DVD/BD burn program
Copyright (C) 2019, Thomas Schmitt <scdbackup@gmx.net>, libburnia project.
xorriso version   :  1.5.4
Version timestamp :  2021.01.30.150001
Build timestamp   :  -none-given-
libisofs   in use :  1.5.4  (min. 1.5.4)
libjte     in use :  2.0.0  (min. 2.0.0)
libburn    in use :  1.5.4  (min. 1.5.4)
libburn OS adapter:  internal GNU/Linux SG_IO adapter sg-linux
libisoburn in use :  1.5.4  (min. 1.5.4)
Provided under GNU GPL version 3 or later, due to libreadline license.
There is NO WARRANTY, to the extent permitted by law.

A: The xorriso run looks ok. I tried with mounted ubuntu-22.04-desktop-amd64.iso
as SRC_DIR and then let xorriso report its boot equipment. The only significant
differences are the volume id (-V) and the --modification-date. Both could be
theoretically needed for GRUB or the booting system to find the ISO. But you
should at least see some message text from GRUB if it fails to find its ISO,
and it should not work better in VirtualBox than on real iron.
Secure Boot comes to my mind as potential source of problems. But i don't
know enough of it to propose experiments, except that you could try to
disable it in the laptop's EFI.
The only other experiment idea i have is that you try whether it works if you
avoid the overlay filesystem and simply repack the ISO with its original
file content.
(If you post results here and receive no reply from me, send mail to
bug-xorriso@gnu.org)

Update after answer by Trevor:
So probably VirtualBox booted via BIOS, not via EFI.

I wish there was some way to automatically pull those offsets :

xorriso in its native command mode can load an ISO, manipulate the loaded
ISO model, and write a new ISO from the data in the old ISO and the changes.
The cumbersome numbers will stay hidden.
See the xorriso run at the end of
https://dev.lovelyhq.com/libburnia/libisoburn/raw/branch/master/test/merge_debian_isos
or the end of my answer to
How to create bootable ISO from custom Ubuntu 22.04 Image?
Essential are -indev, -outdev, and -boot_image "any" "replay".

A: @Thomas, the problem was that the location of the reused partitions in the original ISO had shifted position during development, and I had not noticed.  I needed to update the byte offsets.  Please see:
@@ -144,7 +144,7 @@ Makefile
                -partition_cyl_align off \
                -partition_offset 16 \
                --mbr-force-bootable \
-               -append_partition 2 28732ac11ff8d211ba4b00a0c93ec93b --interval:local_fs:7129428d-7137923d::'jammy-desktop-amd64.iso' \
+               -append_partition 2 28732ac11ff8d211ba4b00a0c93ec93b --interval:local_fs:8031684d-8040179d::'jammy-desktop-amd64.iso' \
                -appended_part_as_gpt -iso_mbr_part_type a2a0d0ebe5b9334487c068b6b72699c7 \
                -c '/boot.catalog' \
                -b '/boot/grub/i386-pc/eltorito.img' \
@@ -152,7 +152,7 @@ Makefile
                -boot-load-size 4 \
                -boot-info-table \
                --grub2-boot-info \
-               -eltorito-alt-boot -e '--interval:appended_partition_2_start_1782357s_size_8496d:all::' \
+               -eltorito-alt-boot -e '--interval:appended_partition_2_start_2007921s_size_8496d:all::' \
                -no-emul-boot \
                -boot-load-size 8496 \
                iso/overlay

It works now.  I should have paid closer attention to the xorriso report output while posting the question.  Sorry for the distraction.
I wish there was some way to automatically pull those offsets instead of hard-coding them.  But, I think that's a question for another day?  :)


text:
Q: virtual pbx using x-lite stuck at offline I am using x-lite to connect to virtualpbx.net. One of my user's x-lite is stuck at offline and the availability dropdown box is grayed out. I don't see any error messages in x-lite or virtualpbx.net. He can still make outgoing calls.
I didn't setup this system and don't know much about VOIP phones, etc. Everytime I google x-lite or virtualpbx i get sales pages. I've looked at https://support.counterpath.com/ but don't see anything there.

A: *

*In X-lite

*Softphone -> Account Settings

*Under "Allow this account for"

*Check "IM / Presence"

I can't believe this took me so long to figure out but I also can't believe I couldn't find an answer to this anywhere.


text:
Q: pubnub.publish message string format I tried to publish message writing code,
MyService.pubnub.publish().channel("birdpeek").message("{"rlysw":{"0":1}}").async(new PNCallback<PNPublishResult>()

But the android returns error by turning red

I even put \" and it turns green out of blue but problem is what got on pubnub console the message is Sat Nov 12 2016 18:57:40:592 : <birdpeek> "{\"rlysw\":{\"0\":1}}".
What proper statement i should have inserted i need advise. And here's the json object i wanna publish,
{"rlysw":{"1":0}}

A: You should just publish the json object. The SDK will do the conversion on the hood for you. Use the following code to properly build the object.
Map<String, Map<String, Object>> payload = new HashMap<>();
Map<String, Object> innerPayload = new HashMap<>();
innerPayload.put("0", 1);
payload.put("rlysw", innerPayload);

Eric


text:
Q: Zoom into the content of a single cell in a UICollectionView I am trying to achieve the same behaviour as in the Photos app when one image is open in full screen; i.e., I want to be able to scroll between my different images and also to pinch to zoom in any of them. As in the Photos app, after I have zoomed into a particular image, I would like to be able to scroll between the different images of my gallery.
My situation is as follows: I have a UICollectionView, a custom UICollectionViewFlowLayout where the itemSize is set to be the size of the screen, and a custom UICollectionViewCell that has an UIImageView. That works just fine scrolling through the different photos, the problem is scrolling into them.
The first approach I tried is the one depicted in the WWDC 2012 session: 'Advanced Collection Views and Building Custom Layouts'. The effect one gets with this approach is the cell scaling properly but then it will overlap with the cells next to it creating an undesirable effect.
The second approach is like the one suggested in WWDC 2010 session: 'Designing Apps with Scroll Views'. However, I am not entirely sure this approach would work having a UICollectionView instead of a UIScrollView + subviews. I set my view controller as the UIScrollViewDelegate and override viewForZoomingInScrollView: where I return the UIImageView of the visible cell at that given point. Nothing happens if I do that. I have also tried returning the cell and in that case the whole layout of the UICollectionView is messed up. I have taken a look at the sample project Apple put together (PhotoScroller) that successfully implements what I want, but in there they just have a UIImageView as a subview of the UIScrollView.
I think that in order to implement the Photos app behaviour with a UICollectionView, I need to do that by going with the first approach and modifying the layout attributes of the other cells in my collection view and not only the one being zoomed in.
That sounds like a quite low level solution to me and I was wondering if somebody is aware of a better approach to this problem.

A: After a few more days investigating this, I came up with a solution where I had to make some compromises but it is acceptable for my requirements.
What I ended up doing is to have a UIScrollView as the top-most view of my custom UICollectionViewCell and adding the UIImageView as a subview of that UIScrollView. The first problem I need to solve when I added that is that UIScrollViews do not play well with AutoLayout as explained here. So, if you want your image to be full screen both in portrait and landscape, remember to use the appropriate autoresizing masks. By doing that and returning my UIImageView in viewForZoomingInScrollView: I got the zooming effect I was looking for.
The compromise I had to do though was that I do not allow the user to scroll between different images if there is any zoom applied (i.e., zoom scale is different than 1.0). Apart from that, it works fine.


text:
Q: How do I override inline CSS with !important value? I am developing a website on WordPress. I want to override an inline CSS rule to style the menu in mobile. Problem is, the inline rule has !important value. I believe the inline styles is being generated dynamically.
Inline styles:

.et_pb_menu_0_tb_header.et_pb_menu .et_mobile_menu{
  background-color: RGBA(0,0,0,0) !important;
}

Inline rule result
Here is the external style

.et_pb_menu_0_tb_header.et_pb_menu .et_mobile_menu{
  background-color: RGBA(10,14,13,0.9) !important;
  }

External rule result
I have read that you can use JavaScript to override the inline rule, but am not sure where to post the JavaScript post.
Your insight is much appreciated.

A: In Js ... but You must know how and when include JS in function.php
$(window).on("load", function() {

    $(body).find('.et_pb_menu_0_tb_header.et_pb_menu
                  .et_mobile_menu).removeAttr("style");

    $(body).find('.et_pb_menu_0_tb_header.et_pb_menu
                  .et_mobile_menu).css('background-color',"rgba(10,14,13,0.9)")
});

If RGBA won't work, just add color hex.


text:
Q: Função FWRITE não está gravando em formato binário em linguagem C Não estou conseguindo gravar dados em binário em um arquivo utilizando a linguagem C. Mesmo usando 'wb' a saída do arquivo são caracteres.
Como posso proceder?
Eis aqui parte do meu código:

void cadastrar(void)
{
     if((fp=fopen("Jogos.dat", "wb"))==NULL)
     {
        printf("\nO arquivo nao pode ser aberto!\n");
        getch();
        exit(1);
     }
     fseek(fp,0L, SEEK_END);

 do
 {
    printf("\n Digite o Nome do Jogo ('FIM' para sair): ");
    gets(reg[quantidade_cadastro].nome_jogo);

    if ((strcmp(reg[quantidade_cadastro].nome_jogo,"fim")!=0)&&(strcmp(reg[quantidade_cadastro].nome_jogo,"FIM")!=0))
    {
        printf("\n Ano de Lancamento: ");
        scanf("%d",&reg[quantidade_cadastro].ano_lancamento);
        fflush(stdin);

        printf("\n Genero: ");
        gets(reg[quantidade_cadastro].genero);

        printf("\n Plataforma: ");
        gets(reg[quantidade_cadastro].plataforma);

        reg[0].status='1';

        if(fwrite(&reg, sizeof(struct registro), 1, fp) != 1)
        {
            printf("\nErro de Gravacao :/");
            getch();
        }
        else
        {
            quantidade_cadastro++;
            printf("\n Jogo Gravado no Arquivo!\n\n");
        }
    }
 }while((strcmp(reg[quantidade_cadastro].nome_jogo,"fim")!=0)&&(strcmp(reg[quantidade_cadastro].nome_jogo,"FIM")!=0));
 fclose(fp);}

A: O seu arquivo tem caracteres pelo seguinte motivo.
Como sua struct é composta por 4 campos char e um campo int, o normal é que os dados possam ser lidos.
O método fwrite escreve diretamente os valores de sua struct dentro de arquivo, sem fazer conversão de valores como o printf.
Os valores usados são os da tabela ascii. Supondo que você tenha a seguinte string "ABCD", os valores seriam escritos como: 65,66,67,68. E quando o editor de texto fosse ler esses valores ele exibiria ABCD.
Caso um int seja escrito no arquivo, o tamanho do int em 64bits vale 4, e o valor a ser escrito será 65. O valor escrito no arquivo será 65,0,0,0 ou A para o editor de texto. Caso o valore escrito seja 16961, deverá escrever AB.
Se usar o comando string (presente no bin/ do gcc) será possível ver os nomes dos métodos, as strings e das bibliotecas usadas pelo seu sistema, isso por causa da interpretação da tabela ascii quando se lê o arquivo.
Caso queira um arquivo com valores ilegíveis (sem caracteres A-Za-z-0-9), você deve armazenas valores que fujam o máximo possível dos caracteres literários e numéricos.

A: O conteúdo dos objectos de tipo struct registro é basicamente só texto. Não admira que o conteúdo do ficheiro sejam caracteres.
Verifica a parte do ano_lancamento no ficheiro "Jogos.dat".
Como gostarias que o registo seguinte fosse apresentado "em binário"?
strcpy(reg[0].nome_jogo, "jogo um");
reg[0].ano_lancamento = 2014;
strcpy(reg[0].genero, "sorte");
strcpy(reg[0].plataforma, "papel e lápis");

A diferença entre um ficheiro de texto ou binário prende-se basicamente no tratamento de "\n". Um ficheiro binário não faz tratamento desse caracter, um ficheiro de texto pode converter em "\r\n". Para mais detalhes lê as secções 7,21,2 e 7.21.3 do Standard C11 (em inglês).


text:
Q: How can I use raycasthit according to the mouse cursor position? public Camera mapCamera;

private Camera[] cameras;
private GameObject mouseOvered;

void Update()
    {
        if (Input.GetKeyDown(KeyCode.M))
        {
            if (mapCamera.enabled == false)
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = false;
                }
                mapCamera.enabled = true;
            }
            else
            {
                foreach (Camera cam in cameras)
                {
                    cam.enabled = true;
                }
                mapCamera.enabled = false;
            }
        }

        bool rcHit = false;
        Vector3 mouse = Input.mousePosition;
        Ray castPoint = mapCamera.ScreenPointToRay(mouse);
        RaycastHit hit;
        Debug.DrawRay(mapCamera.transform.position,
        mapCamera.transform.forward * Mathf.Infinity, Color.magenta);
        if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
        {
            rcHit = true;
        if (mouseOvered != hit.collider.gameObject)
        {
            mouseOvered = hit.collider.gameObject;
        }
        print(mouseOvered.name);
        //do your thing here to apply/change the material
    }
    if (!rcHit && mouseOvered != null)
    {
        //do your thing to undo the material change
        mouseOvered = null;
    }
   }

The problem is when I'm running the game I see the raycast laser still if I change in the Debug.DrawRay form Mathf.Infinity to 1000  and it's not moving according to the mouse cursor position. I'm moving the mouse cursor around but the raycast laser seems to stay at the same place so I guess It's hitting only specific places/objects and not everything ? Not sure what is going on.
If I'm using Mathf.Infinity I don't see the laser of the raycast at all.
And when I'm moving the mouse cursor around the space station only once it's detecting object and print it's name.
What I want to do is when I'm moving the mouse cursor around when it's hitting any object of the space station print it's name.
Only if I change on this line to 1000 for example then I see the magenta color:
Debug.DrawRay(mapCamera.transform.position, mapCamera.transform.forward * 1000, Color.magenta);

If it's Mathf.Infinity I don't see any magenta of the laser.

A: There is nothing wrong with the raycasting itself, the problem solely lies with what you draw. You dont draw the Ray, but a "Ray" from the camera position along its forward vector.
Replace
Debug.DrawRay(mapCamera.transform.position, mapCamera.transform.forward * Mathf.Infinity, Color.magenta);

With
Debug.DrawRay(castPoint.origin, castPoint.direction * Matf.Infinity, Color.magenta);

Tough im not sure if multiplying with infinity will work. Something like 1000 units (maybe even use mapCamera.farClipPlane as its unlikely a player wants to pick something outside it anyway) should be (more than) sufficient for most scenarios.


text:
Q: Lyx Cross referencing shows label instead of figure number for  on page  format Hi I'm currently writing my thesis,
I have separated my chapters out into individual lyx documents and includes them into a main lyx document
As I render, I get
seen in Figure ??fig:Modified-Ludzack-ettinger on the following page.
instead of
seen in Figure 2.1 on the following page.
If i switch the cross referencing format to just reference (without page) it renders correctly.
Anyone has any idea what's causing this?


text:
Q: Listing all products that contain current tag (on product page) I've tried searching but couldn't figure this out.
I'm wondering if it's possible to list all products that use the same tag as the current product.
For instance, if I'm on a product page that uses the tag "red", I'd like to list all of the other products that also use that tag.
Is this possible and if so how would I accomplish this?

A: There are some ways but I'm not sure if these will do you any good.
1) AJAX
The easiest ways is to make an AJAX request to the /collections/all/TAG and get the required products and append them.
2) Paginate hack
{% paginate collection.all.products by 1000 %}
  {%- for _product in collection.all.products -%}
    {%- if _product.tags contains 'red' -%}
      list the product
    {%- endif -%}
  {%- endfor -%}
{% endpaginate %}

Please note that this may increase the load time drastically depending how many products you have.


text:
Q: Mysql Update not working, with no mysql error I am sure there is something simple I am missing, but this update query is not working. It is returning the 'We were unable to reset your password...' error, but there is no mysql_error() shown.
    $usr = mysql_real_escape_string($_POST['username']);
    $email = mysql_real_escape_string($_POST['email']);

    $fpquery = "SELECT id, usr, email, rand FROM membertable WHERE usr = '$usr' AND email = '$email'";

    $fpresult = mysql_query($fpquery,$link);

    if(mysql_num_rows($fpresult) < 1) {

        $_SESSION['msg']['forgotpassword-err']= 'This username or email does not exist in our records. Make sure your capitalization is correct and please try again.';

        echo header("Location: ../forgotpassword.php");

    }

elseif(mysql_num_rows($fpresult) == 1) {

    $rand = $fpresult['rand'];

    $pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
    $insertpassword = hash("sha256",$pass.$rand);
    $fpid = $fpresult['id'];
    $fpusr = $fpresult['usr'];
    $fpemail = $fpresult['email'];

    $updatequery = "UPDATE membertable SET
                pass='$insertpassword',
                yn='2'
                WHERE id='$fpid' AND usr='$fpusr' AND email='$fpemail'";
    $updateresult = mysql_query($updatequery, $link);

    if(mysql_affected_rows($updateresult) == 1)
    {

        $_SESSION['msg']['forgotpassword-err']='You will receive an email with your temporary password. Please return to the home page and log in with this password to reset your password permanently';

        echo header("Location: ../forgotpassword.php");

    }

    else {

        $_SESSION['msg']['forgotpassword-err']='We were unable to reset your password. Please contact customer service at 888-888-8888 and mention the following error: ' . mysql_error();

        echo header("Location: ../forgotpassword.php");
    }
}

A: Shouldn't you fetch the results of $fpquery at some time with mysql_fetch_array() ?

A: First always use limit 1 if you need one row.
$fpquery = "SELECT id, usr, email, rand FROM membertable WHERE usr = '$usr' AND email = '$email' LIMIT 1";

You need to fetch the result:
try this:
$result = mysql_query($fpquery,$link);
$fpresult = mysql_fetch_array($result);

A: The update could be affecting either zero rows or more than one row - neither of these scenarios would produce an error, but would result in the 'We were unable to reset your password.' message.